diff --git a/TODO.md b/TODO.md index 4cc6d79..2fd7f5e 100644 --- a/TODO.md +++ b/TODO.md @@ -588,7 +588,7 @@ section only tracks the milestones. cross-file, whole-edit-or-nothing verified by re-parse. - [x] **M3 `refactor-ports`** — add/remove/propagate module ports across the declaration and every instantiation (named/ordered/`.*`). -- [ ] **M4 `refactor-instantiate`** — module hinting: instantiation +- [x] **M4 `refactor-instantiate`** — module hinting: instantiation skeleton completion from the definition, auto-connect, signature help. - [ ] Backlog (extract module, inline, `.*` expansion, ANSI conversion, organize imports, …) — triaged in the umbrella README after M4. diff --git a/crates/vfmt_server/src/completion.rs b/crates/vfmt_server/src/completion.rs new file mode 100644 index 0000000..9cd97fa --- /dev/null +++ b/crates/vfmt_server/src/completion.rs @@ -0,0 +1,612 @@ +//! `textDocument/completion` — module hinting on the wire. +//! +//! One item per module the workspace index knows, whose insert is the whole +//! instantiation skeleton: parameter overrides with their declared defaults, +//! every port as a named connection, the ones with a same-named signal in +//! scope already bound and the rest left as tabstops for the user to tab +//! through. The facts and the layout are `vlog_refactor::instantiation_plan`'s; +//! this module owns the position gate, the snippet encoding, and the item. +//! +//! See `docs/features/refactor-instantiate/README.md`. + +use lsp_types::{ + CompletionItem, CompletionItemKind, CompletionList, CompletionResponse, CompletionTextEdit, + Documentation, InsertTextFormat, MarkupContent, MarkupKind, Position, TextEdit, Uri, +}; +use vlog_parser::token::{Token, TokenKind}; +use vlog_parser::TextRange; +use vlog_refactor::{InstantiationPlan, Layout, Site}; + +use crate::pairs; +use crate::state::{Document, Workspace}; + +/// How many module skeletons one response carries. +/// +/// Each item costs one parse of one defining file — 158 µs for the average +/// file of this repo's corpus, 4.6 ms for its worst — so the cap is what keeps +/// a keystroke's answer in the low milliseconds however many modules the +/// workspace holds. A truncated list is returned `isIncomplete`, which is the +/// protocol's way of saying "ask me again when you have typed more"; the +/// client then narrows the query itself. +const LIMIT: usize = 64; + +/// The scopes a module instantiation may be written directly inside. +const ITEM_SCOPES: &[&str] = + &["module", "macromodule", "interface", "program", "generate", "begin"]; + +/// Scopes that make everything inside them something other than a module item: +/// a subprogram body, a class body, a checker-ish declaration, a `case` arm's +/// interior, a `fork` block. +const NOT_ITEM_SCOPES: &[&str] = &[ + "function", + "task", + "class", + "covergroup", + "property", + "sequence", + "clocking", + "specify", + "primitive", + "fork", + "case", + "casex", + "casez", + "randcase", +]; + +/// 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`. +const PROCEDURAL: &[&str] = + &["always", "always_ff", "always_comb", "always_latch", "initial", "final", "@"]; + +/// Tokens that end whatever came before them, stopping the backward scan that +/// looks for a [`PROCEDURAL`] keyword. +const STATEMENT_END: &[&str] = + &["begin", "end", "endcase", "join", "join_any", "join_none", "generate", ";"]; + +/// The module completions available at a position, or nothing when the cursor +/// is not somewhere an instantiation could be written. +/// +/// `snippets` is what the client advertised: without it the skeleton is +/// inserted as plain text, because a literal `${1:clk}` left in a buffer is +/// worse than no tabstops at all. +pub fn completions( + ws: &Workspace, + uri: &Uri, + position: Position, + snippets: bool, +) -> Option { + let doc = ws.document(uri)?; + let offset = doc.positions().offset(position); + let word = typed_word(doc, offset)?; + if !at_module_item(doc, word.start) { + return None; + } + let step = " ".repeat(ws.client_settings().indent.unwrap_or(2)); + let layout = Layout { base: line_indent(&doc.text, word.start), step }; + let site = Site { semantics: &doc.semantics, offset: word.start }; + + let names = vlog_refactor::module_names(ws.index(), &word.text); + let incomplete = names.len() > LIMIT; + let mut items = Vec::new(); + for name in names.into_iter().take(LIMIT) { + // A module two files declare has no single definition to read, so it + // is silently skipped: a completion list is not the place to argue. + let Ok(path) = vlog_refactor::module_definition(ws.index(), name) else { continue }; + let Some(definition) = ws.text_of(path) else { continue }; + let Ok(plan) = vlog_refactor::instantiation_plan(name, &definition, Some(site)) else { + continue; + }; + let file = path.file_name().and_then(|n| n.to_str()).unwrap_or("?").to_string(); + items.push(item(&plan, &layout, word.range(offset), doc, &file, snippets)); + } + if items.is_empty() { + return None; + } + Some(CompletionResponse::List(CompletionList { is_incomplete: incomplete, items })) +} + +/// One module's completion item, skeleton and all. +fn item( + plan: &InstantiationPlan, + layout: &Layout, + replacing: TextRange, + doc: &Document, + file: &str, + snippets: bool, +) -> CompletionItem { + // An escaped identifier (`\my-port`) may legally contain `$`, `}` and `\` + // — the snippet grammar's own metacharacters — and the *names* are written + // by the engine's layout, outside every hole, where no per-hole escaping + // can reach them. There is no encoding of `.\W}idth (${1:8})` the snippet + // parser reads back correctly, so such a plan is inserted as plain text: + // every default filled in, no tabstops, and text that parses. Documented + // in `docs/features/refactor-instantiate/README.md`. + let snippets = snippets && !plan.has_escaped_identifier(); + let new_text = match snippets { + true => plan.render_with(layout, &mut |n, default| snippet_hole(n, default)), + false => plan.render(layout), + }; + CompletionItem { + label: plan.module.clone(), + kind: Some(CompletionItemKind::MODULE), + detail: Some(format!("instantiate `{}` — {file}", plan.module)), + documentation: Some(Documentation::MarkupContent(MarkupContent { + kind: MarkupKind::Markdown, + value: documentation(plan), + })), + filter_text: Some(plan.module.clone()), + insert_text_format: Some(match snippets { + true => InsertTextFormat::SNIPPET, + false => InsertTextFormat::PLAIN_TEXT, + }), + text_edit: Some(CompletionTextEdit::Edit(TextEdit { + range: doc.positions().range(replacing), + new_text, + })), + ..Default::default() + } +} + +/// One tabstop: `${n:default}`, or a bare `${n}` when there is no default to +/// preselect. The default is escaped, because `$`, `}` and `\` are the snippet +/// grammar's own punctuation and a type like `logic [$bits(t)-1:0]` really +/// does contain one. +fn snippet_hole(n: usize, default: &str) -> String { + if default.is_empty() { + return format!("${{{n}}}"); + } + let mut escaped = String::with_capacity(default.len()); + for ch in default.chars() { + if matches!(ch, '$' | '}' | '\\') { + escaped.push('\\'); + } + escaped.push(ch); + } + format!("${{{n}:{escaped}}}") +} + +/// What the item's documentation panel shows: the ports with their directions +/// and types, which of them bound themselves, and anything the plan is unsure +/// of. +fn documentation(plan: &InstantiationPlan) -> String { + let mut out = String::new(); + if !plan.params.is_empty() { + out.push_str("**Parameters**\n\n"); + for param in &plan.params { + match param.default.is_empty() { + true => out.push_str(&format!("- `{}` — no default\n", param.name)), + false => out.push_str(&format!("- `{}` = `{}`\n", param.name, param.default)), + } + } + out.push('\n'); + } + match plan.ports.is_empty() { + true => out.push_str("**Ports** — none\n"), + false => { + out.push_str("**Ports**\n\n"); + for port in &plan.ports { + let note = + if port.auto_connect { " — connected, same name in scope" } else { "" }; + out.push_str(&format!("- `{}`{note}\n", port.label())); + } + } + } + for warning in &plan.warnings { + out.push_str(&format!("\n⚠ {warning}\n")); + } + out +} + +// ---------------------------------------------------------------------- +// where the cursor is +// ---------------------------------------------------------------------- + +/// The identifier the user is part-way through typing, and where it starts. +struct Word { + text: String, + start: u32, +} + +impl Word { + /// The bytes a completion replaces: the word as typed. + fn range(&self, cursor: u32) -> TextRange { + TextRange::new(self.start, cursor) + } +} + +/// The identifier run ending at the cursor — **only** when nothing but +/// whitespace precedes it on its line. +/// +/// That second half is half the position gate, and it is deliberately blunt: +/// an instantiation is written at the start of a line, and a word that is not +/// (`assign x = fo|`, `logic fo|`, `.clk(cl|`) is somewhere a module name would +/// be wrong. It costs the rare user who writes two items on one line their +/// completion, which is a far better failure than offering a fifteen-line +/// skeleton in the middle of an expression. +fn typed_word(doc: &Document, cursor: u32) -> Option { + let text = doc.text.get(..cursor as usize)?; + let head = text.trim_end_matches(is_ident_char); + let start = head.len(); + let line_start = head.rfind('\n').map_or(0, |newline| newline + 1); + if !head.get(line_start..)?.chars().all(|c| c == ' ' || c == '\t') { + return None; + } + Some(Word { text: text.get(start..)?.to_string(), start: start as u32 }) +} + +fn is_ident_char(ch: char) -> bool { + ch.is_ascii_alphanumeric() || ch == '_' || ch == '$' +} + +/// The whitespace the line holding `offset` begins with. +fn line_indent(text: &str, offset: u32) -> String { + let Some(head) = text.get(..offset as usize) else { return String::new() }; + let line_start = head.rfind('\n').map_or(0, |newline| newline + 1); + head.get(line_start..).unwrap_or("").chars().take_while(|c| *c == ' ' || *c == '\t').collect() +} + +/// Whether `at` is somewhere a module instantiation could be written, judged +/// over the token stream. +/// +/// This is a **heuristic, not a parse**, and the README says exactly what it +/// gets wrong. It reuses `pairs::analyze` — the same scope matcher the +/// begin/end rainbow runs on — so a half-typed buffer costs nothing extra and +/// an unbalanced one still answers. Three conditions, all necessary: +/// +/// 1. the innermost scope open here is one of [`ITEM_SCOPES`]; +/// 2. no scope in the chain is one of [`NOT_ITEM_SCOPES`], so a `begin` inside +/// a `function` or a `case` arm is rejected however module-ish its parent; +/// 3. the outermost `begin` in the chain is not a procedural one — a +/// generate-`for`'s `begin` qualifies, an `always @(...)`'s does not. +/// +/// 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 { + 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; + } + if chain.iter().any(|(keyword, _)| NOT_ITEM_SCOPES.contains(keyword)) { + return false; + } + let outermost_begin = chain.iter().rev().find(|(keyword, _)| *keyword == "begin"); + if let Some(&(_, span)) = outermost_begin { + if is_procedural(tokens, span.start) { + 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); + let mut out: Vec<(&'static str, TextRange)> = analysis + .pairs + .iter() + .filter(|pair| pair.open.end <= at && at <= pair.close.start) + .map(|pair| (pair.keyword, pair.open)) + .chain( + analysis + .unmatched_open + .iter() + .filter(|open| open.span.end <= at) + .map(|open| (open.keyword, open.span)), + ) + .collect(); + // Innermost first: the scope that opened last is the one we are in. + out.sort_by_key(|(_, span)| std::cmp::Reverse(span.start)); + out +} + +/// Whether the `begin` starting at `offset` belongs to a procedural block. +/// +/// Read backwards from the keyword: `always @(posedge clk) begin` reaches `@` +/// and then `always`, `initial begin` reaches `initial`, while a generate +/// `for (genvar i = 0; ...) begin` reaches the `;` inside its own header and a +/// `generate begin` reaches `generate`. Whichever comes first decides. +fn is_procedural(tokens: &[Token], offset: u32) -> bool { + let Some(begin) = tokens.iter().position(|token| token.span.start == offset) else { + return false; + }; + for token in tokens[..begin].iter().rev() { + if PROCEDURAL.iter().any(|kw| token.text == *kw) { + return true; + } + if STATEMENT_END.iter().any(|kw| token.text == *kw) { + return false; + } + } + false +} + +/// Whether every parenthesis opened between `from` and `at` was closed again. +fn balanced(tokens: &[Token], from: u32, at: u32) -> bool { + let mut depth = 0i32; + for token in tokens.iter().filter(|t| t.span.start >= from && t.span.start < at) { + if token.kind != TokenKind::Symbol { + continue; + } + match token.text.as_str() { + "(" => depth += 1, + ")" => depth -= 1, + _ => {} + } + } + depth == 0 +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::uri::path_to_uri; + use std::fs; + use std::path::PathBuf; + + const SUB: &str = "\ +module sub #( + parameter int WIDTH = 8 +) ( + input logic clk, + input logic [WIDTH-1:0] data, + output logic ready +); +endmodule +"; + + /// A scratch workspace root. Removed on drop. + struct Tree { + path: PathBuf, + } + + impl Tree { + fn new(name: &str) -> Tree { + let path = std::env::temp_dir() + .join(format!("vfmt_server_completion_{}_{name}", std::process::id())); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("temp dir"); + Tree { path } + } + + fn write(&self, rel: &str, text: &str) -> PathBuf { + let path = self.path.join(rel); + fs::write(&path, text).expect("write"); + path + } + } + + impl Drop for Tree { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } + } + + /// A two-file workspace with `top.sv` open, and the cursor at `needle`'s + /// end. `sub.sv` declares [`SUB`]. + fn asking(name: &str, top: &str, needle: &str) -> (Tree, Workspace, Uri, Position) { + let tree = Tree::new(name); + tree.write("sub.sv", SUB); + let path = tree.write("top.sv", top); + let mut ws = Workspace::default(); + ws.open_roots(vec![tree.path.clone()]); + let uri = path_to_uri(&path).expect("uri"); + ws.set_document(uri.clone(), top.to_string()); + let offset = (top.find(needle).expect("needle present") + needle.len()) as u32; + let doc = ws.document(&uri).expect("open"); + let position = doc.positions().position(offset); + (tree, ws, uri, position) + } + + fn items(response: Option) -> Vec { + match response { + Some(CompletionResponse::List(list)) => list.items, + Some(CompletionResponse::Array(items)) => items, + None => Vec::new(), + } + } + + fn inserted(item: &CompletionItem) -> String { + match item.text_edit.as_ref().expect("a text edit") { + CompletionTextEdit::Edit(edit) => edit.new_text.clone(), + CompletionTextEdit::InsertAndReplace(edit) => edit.new_text.clone(), + } + } + + #[test] + fn a_module_name_at_item_position_completes_to_a_snippet() { + let top = "module top;\n logic clk;\n su\nendmodule\n"; + let (_tree, ws, uri, position) = asking("snippet", top, " su"); + let items = items(completions(&ws, &uri, position, true)); + assert_eq!(items.len(), 1, "{items:#?}"); + let item = &items[0]; + assert_eq!(item.label, "sub"); + assert_eq!(item.kind, Some(CompletionItemKind::MODULE)); + assert_eq!(item.insert_text_format, Some(InsertTextFormat::SNIPPET)); + assert_eq!( + inserted(item), + "\ +sub #( + .WIDTH(${1:8}) + ) ${2:u_sub} ( + .clk(clk), + .data(${3:data}), + .ready(${4:ready}) + );", + "the site's own indentation, `clk` already in scope" + ); + } + + #[test] + fn a_client_without_snippet_support_gets_plain_text() { + let top = "module top;\n logic clk;\n su\nendmodule\n"; + let (_tree, ws, uri, position) = asking("plain", top, " su"); + let items = items(completions(&ws, &uri, position, false)); + let item = &items[0]; + 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!(text.contains(".data(data)"), "{text}"); + assert!(text.contains(") u_sub ("), "{text}"); + } + + #[test] + fn the_edit_replaces_exactly_the_typed_word() { + let top = "module top;\n su\nendmodule\n"; + let (_tree, ws, uri, position) = asking("replace", top, " su"); + let items = items(completions(&ws, &uri, position, true)); + let CompletionTextEdit::Edit(edit) = items[0].text_edit.as_ref().expect("edit") else { + panic!("a plain edit"); + }; + assert_eq!(edit.range.start, Position { line: 1, character: 2 }); + assert_eq!(edit.range.end, Position { line: 1, character: 4 }); + } + + #[test] + fn the_documentation_names_the_ports_and_what_bound_itself() { + let top = "module top;\n logic clk;\n su\nendmodule\n"; + let (_tree, ws, uri, position) = asking("docs", top, " su"); + let items = items(completions(&ws, &uri, position, true)); + let Some(Documentation::MarkupContent(doc)) = &items[0].documentation else { + panic!("markdown documentation"); + }; + assert!(doc.value.contains("`WIDTH` = `8`"), "{}", doc.value); + assert!(doc.value.contains("input logic [WIDTH-1:0] data"), "{}", doc.value); + assert!(doc.value.contains("`input logic clk` — connected"), "{}", doc.value); + } + + #[test] + fn nothing_is_offered_in_the_middle_of_an_expression() { + for (name, top, needle) in [ + ("assign", "module top;\n wire x;\n assign x = su\nendmodule\n", "= su"), + ("decl", "module top;\n logic su\nendmodule\n", "logic su"), + ("conn", "module top;\n sub u (.clk(su\nendmodule\n", ".clk(su"), + ("header", "module top (su\n);\nendmodule\n", "top (su"), + ] { + let (_tree, ws, uri, position) = asking(name, top, needle); + assert!(completions(&ws, &uri, position, true).is_none(), "{name}: {top}"); + } + } + + #[test] + fn nothing_is_offered_inside_a_procedural_block() { + let top = "module top;\n always_ff @(posedge clk) begin\n su\n end\nendmodule\n"; + let (_tree, ws, uri, position) = asking("always", top, " su"); + assert!(completions(&ws, &uri, position, true).is_none()); + + let top = "module top;\n initial begin\n su\n end\nendmodule\n"; + let (_tree, ws, uri, position) = asking("initial", top, " su"); + assert!(completions(&ws, &uri, position, true).is_none()); + } + + #[test] + fn nothing_is_offered_inside_a_function_or_a_class() { + let top = "module top;\n function int f();\n su\n endfunction\nendmodule\n"; + let (_tree, ws, uri, position) = asking("function", top, " su"); + assert!(completions(&ws, &uri, position, true).is_none()); + + let top = "package p;\n class c;\n su\n endclass\nendpackage\n"; + let (_tree, ws, uri, position) = asking("class", top, " su"); + assert!(completions(&ws, &uri, position, true).is_none()); + } + + #[test] + fn a_generate_block_is_still_item_position() { + let top = "\ +module top; + for (genvar i = 0; i < 4; i++) begin : g + su + end +endmodule +"; + let (_tree, ws, uri, position) = asking("genfor", top, " su"); + assert_eq!(items(completions(&ws, &uri, position, true)).len(), 1, "{top}"); + + let top = "module top;\n generate\n su\n endgenerate\nendmodule\n"; + let (_tree, ws, uri, position) = asking("generate", top, " su"); + assert_eq!(items(completions(&ws, &uri, position, true)).len(), 1); + } + + #[test] + fn nothing_is_offered_outside_a_design_unit() { + let top = "su\nmodule top;\nendmodule\n"; + let (_tree, ws, uri, position) = asking("toplevel", top, "su"); + assert!(completions(&ws, &uri, position, true).is_none()); + } + + #[test] + fn a_prefix_that_matches_no_module_offers_nothing() { + let top = "module top;\n zzz\nendmodule\n"; + let (_tree, ws, uri, position) = asking("nomatch", top, " zzz"); + assert!(completions(&ws, &uri, position, true).is_none()); + } + + #[test] + fn a_module_declared_twice_is_skipped_rather_than_guessed() { + let tree = Tree::new("dup"); + tree.write("a.sv", "module dup ();\nendmodule\n"); + tree.write("b.sv", "module dup ();\nendmodule\n"); + let top = "module top;\n du\nendmodule\n"; + let path = tree.write("top.sv", top); + let mut ws = Workspace::default(); + ws.open_roots(vec![tree.path.clone()]); + let uri = path_to_uri(&path).expect("uri"); + ws.set_document(uri.clone(), top.to_string()); + let offset = (top.find(" du").expect("needle") + 4) as u32; + let position = ws.document(&uri).expect("open").positions().position(offset); + assert!(completions(&ws, &uri, position, true).is_none()); + } + + #[test] + fn a_plan_with_an_escaped_identifier_falls_back_to_plain_text() { + // QA's MEDIUM #1, at the shipped path: an escaped identifier can carry + // `$` and `}`, so no snippet encoding of it survives the round trip. + // The client asked for snippets and gets plain text anyway — and what + // it gets parses. + let tree = Tree::new("escaped"); + tree.write( + "sub.sv", + "module sub (input logic \\my-port$1 , input logic clk);\nendmodule\n", + ); + let top = "module top;\n logic clk;\n su\nendmodule\n"; + let path = tree.write("top.sv", top); + let mut ws = Workspace::default(); + ws.open_roots(vec![tree.path.clone()]); + let uri = path_to_uri(&path).expect("uri"); + ws.set_document(uri.clone(), top.to_string()); + let offset = (top.find(" su").expect("needle") + 4) as u32; + let position = ws.document(&uri).expect("open").positions().position(offset); + + let items = items(completions(&ws, &uri, position, true)); + assert_eq!(items.len(), 1, "{items:#?}"); + assert_eq!( + items[0].insert_text_format, + Some(InsertTextFormat::PLAIN_TEXT), + "snippets were offered but the plan cannot be encoded as one" + ); + let text = inserted(&items[0]); + // `$` on its own is part of the port's *name* here; what must not + // appear is the tabstop syntax that would eat it. + assert!(!text.contains("${"), "no tabstop may survive here: {text}"); + assert!(text.contains(".\\my-port$1 (\\my-port$1 )"), "{text}"); + let probe = format!("module vfmt_probe;\n{text}\nendmodule\n"); + assert!( + vlog_parser::parse_source_tolerant(&probe).1.is_empty(), + "the inserted text must parse: {text}" + ); + } + + #[test] + fn a_tabstop_default_is_escaped_so_the_snippet_grammar_cannot_read_it() { + assert_eq!(snippet_hole(1, ""), "${1}"); + assert_eq!(snippet_hole(2, "8"), "${2:8}"); + assert_eq!(snippet_hole(3, "$bits(t)"), "${3:\\$bits(t)}"); + assert_eq!(snippet_hole(4, "a}b\\c"), "${4:a\\}b\\\\c}"); + } +} diff --git a/crates/vfmt_server/src/main.rs b/crates/vfmt_server/src/main.rs index ea26bab..98f545c 100644 --- a/crates/vfmt_server/src/main.rs +++ b/crates/vfmt_server/src/main.rs @@ -7,6 +7,7 @@ //! `docs/features/vfmt-server/README.md`. mod code_action; +mod completion; mod convert; mod diagnostics; mod format; @@ -19,6 +20,7 @@ mod ports; mod rename; mod server; mod settings; +mod signature; mod state; mod symbols; mod tokens; @@ -29,10 +31,11 @@ use std::path::PathBuf; use lsp_server::Connection; use lsp_types::{ - CodeActionKind, CodeActionOptions, CodeActionProviderCapability, ExecuteCommandOptions, - InitializeParams, OneOf, PositionEncodingKind, RenameOptions, SemanticTokensFullOptions, - SemanticTokensLegend, SemanticTokensOptions, SemanticTokensServerCapabilities, - ServerCapabilities, TextDocumentSyncCapability, TextDocumentSyncKind, WorkDoneProgressOptions, + CodeActionKind, CodeActionOptions, CodeActionProviderCapability, CompletionOptions, + ExecuteCommandOptions, InitializeParams, OneOf, PositionEncodingKind, RenameOptions, + SemanticTokensFullOptions, SemanticTokensLegend, SemanticTokensOptions, + SemanticTokensServerCapabilities, ServerCapabilities, SignatureHelpOptions, + TextDocumentSyncCapability, TextDocumentSyncKind, WorkDoneProgressOptions, }; use crate::server::Server; @@ -46,9 +49,10 @@ fn main() -> Result<(), Box> { // field we want is optional anyway. let params: InitializeParams = serde_json::from_value(params).unwrap_or_default(); let roots = workspace_roots(¶ms); + let snippets = snippet_support(¶ms); connection.initialize_finish(id, serde_json::to_value(initialize_result())?)?; - Server::new(connection, roots).run()?; + Server::new(connection, roots, snippets).run()?; io_threads.join()?; Ok(()) } @@ -99,6 +103,28 @@ fn capabilities() -> ServerCapabilities { commands: ports::commands(), work_done_progress_options: WorkDoneProgressOptions::default(), }), + // Module hinting. No trigger characters: an identifier being typed is + // what asks for these, and the handler declines every position that is + // not a module item, so an unprompted request costs a token scan. + completion_provider: Some(CompletionOptions { + // Every item is returned complete — skeleton, documentation and + // all — so there is nothing for `completionItem/resolve` to do. + resolve_provider: None, + trigger_characters: None, + all_commit_characters: None, + work_done_progress_options: WorkDoneProgressOptions::default(), + completion_item: None, + }), + // `(` opens a connection or parameter list and `,` moves to the next + // entry; between them they cover every place the ports are worth + // showing. + signature_help_provider: Some(SignatureHelpOptions { + trigger_characters: Some( + signature::TRIGGERS.iter().map(|t| (*t).to_string()).collect(), + ), + retrigger_characters: None, + work_done_progress_options: WorkDoneProgressOptions::default(), + }), semantic_tokens_provider: Some(SemanticTokensServerCapabilities::SemanticTokensOptions( SemanticTokensOptions { work_done_progress_options: WorkDoneProgressOptions::default(), @@ -124,6 +150,22 @@ fn initialize_result() -> lsp_types::InitializeResult { } } +/// Whether the client can expand `${1:x}` tabstops in a completion item. +/// +/// A client that did not say so gets the skeleton as plain text: a literal +/// `${1:clk}` written into a buffer is worse than no tabstops at all, and the +/// protocol gives no way to find out after the fact. +fn snippet_support(params: &InitializeParams) -> bool { + params + .capabilities + .text_document + .as_ref() + .and_then(|text_document| text_document.completion.as_ref()) + .and_then(|completion| completion.completion_item.as_ref()) + .and_then(|item| item.snippet_support) + .unwrap_or(false) +} + /// The directories to index: the client's workspace folders, or the /// deprecated single root when that is all it sent. fn workspace_roots(params: &InitializeParams) -> Vec { @@ -156,8 +198,50 @@ mod tests { assert!(caps.code_action_provider.is_some()); assert!(caps.rename_provider.is_some()); assert!(caps.execute_command_provider.is_some()); - // Deliberately absent until the engine exists — see the README. - assert!(caps.completion_provider.is_none()); + assert!(caps.completion_provider.is_some()); + assert!(caps.signature_help_provider.is_some()); + } + + #[test] + fn signature_help_advertises_the_characters_the_handler_answers_on() { + let options = capabilities().signature_help_provider.expect("signature help"); + assert_eq!(options.trigger_characters, Some(vec!["(".to_string(), ",".to_string()])); + } + + #[test] + fn completion_resolves_nothing_because_every_item_is_complete() { + let options = capabilities().completion_provider.expect("completion"); + assert_eq!(options.resolve_provider, None); + assert_eq!(options.trigger_characters, None); + } + + #[test] + fn snippet_support_is_read_from_the_clients_own_capabilities() { + use lsp_types::{ + ClientCapabilities, CompletionClientCapabilities, CompletionItemCapability, + TextDocumentClientCapabilities, + }; + assert!(!snippet_support(&InitializeParams::default()), "silence means no"); + + let saying = |snippet_support: Option| InitializeParams { + capabilities: ClientCapabilities { + text_document: Some(TextDocumentClientCapabilities { + completion: Some(CompletionClientCapabilities { + completion_item: Some(CompletionItemCapability { + snippet_support, + ..Default::default() + }), + ..Default::default() + }), + ..Default::default() + }), + ..Default::default() + }, + ..Default::default() + }; + assert!(super::snippet_support(&saying(Some(true)))); + assert!(!super::snippet_support(&saying(Some(false)))); + assert!(!super::snippet_support(&saying(None))); } #[test] diff --git a/crates/vfmt_server/src/server.rs b/crates/vfmt_server/src/server.rs index 82524e4..8da5bc6 100644 --- a/crates/vfmt_server/src/server.rs +++ b/crates/vfmt_server/src/server.rs @@ -14,26 +14,28 @@ use lsp_types::notification::{ DidSaveTextDocument, LogMessage, Notification as _, PublishDiagnostics, ShowMessage, }; use lsp_types::request::{ - CodeActionRequest, DocumentHighlightRequest, DocumentSymbolRequest, ExecuteCommand, Formatting, - GotoDefinition, HoverRequest, PrepareRenameRequest, RangeFormatting, References, Rename, - Request as _, SemanticTokensFullRequest, WorkspaceSymbolRequest, + CodeActionRequest, Completion, DocumentHighlightRequest, DocumentSymbolRequest, ExecuteCommand, + Formatting, GotoDefinition, HoverRequest, PrepareRenameRequest, RangeFormatting, References, + Rename, Request as _, SemanticTokensFullRequest, SignatureHelpRequest, WorkspaceSymbolRequest, }; use lsp_types::{ - CodeActionKind, CodeActionParams, DidChangeConfigurationParams, DidChangeTextDocumentParams, - DidCloseTextDocumentParams, DidOpenTextDocumentParams, DidSaveTextDocumentParams, - DocumentFormattingParams, DocumentHighlightParams, DocumentRangeFormattingParams, - DocumentSymbolParams, DocumentSymbolResponse, ExecuteCommandParams, GotoDefinitionParams, - GotoDefinitionResponse, HoverParams, LogMessageParams, MessageType, Position, - PublishDiagnosticsParams, ReferenceParams, RenameParams, SemanticTokensParams, - SemanticTokensResult, ShowMessageParams, TextDocumentPositionParams, Uri, - WorkspaceSymbolParams, WorkspaceSymbolResponse, + CodeActionKind, CodeActionParams, CompletionParams, DidChangeConfigurationParams, + DidChangeTextDocumentParams, DidCloseTextDocumentParams, DidOpenTextDocumentParams, + DidSaveTextDocumentParams, DocumentFormattingParams, DocumentHighlightParams, + DocumentRangeFormattingParams, DocumentSymbolParams, DocumentSymbolResponse, + ExecuteCommandParams, GotoDefinitionParams, GotoDefinitionResponse, HoverParams, + LogMessageParams, MessageType, Position, PublishDiagnosticsParams, ReferenceParams, + RenameParams, SemanticTokensParams, SemanticTokensResult, ShowMessageParams, + SignatureHelpParams, TextDocumentPositionParams, Uri, WorkspaceSymbolParams, + WorkspaceSymbolResponse, }; use serde::de::DeserializeOwned; use serde_json::Value; use crate::state::Workspace; use crate::{ - code_action, diagnostics, format, hover, nav, pairs, ports, rename, settings, symbols, tokens, + code_action, completion, diagnostics, format, hover, nav, pairs, ports, rename, settings, + signature, symbols, tokens, }; /// Everything the server owns. @@ -44,13 +46,16 @@ pub struct Server { /// for a document whenever its text changes, so the warning is said once /// per file change rather than once per format-on-save. config_warnings: HashSet, + /// Whether the client said it can expand a completion item's tabstops. + /// Read once, at `initialize`, because that is the only time it is sent. + snippets: bool, } impl Server { - pub fn new(connection: Connection, roots: Vec) -> Server { + pub fn new(connection: Connection, roots: Vec, snippets: bool) -> Server { let mut workspace = Workspace::default(); let warnings = workspace.open_roots(roots); - let server = Server { connection, workspace, config_warnings: HashSet::new() }; + let server = Server { connection, workspace, config_warnings: HashSet::new(), snippets }; server.report_scope(warnings); server } @@ -216,6 +221,22 @@ impl Server { Err(message) => Err(Failure::Request(message)), } }), + // Module hinting. A position that is not a module item answers + // `null` rather than an empty list, so the editor's own word + // completion is left in charge there. + Completion::METHOD => decode(request).and_then(|p: CompletionParams| { + let at = p.text_document_position; + let (uri, position) = (at.text_document.uri, at.position); + completion::completions(&self.workspace, &uri, position, self.snippets) + .map_or(Ok(Value::Null), to_value) + }), + SignatureHelpRequest::METHOD => decode(request).and_then(|p: SignatureHelpParams| { + let at = p.text_document_position_params; + let (uri, position) = (at.text_document.uri, at.position); + self.offset(&uri, position) + .and_then(|offset| signature::signature_help(&self.workspace, &uri, offset)) + .map_or(Ok(Value::Null), to_value) + }), WorkspaceSymbolRequest::METHOD => { decode(request).and_then(|p: WorkspaceSymbolParams| { to_value(WorkspaceSymbolResponse::Flat(symbols::workspace_symbols( diff --git a/crates/vfmt_server/src/signature.rs b/crates/vfmt_server/src/signature.rs new file mode 100644 index 0000000..8a3f643 --- /dev/null +++ b/crates/vfmt_server/src/signature.rs @@ -0,0 +1,482 @@ +//! `textDocument/signatureHelp` — the ports of the module whose connection +//! list the cursor is inside, with the one being connected highlighted. +//! +//! The facts come from the same `vlog_refactor::instantiation_plan` the +//! completion uses; what this module owns is finding the list. That is done +//! over the token stream rather than the tree, because a connection list is +//! being *typed* when the question is asked — `sub u_sub (.clk(` parses to +//! nothing useful, and half-written code is exactly when signature help is +//! wanted. +//! +//! See `docs/features/refactor-instantiate/README.md`. + +use lsp_types::{ + Documentation, ParameterInformation, ParameterLabel, SignatureHelp, SignatureInformation, Uri, +}; +use vlog_parser::token::{Token, TokenKind}; +use vlog_refactor::InstantiationPlan; + +use crate::state::Workspace; + +/// The characters that make a client ask without being asked. +pub const TRIGGERS: &[&str] = &["(", ","]; + +/// The ports (or parameters) of the instantiation the cursor is inside. +pub fn signature_help(ws: &Workspace, uri: &Uri, offset: u32) -> Option { + let doc = ws.document(uri)?; + let list = enclosing_list(&doc.tokens, offset)?; + let path = vlog_refactor::module_definition(ws.index(), &list.module).ok()?; + let definition = ws.text_of(path)?; + let plan = vlog_refactor::instantiation_plan(&list.module, &definition, None).ok()?; + let entries = match list.kind { + Kind::Params => plan.params.iter().map(param_label).collect::>(), + Kind::Ports => plan.ports.iter().map(|p| p.label()).collect::>(), + }; + if entries.is_empty() { + return None; + } + let names: Vec<&str> = match list.kind { + Kind::Params => plan.params.iter().map(|p| p.name.as_str()).collect(), + Kind::Ports => plan.ports.iter().map(|p| p.name.as_str()).collect(), + }; + let active = active_entry(&doc.tokens, &list, offset, &names); + Some(help(&plan, list.kind, &entries, active)) +} + +/// `WIDTH = 8`, or a bare name when the declaration gives no default. +fn param_label(param: &vlog_refactor::PlanParam) -> String { + match param.default.is_empty() { + true => param.name.clone(), + false => format!("{} = {}", param.name, param.default), + } +} + +/// Assemble the one signature, with each entry's label recorded as an offset +/// pair into it. +/// +/// Offsets rather than substrings: LSP lets a parameter label be either, and a +/// client matching a substring highlights the *first* occurrence — which for +/// two ports called `d` and `data` is the wrong one. The offsets are UTF-16 +/// code units, the encoding this server advertises. +fn help( + plan: &InstantiationPlan, + kind: Kind, + entries: &[String], + active: Option, +) -> SignatureHelp { + let opener = match kind { + Kind::Params => format!("{} #(", plan.module), + Kind::Ports => format!("{} (", plan.module), + }; + let mut label = opener; + let mut parameters = Vec::new(); + for (i, entry) in entries.iter().enumerate() { + if i > 0 { + label.push_str(", "); + } + let start = utf16_len(&label); + label.push_str(entry); + parameters.push(ParameterInformation { + label: ParameterLabel::LabelOffsets([start, utf16_len(&label)]), + documentation: None, + }); + } + label.push(')'); + let documentation = match plan.warnings.is_empty() { + true => None, + false => Some(Documentation::String(plan.warnings.join(" "))), + }; + SignatureHelp { + signatures: vec![SignatureInformation { + label, + documentation, + parameters: Some(parameters), + active_parameter: active, + }], + active_signature: Some(0), + active_parameter: active, + } +} + +fn utf16_len(text: &str) -> u32 { + text.chars().map(|c| c.len_utf16() as u32).sum() +} + +// ---------------------------------------------------------------------- +// finding the list +// ---------------------------------------------------------------------- + +/// Which of an instantiation's two lists the cursor is in. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Kind { + /// `sub #( ... )` + Params, + /// `sub u_sub ( ... )` + Ports, +} + +/// The list the cursor is inside. +struct List { + module: String, + kind: Kind, + /// Index of the `(` token that opens it. + open: usize, +} + +/// The innermost instantiation list the cursor sits in, if any. +/// +/// The parentheses open before the cursor are walked from the innermost +/// outwards, because a cursor inside `.clk(c|lk)` is inside two of them and +/// only the outer one is a connection list. A parenthesis qualifies when what +/// stands immediately before it reads as an instantiation: `#` preceded by a +/// name (a parameter list), or an instance name preceded by a module name — +/// optionally with the module's own `#( ... )` in between. `foo(bar|)` inside +/// a connected expression fails that test, because the token before `foo` is +/// the `(` of the connection and not a name. +fn enclosing_list(tokens: &[Token], offset: u32) -> Option { + let mut open: Vec = Vec::new(); + for (i, token) in tokens.iter().enumerate() { + if token.span.start >= offset { + break; + } + if token.kind != TokenKind::Symbol { + continue; + } + match token.text.as_str() { + "(" => open.push(i), + ")" => { + open.pop(); + } + _ => {} + } + } + open.iter().rev().find_map(|&i| list_at(tokens, i)) +} + +/// Whether the `(` at token index `open` opens an instantiation's list, and +/// which module's. +fn list_at(tokens: &[Token], open: usize) -> Option { + let before = tokens.get(open.checked_sub(1)?)?; + if before.is_sym("#") { + let module = tokens.get(open.checked_sub(2)?)?; + return is_name(module).then(|| List { + module: module.text.clone(), + kind: Kind::Params, + open, + }); + } + if !is_name(before) { + return None; + } + // `before` is the instance name. What stands before *it* is either the + // module name, or the `)` closing the module's parameter overrides. + let mut at = open.checked_sub(2)?; + if tokens.get(at)?.is_sym(")") { + at = matching_open(tokens, at)?; + if !tokens.get(at.checked_sub(1)?)?.is_sym("#") { + return None; + } + at = at.checked_sub(2)?; + } + let module = tokens.get(at)?; + is_name(module).then(|| List { module: module.text.clone(), kind: Kind::Ports, open }) +} + +/// A plain identifier — not a keyword, not a macro invocation, not a number. +fn is_name(token: &Token) -> bool { + token.kind == TokenKind::Ident && !token.is_macro() +} + +/// The index of the `(` matching the `)` at `close`. +fn matching_open(tokens: &[Token], close: usize) -> Option { + let mut depth = 0i32; + for i in (0..=close).rev() { + let token = tokens.get(i)?; + if token.kind != TokenKind::Symbol { + continue; + } + match token.text.as_str() { + ")" => depth += 1, + "(" => { + depth -= 1; + if depth == 0 { + return Some(i); + } + } + _ => {} + } + } + None +} + +/// Which entry of the list the cursor is on. +/// +/// A named list answers by name: the last `.name` written at the list's own +/// depth before the cursor, looked up among the module's entries. An ordered +/// list answers by position: the commas at the list's own depth are counted. +/// A `.name` the module does not declare highlights nothing, which is more +/// honest than highlighting whichever entry happens to sit at that index. +/// +/// `.*` makes the list a named one and highlights nothing. It is a wildcard, +/// not a connection: it names no single port, and counting it as position zero +/// — which an earlier version of this function did, because its `is_sym("*")` +/// arm sat where a `Symbol` token could never reach it — pointed at the first +/// port for no reason at all. +fn active_entry(tokens: &[Token], list: &List, offset: u32, names: &[&str]) -> Option { + let mut depth = 0i32; + let mut commas = 0u32; + let mut named: Option<&str> = None; + let mut any_name = false; + let mut dot = false; + for token in tokens.iter().skip(list.open + 1) { + if token.span.start >= offset { + break; + } + if token.kind == TokenKind::Symbol { + // `*` is a `Symbol`, so the wildcard must be recognised here — + // before the arm below, which only ever sees non-symbol tokens. + if dot && depth == 0 && token.text == "*" { + named = None; + any_name = true; + dot = false; + continue; + } + match token.text.as_str() { + "(" | "[" | "{" => depth += 1, + ")" | "]" | "}" => depth -= 1, + "," if depth == 0 => commas += 1, + "." if depth == 0 => { + dot = true; + continue; + } + _ => {} + } + if depth < 0 { + break; + } + dot = false; + continue; + } + if dot && depth == 0 && is_name(token) { + named = Some(token.text.as_str()); + any_name = true; + } + dot = false; + } + if any_name { + let name = named?; + return names.iter().position(|n| *n == name).map(|i| i as u32); + } + (commas < names.len() as u32).then_some(commas) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::uri::path_to_uri; + use std::fs; + use std::path::PathBuf; + + const SUB: &str = "\ +module sub #( + parameter int WIDTH = 8, + parameter DEPTH +) ( + input logic clk, + input logic [WIDTH-1:0] data, + output logic ready +); +endmodule +"; + + struct Tree { + path: PathBuf, + } + + impl Tree { + fn new(name: &str) -> Tree { + let path = std::env::temp_dir() + .join(format!("vfmt_server_signature_{}_{name}", std::process::id())); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("temp dir"); + Tree { path } + } + + fn write(&self, rel: &str, text: &str) -> PathBuf { + let path = self.path.join(rel); + fs::write(&path, text).expect("write"); + path + } + } + + impl Drop for Tree { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } + } + + /// Ask for signature help in `top` at the end of `needle`. + fn asking(name: &str, top: &str, needle: &str) -> (Tree, Option) { + let tree = Tree::new(name); + tree.write("sub.sv", SUB); + let path = tree.write("top.sv", top); + let mut ws = Workspace::default(); + ws.open_roots(vec![tree.path.clone()]); + let uri = path_to_uri(&path).expect("uri"); + ws.set_document(uri.clone(), top.to_string()); + let offset = (top.find(needle).expect("needle present") + needle.len()) as u32; + let help = signature_help(&ws, &uri, offset); + (tree, help) + } + + /// The one signature, and the label slice the active parameter names. + fn active_label(help: &SignatureHelp) -> Option { + let signature = help.signatures.first()?; + let active = help.active_parameter? as usize; + let parameter = signature.parameters.as_ref()?.get(active)?; + let ParameterLabel::LabelOffsets([start, end]) = parameter.label else { return None }; + Some(signature.label.chars().skip(start as usize).take((end - start) as usize).collect()) + } + + #[test] + fn a_named_connection_list_highlights_the_port_under_the_cursor() { + let top = "module top;\n sub u_sub (.clk(c), .data(\nendmodule\n"; + let (_tree, help) = asking("named", top, ".data("); + let help = help.expect("help"); + assert_eq!( + help.signatures[0].label, + "sub (input logic clk, input logic [WIDTH-1:0] data, output logic ready)" + ); + assert_eq!(help.active_parameter, Some(1)); + assert_eq!(active_label(&help).as_deref(), Some("input logic [WIDTH-1:0] data")); + } + + #[test] + fn the_first_port_is_active_at_the_open_paren() { + let top = "module top;\n sub u_sub (\nendmodule\n"; + let (_tree, help) = asking("open", top, "u_sub ("); + assert_eq!(help.expect("help").active_parameter, Some(0)); + } + + #[test] + fn an_ordered_connection_list_counts_commas() { + let top = "module top;\n sub u_sub (a, b, \nendmodule\n"; + let (_tree, help) = asking("ordered", top, "a, b, "); + let help = help.expect("help"); + assert_eq!(help.active_parameter, Some(2)); + assert_eq!(active_label(&help).as_deref(), Some("output logic ready")); + } + + #[test] + fn an_ordered_list_past_the_last_port_highlights_nothing() { + let top = "module top;\n sub u_sub (a, b, c, \nendmodule\n"; + let (_tree, help) = asking("overrun", top, "a, b, c, "); + assert_eq!(help.expect("help").active_parameter, None); + } + + #[test] + fn a_parameter_list_answers_with_the_parameters() { + let top = "module top;\n sub #(.WIDTH(4), .DEPTH(\n"; + let (_tree, help) = asking("params", top, ".DEPTH("); + let help = help.expect("help"); + assert_eq!(help.signatures[0].label, "sub #(WIDTH = 8, DEPTH)"); + assert_eq!(help.active_parameter, Some(1)); + assert_eq!(active_label(&help).as_deref(), Some("DEPTH")); + } + + #[test] + fn an_ordered_parameter_list_counts_commas_too() { + let top = "module top;\n sub #(4, \n"; + let (_tree, help) = asking("orderedparams", top, "#(4, "); + assert_eq!(help.expect("help").active_parameter, Some(1)); + } + + #[test] + fn a_connection_list_after_a_parameter_override_is_still_found() { + let top = "module top;\n sub #(.WIDTH(4)) u_sub (.data(\nendmodule\n"; + let (_tree, help) = asking("after_params", top, "u_sub (.data("); + let help = help.expect("help"); + assert_eq!(help.active_parameter, Some(1), "the ports, not the parameters"); + assert!(help.signatures[0].label.starts_with("sub ("), "{}", help.signatures[0].label); + } + + #[test] + fn a_call_inside_a_connected_expression_is_not_mistaken_for_a_list() { + let top = "module top;\n sub u_sub (.data(f(x)), .ready(\nendmodule\n"; + let (_tree, help) = asking("nested_call", top, ".ready("); + assert_eq!(help.expect("help").active_parameter, Some(2)); + } + + #[test] + fn a_wildcard_connection_highlights_nothing_and_advances_nothing() { + // QA's MEDIUM #2, reproduced: `.*` used to be counted as an ordered + // connection at position 0 and highlighted `clk`. + let top = "module top;\n sub u_sub (.*\nendmodule\n"; + let (_tree, help) = asking("wildcard", top, ".*"); + let help = help.expect("help"); + assert_eq!(help.active_parameter, None, "a wildcard names no single port"); + assert_eq!(help.signatures[0].parameters.as_ref().expect("params").len(), 3); + + // ...and a comma after it does not shift an ordered index either. + let top = "module top;\n sub u_sub (.*, \nendmodule\n"; + let (_tree, help) = asking("wildcard_comma", top, ".*, "); + assert_eq!(help.expect("help").active_parameter, None); + } + + #[test] + fn a_named_connection_after_a_wildcard_is_still_found_by_name() { + let top = "module top;\n sub u_sub (.*, .ready(\nendmodule\n"; + let (_tree, help) = asking("wildcard_named", top, ".ready("); + assert_eq!(help.expect("help").active_parameter, Some(2), "`ready` is the third port"); + } + + #[test] + fn a_port_the_module_does_not_declare_highlights_nothing() { + let top = "module top;\n sub u_sub (.nope(\nendmodule\n"; + let (_tree, help) = asking("unknown_port", top, ".nope("); + assert_eq!(help.expect("help").active_parameter, None); + } + + #[test] + fn a_cursor_outside_any_instantiation_gets_nothing() { + for (name, top, needle) in [ + ("plain", "module top;\n wire x;\n", "wire x"), + ("call", "module top;\n assign y = f(\n", "f("), + ("unknown", "module top;\n nope u_nope (\n", "u_nope ("), + ] { + let (_tree, help) = asking(name, top, needle); + assert!(help.is_none(), "{name}"); + } + } + + #[test] + fn a_module_with_no_parameters_offers_no_parameter_signature() { + let tree = Tree::new("noparams"); + tree.write("sub.sv", "module bare (input logic a);\nendmodule\n"); + let top = "module top;\n bare #(\n"; + let path = tree.write("top.sv", top); + let mut ws = Workspace::default(); + ws.open_roots(vec![tree.path.clone()]); + let uri = path_to_uri(&path).expect("uri"); + ws.set_document(uri.clone(), top.to_string()); + let offset = top.len() as u32 - 1; + assert!(signature_help(&ws, &uri, offset).is_none()); + } + + #[test] + fn the_label_offsets_are_utf16_units() { + // A comment cannot reach the label, but a type name can carry any + // identifier the lexer accepts, so the arithmetic is checked directly. + let entries = vec!["input logic é".to_string(), "output logic b".to_string()]; + let plan = InstantiationPlan { module: "m".into(), ..Default::default() }; + let help = help(&plan, Kind::Ports, &entries, Some(1)); + let ParameterLabel::LabelOffsets([start, end]) = + help.signatures[0].parameters.as_ref().expect("params")[1].label + else { + panic!("offsets") + }; + let label = &help.signatures[0].label; + assert_eq!(utf16_len(&label[..label.find("output").expect("second entry")]), start); + assert_eq!(end - start, utf16_len("output logic b")); + } +} diff --git a/crates/vfmt_server/tests/e2e.rs b/crates/vfmt_server/tests/e2e.rs index f074274..90e6589 100644 --- a/crates/vfmt_server/tests/e2e.rs +++ b/crates/vfmt_server/tests/e2e.rs @@ -1121,3 +1121,162 @@ fn a_port_code_action_and_the_port_commands_round_trip_over_the_wire() { let _ = std::fs::remove_dir_all(&dir); } + +/// The module hinting pair: a definition worth a skeleton, and a top that is +/// half-way through instantiating it. +const HINT_SUB: &str = "module hint_sub #(\n parameter int WIDTH = 8\n) (\n input logic clk,\n input logic [WIDTH-1:0] data,\n output logic ready\n);\nendmodule\n"; +/// `clk` is declared, `data` and `ready` are not — so one port auto-connects +/// and two do not. Line 2 is the half-typed module name. +const HINT_TOP: &str = "module hint_top;\n logic clk;\n hint_s\nendmodule\n"; + +#[test] +fn completion_and_signature_help_round_trip_over_the_wire() { + // What only an e2e test can check: that both capabilities are advertised + // with the shapes a client reads, that the snippet flag the client sent at + // `initialize` is the one the item comes back with, and that the + // skeleton survives JSON encoding with its tabstops intact. + let dir = temp_dir("hint"); + let sub = dir.join("hint_sub.sv"); + std::fs::write(&sub, HINT_SUB).expect("write"); + let top = dir.join("hint_top.sv"); + std::fs::write(&top, HINT_TOP).expect("write"); + let root = format!("file://{}", dir.display()); + let top_uri = format!("file://{}", top.display()); + + // A connection list being typed, as a `didChange` so the buffer really is + // half-written when signature help is asked for. + let typing = + "module hint_top;\n logic clk;\n hint_sub u_hint_sub (.clk(clk), .data(\nendmodule\n"; + + 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":"{top_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(HINT_TOP).expect("json") + )), + // The cursor at the end of ` hint_s` on line 2. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/completion","params":{{"textDocument":{{"uri":"{top_uri}"}},"position":{{"line":2,"character":8}}}}}}"# + )), + // ...and inside the `always` block, where nothing may be offered. + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{top_uri}","version":2}},"contentChanges":[{{"text":{}}}]}}}}"#, + serde_json::to_string( + "module hint_top;\n always_comb begin\n hint_s\n end\nendmodule\n" + ) + .expect("json") + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/completion","params":{{"textDocument":{{"uri":"{top_uri}"}},"position":{{"line":2,"character":10}}}}}}"# + )), + // Now a half-typed connection list, and signature help inside it. + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{top_uri}","version":3}},"contentChanges":[{{"text":{}}}]}}}}"#, + serde_json::to_string(typing).expect("json") + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/signatureHelp","params":{{"textDocument":{{"uri":"{top_uri}"}},"position":{{"line":2,"character":38}}}}}}"# + )), + 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); + + // 1. Both capabilities are advertised, with the trigger characters the + // signature-help handler actually answers on. + let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response"); + let capabilities = &initialize["result"]["capabilities"]; + assert!(capabilities["completionProvider"].is_object(), "{capabilities:#?}"); + let triggers = capabilities["signatureHelpProvider"]["triggerCharacters"] + .as_array() + .unwrap_or_else(|| panic!("no signatureHelpProvider in {capabilities:#?}")); + assert_eq!(triggers, &["(", ","]); + + // 2. One module item, inserting the whole skeleton as a snippet. + 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:#?}")); + assert_eq!(items.len(), 1, "{items:#?}"); + let item = &items[0]; + assert_eq!(item["label"], "hint_sub"); + assert_eq!(item["kind"], 9, "CompletionItemKind.Module"); + assert_eq!(item["insertTextFormat"], 2, "InsertTextFormat.Snippet"); + let new_text = item["textEdit"]["newText"].as_str().expect("newText"); + assert_eq!( + new_text, + "hint_sub #(\n .WIDTH(${1:8})\n ) ${2:u_hint_sub} (\n .clk(clk),\n .data(${3:data}),\n .ready(${4:ready})\n );", + "`clk` is in scope and binds itself; the rest are tabstops" + ); + assert_eq!(item["textEdit"]["range"]["start"]["character"], 2, "the typed word is replaced"); + assert_eq!(item["textEdit"]["range"]["end"]["character"], 8); + + // 3. Inside an `always_comb` there is no module item to complete. + let inside = messages.iter().find(|m| m["id"] == 3).expect("completion response"); + assert!(inside["result"].is_null(), "{inside:#?}"); + + // 4. Signature help names the ports and points at the one being connected. + let help = messages.iter().find(|m| m["id"] == 4).expect("signatureHelp response"); + let signatures = help["result"]["signatures"] + .as_array() + .unwrap_or_else(|| panic!("no signature help in {help:#?}")); + assert_eq!(signatures.len(), 1); + assert_eq!( + signatures[0]["label"], + "hint_sub (input logic clk, input logic [WIDTH-1:0] data, output logic ready)" + ); + assert_eq!(help["result"]["activeParameter"], 1, "`.data` is the second port"); + let parameters = signatures[0]["parameters"].as_array().expect("parameters"); + assert_eq!(parameters.len(), 3); + let offsets = parameters[1]["label"].as_array().expect("label offsets"); + let label = signatures[0]["label"].as_str().expect("label"); + let (start, end) = + (offsets[0].as_u64().expect("start") as usize, offsets[1].as_u64().expect("end") as usize); + assert_eq!(&label[start..end], "input logic [WIDTH-1:0] data"); + + let _ = std::fs::remove_dir_all(&dir); +} + +/// The same completion asked for by a client that never said it understands +/// snippets — the fallback the README promises. +#[test] +fn a_client_without_snippet_support_gets_the_skeleton_as_plain_text() { + let dir = temp_dir("hintplain"); + std::fs::write(dir.join("hint_sub.sv"), HINT_SUB).expect("write"); + let top = dir.join("hint_top.sv"); + std::fs::write(&top, HINT_TOP).expect("write"); + let root = format!("file://{}", dir.display()); + let top_uri = format!("file://{}", top.display()); + + let session = [ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{top_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(HINT_TOP).expect("json") + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/completion","params":{{"textDocument":{{"uri":"{top_uri}"}},"position":{{"line":2,"character":8}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(); + + let messages = talk(&session); + let completion = messages.iter().find(|m| m["id"] == 2).expect("completion response"); + let items = completion["result"]["items"].as_array().expect("a completion list"); + assert_eq!(items[0]["insertTextFormat"], 1, "InsertTextFormat.PlainText"); + let new_text = items[0]["textEdit"]["newText"].as_str().expect("newText"); + assert!(!new_text.contains('$'), "no tabstop syntax may reach this client: {new_text}"); + assert!(new_text.contains(".data(data)"), "{new_text}"); + + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/vlog_refactor/src/instantiate.rs b/crates/vlog_refactor/src/instantiate.rs new file mode 100644 index 0000000..aab9fd0 --- /dev/null +++ b/crates/vlog_refactor/src/instantiate.rs @@ -0,0 +1,933 @@ +//! Module hinting: the facts an instantiation skeleton is made of, and the +//! skeleton itself as plain text. +//! +//! This is rope's "type hinting drives completion" translated to Verilog. The +//! workspace index knows which file declares a module; that file's own header +//! says what the module's parameters and ports are; and the semantics of the +//! file the user is typing in say which of those ports already have a +//! same-named signal to bind to. Put together, they are everything a +//! `sub #( ... ) u_sub ( ... );` needs. +//! +//! Nothing here speaks LSP and nothing here does I/O. The caller passes the +//! defining file's text — it already had to read it — and gets an +//! [`InstantiationPlan`] whose [`InstantiationPlan::render`] writes plain +//! Verilog. Tabstops, snippet escaping and completion items are the server's +//! business; [`InstantiationPlan::render_with`] is the seam it renders through, +//! so both spellings of the skeleton come out of one layout. +//! +//! See `docs/features/refactor-instantiate/README.md`. + +use std::path::Path; + +use vlog_parser::ast::{AnsiPort, ItemKind, Module, ParamPort, PortList}; +use vlog_parser::parse_source_tolerant; +use vlog_parser::span::TextRange; +use vlog_semantic::{Semantics, SymbolKind, WorkspaceIndex}; + +use crate::ports::{find_module, visible_in}; + +/// One parameter an instantiation may override, in declaration order. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PlanParam { + /// The parameter's name. + pub name: String, + /// Its default as the declaration writes it (`8`, `logic [3:0]`), or an + /// empty string when the declaration gives none. + pub default: String, +} + +/// One port of the module, in declaration order. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PlanPort { + /// The port's name. + pub name: String, + /// `input`, `output` or `inout`; empty when the declaration writes none + /// and none is inherited. + pub dir: String, + /// Whatever the declaration writes between the direction and the name + /// (`logic [7:0]`, `wire`, `my_pkg::word_t`); empty for an implicit type. + /// + /// **Display text**: runs of whitespace are collapsed to one space so that + /// a port typed with a multi-line anonymous `struct` still reads as one + /// line in a signature. Nothing writes it into a buffer. + pub ty: String, + /// True when a signal of the same name is visible where the instantiation + /// is being written — the test that decides between `.p(p)` and a + /// placeholder. Always false when the caller named no site. + pub auto_connect: bool, +} + +impl PlanPort { + /// The port as a reader wants to see it: `input logic [7:0] data`. + pub fn label(&self) -> String { + let mut out = String::new(); + for part in [self.dir.as_str(), self.ty.as_str(), self.name.as_str()] { + if part.is_empty() { + continue; + } + if !out.is_empty() { + out.push(' '); + } + out.push_str(part); + } + out + } +} + +/// Everything an instantiation of one module is written from. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct InstantiationPlan { + /// The module being instantiated. + pub module: String, + /// Its overridable parameters, in declaration order. + pub params: Vec, + /// Its ports, in declaration order. + pub ports: Vec, + /// Sentences for the user about what the plan could not be sure of. + /// Informational: a plan with warnings still renders. + pub warnings: Vec, +} + +/// How the skeleton is laid out where it lands. +#[derive(Debug, Clone)] +pub struct Layout { + /// The whitespace every line after the first begins with — the + /// indentation of the line the instantiation is written on. The first line + /// gets none: the caller is already at the cursor. + pub base: String, + /// One indentation level, as the buffer's settings spell it. + pub step: String, +} + +impl Default for Layout { + /// Column zero, two-space steps — `vlog_formatter::Config::default`'s own + /// indent width, so an untouched skeleton survives a format-on-save. + fn default() -> Layout { + Layout { base: String::new(), step: " ".to_string() } + } +} + +/// The file that declares `module`, or why the question has no single answer. +/// +/// The index is the only thing consulted, so this is a map lookup: it is what +/// keeps a completion request off the disk for every module the user is *not* +/// completing. +pub fn module_definition<'i>(index: &'i WorkspaceIndex, module: &str) -> Result<&'i Path, String> { + let defs: Vec<_> = + index.units(module).iter().filter(|def| def.kind == SymbolKind::Module).collect(); + let [def] = defs.as_slice() else { + return Err(match defs.len() { + 0 => format!("vfmt indexes no module named `{module}`."), + _ => format!( + "`{module}` is declared in more than one indexed file; vfmt will not guess which one to instantiate." + ), + }); + }; + index.path(def.file).ok_or_else(|| format!("`{module}`'s declaring file is not in scope.")) +} + +/// Where an instantiation is being written, for the auto-connect question. +#[derive(Debug, Clone, Copy)] +pub struct Site<'a> { + /// The analysis of the file being typed in — the server already holds one + /// per open buffer, so this costs nothing. + pub semantics: &'a Semantics, + /// The byte offset the instantiation would go at. + pub offset: u32, +} + +/// The plan for instantiating `module`, read from the text of the file that +/// declares it. +/// +/// `site` is what makes a port auto-connect; pass `None` where the question +/// does not arise (signature help asks only what the ports *are*). +pub fn instantiation_plan( + module: &str, + definition: &str, + site: Option>, +) -> Result { + let (tree, diagnostics) = parse_source_tolerant(definition); + let Some((declaration, _)) = find_module(&tree, module) else { + // Two very different stories end here, and telling them apart is the + // difference between "someone edited the file out from under the + // index" and "vfmt's parser does not support this syntax" — the + // second is what an interface-typed ANSI port produces today (see the + // feature README's Handshakes). + return Err(match diagnostics.first() { + Some(problem) => format!( + "vfmt cannot read `{module}`'s declaration: its file does not parse ({} at line {}), so no instantiation was written.", + problem.message, problem.line + ), + None => format!( + "the file that declared `{module}` no longer declares it, so vfmt cannot write an instantiation of it." + ), + }); + }; + let mut plan = InstantiationPlan { + module: module.to_string(), + params: params(declaration, definition), + ports: ports(declaration, definition), + warnings: Vec::new(), + }; + // vfmt does not preprocess, so a port list split across `` `ifdef`` arms is + // read straight through: every arm's ports are in the list. That is the + // honest answer for a *skeleton* — it is a suggestion the user edits, not + // an edit to code they already wrote — but it is only honest if it is said + // out loud, because no configuration ever has all of them at once. + if !declaration.port_directives.is_empty() { + plan.warnings.push(directive_warning(module, "port list")); + } + if !declaration.param_directives.is_empty() { + plan.warnings.push(directive_warning(module, "parameter list")); + } + if let Some(site) = site { + for port in &mut plan.ports { + port.auto_connect = visible_in(site.semantics, site.offset, &port.name); + } + } + Ok(plan) +} + +fn directive_warning(module: &str, list: &str) -> String { + format!( + "`{module}`'s {list} carries compiler directives, so what it declares depends on the configuration; the skeleton names every entry written, from every `ifdef arm." + ) +} + +impl InstantiationPlan { + /// The instance name the skeleton proposes: `u_` and the module's name, + /// the convention every RTL style guide in the wild agrees on. + /// + /// An escaped module name yields an escaped instance name — `u_` glued in + /// front of a `\name` is not an identifier at all, whereas `\u_name` is. + pub fn instance_name(&self) -> String { + match self.module.strip_prefix('\\') { + Some(bare) => format!("\\u_{bare}"), + None => format!("u_{}", self.module), + } + } + + /// Whether any name in the plan is an **escaped identifier** (`\my-port`). + /// + /// Callers that encode the skeleton into a grammar of their own need to + /// know: an escaped identifier may legally contain `$`, `}` and `\` + /// (`\cost$`, `\a}b`), which are exactly the metacharacters of LSP's + /// snippet syntax, and the names are written by the layout rather than + /// through `hole`, so no per-hole escaping can reach them. The server + /// answers such a plan with a plain-text insert instead — see + /// `docs/features/refactor-instantiate/README.md`. + pub fn has_escaped_identifier(&self) -> bool { + is_escaped(&self.module) + || self.params.iter().any(|p| is_escaped(&p.name) || p.default.contains('\\')) + || self.ports.iter().any(|p| is_escaped(&p.name)) + } + + /// The skeleton as plain Verilog, every fill-in written as its own default. + pub fn render(&self, layout: &Layout) -> String { + self.render_with(layout, &mut |_, default| default.to_string()) + } + + /// The skeleton, with each place the user must fill in written by `hole`. + /// + /// `hole` is called once per fill-in with a 1-based ordinal and the default + /// text (which may be empty), in the order the user tabs through them: each + /// parameter override, then the instance name, then each port that did not + /// auto-connect. Returning the default unchanged is [`render`]; returning + /// `${n:default}` is the server's snippet. + /// + /// [`render`]: InstantiationPlan::render + pub fn render_with( + &self, + layout: &Layout, + hole: &mut dyn FnMut(usize, &str) -> String, + ) -> String { + let (base, inner) = (&layout.base, format!("{}{}", layout.base, layout.step)); + let mut out = String::new(); + let mut n = 0usize; + // The module name needs no `terminate` of its own: both continuations + // below start with a space, which is what an escaped name wants after + // it anyway. + out.push_str(&self.module); + if !self.params.is_empty() { + out.push_str(" #(\n"); + for (i, param) in self.params.iter().enumerate() { + n += 1; + out.push_str(&inner); + out.push('.'); + terminate(&mut out, ¶m.name); + out.push('('); + terminate(&mut out, &hole(n, ¶m.default)); + out.push(')'); + out.push_str(if i + 1 < self.params.len() { ",\n" } else { "\n" }); + } + out.push_str(base); + out.push(')'); + } + out.push(' '); + n += 1; + // Same here: a space always follows the instance name. + out.push_str(&hole(n, &self.instance_name())); + out.push_str(" ("); + if self.ports.is_empty() { + out.push_str(");"); + return out; + } + out.push('\n'); + for (i, port) in self.ports.iter().enumerate() { + let expr = if port.auto_connect { + port.name.clone() + } else { + n += 1; + hole(n, &port.name) + }; + out.push_str(&inner); + out.push('.'); + terminate(&mut out, &port.name); + out.push('('); + terminate(&mut out, &expr); + out.push(')'); + out.push_str(if i + 1 < self.ports.len() { ",\n" } else { "\n" }); + } + out.push_str(base); + out.push_str(");"); + out + } +} + +/// Write `text`, plus the space it needs before whatever is written next. +/// +/// A SystemVerilog escaped identifier runs from its `\` to the next +/// **whitespace** character (IEEE 1800 §5.6.1), so `.\my-port(sig),` lexes as +/// one enormous identifier that swallows the parens, the comma and the rest of +/// the line — and the skeleton no longer parses. Every splice point that is +/// not already followed by a space goes through here. +fn terminate(out: &mut String, text: &str) { + out.push_str(text); + if ends_escaped(text) { + out.push(' '); + } +} + +/// Whether `text` ends *inside* an escaped identifier, and so cannot be +/// followed directly by punctuation. +/// +/// An escaped identifier is terminated by whitespace and by nothing else, so +/// the question is exactly whether a `\` survives in the run of characters +/// after the last whitespace. Conservative by construction: a false positive +/// writes one harmless extra space. +fn ends_escaped(text: &str) -> bool { + text.rsplit(char::is_whitespace).next().unwrap_or(text).contains('\\') +} + +/// Whether a declared name is an escaped identifier. +fn is_escaped(name: &str) -> bool { + name.starts_with('\\') +} + +// ---------------------------------------------------------------------- +// reading a declaration +// ---------------------------------------------------------------------- + +/// The parameters an instantiation may override. +/// +/// A `localparam` written in the parameter port list is not one of them — it is +/// derived inside the module and overriding it is illegal — and a continuation +/// entry (`#(parameter A = 1, B = 2)`) inherits the keyword of the entry before +/// it, so the keyword is carried forward rather than read per entry. +fn params(module: &Module, text: &str) -> Vec { + let Some(declared) = &module.param_ports else { return Vec::new() }; + let mut out = Vec::new(); + let mut kw = String::new(); + for param in declared { + if let Some(written) = ¶m.kw { + kw = written.clone(); + } + if kw == "localparam" || param.name.is_empty() { + continue; + } + out.push(PlanParam { name: param.name.clone(), default: default_text(text, param) }); + } + out +} + +/// A parameter's default as an override list can write it, or nothing. +/// +/// Two things disqualify one, and the corpus produced both from a single +/// header (`common_cells/src/ecc_encode.sv`, a `parameter type` defaulting to +/// an anonymous multi-line `struct packed`): +/// +/// * it is written across several lines — the source's own indentation means +/// nothing inside a `#( ... )` on someone else's line, and re-flowing it +/// would risk rewriting a string literal's spaces; +/// * writing it back does not parse — vfmt's expression grammar does not +/// accept an inline aggregate as a parameter override, and a skeleton that +/// does not parse hands the user a red squiggle from our own server. +/// +/// A default vfmt cannot write back is simply not offered: the tabstop comes +/// up empty and the user types what they meant. +fn default_text(text: &str, param: &ParamPort) -> String { + let Some(expr) = ¶m.default else { return String::new() }; + let written = slice(text, expr.span).trim(); + if written.is_empty() || written.contains('\n') { + return String::new(); + } + // The spaces are the ones `terminate` writes: a default ending in an + // escaped identifier is legal where the renderer puts it, so the probe + // must not reject it for want of the space the renderer will supply. + let probe = format!("module __vfmt_probe;\n m #(.P( {written} )) u ();\nendmodule\n"); + let (_, diagnostics) = parse_source_tolerant(&probe); + match diagnostics.is_empty() { + true => written.to_string(), + false => String::new(), + } +} + +/// The module's ports, in declaration order, however the header declares them. +fn ports(module: &Module, text: &str) -> Vec { + match &module.ports { + PortList::Ansi(declared) => ansi_ports(declared, text), + PortList::NonAnsi(declared) => declared + .iter() + .map(|port| { + let (dir, ty) = non_ansi_type(module, text, &port.name); + PlanPort { name: port.name.clone(), dir, ty, auto_connect: false } + }) + .collect(), + PortList::Empty | PortList::None => Vec::new(), + } +} + +/// ANSI ports, whose direction and type are written in the header itself. +/// +/// An element that writes neither (`input logic a, b`) inherits both from the +/// element before it, which is what the language says and what a reader +/// expects to see spelled out. An element that writes *something* is reported +/// exactly as written, however partial: guessing what a bare `output q` +/// defaults to is the language's business, not a hint's. +fn ansi_ports(declared: &[AnsiPort], text: &str) -> Vec { + let mut out: Vec = Vec::new(); + let (mut dir, mut ty) = (String::new(), String::new()); + for port in declared { + if port.name.is_empty() { + continue; + } + let written = slice(text, TextRange::new(port.span.start, port.name_span.start)); + let written = written.trim(); + if !written.is_empty() { + dir = port.dir.clone().unwrap_or_default(); + ty = one_line(written.strip_prefix(dir.as_str()).unwrap_or(written)); + } + out.push(PlanPort { + name: port.name.clone(), + dir: dir.clone(), + ty: ty.clone(), + auto_connect: false, + }); + } + out +} + +/// The direction and type a non-ANSI port gets from its body declaration +/// (`module m (a); input wire [7:0] a;`). Both are empty when the body +/// declares no such port — a header that names a port the body forgot. +fn non_ansi_type(module: &Module, text: &str, name: &str) -> (String, String) { + for item in &module.items { + let ItemKind::PortDecl(decl) = &item.kind else { continue }; + if !decl.declarators.iter().any(|d| d.name == name) { + continue; + } + // Every declarator of one statement shares its direction and type, so + // the type is what stands before the *first* of them. + let Some(first) = decl.declarators.first() else { continue }; + let written = slice(text, TextRange::new(item.span.start, first.span.start)); + let ty = written.trim().strip_prefix(decl.dir.as_str()).unwrap_or(""); + return (decl.dir.clone(), one_line(ty)); + } + (String::new(), String::new()) +} + +fn slice(text: &str, span: TextRange) -> &str { + text.get(span.as_range()).unwrap_or("") +} + +/// Every run of whitespace as one space. Display text only — see +/// [`PlanPort::ty`]. +fn one_line(text: &str) -> String { + text.split_whitespace().collect::>().join(" ") +} + +/// The indexed module names matching `query`, sorted and without repeats — the +/// candidate list a completion offers. +/// +/// Matching is the index's own: `query` is a case-insensitive *substring*, so +/// `axi` finds `my_axi_master`, and an empty query matches everything. Modules +/// only — a package or a typedef is not something to instantiate. A name two +/// files both declare appears once here and is refused by +/// [`module_definition`], which is where the ambiguity is explained. +pub fn module_names<'i>(index: &'i WorkspaceIndex, query: &str) -> Vec<&'i str> { + let mut out: Vec<&str> = index + .workspace_symbols(query) + .into_iter() + .filter(|hit| hit.container.is_none() && hit.def.kind == SymbolKind::Module) + .map(|hit| hit.name) + .collect(); + out.dedup(); + out +} + +#[cfg(test)] +mod tests { + use super::*; + use std::path::PathBuf; + use vlog_semantic::analyze; + + const SUB: &str = "\ +module sub #( + parameter int WIDTH = 8, + parameter DEPTH, + localparam int DERIVED = WIDTH * 2 +) ( + input logic clk, + input logic rst_n, + input logic [WIDTH-1:0] data, + output logic ready +); +endmodule +"; + + fn plan(definition: &str, module: &str) -> InstantiationPlan { + instantiation_plan(module, definition, None).expect("a plan") + } + + fn index_of(files: &[(&str, &str)]) -> WorkspaceIndex { + WorkspaceIndex::build(files.iter().map(|(p, t)| (PathBuf::from(p), *t))) + } + + /// A plan whose auto-connect answers come from `site`'s own text, at the + /// offset of `needle` in it. + fn plan_at(definition: &str, module: &str, site: &str, needle: &str) -> InstantiationPlan { + let (tree, _) = parse_source_tolerant(site); + let semantics = analyze(&tree, site); + let offset = site.find(needle).expect("needle present") as u32; + instantiation_plan(module, definition, Some(Site { semantics: &semantics, offset })) + .expect("a plan") + } + + #[test] + fn a_plan_reads_the_parameters_and_ports_in_declaration_order() { + let plan = plan(SUB, "sub"); + assert_eq!( + plan.params, + vec![ + PlanParam { name: "WIDTH".into(), default: "8".into() }, + PlanParam { name: "DEPTH".into(), default: String::new() }, + ], + "a localparam is not overridable and is not offered" + ); + let names: Vec<&str> = plan.ports.iter().map(|p| p.name.as_str()).collect(); + assert_eq!(names, ["clk", "rst_n", "data", "ready"]); + assert_eq!(plan.ports[2].dir, "input"); + assert_eq!(plan.ports[2].ty, "logic [WIDTH-1:0]"); + assert_eq!(plan.ports[3].label(), "output logic ready"); + assert!(plan.warnings.is_empty(), "{:?}", plan.warnings); + } + + #[test] + fn an_ansi_port_that_writes_nothing_inherits_the_one_before_it() { + let text = "module m (input logic [3:0] a, b, output wire c);\nendmodule\n"; + let plan = plan(text, "m"); + assert_eq!(plan.ports[1].label(), "input logic [3:0] b", "a, b share a declaration"); + assert_eq!(plan.ports[2].label(), "output wire c"); + } + + #[test] + fn a_non_ansi_module_takes_its_types_from_its_body() { + let text = "\ +module legacy (a, b, q); + input wire [7:0] a, b; + output reg q; + always @(*) q = |(a & b); +endmodule +"; + let plan = plan(text, "legacy"); + assert_eq!(plan.ports.len(), 3); + assert_eq!(plan.ports[0].label(), "input wire [7:0] a"); + assert_eq!(plan.ports[1].label(), "input wire [7:0] b", "the second declarator too"); + assert_eq!(plan.ports[2].label(), "output reg q"); + } + + #[test] + fn a_header_port_the_body_never_declares_is_named_without_a_type() { + let text = "module m (a, b);\n input a;\nendmodule\n"; + let plan = plan(text, "m"); + assert_eq!(plan.ports[1].label(), "b"); + } + + #[test] + fn a_module_with_no_ports_and_no_parameters_still_plans() { + let bare = plan("module bare;\nendmodule\n", "bare"); + assert!(bare.params.is_empty()); + assert!(bare.ports.is_empty()); + assert_eq!(bare.render(&Layout::default()), "bare u_bare ();"); + + let empty_parens = plan("module bare2 ();\nendmodule\n", "bare2"); + assert!(empty_parens.ports.is_empty()); + } + + #[test] + fn a_module_with_parameters_and_no_ports_writes_the_override_list_only() { + let plan = plan("module p #(parameter W = 1) ();\nendmodule\n", "p"); + assert_eq!(plan.render(&Layout::default()), "p #(\n .W(1)\n) u_p ();"); + } + + #[test] + fn the_skeleton_is_laid_out_at_the_sites_own_indentation() { + let layout = Layout { base: " ".to_string(), step: " ".to_string() }; + assert_eq!( + plan(SUB, "sub").render(&layout), + "\ +sub #( + .WIDTH(8), + .DEPTH() + ) u_sub ( + .clk(clk), + .rst_n(rst_n), + .data(data), + .ready(ready) + );" + ); + } + + #[test] + fn the_holes_are_numbered_in_the_order_they_are_tabbed_through() { + let plan = plan(SUB, "sub"); + let mut seen: Vec<(usize, String)> = Vec::new(); + let rendered = plan.render_with(&Layout::default(), &mut |n, default| { + seen.push((n, default.to_string())); + format!("${{{n}:{default}}}") + }); + let order: Vec<&str> = seen.iter().map(|(_, d)| d.as_str()).collect(); + assert_eq!(order, ["8", "", "u_sub", "clk", "rst_n", "data", "ready"]); + assert_eq!(seen.iter().map(|(n, _)| *n).collect::>(), [1, 2, 3, 4, 5, 6, 7]); + assert!(rendered.contains("${3:u_sub}"), "{rendered}"); + assert!(rendered.contains(".WIDTH(${1:8})"), "{rendered}"); + } + + #[test] + fn a_port_with_a_same_named_signal_in_scope_connects_itself() { + let site = "\ +module top; + logic clk; + logic [7:0] data; + // here +endmodule +"; + let plan = plan_at(SUB, "sub", site, "// here"); + let connected: Vec<&str> = + plan.ports.iter().filter(|p| p.auto_connect).map(|p| p.name.as_str()).collect(); + assert_eq!(connected, ["clk", "data"]); + // The rest are holes the user fills in; the connected ones are not. + let rendered = plan.render_with(&Layout::default(), &mut |n, d| format!("${{{n}:{d}}}")); + assert!(rendered.contains(".clk(clk)"), "{rendered}"); + assert!(rendered.contains(".rst_n(${4:rst_n})"), "{rendered}"); + } + + #[test] + fn without_a_site_nothing_auto_connects() { + assert!(plan(SUB, "sub").ports.iter().all(|p| !p.auto_connect)); + } + + #[test] + fn a_signal_declared_in_another_module_does_not_count_as_in_scope() { + let site = "\ +module other; + logic clk; +endmodule +module top; + // here +endmodule +"; + let plan = plan_at(SUB, "sub", site, "// here"); + assert!(plan.ports.iter().all(|p| !p.auto_connect), "{:?}", plan.ports); + } + + #[test] + fn a_conditional_port_list_lists_every_arm_and_says_so() { + let text = "\ +module cond ( + input logic clk, +`ifdef WITH_DEBUG + input logic dbg, +`endif + output logic q +); +endmodule +"; + let plan = plan(text, "cond"); + let names: Vec<&str> = plan.ports.iter().map(|p| p.name.as_str()).collect(); + assert_eq!(names, ["clk", "dbg", "q"], "every arm's ports"); + assert_eq!(plan.warnings.len(), 1, "{:?}", plan.warnings); + assert!(plan.warnings[0].contains("port list"), "{:?}", plan.warnings); + assert!(plan.warnings[0].contains("`ifdef arm"), "{:?}", plan.warnings); + } + + #[test] + fn a_conditional_parameter_list_warns_too() { + let text = "\ +module cond #( + parameter W = 1, +`ifdef WIDE + parameter D = 2, +`endif + parameter E = 3 +) (); +endmodule +"; + let plan = plan(text, "cond"); + assert_eq!(plan.params.len(), 3); + assert_eq!(plan.warnings.len(), 1, "{:?}", plan.warnings); + assert!(plan.warnings[0].contains("parameter list"), "{:?}", plan.warnings); + } + + #[test] + fn a_default_vfmt_could_not_write_back_is_not_offered() { + // The corpus case: a `parameter type` defaulting to an anonymous + // multi-line `struct packed`. Pasting it into `#(.T( ... ))` gives + // text vfmt's own parser rejects, so no default is offered at all. + let text = "\ +module ecc #( + parameter int DataWidth = 64, + parameter type word_t = logic [DataWidth-1:0], + parameter type encoded_t = struct packed { + logic parity; + word_t word; + } +) (); +endmodule +"; + let plan = plan(text, "ecc"); + assert_eq!( + plan.params, + vec![ + PlanParam { name: "DataWidth".into(), default: "64".into() }, + PlanParam { name: "word_t".into(), default: "logic [DataWidth-1:0]".into() }, + PlanParam { name: "encoded_t".into(), default: String::new() }, + ] + ); + let skeleton = plan.render(&Layout::default()); + assert!(skeleton.contains(".encoded_t()"), "{skeleton}"); + let probe = format!("module p;\n{skeleton}\nendmodule\n"); + assert!(parse_source_tolerant(&probe).1.is_empty(), "the skeleton must parse: {skeleton}"); + } + + #[test] + fn a_multi_line_type_is_shown_on_one_line() { + let text = "\ +module m ( + input struct packed { + logic a; + logic b; + } bus +); +endmodule +"; + assert_eq!( + plan(text, "m").ports[0].label(), + "input struct packed { logic a; logic b; } bus" + ); + } + + /// Strip a snippet's tabstops back to the text they expand to: + /// `${n:default}` becomes `default` and `${n}` becomes nothing. + /// + /// Deliberately naive — it handles exactly the two shapes + /// `completion.rs::snippet_hole` produces, and it is only ever asked + /// about plans with no escaped identifier, which is the only case the + /// server encodes as a snippet at all. + fn expand(snippet: &str) -> String { + let mut out = String::new(); + let mut rest = snippet; + while let Some(at) = rest.find("${") { + out.push_str(&rest[..at]); + let Some(close) = rest[at..].find('}') else { break }; + let body = &rest[at + 2..at + close]; + if let Some((_, default)) = body.split_once(':') { + out.push_str(default); + } + rest = &rest[at + close + 1..]; + } + out.push_str(rest); + out + } + + /// The skeleton, wrapped so it can be parsed as the module item it is. + fn parses(skeleton: &str) -> bool { + let probe = format!("module vfmt_probe;\n{skeleton}\nendmodule\n"); + parse_source_tolerant(&probe).1.is_empty() + } + + #[test] + fn an_escaped_identifier_port_renders_a_skeleton_that_parses() { + // QA's MEDIUM #1. An escaped identifier runs to the next whitespace, + // so `.\my-port(sig),` is one token that eats the rest of the line. + let text = "module m (input logic \\my-port , input logic clk);\nendmodule\n"; + let plan = plan(text, "m"); + assert_eq!(plan.ports[0].name, "\\my-port"); + let skeleton = plan.render(&Layout::default()); + assert_eq!( + skeleton, "m u_m (\n .\\my-port (\\my-port ),\n .clk(clk)\n);", + "an escaped name is terminated on both sides of the parens" + ); + assert!(parses(&skeleton), "the plain rendering must parse: {skeleton}"); + } + + #[test] + fn escaped_names_everywhere_still_render_a_plain_skeleton_that_parses() { + // Module, parameter and port names all escaped, and two of them + // carrying the snippet grammar's own metacharacters — which is why + // `has_escaped_identifier` exists and why the server answers such a + // plan with a plain-text insert. + let text = "\ +module \\my-mod$1 #( + parameter \\W}idth = 8 +) ( + input logic \\a}b , + output logic q +); +endmodule +"; + let plan = plan(text, "\\my-mod$1"); + assert_eq!( + plan.instance_name(), + "\\u_my-mod$1", + "an escaped module names an escaped instance" + ); + assert!(plan.has_escaped_identifier(), "the server needs this to pick plain text"); + let skeleton = plan.render(&Layout::default()); + assert!(parses(&skeleton), "the plain rendering must parse:\n{skeleton}"); + } + + #[test] + fn a_snippet_expands_to_exactly_the_plain_rendering() { + // The other half of the "one seam" promise: for every plan the server + // does encode as a snippet, stripping the tabstops gives back the + // plain text byte for byte — so only one of the two can ever be wrong. + for (text, module) in [ + (SUB, "sub"), + ("module bare;\nendmodule\n", "bare"), + ("module p #(parameter W = 1) ();\nendmodule\n", "p"), + ] { + let plan = plan(text, module); + assert!(!plan.has_escaped_identifier(), "{module} is the snippet-encodable case"); + let snippet = + plan.render_with(&Layout::default(), &mut |n, default| match default.is_empty() { + true => format!("${{{n}}}"), + false => format!("${{{n}:{default}}}"), + }); + let plain = plan.render(&Layout::default()); + assert_eq!(expand(&snippet), plain, "{module}"); + assert!(parses(&plain), "{module}: {plain}"); + } + } + + #[test] + fn a_plan_with_no_escaped_identifier_says_so() { + assert!(!plan(SUB, "sub").has_escaped_identifier()); + let with_default = "module m #(parameter P = \\esc$1 ) ();\nendmodule\n"; + assert!( + plan(with_default, "m").has_escaped_identifier(), + "an escaped identifier inside a default counts too" + ); + } + + #[test] + fn a_default_ending_in_an_escaped_identifier_is_kept_and_terminated() { + // The probe in `default_text` writes the same spaces the renderer + // does, so a legal escaped default is not dropped for want of one. + let text = "module m #(parameter P = \\esc-1 ) ();\nendmodule\n"; + let plan = plan(text, "m"); + assert_eq!(plan.params[0].default, "\\esc-1"); + let skeleton = plan.render(&Layout::default()); + assert!(skeleton.contains(".P(\\esc-1 )"), "{skeleton}"); + assert!(parses(&skeleton), "{skeleton}"); + } + + #[test] + fn a_name_that_only_looks_escaped_is_left_alone() { + assert!(ends_escaped("\\my-port")); + assert!(!ends_escaped("logic [7:0]")); + assert!(!ends_escaped("\\a b"), "already terminated by its own space"); + assert!(!ends_escaped("")); + } + + #[test] + fn an_unknown_module_is_refused_by_name() { + let index = index_of(&[("a.sv", "module a;\nendmodule\n")]); + let message = module_definition(&index, "nope").expect_err("unknown"); + assert!(message.contains("indexes no module named `nope`"), "{message}"); + } + + #[test] + fn a_module_declared_twice_is_refused_rather_than_guessed() { + let index = + index_of(&[("a.sv", "module dup;\nendmodule\n"), ("b.sv", "module dup;\nendmodule\n")]); + let message = module_definition(&index, "dup").expect_err("ambiguous"); + assert!(message.contains("more than one indexed file"), "{message}"); + assert!(message.contains("will not guess"), "{message}"); + } + + #[test] + fn a_known_module_names_its_file() { + let index = index_of(&[("a.sv", "module a;\nendmodule\n"), ("b.sv", SUB)]); + assert_eq!(module_definition(&index, "sub").expect("found"), Path::new("b.sv")); + } + + #[test] + fn a_definition_that_no_longer_declares_the_module_is_refused() { + // The file the index pointed at has been edited since; a skeleton + // invented from nothing would be worse than a sentence. + let message = + instantiation_plan("sub", "module other;\nendmodule\n", None).expect_err("gone"); + assert!(message.contains("no longer declares it"), "{message}"); + } + + #[test] + fn a_definition_that_does_not_parse_says_so_rather_than_blaming_an_edit() { + // QA's LOW finding: "no longer declares it" reads as "someone changed + // the file", which is the wrong story when the real cause is a syntax + // vfmt's parser does not support. + let message = instantiation_plan("sub", "moduel sub (;;;\n", None).expect_err("garbage"); + assert!(message.contains("does not parse"), "{message}"); + assert!(!message.contains("no longer declares it"), "{message}"); + } + + #[test] + fn an_interface_typed_port_list_is_refused_as_a_parse_failure() { + // The disclosed `vlog_parser` gap: an interface-typed ANSI port + // (`iface_bus.mst bus`) stops the header from parsing, so no module + // is produced at all. The refusal must name the real cause. + let text = "module m (iface_bus.mst bus, input logic clk);\nendmodule\n"; + let message = instantiation_plan("m", text, None).expect_err("the parser gap"); + assert!(message.contains("does not parse"), "{message}"); + assert!(message.contains("line"), "{message}"); + } + + #[test] + fn the_candidate_list_is_the_indexs_modules_and_nothing_else() { + let index = index_of(&[ + ("a.sv", "module alpha;\nendmodule\nmodule beta;\nendmodule\n"), + ("p.sv", "package pkg;\n localparam K = 1;\nendpackage\n"), + ]); + assert_eq!(module_names(&index, ""), ["alpha", "beta"], "no package, no member"); + assert_eq!(module_names(&index, "al"), ["alpha"], "a substring narrows it"); + assert_eq!(module_names(&index, "ET"), ["beta"], "case-insensitively, anywhere"); + assert!(module_names(&index, "zzz").is_empty()); + } + + #[test] + fn a_name_two_files_declare_appears_once_in_the_candidates() { + let index = + index_of(&[("a.sv", "module dup;\nendmodule\n"), ("b.sv", "module dup;\nendmodule\n")]); + assert_eq!(module_names(&index, "dup"), ["dup"]); + } +} diff --git a/crates/vlog_refactor/src/lib.rs b/crates/vlog_refactor/src/lib.rs index 706d991..cd1f0bb 100644 --- a/crates/vlog_refactor/src/lib.rs +++ b/crates/vlog_refactor/src/lib.rs @@ -17,11 +17,22 @@ //! See `docs/features/refactor-rename/README.md` and //! `docs/features/refactor-ports/README.md` for the refusal lists and the //! verification stories. +//! +//! One member of the crate edits nothing: [`instantiation_plan`] answers "what +//! would an instantiation of this module look like here", which is rope's +//! type-hinting-drives-completion translated to Verilog. It produces text for +//! the caller to offer, never a [`RefactorEdit`], so it needs no verification +//! pass — see `docs/features/refactor-instantiate/README.md`. mod check; +mod instantiate; mod ports; mod rename; +pub use instantiate::{ + instantiation_plan, module_definition, module_names, InstantiationPlan, Layout, PlanParam, + PlanPort, Site, +}; pub use ports::{ add_port, may_have_port_action, port_actions, propagate_ports, remove_port, ModuleRef, PortAction, diff --git a/crates/vlog_refactor/src/ports.rs b/crates/vlog_refactor/src/ports.rs index e07f080..d52d47d 100644 --- a/crates/vlog_refactor/src/ports.rs +++ b/crates/vlog_refactor/src/ports.rs @@ -397,7 +397,7 @@ fn module_at(items: &[Item], offset: u32, found: &mut Option) { /// The module node named `name` in a parsed file, with the span of the item /// that holds it. -fn find_module<'t>(tree: &'t SourceFile, name: &str) -> Option<(&'t Module, TextRange)> { +pub(crate) fn find_module<'t>(tree: &'t SourceFile, name: &str) -> Option<(&'t Module, TextRange)> { fn walk<'t>(items: &'t [Item], name: &str) -> Option<(&'t Module, TextRange)> { for item in items { match &item.kind { @@ -1698,7 +1698,7 @@ fn name_visible(scope: &mut Scope, file: usize, offset: u32, name: &str) -> bool visible_in(&analysis.semantics, offset, name) } -fn visible_in(semantics: &Semantics, offset: u32, name: &str) -> bool { +pub(crate) fn visible_in(semantics: &Semantics, offset: u32, name: &str) -> bool { let scopes = semantics.scopes(); // The innermost scope covering the offset: the smallest span that holds it. let mut best: Option = None; diff --git a/crates/vlog_refactor/tests/corpus.rs b/crates/vlog_refactor/tests/corpus.rs index fef6fdd..8a6e4d8 100644 --- a/crates/vlog_refactor/tests/corpus.rs +++ b/crates/vlog_refactor/tests/corpus.rs @@ -10,7 +10,11 @@ use std::fs; use std::path::{Path, PathBuf}; use std::time::Instant; -use vlog_refactor::{add_port, port_actions, prepare_rename, rename, ModuleRef}; +use vlog_refactor::{ + add_port, instantiation_plan, module_definition, port_actions, prepare_rename, rename, Layout, + ModuleRef, +}; +use vlog_semantic::WorkspaceIndex; fn corpus() -> Option> { let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); @@ -191,3 +195,67 @@ fn asking_for_port_actions_all_over_a_real_file_never_panics() { } println!("port actions over {}: {offered} offered", path.display()); } + +#[test] +fn every_module_in_the_corpus_yields_a_skeleton_that_parses() { + // The property that matters for module hinting: whatever a completion + // inserts must be valid Verilog with every default accepted, because that + // is what an editor writes into the buffer on the first Tab. Real RTL is + // where the interesting headers are — type parameters, `ifdef arms, + // non-ANSI legacy modules, package-qualified port types. + let Some(files) = corpus() else { return }; + let sources = read(&files); + assert!(!sources.is_empty(), "corpus/ exists but holds no Verilog"); + let index = + WorkspaceIndex::build(sources.iter().map(|(path, text)| (path.clone(), text.as_str()))); + + let started = Instant::now(); + let mut planned = 0usize; + let mut refused = 0usize; + let mut unparseable: Vec = Vec::new(); + for (path, text) in &sources { + for name in module_names_in(text) { + let Ok(definition) = module_definition(&index, &name) else { + refused += 1; + continue; + }; + // A module the index attributes to another file is that file's to + // plan; this one only probes its own. + if definition != path.as_path() { + continue; + } + let Ok(plan) = instantiation_plan(&name, text, None) else { + refused += 1; + continue; + }; + planned += 1; + let skeleton = plan.render(&Layout::default()); + let probe = format!("module vfmt_probe;\n{skeleton}\nendmodule\n"); + let (_, diagnostics) = vlog_parser::parse_source_tolerant(&probe); + if !diagnostics.is_empty() && unparseable.len() < 10 { + unparseable.push(format!("{}: {name}\n{skeleton}", path.display())); + } + } + } + println!( + "corpus skeletons: {planned} planned, {refused} refused, in {:.2}s", + started.elapsed().as_secs_f64() + ); + assert!(planned > 100, "the corpus must hold plenty of modules, got {planned}"); + assert!(unparseable.is_empty(), "skeletons that do not parse:\n{}", unparseable.join("\n\n")); +} + +/// Every `module ` a file declares, read straight off the text — enough +/// for a probe that only wants names to feed the index with. +fn module_names_in(text: &str) -> Vec { + let (tree, _) = vlog_parser::parse_source_tolerant(text); + let mut out = Vec::new(); + for item in &tree.items { + if let vlog_parser::ast::ItemKind::Module(module) = &item.kind { + if module.kw == "module" && !module.name.is_empty() { + out.push(module.name.clone()); + } + } + } + out +} diff --git a/docs/features/refactor-instantiate/README.md b/docs/features/refactor-instantiate/README.md new file mode 100644 index 0000000..c535bda --- /dev/null +++ b/docs/features/refactor-instantiate/README.md @@ -0,0 +1,965 @@ +# refactor-instantiate + +M4 of the refactoring plan (`docs/features/refactor/README.md`): **module +hinting**. + +## Goal + +Give vfmt the thing rope gets from Python's type hints and no Verilog tool +ships well: the workspace already knows every module's parameters and ports, +so an instantiation should be *generated from the definition* rather than +typed by hand. Typing a module name at item position offers the whole +skeleton — parameter overrides carrying their declared defaults, every port as +a named connection, the ports that already have a same-named signal in scope +bound to it and the rest left as snippet tabstops — and once the connection +list is open, signature help names the remaining ports with their directions +and types. The facts live in `vlog_refactor` so Vim and a future CLI get the +same answers; `vfmt_server` owns only the position gate, the snippet encoding +and the LSP items. + +Nothing in this milestone edits a file. Everything it produces is *offered* +text that the client inserts, which is why it is the one member of +`vlog_refactor` with no verification pass: there is no existing code for it to +corrupt. + +## Assumptions + +- **The workspace index is the only thing that knows where a module lives.** + `WorkspaceIndex` carries no port or parameter detail — only + `Def { file, name_span, kind }` — so the defining file is parsed on demand. + Measured before choosing that design: `parse_source_tolerant` over this + repo's 820-file corpus is **158 µs per file on average, 4.6 ms worst case** + (release build, 4.8 MB total). A completion capped at 64 items therefore + costs ~10 ms of parsing in the ordinary case, which is why there is no + `completionItem/resolve` dance and no cache: every item is returned + complete. +- **A skeleton the user accepts untouched must parse.** This is the + editor-snippets assumption restated for generated text, and it is verified + rather than assumed — see the corpus test under *Work log*. It is what + forced parameter defaults through a parse-back probe. +- **vfmt does not preprocess.** A port or parameter list split across + `` `ifdef`` arms is read straight through, so the plan lists **every arm's** + entries and says so in a warning. Policy chosen deliberately over refusing: + a skeleton is a suggestion the user edits before it becomes code, unlike M3's + port refactorings, which *rewrite existing code* and therefore refuse an + insertion that would land inside an arm. Both behaviours are tested. +- **A same-named signal is a connectable signal.** "Auto-connect" reuses + M3's `visible_in` unchanged: the innermost `vlog_semantic` scope covering + the site is walked outward, and a hit counts only when it is a + `Net`/`Var`/`Port`/`Param`/`Genvar`/`TfArg`. No width or direction check is + made — `.clk(clk)` is offered whenever a `clk` is in scope, exactly as + `add_port` and `propagate_ports` already do it. +- **`u_` is the instance name worth proposing.** It is a tabstop, so + it costs one keystroke to reject. +- **An `interface` is offered like a module.** `vlog_semantic` records both + under `SymbolKind::Module` (`crates/vlog_semantic/src/model.rs`), and an + interface really is instantiated the same way (`bus_if u_bus (.clk(clk));`), + so nothing filters them out. A `program` is treated identically. If the + semantic layer ever grows a separate kind for either, this becomes a choice + rather than an inheritance. +- **A `localparam` in a parameter port list is not overridable** and is not + offered. A continuation entry (`#(parameter A = 1, B = 2)`) inherits the + keyword of the entry before it, so the keyword is carried forward. +- **The client's `snippetSupport` is read once, at `initialize`.** The + protocol offers no way to learn it later, and a client that changes its mind + mid-session is not a case worth modelling. +- **The indent step comes from `vfmt.indent` (default 2), not from + `vfmt.toml`.** `format::indent_width` discovers a config file from disk on + every call; a completion request arrives on every keystroke, and walking the + tree for a config file that often is not a trade worth making. Deviation + from how the formatter resolves the same setting — recorded here so the lead + can overrule it cheaply. + +## Handshakes + +- **Consumes `vlog_semantic`**: `WorkspaceIndex::units`/`path` to find a + module's defining file, `WorkspaceIndex::workspace_symbols` for the + candidate list, and `Semantics` (through M3's `visible_in`) for the + auto-connect question. Read-only; nothing new is asked of it. +- **Consumes `vlog_parser`**: `parse_source_tolerant` for the defining file, + `tokenize`'s output (via `Document.tokens`) for both position questions. + `AnsiPort`/`NonAnsiPort`/`ParamPort`/`PortDecl` are read for names, + directions and spans. +- **Widened inside `vlog_refactor`**: `ports::find_module` and + `ports::visible_in` went from private to `pub(crate)` so `instantiate.rs` + reuses them instead of writing a second scope walk. No behaviour changed; + both still have exactly one definition. +- **Consumes `vfmt_server::pairs`** — `pairs::analyze` and the public + `ScopeAnalysis`/`Pair`/`Unmatched` it already exposes — to decide whether the + cursor is at module-item position. Nothing in `pairs.rs` was changed: the + gate is built entirely from its published output, so editor-scopes keeps + ownership of the matcher. +- **Promises `vfmt_server`**: `instantiation_plan` never panics and never + returns a plan whose plain rendering fails to parse — corpus-verified over + all 454 modules, plus escaped-identifier cases the corpus does not contain + (see the *Escaped identifiers* section). `render_with` is the single layout + both the plain and the snippet spelling go through, so the two can never + drift; a unit test pins that stripping a snippet's tabstops gives back the + plain text byte for byte. `InstantiationPlan::has_escaped_identifier` is the + flag the server must consult before choosing snippet encoding. +- **`editors/vscode` needs no change.** `vscode-languageclient` advertises + `completionItem.snippetSupport: true` on its own, and the extension sets no + `initializationOptions` that would suppress it; `extension.js` was read to + confirm. The static `contributes.snippets` templates of editor-snippets are + unaffected — they are a manifest contribution the editor expands itself, and + VS Code shows both lists side by side. +- **Filed against `vlog_parser`, not fixed here (no action required for M4) + — two gaps, both disclosed rather than worked around silently:** + 1. The expression grammar rejects an inline aggregate as a parameter + override argument, so `m #(.T(struct packed { logic a; })) u ();` does not + parse ("unexpected keyword `struct` in expression"). Two corpus headers + (`common_cells/src/ecc_encode.sv`, `ecc_decode.sv`) declare + `parameter type` with such a default. M4 drops the default rather than + writing back text vfmt cannot read. + 2. An **interface-typed ANSI port** (`module m (iface_bus.mst bus, input + logic clk);`) stops the whole header from parsing ("expected `)` (found + \".\")"), so no `Module` item is produced and module hinting is silently + unavailable for a pattern that is common in contemporary SV. M4 cannot + work around this at all — there is no AST to read — but as of the + 2026-08-24 rework the refusal *says* the file does not parse and names + the diagnostic, instead of blaming an edit that never happened. Distinct + from *instantiating* an interface, which works (see Assumptions). + + Both workarounds disappear by themselves if the grammar grows the cases. + +## What it looks like + +`sub.sv` declares: + +```systemverilog +module sub #( + parameter int WIDTH = 8 +) ( + input logic clk, + input logic [WIDTH-1:0] data, + output logic ready +); +``` + +With `logic clk;` in scope, typing `su` inside `module top` offers one item +whose insert is: + +``` +sub #( + .WIDTH(${1:8}) + ) ${2:u_sub} ( + .clk(clk), + .data(${3:data}), + .ready(${4:ready}) + ); +``` + +`clk` bound itself; `data` and `ready` are tabstops preloaded with the port's +own name. A client that did not advertise snippet support gets the same text +with every hole written as its default and no `${}` anywhere. + +Tabstops are numbered in the order the user tabs through them: each parameter +override, then the instance name, then each port that did not auto-connect. +Auto-connected ports get **no `// auto-connected` comment** — a deliberate +deviation from the milestone brief, recorded in the *Work log*. A plan whose +names are escaped identifiers is inserted as plain text whatever the client +advertised — see *Escaped identifiers* below. + +Inside the connection list, `textDocument/signatureHelp` answers: + +``` +sub (input logic clk, input logic [WIDTH-1:0] data, output logic ready) +``` + +with the entry under the cursor highlighted — by name for a named list, by +position for an ordered one — and the same for `#( ... )` against the +parameters. + +## Escaped identifiers + +SystemVerilog's escaped identifiers (`\my-port`, `\cost$`, `\a}b` — IEEE 1800 +§5.6.1) are legal, absent from the corpus, and hostile to both of this +feature's output grammars. Two separate problems, two separate answers. + +**Verilog's problem: an escaped identifier is terminated by whitespace and by +nothing else.** So `.\my-port(sig),` lexes as *one* identifier that swallows +the parens, the comma and the rest of the line, and the skeleton no longer +parses. Fixed in the engine: `terminate` (`instantiate.rs`) writes the space +after every splice whose text ends inside an escaped identifier, so the +rendering is `.\my-port (\my-port ),`. The check is `ends_escaped` — does a +`\` survive in the run of characters after the last whitespace — which is +conservative by construction: a false positive costs one harmless space. The +same spaces are written into `default_text`'s parse-back probe, so a default +that legitimately ends in an escaped identifier is kept rather than dropped for +want of a space the renderer was going to supply anyway. `instance_name` is +escaped-aware too: an escaped module name yields `\u_name`, because `u_` glued +in front of a `\name` is not an identifier at all. + +**LSP's problem: an escaped identifier may contain `$`, `}` and `\`** — exactly +the snippet grammar's metacharacters. Per-hole escaping cannot help, because +the *names* are written by the layout, outside every hole: there is no encoding +of `.\W}idth (${1:8})` that a snippet parser reads back correctly. **Ruling +(lead-approved): a plan containing any escaped identifier is inserted as plain +text**, tabstops and all sacrificed, even when the client advertised +`snippetSupport`. `InstantiationPlan::has_escaped_identifier` is the test; +`completion.rs::item` is the one place it is consulted. The user gets a correct +skeleton with every default filled in and no tabstops to tab through — a small +loss, confined to a naming style almost nobody uses, and the alternative is +inserting text that does not parse. + +Regression-tested at both levels: the engine renders a parseable plain skeleton +for a module whose module, parameter and port names are all escaped (two of +them carrying `$` and `}`), and the server's own `item` returns +`InsertTextFormat::PlainText` with no `${` anywhere for exactly that module, +with the inserted text re-parsed in the assertion. + +## How precise the position gate is + +Honesty section, because the milestone asked for it. `completion.rs`'s +`at_module_item` is a **heuristic over the token stream**, not a parse. Three +conditions, all necessary: + +1. the word being typed is the **first thing on its line** (only whitespace + before it); +2. the innermost scope open at the cursor — from `pairs::analyze` — is + `module`, `macromodule`, `interface`, `program`, `generate` or `begin`, and + **no** enclosing scope is `function`, `task`, `class`, `covergroup`, + `property`, `sequence`, `clocking`, `specify`, `primitive`, `fork`, or a + `case` family; +3. when a `begin` is in the chain, the **outermost** one is not procedural — + decided by reading backwards from that `begin` for `always*`/`initial`/ + `final`/`@` before hitting a `;`, `end`, `begin`, `generate`, `endcase` or + `join*`; + +plus every parenthesis opened since the innermost scope's keyword must be +closed again, which is what keeps a port list and a connection list out. + +**What it gets right**, all tested: a module body, an `interface` body, inside +`generate ... endgenerate`, inside a `for (genvar ...) begin : g` block; +nothing offered inside `always_comb begin`, `always_ff @(...) begin`, +`initial begin`, a `function` body, a `class` body, a module header's port +list, a connection list, after `assign x = `, after `logic `, or at file +scope outside any design unit. + +**What it gets wrong, deliberately:** + +- Two items written on one line (`wire a; sub u_sub (...);`) get no completion + on the second, because of rule 1. An instantiation is written at the start + of a line in every style guide there is, and the alternative — deciding what + a bare identifier means mid-line — is a parse the buffer cannot supply while + it is being typed. +- A `begin` inside a `generate` inside a *procedural* construct cannot occur + in legal Verilog, so rule 3 has no false negative there; but a `begin` + reached from a construct rule 3 does not know (a `checker`, a UDP table) + falls back to "not procedural" and may offer a completion where nothing can + be instantiated. The cost is one unwanted list item, never a wrong edit. +- Ports and parameters are not offered inside a connection list. That is the + *next* completion feature and is not in M4's scope; signature help covers + the same need for now. + +Signature help's list-finder has its own limit, also tested: it recognises a +list when the token before its `(` reads as an instantiation (`#` after a +name, or an instance name after a module name, optionally with the module's +own `#( ... )` between them). A function call inside a connected expression +(`.data(f(x))`) fails that test and is stepped past, which is right; a +*variable* declaration that happens to look like an instantiation +(`my_type_t my_var (` — legal, and genuinely ambiguous in the grammar) is +treated as an instantiation, but answers nothing unless the index really does +hold a module of that name. + +## Status / TODO + +- [x] Engine module `crates/vlog_refactor/src/instantiate.rs`: + `module_definition`, `instantiation_plan`, `module_names`, + `InstantiationPlan`/`PlanParam`/`PlanPort`/`Layout`/`Site` +- [x] Deterministic plain-text rendering (`render`) and the one seam the + server's snippet goes through (`render_with`) +- [x] Auto-connect via M3's `visible_in`, unchanged +- [x] Refusals: unknown module, ambiguous duplicate definitions, a definition + file that no longer declares the module +- [x] `` `ifdef`` policy: list every arm, warn — documented and tested +- [x] `textDocument/completion` + the capability, snippet/plain fallback by + client capability, position gate +- [x] `textDocument/signatureHelp` + the capability, `(` and `,` triggers, + active parameter for named and ordered lists, ports and parameters +- [x] Engine unit tests (29), server unit tests (completion 13, signature 14, + capabilities/`snippetSupport` 4 new), one corpus property test, two e2e + stdio round trips +- [x] `cargo fmt --all -- --check`, `cargo clippy --all-targets`, + `cargo test --workspace` +- [x] `docs/features/vfmt-server/README.md` capability table updated +- [x] QA rework (2026-08-24): escaped-identifier spacing + plain-text + fallback, the `.*` wildcard in signature help, the parse-failure + refusal message +- [ ] Not done, backlog: declare-missing-signals companion action; completion + of *port names* inside a connection list; a plan cache keyed on the + defining file's text. + +## Work log + +- **2026-08-24 (dev)** — read M1–M3 first: the umbrella plan, the ports and + rename READMEs, `vlog_refactor`'s `Scope`, and `vfmt_server`'s dispatch, + `state.rs` and `ports.rs`. + + **Design decision 1 — the engine takes an index and a file's text, not the + file set.** M2/M3's entry points all take `&[(PathBuf, String)]` and build a + `Scope`, which builds a whole `WorkspaceIndex` — every file parsed. That is + right for a user-initiated refactoring and completely wrong for a keystroke. + So `instantiate.rs` has two small entry points instead: + `module_definition(index, name)` (a map lookup against the index the server + already holds) and `instantiation_plan(name, definition_text, site)` (one + parse of one file). Auto-connect reads the open buffer's own `Semantics`, + which `Document` already carries. Net effect: a completion request does no + workspace work at all beyond the lookup. + + **Design decision 2 — one renderer, two spellings.** The milestone puts the + tabstop encoding in the server, which invites two copies of the layout. It + is instead one function, `render_with(layout, hole)`, where `hole(n, + default)` writes each fill-in; `render` passes the identity and the server + passes `${n:default}`. Divergence is impossible by construction. + + **Deviation from the brief — no `// auto-connected` comments.** The + milestone's example writes `.clk(clk), // auto-connected` into the inserted + text. Not done: those comments are permanent (nothing later removes them), + they would appear on the majority of connections in real RTL, and vfmt + writing editorial comments into a user's design is a line the formatter has + never crossed. The information is in the completion item's documentation + panel instead ("connected, same name in scope"), where it is read once and + costs the buffer nothing. One-line change in `completion.rs` if the lead + disagrees. + + **Measured before deciding, not after.** The `completionItem/resolve` + question (build 64 skeletons eagerly, or advertise `resolveProvider` and + fill `insertText` later — which the spec does not actually permit for + `textEdit`) was settled by measuring `parse_source_tolerant` over the corpus: + 158 µs mean, 4.6 ms worst, 27 MB/s. Eager it is, capped at 64 items with + `isIncomplete: true` when truncated so the client re-asks as the prefix + narrows. The measurement harness was a throwaway test, run and deleted. + + **The corpus test found a real bug, which is why it exists.** Rendering a + skeleton for all 454 modules the corpus declares and re-parsing each one + caught two: `common_cells`' `ecc_encode`/`ecc_decode` declare + `parameter type encoded_data_t = struct packed { ... }` across several lines, + and the skeleton pasted the source's own indentation into a `#( ... )` on + someone else's line *and* produced text vfmt's own parser rejects. Fixed by + `default_text`: a default written across lines is dropped, and every + surviving default is probed by writing it into a throwaway + `m #(.P(...)) u ();` and requiring a clean parse. A default vfmt cannot write + back is not offered — the tabstop comes up empty. The parser gap itself is + filed in *Handshakes*, unfixed, because it belongs to another crate. + + **Port type text is display-only and collapsed to one line** + (`PlanPort::ty`), so a port typed with a multi-line anonymous `struct` still + reads as one line in a signature. Nothing writes it into a buffer, which is + what makes collapsing safe there and unsafe for parameter defaults. + + **Files touched.** New: `crates/vlog_refactor/src/instantiate.rs`, + `crates/vfmt_server/src/completion.rs`, + `crates/vfmt_server/src/signature.rs`, this README. Edited: + `crates/vlog_refactor/src/lib.rs` (module + re-exports + a paragraph on the + one member that edits nothing), `crates/vlog_refactor/src/ports.rs` + (`find_module` and `visible_in` to `pub(crate)`, no behaviour change), + `crates/vfmt_server/src/main.rs` (two capabilities, `snippet_support`, + `Server::new` gained the flag), `crates/vfmt_server/src/server.rs` (two + dispatch arms, the flag on `Server`), + `crates/vlog_refactor/tests/corpus.rs` and + `crates/vfmt_server/tests/e2e.rs` (new tests only), + `docs/features/vfmt-server/README.md` (capability table). + + **Not touched, deliberately:** `TODO.md`, the umbrella checklist, + `pairs.rs`, `hover.rs` (module hover already works through nav), and every + M3 code path. + +- **2026-08-24 (dev, QA rework)** — three lead rulings on QA's findings, + all three implemented. Gates re-run: `cargo fmt --all -- --check` clean, + `cargo clippy --all-targets` zero warnings, `cargo test --workspace` green + at **1232 passed, 0 failed** (1222 before this round) — ten new tests (seven in `instantiate.rs`, one + in `completion.rs`, two in `signature.rs`), plus one existing test renamed + and re-asserted in place because it was pinning the message ruling 3 + replaced. No commits. + + **Ruling 1 — escaped identifiers (QA MEDIUM #1).** Fixed at both levels and + written up in full under *Escaped identifiers* above. Engine: `terminate` + + `ends_escaped` put the required space after every splice point that ends + inside an escaped identifier — audited all five in `render_with` and found + two that needed it (`.{name}(` and the value inside the parens) and three + that already had a space following them (the module name, whose two + continuations both start with one, and the instance name). `instance_name` + now yields `\u_name` for an escaped module. `default_text`'s probe gained + the same spaces so a legal escaped default is no longer dropped. + + Server: took the lead's pre-approved out for the snippet half. Confirmed + first that it really is unfixable rather than merely awkward — the failing + render is `.\W}idth (${1:8})` … `${3:\\a}b} )`, where the port name's own `}` + closes a placeholder the layout never opened and the instance default's `$1` + reads as a nested tabstop; both are *outside* every hole, so `snippet_hole`'s + escaping cannot reach them by construction. So: `has_escaped_identifier` on + the plan, consulted once in `completion.rs::item`, and such a plan is + inserted as plain text however the client is configured. + + The promise in *Handshakes* is true again, and now says what it is verified + against. Added on top of what was asked: a test that stripping a snippet's + tabstops gives back the plain rendering byte for byte, which is the "one + seam, two spellings" claim turned into an assertion rather than an argument. + + **Ruling 2 — the dead `.*` branch (QA MEDIUM #2).** QA's diagnosis was + exactly right: `*` lexes as a `Symbol`, and the `Symbol` arm `continue`d past + the `is_sym("*")` test that could therefore never fire, so `.*` fell through + to the ordered-connection count and highlighted port 0. The wildcard is now + recognised inside the `Symbol` arm, *before* the depth bookkeeping, and sets + `any_name` with no name — so `.*` highlights nothing, does not advance the + ordered index, and a later `.ready(` after a `.*` still resolves by name. + Dead condition deleted. Two regression tests from QA's repro (cursor at the + `.*`, and a comma after it), plus the named-after-wildcard case. + + **Ruling 3 — the refusal message (QA LOW).** `instantiation_plan` now keeps + the parse diagnostics and splits the message: a file with diagnostics gets + "its file does not parse (`` at line N)", a clean parse that simply + has no such module keeps "no longer declares it". Two tests — the garbage + input the old test used (assertion updated, since it was pinning the wrong + message) and QA's interface-typed-port case. The `vlog_parser` interface-port + gap is now disclosed in *Handshakes* alongside the `parameter type` one, as + QA suggested. + + **Files touched this round:** `crates/vlog_refactor/src/instantiate.rs`, + `crates/vfmt_server/src/completion.rs`, + `crates/vfmt_server/src/signature.rs`, this README. Nothing else; no + behaviour outside M4 was reached. + +## QA log + +**2026-08-24 — QA agent.** + +### Gates + +- `cargo fmt --all -- --check` — clean. +- `cargo clippy --all-targets` — clean, zero warnings, workspace-wide. +- `cargo test --workspace` — green, **1222** tests (matches the Work log's + number exactly; summed the per-crate `test result` lines myself rather than + trusting the printed total). `cargo test --release -p vlog_refactor --test + corpus every_module_in_the_corpus_yields_a_skeleton_that_parses -- --nocapture` + re-run in isolation: `corpus skeletons: 454 planned, 81 refused, in 0.24s` — + the 454 figure matches the README exactly. + +All three gates: **pass, claims confirmed.** + +### Design review (`instantiate.rs`, `completion.rs`, `signature.rs`) + +Read against the spec and CLAUDE.md. `render`/`render_with` being the one +seam both spellings go through is exactly the right shape — verified by +reading, not just trusting the README, that `render` really does call +`render_with` with the identity hole (`instantiate.rs:194-196`) and that +`completion.rs::item` is the only other caller (`completion.rs:119-122`). +`module_definition`/`find_module`/`visible_in` reuse from `ports.rs` is a +clean `pub(crate)` widening with no behavior change, confirmed against +`git diff` — a two-line diff, exactly as claimed. No `unwrap`/`expect`/ +`panic!`/`unsafe` found in any non-test path of the three new files. + +### Attacks — skeleton correctness (`instantiate.rs`) + +Probed via 12 temporary tests added to `instantiate.rs`'s and +`completion.rs`'s own test modules (`cargo test qa_probe -- --nocapture`), +run and then fully reverted — nothing left in the tree (confirmed with +`grep -rn qa_probe` after cleanup, zero hits, and a final clean `cargo fmt` ++ `clippy` + `test --workspace` re-run). + +**Passed:** +- Zero ports (`module bare;`) and zero params both render correctly: no + dangling `#()` ever (guarded by `if !self.params.is_empty()`, + `instantiate.rs:216`), and an empty port list renders `);` directly + (`instantiate.rs:231-234`) — matches the existing + `a_module_with_no_ports_and_no_parameters_still_plans` test. +- ANSI port with an unpacked dimension (`input logic a [3:0]`) — the + dimension is (correctly) display-only and never appears in the + connection: skeleton renders `.a(a)`, which parses clean. Not a + finding — a connection never needs to repeat the declared width. +- `parameter type T = logic [7:0]`, a default referencing another + parameter (`parameter D = W*2`), a default containing nested parens + (`parameter AW = $clog2(W)`), and a default containing a `)` inside a + string literal (`parameter string S = ")"`) — all four are kept + (not dropped) and round-trip through `default_text`'s parse-back probe + correctly, exactly as `instantiate.rs:294-306`'s doc comment describes: + syntax-only checking, no width/reference resolution attempted or needed. +- Auto-connect to a `genvar` and to a `parameter` (not just a net) — both + bind, matching the Assumptions section's documented widened definition + of "visible" (`Net`/`Var`/`Port`/`Param`/`Genvar`/`TfArg`) inherited + unchanged from M3's `visible_in`. Not a finding; working as documented. +- Auto-connect to a signal declared **after** the instantiation site + (`// here` before `logic clk;` in the same module) — binds. This is + correct Verilog scoping (module-scope declarations are visible + throughout the module regardless of textual order) and is `visible_in`'s + existing, already-QA'd-at-M3 behavior, reused unchanged; not a new + finding. +- A signal declared in an enclosing `generate`/`endgenerate` block before + the site — binds, as expected. + +**MEDIUM — an escaped-identifier port name produces a skeleton `vfmt`'s own +parser rejects, falsifying the feature's own stated invariant** + +`docs/features/refactor-instantiate/README.md`'s Handshakes section +promises: *"`instantiation_plan` never panics and never returns a plan +whose plain rendering fails to parse (corpus-verified)."* That promise is +false for a module declaring an escaped identifier port — legal +SystemVerilog, just absent from the corpus, which is why the corpus +property test (`crates/vlog_refactor/tests/corpus.rs`) didn't catch it. + +```systemverilog +module m (input logic \my-port , input logic clk); +endmodule +``` + +`instantiation_plan("m", ..., None).render(&Layout::default())` produces: + +``` +m u_m ( + .\my-port(\my-port), + .clk(clk) +); +``` + +which fails to re-parse: `expected \`)\` (found ".")`, at the `.` of +`.clk` on the next line. Root cause: a SystemVerilog escaped identifier +runs until the next whitespace character, and `render_with` +(`crates/vlog_refactor/src/instantiate.rs:207-250`) writes +`.{name}({expr})` with no whitespace anywhere around an escaped `name` — +so `.\my-port(\my-port),` lexes as **one single token** (the backslash, +every character up to the newline including `(`, `)`, and `,`), and the +following line's leading `.` is what the parser chokes on. This is not +specific to snippet encoding — `completion.rs`'s `snippet_hole` correctly +escapes the backslash in the *default text* (`\` → `\\`, confirmed by the +existing `a_tabstop_default_is_escaped...` test), but that's irrelevant +here: the corruption is in the shared plain-text layout both spellings go +through, so plain and snippet skeletons are equally broken. + +Confirmed via a temporary test in `instantiate.rs`'s test module (run, +then reverted): `parse_source_tolerant` on the rendered skeleton reports +exactly `expected \`)\` (found ".")`. + +Not a hard-invariant-1 violation (no existing file is touched or +corrupted — this is offered text the user must accept via Tab, and the +failure is loud, not silent: red squiggles the moment it lands). But it +does concretely falsify a promise the feature's own README makes, for a +legal port-naming style the corpus simply doesn't exercise. Not fixed — +this needs a design call (write a trailing space after any hole whose +following text is an escaped identifier, or after *every* hole +unconditionally, or detect and special-case `\`-prefixed names) rather +than a one-line patch; flagging for dev/lead. + +**LOW/informational, not filed as a MEDIUM finding — interface-typed ports +are invisible to module hinting, with a slightly misleading refusal** + +```systemverilog +module m (iface_bus.mst bus, input logic clk); +endmodule +``` + +`vlog_parser` itself cannot parse this port list +(`expected \`)\` (found ".")`, confirmed directly against +`parse_source_tolerant`), so no `Module` item is produced for `m` at all, +and `instantiation_plan("m", ...)` refuses with *"the file that declared +\`m\` no longer declares it, so vfmt cannot write an instantiation of +it."* — a message that reads as "someone edited the file out from under +the index" when the real cause is "the parser never supported this +syntax." This is the identical class of gap the dev already found and +disclosed in Handshakes for `parameter type ... = struct packed { ... }` +(filed against `vlog_parser`, not fixed here) — just a different trigger +(an interface-typed ANSI port, distinct from *instantiating* an +interface, which the Assumptions section does correctly cover and which +works). Interface ports are common in contemporary SV, so this quietly +disables completion for a real, non-exotic pattern; worth the same +Handshake-style disclosure the `parameter type` case already got, and +worth a refusal message that distinguishes "does not parse" from "no +longer declares it" if the dev revisits this area. Not filing as a +blocking finding: it's a pre-existing `vlog_parser` limitation, not +something `instantiate.rs` introduced, and the refusal is honest in +substance (no skeleton is offered) even if imprecise in wording. + +### Attacks — signature help (`signature.rs`) + +**MEDIUM — dead code means `.*` inside a connection list is never +recognized, so it falls through into a wrong active-parameter count** + +`active_entry` (`crates/vfmt_server/src/signature.rs:219-257`) has this +branch, evidently meant to treat `.*` as a name (so that, like an unknown +`.name`, it highlights nothing rather than being mistaken for an ordered +connection): + +```rust +if dot && depth == 0 && (is_name(token) || token.is_sym("*")) { +``` + +But this line is **unreachable for `*`**. `*` always lexes as +`TokenKind::Symbol` (`crates/vlog_parser/src/token.rs`, `is_sym` requires +`kind == TokenKind::Symbol`), and the loop's `if token.kind == +TokenKind::Symbol { ... continue; }` branch (lines 229-244) unconditionally +handles and `continue`s past every symbol token — including `*` — before +this line is ever reached; `*` falls into that block's `_ => {}` arm, then +hits the shared `dot = false; continue;`, silently discarding the pending +`dot` flag from the preceding `.` without ever checking `is_sym("*")`. + +Consequence, reproduced with a temporary test (run, then reverted): +`sub u_sub (.*` with the cursor right after `.*` returns +`active_parameter = Some(0)` — the first port (`clk`) is highlighted, as +if `.*` were an ordinary empty ordered connection at position 0, which is +not what a wildcard connection is. (When a real named connection follows +the `.*` before the cursor, e.g. `.*, .data(`, the later `.data` correctly +overwrites `named`/`any_name`, so the bug is only visible with the cursor +at or immediately after the `.*` itself — which is exactly when a user +would be looking at signature help to decide what to type next.) + +Read-only and cosmetic — nothing is written to a buffer, this only +mis-highlights a tooltip parameter — so I'm rating it MEDIUM rather than +HIGH, but it's a genuine, reproducible bug with dead code sitting right +next to the fix, not a design question. Not fixed here: the right repair +(delete the two-line dead branch and instead special-case `*` inside the +existing Symbol match, e.g. treat `.` immediately followed by `*` as +"named, with no matching entry") is a small, mechanical change but +touches control flow I'd rather the dev sign off on given how easy it is +to get the depth bookkeeping subtly wrong a second time. + +### Attacks — completion gating (`completion.rs`) + +All via temporary probes, reverted: + +- Cursor inside a `//` line comment, inside a `/* ... */` block comment, + and inside a string literal (`$display("su`) — all three correctly + offer **zero** items. `typed_word`/`at_module_item` operate over the + token stream, and a comment or string is not an identifier token, so + there's nothing for `typed_word` to find a word in; not a finding. +- Case sensitivity: typing `SU` against a declared `sub` still offers the + item (module_names' documented case-insensitive substring match, same + contract the existing `a_module_with_no_ports...`/`the_candidate_list...` + tests already pin at the engine level). Confirmed the behavior survives + the full completion pipeline, not just `module_names` in isolation. Not + a finding — matches the documented contract exactly. +- 64-item cap + `isIncomplete`: built a 70-module workspace, asked for the + `mod_` prefix (matches all 70) — got back exactly 64 items with + `is_incomplete: true`, matching `LIMIT` and the README's claim exactly. +- `sub #(8) u (a, b` (param list already closed, cursor in the port list) + — traced `signature.rs::list_at` by hand against the actual token + sequence: the innermost unclosed `(` is the *ports* one, and `list_at` + correctly walks back through the closed `#(...)` via `matching_open` to + confirm the module name, returning `Kind::Ports`. The existing + `a_connection_list_after_a_parameter_override_is_still_found` test + covers this exact shape without the literal `#(8)` numeral; traced by + hand to be certain the numeral (vs. a named override) doesn't change + the token-position arithmetic — it doesn't. +- `.data(` with the cursor inside a **nested, unclosed** call + (`.data(f(x,` with the cursor right after the inner comma) — traced by + hand through `active_entry`'s depth counter: entering `f(` takes depth + to 1 (or 2, depending on how deep), so the inner `,` hits the `_ => {}` + arm (only depth-0 commas increment `commas`) and is correctly ignored; + `named` stays pinned to `data` from before the nested call opened. Does + not advance the port index, as required. The existing + `a_call_inside_a_connected_expression_is_not_mistaken_for_a_list` test + covers the *closed*-call case; I additionally hand-traced the *unclosed* + (mid-typing) case since that's the state a real keystroke produces and + it isn't quite what that test exercises — same result, no discrepancy. + +### Real server binary over stdio + +Ran the dev's own `completion_and_signature_help_round_trip_over_the_wire` +and `a_client_without_snippet_support_gets_the_skeleton_as_plain_text` +(`crates/vfmt_server/tests/e2e.rs`) as part of the full-suite gate run — +both pass, part of the workspace's 1222. They already exercise exactly +what the brief asked for: one real `initialize` → `completion` round trip +over stdio asserting the JSON-decoded snippet text is byte-for-byte the +expected `${n:...}` syntax, one `signatureHelp` round trip with UTF-16 +label-offset arithmetic checked against the decoded label string, and the +advertised `completionProvider`/`signatureHelpProvider` capability shapes. +Re-ran both in isolation (`cargo test -p vfmt_server --test e2e +completion_and_signature_help_round_trip -- --nocapture` and the plain-text +one) to confirm independently rather than trust the aggregate count — both +pass standalone. + +### The seven work-log decisions/deviations + +No disagreements to file. Specifically: + +1. Two narrow entry points (`module_definition`, `instantiation_plan`) + instead of M2/M3's whole-`Scope` construction — right call for a + per-keystroke request; verified the completion path really does only + one file-text lookup plus one parse per candidate (`completion.rs:96-100`), + no workspace rebuild. +2. `render`/`render_with` as one seam — verified by reading, see Design + review above; divergence between the two spellings is impossible by + construction, confirmed. +3. No `// auto-connected` comments — reasonable; the stated reasons + (permanent, majority-case noise, a line vfmt hasn't crossed elsewhere) + are sound, and the alternative (documentation panel) genuinely carries + the same information. Agree. +4. Measuring `parse_source_tolerant` before choosing eager-vs-`resolve` — + sound methodology; the LIMIT=64 + `isIncomplete` result is verified + above. +5. `default_text`'s parse-back probe, added because the corpus test found + the `parameter type ... struct packed` case — verified it also + correctly *keeps* everything it should (cross-param references, + `$clog2(...)` nesting, string literals containing `)`), not just that + it drops what it must. +6. Port type text collapsed to one line, display-only — confirmed nothing + writes `PlanPort::ty` into a buffer (only `label()`, used by + `documentation()` and `signature.rs`'s labels); safe as described. +7. `` `ifdef `` policy — list every arm + warn, the deliberate opposite of + M3's refuse-and-name-the-arm — agree with the stated reasoning + (nothing is written to an existing file until the user accepts the + Tab-completed text, unlike M3's port refactorings which rewrite code + that already exists), and confirmed both the port-list and + parameter-list warning paths fire via the existing + `a_conditional_port_list_lists_every_arm_and_says_so` / + `a_conditional_parameter_list_warns_too` tests. + +### Verdict + +**Ship-after-fixes.** Both MEDIUM findings are real, reproducible, and +narrow — neither touches an existing file (hard invariant 1 is not at +risk; this milestone edits nothing) and neither is a design-level +rethink, but both are concrete bugs a lead should see fixed before this +ships: the escaped-identifier skeleton corruption (falsifies the +feature's own stated "always parses" promise) and the `.*` dead-code +mis-highlight in signature help. The LOW/informational interface-port gap +is the same shape as an already-disclosed, already-accepted `vlog_parser` +limitation and does not block shipping on its own. + +### Files touched during QA (all reverted; nothing left in the tree) + +`crates/vlog_refactor/src/instantiate.rs`, `crates/vfmt_server/src/completion.rs`, +`crates/vfmt_server/src/signature.rs` — 12 temporary `qa_probe_*`/probe +tests added, run with `--nocapture`, then removed. Verified clean with +`grep -rn qa_probe` (zero hits) and a final `cargo fmt --all -- --check` + +`cargo clippy --all-targets` + `cargo test --workspace` (1222 passed) +re-run after cleanup. + +--- + +## Round 2 — 2026-08-24 (QA agent) + +Dev reworked per lead rulings on both round-1 MEDIUM findings plus the LOW +refusal-message note. Re-verified at mechanism level (hand-traced the new +control flow, then confirmed every trace with a temporary probe — 11 probes +across the three files this round, run then fully reverted). + +### Gates + +- `cargo fmt --all -- --check` — clean. +- `cargo clippy --all-targets` — clean, zero warnings, workspace-wide. +- `cargo test --workspace` — green, **1232** tests, 0 failures (summed the + per-crate `test result` lines myself; matches the claim exactly, +10 over + round 1's 1222 — the dev's "8 new tests" plus this round's own count came + out at +10, not +8; not chasing the discrepancy further since the gate + itself is what matters and it's green either way). +- `cargo test --release -p vlog_refactor --test corpus + every_module_in_the_corpus_yields_a_skeleton_that_parses -- --nocapture` + re-run standalone: `corpus skeletons: 454 planned, 81 refused, in 0.24s`, + 0 unparseable (the assertion would have failed otherwise) — matches the + claim exactly. + +All three gates: **pass, claims confirmed.** + +### MEDIUM #1 (escaped identifiers) — mechanism review + +Read `terminate`/`ends_escaped` (`crates/vlog_refactor/src/instantiate.rs:297-320`) +and audited all five splice points in `render_with` by hand against the +dev's claim of "all five": + +1. `.{param.name}(` — `terminate`d (line 257). +2. `{hole(n,¶m.default)})` — `terminate`d (line 259). +3. instance name before ` (` — **not** run through `terminate`; instead the + literal `" ("` that always follows it supplies the space unconditionally + (comment at line 268 says so explicitly). Confirmed this is sufficient: + an escaped instance name can never need `terminate`'s help because + nothing ever writes non-whitespace directly after it. +4. `.{port.name}(` — `terminate`d (line 285). +5. `{expr})` (the port's connection, whether auto-connected or a hole) — + `terminate`d (line 287). + +All five accounted for, matches the claim. `instance_name()` builds `\u_bare` +from `\bare` (`format!("\\u_{bare}")`, line 205) rather than gluing `u_` +onto the escaped name — confirmed correct by trace and by probe (below): +`u_` glued directly onto `\weird-mod` would produce `u_\weird-mod`, which +is not a legal identifier at all (an escaped identifier's `\` must be the +very first character); `\u_weird-mod` is. + +**Probed (temporary, reverted):** +- An escaped **default** (`parameter Q = \esc-2`) as the **last** parameter + in the list, immediately before the closing `)` of `#( ... )` — a splice + point the dev's own new test doesn't isolate (their test uses a + single-parameter module). Skeleton: `.Q(\esc-2 )` — parses. +- A port name terminated by a **TAB** in the source rather than a space + (`\my-port,`). The lexer's stored `name` field doesn't carry the + terminator character at all (confirmed: `p.ports[0].name == "\\my-port"` + regardless of whether the source used a space or a tab), so `terminate`'s + hardcoded ASCII space is correct regardless of what the source used — + this was never actually a live risk, but worth confirming rather than + assuming. +- An escaped **module** name with otherwise ordinary (non-escaped) ports — + isolates the module-name-only case from the dev's own + `escaped_names_everywhere...` test, which escapes module *and* param + *and* port together and so can't tell which one is doing the work. + `has_escaped_identifier()` correctly returns `true` from the module-name + check alone; `instance_name()` correctly returns `\u_weird-mod`; the + skeleton `\weird-mod \u_weird-mod (\n .a(a)\n);` parses. +- `crates/vfmt_server/src/completion.rs:126`'s gate + (`snippets && !plan.has_escaped_identifier()`) — confirmed it forces + plain text for the module-name-only case too, not just the + port/param-escaped cases the dev's test already covers. + +**New, LOW finding — the "one seam" byte-for-byte promise does not hold for +a default containing `$` or `}` (metacharacters `snippet_hole` itself must +escape), though nothing corrupts** + +The round-2 attack list specifically asked about metachar escaping at the +tail of a default in a *non-escaped* plan, which turned up a real +mechanism gap, distinct from MEDIUM #1: `terminate` (`instantiate.rs:304`) +is called with `hole(n, &default)` — the **already snippet-encoded** +string — not the raw default. When `default_text` yields something like +`$clog2(8)` (no backslash, so `has_escaped_identifier()` is correctly +`false` and the plan stays snippet-encodable), `snippet_hole` +(`completion.rs:156-168`) escapes the `$` to `\$`, producing +`${1:\$clog2(8)}`. That string now *contains* a backslash — introduced by +snippet-escaping, nothing to do with SystemVerilog escaped identifiers — +and `ends_escaped` can't tell the difference, so `terminate` adds its +"harmless extra space": `.AW(${1:\$clog2(8)} )`. Confirmed end-to-end +through the real `completion::item` pipeline with a temporary probe. + +Consequence, also confirmed with a probe that reimplements `snippet_hole` +locally and calls `render_with` directly: `expand(snippet) != plain` for +this case — `${1:\$clog2(8)} )` strips to `$clog2(8) )` (extra space) +while `plain` renders `$clog2(8))` (no space). The dev's own new regression +test, `a_snippet_expands_to_exactly_the_plain_rendering`, only exercises +`SUB`, `bare`, and `p #(parameter W = 1)` — none of which has a `$`/`}` in +any default — so it cannot see this divergence, and the Handshakes-style +claim "byte-for-byte" is true only for defaults that don't need +`snippet_hole`'s own escaping, not universally as stated. + +Not a corruption and not re-filing MEDIUM #1: both spellings still parse +(an extra space inside parens is legal Verilog), and the code's own +comment on `ends_escaped` already anticipates and accepts exactly this +shape of false positive ("a false positive writes one harmless extra +space") — this probe is the empirical confirmation that the anticipated +harm really is limited to one space, not something worse. Filing as LOW: +worth either tightening the "byte-for-byte" claim's wording (it's +"byte-for-byte modulo one possible harmless space when the default needs +snippet-escaping", not unconditionally byte-for-byte) or, if the dev wants +it exact, having `terminate` receive the *raw* default alongside the +already-encoded one so `ends_escaped` can check the source text instead of +the wire text. Not blocking. + +**Minor observation, not filed as a finding** — a refusal message can cite +a real but unrelated parse diagnostic. Probed: a file where the requested +module is never declared at all (plain typo) but a *different*, unrelated +module later in the same file has a genuine syntax error. The message +reads "...its file does not parse (expected expression (found \";\") at +line 3)..." — technically true (the file does have that error) but not +the actual reason the requested module wasn't found. This is `diagnostics +.first()`'s known limitation (`instantiate.rs:156`, picks the first +diagnostic in the file, not one scoped to the request). Judged not worth +filing: it's strictly more informative than round 1's blanket "no longer +declares it" for every such case, still names a real, actionable problem +in the file, and this exact scenario (index believes a module exists, +direct `instantiation_plan` call with a name the index never vouched for) +doesn't occur on the server's real completion path, where `module +_definition` already filters to names the index found. + +### MEDIUM #2 (`.*` dead code) — mechanism review + +Read the fix (`crates/vfmt_server/src/signature.rs:225-271`). The wildcard +check now lives inside the `if token.kind == TokenKind::Symbol` arm, +*before* the `match` that does depth bookkeeping: + +```rust +if dot && depth == 0 && token.text == "*" { + named = None; + any_name = true; + dot = false; + continue; +} +``` + +This is reachable — `*` really does lex as `TokenKind::Symbol` +(`crates/vlog_parser/src/token.rs`), so this branch is the first thing +that sees it, unlike round 1's dead `is_name(token) || token.is_sym("*")` +check which sat in the *non*-Symbol branch and could never see a Symbol +token at all. Traced by hand: `named = None` (not `Some("*")`) means the +function's final `let name = named?;` short-circuits to `None` the moment +`any_name` is true from a wildcard — correct, "highlights nothing" rather +than trying and failing a name lookup. The `depth == 0` guard confirmed by +trace to correctly exclude a `*` inside a nested expression (e.g. +`.data(a*b)`, multiplication) — depth is 1 there, so the wildcard branch +never fires and `*` falls through to the ordinary `_ => {}` arm, which is +what it should do. + +**Probed (temporary, reverted), covering the round-2 attack list exactly:** +- `u_sub (.*` (wildcard, cursor immediately after, first position, nothing + else typed) — `active_parameter: None`. Same as the dev's own test but + independently re-derived. +- `u_sub (.*, )` — cursor right before the closing paren, after the + wildcard's trailing comma — `None`. (The dev's own test stops at the + comma; this pushes one token further, to the position the round-2 brief + named specifically.) +- `u_sub (.*, a, b, ` — illegal-but-typeable mix of a wildcard with bare + positional entries. **No panic.** `active_parameter: None` — `any_name` + stays sticky `true` from the wildcard, so the later positional commas + never get a chance to answer via the ordered-count branch; a reasonable, + safe answer for input that shouldn't compile anyway. +- `u_sub (a, .*, b, ` — positional, then wildcard, then more positional. + **No panic.** `None`, same reasoning. +- `u_sub (` with **no** wildcard at all, cursor right at the open paren — + `active_parameter: Some(0)`, unchanged from round 1. Confirms the new + Symbol-arm check (which runs on *every* Symbol token, not just `*`) adds + no overhead or side effect to the ordinary, wildcard-free path — the + `token.text == "*"` comparison simply never matches and execution falls + through to the original `match` unchanged. + +No lost behavior found from deleting the dead branch: the only thing it +ever did (for real) was the `is_name(token)` check on a non-Symbol +token, which is identical to — and still performed by — the unchanged +code below the Symbol arm (`if dot && depth == 0 && is_name(token) { ... }`, +line 260). Nothing besides the never-reachable `|| token.is_sym("*")` +disjunct was removed. + +### LOW (refusal-message split) — mechanism review + +`instantiate.rs:150-165`: `diagnostics.first()` decides between the two +messages. Confirmed via the existing three tests +(`a_definition_that_no_longer_declares_the_module_is_refused`, +`a_definition_that_does_not_parse_says_so_rather_than_blaming_an_edit`, +`an_interface_typed_port_list_is_refused_as_a_parse_failure`) plus my own +unrelated-diagnostic probe above. The interface-port case in particular now +says "does not parse (expected \`)\` (found \".\") at line 1)" instead of +blaming an edit that never happened — does what round 1 asked for. + +### Verdict + +**Ship.** Both round-1 MEDIUM findings are fixed and hold up under +mechanism-level review plus 11 targeted probes (including every case the +round-2 attack list named — first-position wildcard, wildcard-then-comma, +illegal wildcard/ordered mixes with an explicit no-panic check, an +escaped-module-name-only plan, an escaped default at the last splice point +before a list closes, and a whitespace-variant terminator). The LOW +refusal-message fix does what was asked. One new LOW-severity, non-blocking +observation surfaced by this round's own attack list (the "byte-for-byte" +snippet/plain equivalence claim has an unstated exception for defaults +needing `$`/`}` snippet-escaping, resulting in one harmless extra space in +the snippet spelling only) — worth a follow-up note or a wording fix in the +Handshakes claim, not a rework. + +### Files touched during round-2 QA (all reverted; nothing left in the tree) + +Same three files as round 1 — 11 temporary probe tests added (`qa2_probe_*` +in `instantiate.rs`, `completion.rs`, `signature.rs`), run with +`--nocapture`, then removed. Verified clean with `grep -rn qa2_probe` (zero +hits) and a final `cargo fmt --all -- --check` + `cargo clippy +--all-targets` + `cargo test --workspace` (1232 passed) re-run after +cleanup. + +## Review + +**2026-08-24 — lead.** Reviewed after QA round 2's ship verdict; gates run +independently (1232 tests, 0 failures, clippy silent). The single-renderer / +two-spellings design held up under QA's stripping test, and the corpus +property test (454 modules' skeletons re-parse) earned its keep by catching +the multi-line-default bug during development. All seven dev deviations are +accepted as argued — in particular no editorial comments in inserted text, +the plain-text fallback for escaped-identifier plans (snippet metachars +outside the holes are genuinely unreachable by hole escaping), and the +ifdef list-and-warn policy, which is correctly the opposite of M3's refusal +because a skeleton is edited before it compiles. QA's round-2 LOW (one +extra space in the snippet spelling when a default carries `$`/`}` — +both spellings still parse) is accepted as a cosmetic known limitation; +fix it if `terminate` is ever touched again. Accepted; M4 checked off in +the umbrella plan and TODO.md §8. diff --git a/docs/features/refactor/README.md b/docs/features/refactor/README.md index 7cedfd5..42bc3d3 100644 --- a/docs/features/refactor/README.md +++ b/docs/features/refactor/README.md @@ -86,12 +86,12 @@ the work is reviewed**. Owner-priority items first (2026-08-24). - [ ] Task/function argument add/remove/reorder — backlog ### Module hinting (instantiation assist) -- [ ] **Instantiate-from-definition**: completion on a module name at item +- [x] **Instantiate-from-definition**: completion on a module name at item position expands a full skeleton — parameter overrides with their declared defaults, every port as `.port(port)` with snippet tabstops → `docs/features/refactor-instantiate/README.md` (M4) -- [ ] **Auto-connect**: a port whose name matches a signal in the enclosing +- [x] **Auto-connect**: a port whose name matches a signal in the enclosing scope is connected to it; the rest get placeholder tabstops → M4 -- [ ] **Signature help inside a connection list** — remaining ports, their +- [x] **Signature help inside a connection list** — remaining ports, their directions and types, from the definition → M4 - [ ] Declare-missing-signals companion action (generate `logic` decls for unconnected skeleton ports) — backlog @@ -179,11 +179,19 @@ commit — in order: - [x] M1 filelist — done, QA clean, reviewed - [x] M2 refactor-rename — done, QA clean after one rework round, reviewed - [x] M3 refactor-ports — done, QA clean after one rework round, reviewed -- [ ] M4 refactor-instantiate +- [x] M4 refactor-instantiate — done, QA clean after one rework round, reviewed - [ ] Backlog triage after M4 ## Work log +- **2026-08-24 (lead, end of day)**: M1–M4 all landed the same day, each + through the full dev → QA → rework → re-QA → lead-review loop (commits + 315bbf2, 33f5819, e338524, 5785fd9). Every milestone needed exactly one + QA-driven rework round; the recurring theme was silent-wrongness at the + preprocessor boundary (`ifdef arms, macro arguments), now handled + uniformly: refuse when placement is uncertain, warn when only visibility + is. Workspace suite grew 1007 → 1232 tests. Backlog triage is the next + session's first task. - **2026-08-24 (lead)**: Umbrella plan created from the rope overview docs and the current state of `vlog_semantic`/`vfmt_server`/`WorkspaceIndex`. Key decisions: server-first (no CLI surface yet), semantic-resolution-only diff --git a/docs/features/vfmt-server/README.md b/docs/features/vfmt-server/README.md index 129e37a..e7f3d12 100644 --- a/docs/features/vfmt-server/README.md +++ b/docs/features/vfmt-server/README.md @@ -26,6 +26,8 @@ looks like language knowledge in here is a bug or a `Handshake` request. | `textDocument/documentSymbol` | `Semantics::document_symbols` | Hierarchical | | `textDocument/prepareRename` | `vlog_refactor::prepare_rename` | Declines with the engine's own sentence (`RequestFailed`), so the box never opens on a rename that would fail | | `textDocument/rename` | `vlog_refactor::rename` | Cross-file `WorkspaceEdit` (`changes`); warnings go out on `window/logMessage`; refusals are `RequestFailed`. See `docs/features/refactor-rename/README.md` | +| `textDocument/completion` | `vlog_refactor::instantiation_plan` | Module hinting: one item per indexed module, inserting the whole instantiation skeleton as a snippet (plain text for a client that did not advertise `snippetSupport`). Capped at 64 items, `isIncomplete` when truncated; declines every position that is not module-item. See `docs/features/refactor-instantiate/README.md` | +| `textDocument/signatureHelp` | `vlog_refactor::instantiation_plan` | The instantiated module's ports (or, inside `#( ... )`, its parameters) with the active one highlighted — by name for a named list, by position for an ordered one. Triggers: `(` and `,`. Same feature README | | `workspace/symbol` | `WorkspaceIndex::workspace_symbols` | Capped at 256 hits | Deferred, deliberately, and named in Status/TODO below: ~~range formatting @@ -39,7 +41,11 @@ their Safe fixes — see `docs/features/server-lint/README.md`**, ~~rename~~ **delivered by refactor-rename (M2 of the refactoring plan): `textDocument/prepareRename` + `textDocument/rename`, edits computed in the new `vlog_refactor` crate — see `docs/features/refactor-rename/README.md`**, -completion / signature help, and cross-file references. +~~completion / signature help~~ **delivered by refactor-instantiate (M4 of the +refactoring plan): `completionProvider` expands a module name at item position +into a full instantiation skeleton and `signatureHelpProvider` names the ports +inside a connection list — see +`docs/features/refactor-instantiate/README.md`**, and cross-file references. (`vfmt.toml` discovery and `.gitignore`-aware indexing, deferred when this was written, were delivered by vfmt-core-lift the same day — lead note.) @@ -389,8 +395,11 @@ it was written rather than starting mid-line. the *same* notification, since LSP replaces rather than merges — plus `textDocument/codeAction` for the Safe fixes. `docs/features/server-lint/README.md`. -- [ ] **Not done:** completion, rename, signature help (TODO.md §6's "then" - list). +- [x] ~~**Not done:** completion, rename, signature help (TODO.md §6's "then" + list).~~ Rename delivered by **refactor-rename** (M2); completion and + signature help delivered by **refactor-instantiate** (M4), both served + from `vlog_refactor::instantiation_plan` so Vim gets the same answers. + `docs/features/refactor-instantiate/README.md`. - [ ] **Not done:** cross-file references. `references_of` is per-file, and answering across the workspace means resolving every other file's references *into* this one — an inverted index the workspace layer does @@ -534,7 +543,9 @@ All PASS: `positionEncoding: "utf-16"`, `textDocumentSync: 1` i.e. Full). Deferred capabilities (`documentRangeFormattingProvider`, `completionProvider`, `renameProvider`, `signatureHelpProvider`) absent from the JSON, not just - falsy. + falsy. *(All four have since shipped — range-formatting, refactor-rename and + refactor-instantiate — and `tests/e2e.rs` now asserts their presence + instead; this entry records the state at the time of that QA pass.)* - `definition` on `B u_b` → `B.sv` at the correct declaration span. - `hover` on `` `WIDTH`` → macro body `` `define WIDTH 8``; `hover` on `K` (reached via `import P::K`) → `**parameter** — declared in pkg.sv:2`.