From d8e37086df5a5555a9c4acac59dbff7dca0296c1 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Mon, 24 Aug 2026 15:07:57 -0700 Subject: [PATCH] Refactoring M5: keyword + project-wide identifier completion; v0.3.0 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Five completion tiers in one response: module skeletons (M4, unchanged gate), scope-visible symbols with real kinds, workspace-index names and `define macros (backtick-aware, never inventing punctuation), Verilog/SV keywords (single-source KEYWORDS list factored from the lexer's table, lexing unchanged), and token-harvested project words — comments and strings contribute nothing and get no completions. Candidate tables build with the index over the M1 scope ladder (94 ms / 860 files, ~1.4 MiB); a keystroke answers in ~300 µs, budget-tested. Version 0.3.0 across the workspace and extension, CHANGELOG covers the M1-M5 refactoring layer. Co-Authored-By: Claude Fable 5 --- CHANGELOG.md | 89 +++ Cargo.lock | 16 +- Cargo.toml | 2 +- README.md | 2 +- TODO.md | 5 +- crates/vfmt_server/src/candidates.rs | 327 +++++++++ crates/vfmt_server/src/completion.rs | 898 +++++++++++++++++++++--- crates/vfmt_server/src/main.rs | 1 + crates/vfmt_server/src/state.rs | 18 +- crates/vfmt_server/tests/e2e.rs | 103 ++- crates/vlog_parser/src/lib.rs | 1 + crates/vlog_parser/src/token.rs | 429 +++++------ docs/features/completion-core/README.md | 658 +++++++++++++++++ docs/features/refactor/README.md | 20 +- editors/vscode/README.md | 4 +- editors/vscode/package-lock.json | 4 +- editors/vscode/package.json | 2 +- tools/RELEASING.md | 22 +- 18 files changed, 2281 insertions(+), 320 deletions(-) create mode 100644 crates/vfmt_server/src/candidates.rs create mode 100644 docs/features/completion-core/README.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b676b8..bcf624f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,95 @@ All notable changes to vfmt are recorded here. Versions follow [semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes (see `README.md`) are the only frozen contract. +## 0.3.0 — 2026-08-24 + +The refactoring release. `0.2.0` shipped a formatter, a linter and a language +server that could *read* a project; this one can change it — rename across +files, add and remove module ports everywhere they are connected, generate an +instantiation from the module's own declaration — and can finally complete what +you are typing. + +### Project scope: filelists + +vfmt now accepts a standard EDA **filelist** (`-f` style: one path per line, +nested `-f`, `+incdir+`/`+define+`, `#` and `//` comments, `$VAR`/`${VAR}` +expansion, unknown `+args`/`-flags` skipped with a warning). When one is +configured — `vfmt.filelist` in the editor, or a `filelist` key in `vfmt.toml` +— it defines *exactly* the set of files the language server indexes, which is +what a project with a build already says out loud. Without one the scope ladder +falls back to the workspace-folder walk, and, when no folder was opened at all, +to the directory the open file sits in. A filelist that cannot be read falls +back with a warning rather than leaving the editor silently empty. Details: +[filelist](docs/features/filelist/README.md). + +### Rename + +`textDocument/rename` and `prepareRename` across every symbol the semantic +layer resolves — nets and variables, ports, parameters and localparams, +genvars, typedefs, enum members, struct fields, functions and tasks, modules, +instances, packages and class members — and **across files**, so a module rename +reaches every instantiation and a package member reaches every import site. +Every edit comes from a resolved reference span; there is no textual +search-and-replace anywhere in it. The rename refuses rather than guesses: on a +collision with an existing name in any affected scope, on an invalid +identifier, and whenever any touched file would no longer parse — whole-edit- +or-nothing, the same contract the formatter has always had. Occurrences inside +a `` `define`` body or an `` `ifdef``-excluded arm are reported as a warning and +left alone, because vfmt does not preprocess. Details: +[rename](docs/features/refactor-rename/README.md). + +### Module signature changes + +Three code actions (and the matching `workspace/executeCommand` entry points, +for editors without a lightbulb): **add a port** to a module, which updates the +declaration — ANSI or non-ANSI — and gives every instantiation a named +connection, bound to a same-named signal when one is in scope; **remove a +port**, which drops it from the declaration and from every instantiation, +turning an ordered connection into an explicit empty position and refusing when +the connected expression has side effects worth preserving; and **propagate +ports**, which diffs a module against each of its instantiations and adds the +missing named connections. Every touched file is re-parsed before the edit is +offered. Details: [ports](docs/features/refactor-ports/README.md). + +### Module hinting and signature help + +Typing a module name at item position now completes to the whole +instantiation, generated from the definition the workspace index found: +parameter overrides carrying their declared defaults, every port as a named +connection, the ports with a same-named signal in scope already bound and the +rest left as snippet tabstops to tab through. A client that does not advertise +`snippetSupport` gets the same text with every hole filled in and no `${}` +anywhere, and a plan containing an escaped identifier is always plain text — +`$`, `}` and `\` are legal inside one and are the snippet grammar's own +punctuation. Inside a connection or parameter list, `textDocument/signatureHelp` +names the ports with their directions and types and highlights the one under +the cursor. Details: +[module hinting](docs/features/refactor-instantiate/README.md). + +### Completion + +The completion list is no longer only about instantiations. One response now +carries, in this order: the module skeleton where one belongs, the declarations +the scope chain at the cursor binds (with their real kinds and the line they +were declared on), what the project declares — packages, package members, +typedefs, classes, modules and `` `define`` names — every reserved word the +lexer knows, and finally every identifier used anywhere in the project, the +word-completion tier editors have trained everyone to expect. A name appears +once, offered by the best tier that has it. Nothing is offered while the cursor +is inside a comment or a string, and a name that appears *only* inside one is +never a candidate: the word list is harvested from the token stream, where +comments are trivia and a string is a single token. Scope is the filelist +ladder's, so a file the project does not build contributes nothing. The tables +are built with the workspace index rather than per keystroke — 860 real-world +files answer a request in about 300 µs. Details: +[completion](docs/features/completion-core/README.md). + +### Editors + +One new setting, `vfmt.filelist`, forwarded like the rest of `vfmt.*`. +Everything else in this release arrives through the server, so no editor +configuration changes. + ## 0.2.0 — 2026-08-19 The first released version. `0.1.0` was the workspace's initial version number diff --git a/Cargo.lock b/Cargo.lock index 3f50860..16aa2e7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -217,7 +217,7 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" [[package]] name = "vfmt" -version = "0.2.0" +version = "0.3.0" dependencies = [ "rayon", "vfmt_core", @@ -228,11 +228,11 @@ dependencies = [ [[package]] name = "vfmt_core" -version = "0.2.0" +version = "0.3.0" [[package]] name = "vfmt_server" -version = "0.2.0" +version = "0.3.0" dependencies = [ "lsp-server", "lsp-types", @@ -248,14 +248,14 @@ dependencies = [ [[package]] name = "vlog_formatter" -version = "0.2.0" +version = "0.3.0" dependencies = [ "vlog_parser", ] [[package]] name = "vlog_linter" -version = "0.2.0" +version = "0.3.0" dependencies = [ "vlog_formatter", "vlog_parser", @@ -263,11 +263,11 @@ dependencies = [ [[package]] name = "vlog_parser" -version = "0.2.0" +version = "0.3.0" [[package]] name = "vlog_refactor" -version = "0.2.0" +version = "0.3.0" dependencies = [ "vlog_parser", "vlog_semantic", @@ -275,7 +275,7 @@ dependencies = [ [[package]] name = "vlog_semantic" -version = "0.2.0" +version = "0.3.0" dependencies = [ "vlog_parser", ] diff --git a/Cargo.toml b/Cargo.toml index d04e4b4..045070b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,7 +12,7 @@ members = [ ] [workspace.package] -version = "0.2.0" +version = "0.3.0" edition = "2021" license = "MIT" diff --git a/README.md b/README.md index 039a200..fd3ad18 100644 --- a/README.md +++ b/README.md @@ -581,7 +581,7 @@ registering the file types and starting the server: ```bash tools/release.sh # builds dist/vfmt-.vsix -code --install-extension dist/vfmt-0.2.0.vsix +code --install-extension dist/vfmt-0.3.0.vsix ``` Sideloading that `.vsix` is the supported install; the extension is not on any diff --git a/TODO.md b/TODO.md index 2fd7f5e..332c32b 100644 --- a/TODO.md +++ b/TODO.md @@ -590,5 +590,8 @@ section only tracks the milestones. the declaration and every instantiation (named/ordered/`.*`). - [x] **M4 `refactor-instantiate`** — module hinting: instantiation skeleton completion from the definition, auto-connect, signature help. +- [x] **M5 `completion-core`** — keyword + project-wide identifier + completion (token-harvested, comments/strings excluded), merged with + M4's module snippets; version 0.3.0. - [ ] Backlog (extract module, inline, `.*` expansion, ANSI conversion, - organize imports, …) — triaged in the umbrella README after M4. + organize imports, …) — triaged in the umbrella README after M5. diff --git a/crates/vfmt_server/src/candidates.rs b/crates/vfmt_server/src/candidates.rs new file mode 100644 index 0000000..5bd11b5 --- /dev/null +++ b/crates/vfmt_server/src/candidates.rs @@ -0,0 +1,327 @@ +//! The tables a completion request reads instead of walking the workspace. +//! +//! Completion fires on every keystroke, so nothing here may be computed per +//! request. Both tables are built once, beside the workspace index and from +//! the same file list, and are thrown away and rebuilt together with it — so +//! the scope ladder (`docs/features/filelist/README.md`) and the +//! open-buffer-beats-disk rule apply to them for free. +//! +//! Two tables, because a completion answer has two kinds of project-wide +//! candidate: +//! +//! * [`Candidates::units`] — what the *index* knows: packages, their members, +//! typedefs, classes and modules, each with the kind it was declared as. +//! * [`Candidates::words`] — every identifier the in-scope files' **token +//! streams** contain. Tokens, so a word that only ever appears inside a +//! comment or a string literal is not a candidate: comments are trivia the +//! lexer detaches and a string is one `String` token, and neither is ever an +//! `Ident`. +//! +//! See `docs/features/completion-core/README.md`. + +use std::cmp::Ordering; +use std::collections::HashSet; +use std::path::PathBuf; + +use vlog_parser::defines::DefineKind; +use vlog_parser::token::TokenKind; +use vlog_parser::tokenize; +use vlog_semantic::{SymbolKind, WorkspaceIndex}; + +/// One name the workspace index knows, flattened for lookup. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Candidate { + /// The declared name, as written. + pub name: String, + /// What it was declared as — the completion item's icon comes from this. + pub kind: SymbolKind, + /// Where it lives, ready to show: `pkg::NAME` for a member, the defining + /// file's name for a unit. + pub detail: String, +} + +/// One `` `define`` name the workspace declares. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Macro { + /// The macro name, without the leading backtick. + pub name: String, + /// The definition as it reads in a completion list. + pub detail: String, +} + +/// The project-wide completion tables, rebuilt with the index. +#[derive(Debug, Default)] +pub struct Candidates { + units: Vec, + macros: Vec, + words: Vec, +} + +impl Candidates { + /// Build both tables from the index and the sources it was built from. + /// + /// `sources` is the list `Workspace::collect_sources` already produced for + /// the index, so the files are read once and the only extra work is one + /// lex per file — see the measurements in the feature README. + pub fn build(index: &WorkspaceIndex, sources: &[(PathBuf, String)]) -> Candidates { + Candidates { units: units_of(index), macros: macros_of(index), words: words_of(sources) } + } + + /// Index names starting with `prefix`, case-insensitively. + pub fn units(&self, prefix: &str) -> &[Candidate] { + matching(&self.units, prefix, |c| &c.name) + } + + /// `` `define`` names starting with `prefix`, case-insensitively. + pub fn macros(&self, prefix: &str) -> &[Macro] { + matching(&self.macros, prefix, |m| &m.name) + } + + /// Project words starting with `prefix`, case-insensitively. + pub fn words(&self, prefix: &str) -> &[String] { + matching(&self.words, prefix, |w| w.as_str()) + } +} + +/// Every name the index carries, as a lookup table. +fn units_of(index: &WorkspaceIndex) -> Vec { + // The empty query means "everything"; it is paid once per index build + // rather than once per keystroke, which is the whole point of this table. + let mut out: Vec = index + .workspace_symbols("") + .into_iter() + .map(|symbol| { + let detail = match symbol.container { + Some(unit) => format!("{unit}::{}", symbol.name), + None => index + .path(symbol.def.file) + .and_then(|path| path.file_name()) + .and_then(|name| name.to_str()) + .unwrap_or("the workspace") + .to_string(), + }; + Candidate { name: symbol.name.to_string(), kind: symbol.def.kind, detail } + }) + .collect(); + sort_by_name(&mut out, |c| c.name.as_str()); + // A name two files declare is one completion item, not two. + out.dedup_by(|a, b| a.name == b.name && a.kind == b.kind); + out +} + +/// Every `` `define`` the workspace declares. `` `undef`` entries are skipped: +/// vfmt does not preprocess, so it cannot say where a name stopped being +/// defined, and offering the name is the honest answer either way. +fn macros_of(index: &WorkspaceIndex) -> Vec { + let mut out: Vec = Vec::new(); + for id in 0..index.files().len() { + let Some(table) = index.defines(vlog_semantic::FileId(id as u32)) else { continue }; + for define in table.entries().iter().filter(|d| d.kind == DefineKind::Define) { + let args = match &define.params { + Some(params) => format!("({})", params.join(", ")), + None => String::new(), + }; + out.push(Macro { + name: define.name.clone(), + detail: format!("`define {}{args}", define.name), + }); + } + } + sort_by_name(&mut out, |m| m.name.as_str()); + out.dedup_by(|a, b| a.name == b.name); + out +} + +/// Every identifier the in-scope files' token streams contain. +fn words_of(sources: &[(PathBuf, String)]) -> Vec { + // Deduplicated as it is collected, not afterwards: a workspace holds two + // orders of magnitude more identifier *tokens* than distinct identifiers + // (900k against 17k over this repo's corpus), and copying every one of + // them only to sort the copies away costs more than the lexing does. + let mut seen: HashSet = HashSet::new(); + for (_, text) in sources { + // A file that does not lex contributes nothing rather than being + // guessed at with a regex — the same all-or-nothing rule the lexer + // gives every other consumer. + let Ok(tokens) = tokenize(text) else { continue }; + for token in tokens.iter().filter(|t| is_word(t.kind, &t.text)) { + if !seen.contains(token.text.as_str()) { + seen.insert(token.text.clone()); + } + } + } + let mut out: Vec = seen.into_iter().collect(); + sort_by_name(&mut out, |w| w.as_str()); + out +} + +/// Whether a token is a word worth offering. +/// +/// `Ident` and `SystemIdent` only, so a comment (lexer trivia) and a string +/// literal (one `String` token) can never contribute. Two `Ident` shapes are +/// dropped: +/// +/// * a **macro usage** (`` `WIDTH ``) — the text is the whole invocation, +/// argument list and all, and the macro *names* have their own table; +/// * an **escaped identifier** (`\my-port`) — inserting one needs a trailing +/// space to terminate it, which a plain word item has no way to promise. +fn is_word(kind: TokenKind, text: &str) -> bool { + matches!(kind, TokenKind::Ident | TokenKind::SystemIdent) + && !text.starts_with('`') + && !text.starts_with('\\') +} + +/// Sort by name, case-insensitively first so [`matching`]'s binary search is +/// valid, then exactly so equal names sit next to each other for `dedup`. +fn sort_by_name(items: &mut [T], name: impl for<'b> Fn(&'b T) -> &'b str) { + items.sort_by(|a, b| { + let (a, b) = (name(a), name(b)); + lower_cmp(a, b).then_with(|| a.cmp(b)) + }); +} + +/// The entries whose name starts with `prefix`, case-insensitively. +/// +/// `items` is sorted by [`lower_cmp`], so the matches are one contiguous run: +/// a binary search for where the prefix would go, then as many entries as +/// still start with it. An empty prefix matches everything. +fn matching<'a, T>( + items: &'a [T], + prefix: &str, + name: impl for<'b> Fn(&'b T) -> &'b str, +) -> &'a [T] { + let start = items.partition_point(|item| lower_cmp(name(item), prefix) == Ordering::Less); + let rest = &items[start..]; + let len = rest.iter().take_while(|item| starts_with_ignore_case(name(item), prefix)).count(); + &rest[..len] +} + +/// ASCII-case-insensitive string order, without allocating a lowercase copy. +fn lower_cmp(a: &str, b: &str) -> Ordering { + a.bytes().map(|c| c.to_ascii_lowercase()).cmp(b.bytes().map(|c| c.to_ascii_lowercase())) +} + +/// Whether `word` starts with `prefix`, ignoring ASCII case. +pub fn starts_with_ignore_case(word: &str, prefix: &str) -> bool { + word.len() >= prefix.len() + && word.as_bytes()[..prefix.len()].eq_ignore_ascii_case(prefix.as_bytes()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sources(files: &[(&str, &str)]) -> Vec<(PathBuf, String)> { + files.iter().map(|(p, t)| (PathBuf::from(p), t.to_string())).collect() + } + + fn built(files: &[(&str, &str)]) -> Candidates { + let sources = sources(files); + let index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.clone(), t.as_str()))); + Candidates::build(&index, &sources) + } + + #[test] + fn words_come_from_tokens_so_comments_and_strings_contribute_nothing() { + let candidates = built(&[( + "/rtl/a.sv", + "module a;\n // comment_only_name\n logic real_name;\n\ + initial $display(\"string_only_name\");\nendmodule\n", + )]); + let names: Vec<&str> = candidates.words("").iter().map(String::as_str).collect(); + assert!(names.contains(&"real_name"), "{names:?}"); + assert!(names.contains(&"a"), "{names:?}"); + assert!(names.contains(&"$display"), "a system task is an identifier too"); + assert!(!names.contains(&"comment_only_name"), "a comment is not code: {names:?}"); + assert!(!names.contains(&"string_only_name"), "a string is not code: {names:?}"); + } + + #[test] + fn a_keyword_is_never_a_word() { + let candidates = built(&[("/rtl/a.sv", "module a;\n logic b;\nendmodule\n")]); + let names: Vec<&str> = candidates.words("").iter().map(String::as_str).collect(); + assert!(!names.contains(&"module"), "keywords have their own tier: {names:?}"); + assert!(!names.contains(&"logic"), "{names:?}"); + } + + #[test] + fn a_macro_usage_and_an_escaped_identifier_are_not_words() { + let candidates = built(&[( + "/rtl/a.sv", + "module a;\n logic \\esc-name ;\n assign x = `SOME_MACRO;\nendmodule\n", + )]); + let names: Vec<&str> = candidates.words("").iter().map(String::as_str).collect(); + assert!(names.contains(&"x"), "{names:?}"); + assert!(!names.iter().any(|n| n.starts_with('\\')), "{names:?}"); + assert!(!names.iter().any(|n| n.starts_with('`')), "{names:?}"); + } + + #[test] + fn a_prefix_matches_case_insensitively_and_contiguously() { + let candidates = built(&[( + "/rtl/a.sv", + "module a;\n logic width_a, WIDTH_B, widget, other;\nendmodule\n", + )]); + let hits: Vec<&str> = candidates.words("wid").iter().map(String::as_str).collect(); + assert_eq!(hits, ["widget", "width_a", "WIDTH_B"], "one run, case-insensitive"); + assert!(candidates.words("zzz").is_empty()); + assert!(candidates.words("").len() >= 4, "an empty prefix matches everything"); + } + + #[test] + fn a_word_is_offered_once_however_many_files_use_it() { + let candidates = built(&[ + ("/rtl/a.sv", "module a;\n logic shared;\nendmodule\n"), + ("/rtl/b.sv", "module b;\n logic shared;\nendmodule\n"), + ]); + assert_eq!(candidates.words("shared").len(), 1); + } + + #[test] + fn index_names_carry_their_kind_and_where_they_live() { + let candidates = built(&[( + "/rtl/p.sv", + "package p;\n localparam WIDTH = 8;\n typedef logic [1:0] pair_t;\nendpackage\n", + )]); + let package = candidates.units("p"); + assert_eq!(package.iter().map(|c| c.name.as_str()).collect::>(), ["p", "pair_t"]); + assert_eq!(package[0].kind, SymbolKind::Package); + assert_eq!(package[0].detail, "p.sv"); + assert_eq!(package[1].kind, SymbolKind::Typedef, "a package member keeps its kind"); + let member = candidates.units("WID"); + assert_eq!(member.len(), 1, "{member:?}"); + assert_eq!(member[0].detail, "p::WIDTH"); + } + + #[test] + fn define_names_are_tabled_with_their_signature() { + let candidates = built(&[( + "/rtl/a.svh", + "`define WIDTH 8\n`define MAX(a, b) ((a) > (b) ? (a) : (b))\n`undef GONE\n", + )]); + let names: Vec<&str> = candidates.macros("").iter().map(|m| m.name.as_str()).collect(); + assert_eq!(names, ["MAX", "WIDTH"]); + assert_eq!(candidates.macros("MAX")[0].detail, "`define MAX(a, b)"); + assert_eq!(candidates.macros("WID")[0].detail, "`define WIDTH"); + } + + #[test] + fn every_table_is_reachable_with_an_empty_prefix() { + let candidates = + built(&[("/rtl/p.sv", "`define ON 1\npackage p;\n localparam K = 1;\nendpackage\n")]); + assert_eq!(candidates.units("").len(), 2, "the package and its member"); + assert_eq!(candidates.macros("").len(), 1); + assert!(candidates.words("").len() >= 2, "at least `p` and `K`"); + } + + #[test] + fn a_file_that_does_not_lex_contributes_nothing_and_does_not_stop_the_rest() { + let candidates = built(&[ + ("/rtl/broken.sv", "module broken;\n logic never_seen; /* unterminated\n"), + ("/rtl/good.sv", "module good;\n logic seen;\nendmodule\n"), + ]); + let names: Vec<&str> = candidates.words("").iter().map(String::as_str).collect(); + assert!(names.contains(&"seen"), "{names:?}"); + assert!(!names.contains(&"never_seen"), "{names:?}"); + } +} diff --git a/crates/vfmt_server/src/completion.rs b/crates/vfmt_server/src/completion.rs index 9cd97fa..2c7d091 100644 --- a/crates/vfmt_server/src/completion.rs +++ b/crates/vfmt_server/src/completion.rs @@ -1,34 +1,66 @@ -//! `textDocument/completion` — module hinting on the wire. +//! `textDocument/completion` — module hinting, keywords, and every name the +//! project uses. //! -//! 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. +//! One response, five tiers, ordered by `sortText`: //! -//! See `docs/features/refactor-instantiate/README.md`. +//! 0. **module skeletons** — at module-item position only, the whole +//! instantiation generated from the definition (M4, unchanged); +//! 1. **what is visible here** — the declarations the scope chain at the +//! cursor binds, from this file's `Semantics`; +//! 2. **what the project declares** — packages, their members, typedefs, +//! classes, modules and `` `define`` names, from the workspace index; +//! 3. **keywords** — every reserved word `vlog_parser` knows; +//! 4. **project words** — every identifier the in-scope files' *token +//! streams* contain, the rope/VS Code word-completion tier. +//! +//! A name is offered once, by the highest tier that claims it. Nothing is +//! offered inside a comment or a string literal, and nothing that only ever +//! appears inside one is ever a candidate — see `candidates.rs`. +//! +//! See `docs/features/completion-core/README.md` and, for tier 0, +//! `docs/features/refactor-instantiate/README.md`. + +use std::collections::HashSet; use lsp_types::{ CompletionItem, CompletionItemKind, CompletionList, CompletionResponse, CompletionTextEdit, - Documentation, InsertTextFormat, MarkupContent, MarkupKind, Position, TextEdit, Uri, + Documentation, InsertTextFormat, MarkupContent, MarkupKind, Position, Range, TextEdit, Uri, }; -use vlog_parser::token::{Token, TokenKind}; -use vlog_parser::TextRange; +use vlog_parser::token::{Comment, Token, TokenKind}; +use vlog_parser::{TextRange, KEYWORDS}; use vlog_refactor::{InstantiationPlan, Layout, Site}; +use vlog_semantic::{Semantics, Symbol, SymbolKind}; +use crate::candidates::starts_with_ignore_case; use crate::pairs; use crate::state::{Document, Workspace}; +use crate::symbols::kind_label; + +/// How many items one response carries, over every tier. +/// +/// Large enough that an *empty* prefix still reaches the last tier — 64 +/// modules plus 181 keywords plus what one scope binds leaves room — and small +/// enough to bound the payload at a few tens of kilobytes. Tiers fill in +/// order, so a truncated list loses the least useful end of it and comes back +/// `isIncomplete`: the protocol's way of saying "ask me again when you have +/// typed more". +const LIMIT: usize = 512; /// 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; +/// Its own cap because it is the one tier that costs *parsing*: each item is +/// one parse of one defining file — 158 µs for the average file of this repo's +/// corpus, 4.6 ms for its worst. Every other tier is a binary search in a +/// table built at index time. Unchanged from M4. +const MODULE_LIMIT: usize = 64; + +/// `sortText` prefixes. The client sorts on these, so they *are* the tier +/// order; the name follows so each tier is alphabetical within itself. +const TIER_MODULE: char = '0'; +const TIER_SCOPE: char = '1'; +const TIER_INDEX: char = '2'; +const TIER_KEYWORD: char = '3'; +const TIER_WORD: char = '4'; /// The scopes a module instantiation may be written directly inside. const ITEM_SCOPES: &[&str] = @@ -65,10 +97,10 @@ const PROCEDURAL: &[&str] = 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. +/// The completions available at a position, or nothing when the cursor is +/// somewhere no name may be written. /// -/// `snippets` is what the client advertised: without it the skeleton is +/// `snippets` is what the client advertised: without it a module 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( @@ -79,18 +111,63 @@ pub fn completions( ) -> 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) { + // A buffer that does not lex has no token stream, so nothing here can tell + // a comment from code — and the commonest way to break the lexer is to + // open a string or a block comment and keep typing. Declining is the safe + // half of that trade; the buffer lexes again as soon as it is closed. + if doc.tokens.is_empty() || in_comment_or_string(doc, offset) { return None; } + let word = typed_word(doc, offset)?; + + // A backtick admits exactly one kind of name, so the answer is only that + // kind — and the backtick already typed is inside the replaced range, so + // it is never doubled. + if word.backtick { + // The backtick itself is replaced, so the item may carry its own. + let replacing = TextRange::new(word.start.saturating_sub(1), offset); + let mut items = Items::new(doc, replacing); + for entry in ws.candidates().macros(&word.text) { + items.simple( + &format!("`{}", entry.name), + CompletionItemKind::CONSTANT, + TIER_INDEX, + entry.detail.clone(), + ); + } + return items.finish(); + } + + let mut items = Items::new(doc, word.range(offset)); + module_tier(&mut items, ws, doc, &word, offset, snippets); + scope_tier(&mut items, doc, &word); + index_tier(&mut items, ws, &word); + keyword_tier(&mut items, &word); + word_tier(&mut items, ws, doc, &word); + items.finish() +} + +/// Tier 0: M4's instantiation skeletons, at module-item position only. +fn module_tier( + items: &mut Items, + ws: &Workspace, + doc: &Document, + word: &Word, + cursor: u32, + snippets: bool, +) { + if !word.at_line_start || !at_module_item(doc, word.start) { + return; + } 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) { + if names.len() > MODULE_LIMIT { + items.incomplete = true; + } + for name in names.into_iter().take(MODULE_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 }; @@ -99,12 +176,260 @@ pub fn completions( 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)); + items.push(item(&plan, &layout, word.range(cursor), doc, &file, snippets)); } - if items.is_empty() { - return None; +} + +/// Tier 1: everything the scope chain at the cursor binds. +fn scope_tier(items: &mut Items, doc: &Document, word: &Word) { + for symbol in visible_symbols(&doc.semantics, word.start) { + if items.full() { + break; + } + if !starts_with_ignore_case(&symbol.name, &word.text) { + continue; + } + items.simple( + &symbol.name, + completion_kind(symbol.kind), + TIER_SCOPE, + declaration_detail(doc, symbol), + ); + } +} + +/// Tier 2: what the workspace index declares, `` `define`` names included. +fn index_tier(items: &mut Items, ws: &Workspace, word: &Word) { + for candidate in ws.candidates().units(&word.text) { + if items.full() { + break; + } + items.simple( + &candidate.name, + completion_kind(candidate.kind), + TIER_INDEX, + format!("{} — {}", kind_label(candidate.kind), candidate.detail), + ); + } + // Bare, with no backtick invented. A macro *use* is spelled with one and + // the user types it (see the early return above); the places a macro name + // is written without one — `` `ifdef NAME ``, `` `undef NAME `` — are + // exactly where this item is the right text. + for entry in ws.candidates().macros(&word.text) { + if items.full() { + break; + } + items.simple(&entry.name, CompletionItemKind::CONSTANT, TIER_INDEX, entry.detail.clone()); + } +} + +/// Tier 3: every reserved word the lexer knows. +fn keyword_tier(items: &mut Items, word: &Word) { + for keyword in KEYWORDS.iter().filter(|kw| starts_with_ignore_case(kw, &word.text)) { + if items.full() { + break; + } + items.simple(keyword, CompletionItemKind::KEYWORD, TIER_KEYWORD, "keyword".to_string()); + } +} + +/// Tier 4: identifiers used anywhere in the project scope. +/// +/// The prebuilt table is as of the last index rebuild, which is `didSave`; the +/// buffer being typed in is harvested afresh from its own token stream, so an +/// unsaved edit contributes to its own file's completions immediately. +fn word_tier(items: &mut Items, ws: &Workspace, doc: &Document, word: &Word) { + // Gathering and sorting the names is the one tier whose *setup* costs + // something, so a response that is already full skips it outright. + if items.full() { + return; + } + let mut names: Vec<&str> = + ws.candidates().words(&word.text).iter().map(String::as_str).collect(); + names.extend( + doc.tokens + .iter() + .filter(|t| matches!(t.kind, TokenKind::Ident | TokenKind::SystemIdent)) + .map(|t| t.text.as_str()) + .filter(|text| !text.starts_with('`') && !text.starts_with('\\')) + .filter(|text| starts_with_ignore_case(text, &word.text)), + ); + names.sort_unstable(); + names.dedup(); + for name in names { + if items.full() { + break; + } + items.simple(name, CompletionItemKind::TEXT, TIER_WORD, "used in this project".to_string()); + } +} + +/// The response under construction: the items, the names already spoken for, +/// and whether the cap cut anything off. +struct Items { + /// The bytes every item replaces, as the client reads them. + range: Range, + items: Vec, + seen: HashSet, + incomplete: bool, +} + +impl Items { + fn new(doc: &Document, replacing: TextRange) -> Items { + Items { + range: doc.positions().range(replacing), + items: Vec::new(), + seen: HashSet::new(), + incomplete: false, + } + } + + /// Whether the cap has been reached. Once it has, every further candidate + /// only sets [`Items::incomplete`] — which is why the tiers ask first + /// rather than building items nobody will see. + fn full(&mut self) -> bool { + if self.items.len() >= LIMIT { + self.incomplete = true; + return true; + } + false + } + + /// Add an item, unless a higher tier already offered that name or the + /// response is full. + fn push(&mut self, item: CompletionItem) { + if self.full() || !self.seen.insert(item.label.clone()) { + return; + } + self.items.push(item); + } + + /// A plain-text item that inserts exactly its own name. + fn simple(&mut self, name: &str, kind: CompletionItemKind, tier: char, detail: String) { + if self.full() || self.seen.contains(name) { + return; + } + let item = CompletionItem { + label: name.to_string(), + kind: Some(kind), + detail: Some(detail), + sort_text: Some(format!("{tier}{name}")), + insert_text_format: Some(InsertTextFormat::PLAIN_TEXT), + text_edit: Some(CompletionTextEdit::Edit(TextEdit { + range: self.range, + new_text: name.to_string(), + })), + ..Default::default() + }; + self.push(item); + } + + fn finish(self) -> Option { + if self.items.is_empty() { + return None; + } + Some(CompletionResponse::List(CompletionList { + is_incomplete: self.incomplete, + items: self.items, + })) + } +} + +/// The LSP icon a declaration gets in a completion list. The same choices +/// `symbols::lsp_kind` makes for the outline, in the other enum. +fn completion_kind(kind: SymbolKind) -> CompletionItemKind { + match kind { + SymbolKind::Module | SymbolKind::Package | SymbolKind::Block => CompletionItemKind::MODULE, + SymbolKind::Port | SymbolKind::StructMember => CompletionItemKind::FIELD, + SymbolKind::Net | SymbolKind::Var | SymbolKind::Genvar | SymbolKind::Instance => { + CompletionItemKind::VARIABLE + } + SymbolKind::Param | SymbolKind::TfArg => CompletionItemKind::CONSTANT, + SymbolKind::Typedef => CompletionItemKind::TYPE_PARAMETER, + SymbolKind::EnumVariant => CompletionItemKind::ENUM_MEMBER, + SymbolKind::Function | SymbolKind::Task => CompletionItemKind::FUNCTION, + SymbolKind::Class => CompletionItemKind::CLASS, + } +} + +/// What a visible declaration shows beside its name: the line it was declared +/// on, which is the cheapest honest summary there is. +fn declaration_detail(doc: &Document, symbol: &Symbol) -> String { + let line = doc.positions().whole_lines(symbol.decl_span).lines().next().unwrap_or("").trim(); + match line.is_empty() { + true => kind_label(symbol.kind).to_string(), + false => shorten(line, 80), + } +} + +/// `text`, cut to `max` characters on a character boundary. +fn shorten(text: &str, max: usize) -> String { + match text.char_indices().nth(max) { + Some((at, _)) => format!("{}…", &text[..at]), + None => text.to_string(), + } +} + +/// Every declaration the scope chain covering `offset` binds, innermost scope +/// first, each name only once — the inner declaration shadows the outer one, +/// which is the rule `vlog_semantic`'s own lookup follows. +fn visible_symbols(semantics: &Semantics, offset: u32) -> Vec<&Symbol> { + let mut out = Vec::new(); + let mut seen = HashSet::new(); + let mut at = innermost_scope(semantics, offset); + while let Some(id) = at { + let Some(scope) = semantics.scope(id) else { break }; + for symbol in scope.symbols.iter().filter_map(|&id| semantics.symbol(id)) { + if seen.insert(symbol.name.as_str()) { + out.push(symbol); + } + } + at = scope.parent; + } + out +} + +/// The smallest scope whose span covers `offset`. +fn innermost_scope(semantics: &Semantics, offset: u32) -> Option { + semantics + .scopes() + .iter() + .enumerate() + .filter(|(_, scope)| scope.span.contains(offset)) + .min_by_key(|(_, scope)| scope.span.len()) + .map(|(i, _)| vlog_semantic::ScopeId(i as u32)) +} + +/// Whether `offset` sits inside a comment or a string literal — the two places +/// a completion list has no business appearing. +/// +/// Comments are lexer trivia hanging off the token that follows (or precedes) +/// them, so this reads both. A linear pass over the token stream: a scan of a +/// few tens of thousands of tokens is tens of microseconds, and a binary +/// search would have to reason about which token a comment attached to. +fn in_comment_or_string(doc: &Document, offset: u32) -> bool { + for token in &doc.tokens { + if token.kind == TokenKind::String && token.span.start < offset && offset < token.span.end { + return true; + } + if token.leading.iter().chain(token.trailing.as_ref()).any(|c| in_comment(c, offset)) { + return true; + } + } + false +} + +/// Whether `offset` is inside `comment`. A `//` comment runs to the end of the +/// line, so a cursor at its last byte is still inside it; a `/* */` one ends +/// at its marker, and the byte after that is code again. +fn in_comment(comment: &Comment, offset: u32) -> bool { + if offset <= comment.span.start { + return false; + } + match comment.text.starts_with("//") { + true => offset <= comment.span.end, + false => offset < comment.span.end, } - Some(CompletionResponse::List(CompletionList { is_incomplete: incomplete, items })) } /// One module's completion item, skeleton and all. @@ -137,6 +462,7 @@ fn item( value: documentation(plan), })), filter_text: Some(plan.module.clone()), + sort_text: Some(format!("{TIER_MODULE}{}", plan.module)), insert_text_format: Some(match snippets { true => InsertTextFormat::SNIPPET, false => InsertTextFormat::PLAIN_TEXT, @@ -203,10 +529,27 @@ fn documentation(plan: &InstantiationPlan) -> String { // where the cursor is // ---------------------------------------------------------------------- -/// The identifier the user is part-way through typing, and where it starts. +/// The identifier the user is part-way through typing, and what stands around +/// it. struct Word { + /// The identifier run, backtick excluded. Empty when the cursor follows + /// something that is not an identifier character. text: String, + /// Where the run starts — the byte after the backtick, when there is one. start: u32, + /// Whether a `` ` `` immediately precedes the run, making this a macro + /// name being typed and nothing else. + backtick: bool, + /// Whether nothing but whitespace precedes the run on its line. + /// + /// Half of the *module* gate, and 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 + /// skeleton — a far better failure than offering a fifteen-line + /// instantiation in the middle of an expression. Every other tier ignores + /// it: a name is a name wherever it is written. + at_line_start: bool, } impl Word { @@ -216,24 +559,26 @@ impl Word { } } -/// 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. +/// The identifier run ending at the cursor, and the shape of the line it sits +/// on. `None` only when the cursor is not on a character boundary of the text +/// the server holds. 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 }) + let backtick = head.ends_with('`'); + let bare = match backtick { + true => head.get(..head.len() - 1)?, + false => head, + }; + let line_start = bare.rfind('\n').map_or(0, |newline| newline + 1); + let at_line_start = !backtick && bare.get(line_start..)?.chars().all(|c| c == ' ' || c == '\t'); + Some(Word { + text: text.get(start..)?.to_string(), + start: start as u32, + backtick, + at_line_start, + }) } fn is_ident_char(ch: char) -> bool { @@ -346,6 +691,7 @@ fn balanced(tokens: &[Token], from: u32, at: u32) -> bool { #[cfg(test)] mod tests { use super::*; + use crate::settings::ClientSettings; use crate::uri::path_to_uri; use std::fs; use std::path::PathBuf; @@ -393,6 +739,11 @@ endmodule fn asking(name: &str, top: &str, needle: &str) -> (Tree, Workspace, Uri, Position) { let tree = Tree::new(name); tree.write("sub.sv", SUB); + opened(tree, top, needle) + } + + /// The same, with whatever `tree` already holds and no `sub.sv` implied. + fn opened(tree: Tree, top: &str, needle: &str) -> (Tree, Workspace, Uri, Position) { let path = tree.write("top.sv", top); let mut ws = Workspace::default(); ws.open_roots(vec![tree.path.clone()]); @@ -419,13 +770,36 @@ endmodule } } + /// The tier an item was filed under, read off its `sortText`. + fn tier(item: &CompletionItem) -> char { + item.sort_text.as_ref().and_then(|s| s.chars().next()).expect("every item is sorted") + } + + /// Only the module skeletons — tier 0, the M4 items. + fn skeletons(items: &[CompletionItem]) -> Vec<&CompletionItem> { + items.iter().filter(|item| tier(item) == TIER_MODULE).collect() + } + + fn find<'a>(items: &'a [CompletionItem], label: &str) -> Option<&'a CompletionItem> { + items.iter().find(|item| item.label == label) + } + + fn labels(items: &[CompletionItem]) -> Vec<&str> { + items.iter().map(|item| item.label.as_str()).collect() + } + + // ------------------------------------------------------------------ + // tier 0 — module hinting (M4, unchanged behaviour) + // ------------------------------------------------------------------ + #[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]; + let skeletons = skeletons(&items); + assert_eq!(skeletons.len(), 1, "{items:#?}"); + let item = skeletons[0]; assert_eq!(item.label, "sub"); assert_eq!(item.kind, Some(CompletionItemKind::MODULE)); assert_eq!(item.insert_text_format, Some(InsertTextFormat::SNIPPET)); @@ -448,7 +822,7 @@ sub #( 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]; + let item = skeletons(&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}"); @@ -461,11 +835,13 @@ sub #( 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 }); + for item in &items { + let CompletionTextEdit::Edit(edit) = item.text_edit.as_ref().expect("edit") else { + panic!("a plain edit"); + }; + assert_eq!(edit.range.start, Position { line: 1, character: 2 }, "{item:#?}"); + assert_eq!(edit.range.end, Position { line: 1, character: 4 }); + } } #[test] @@ -473,7 +849,7 @@ sub #( 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 { + let Some(Documentation::MarkupContent(doc)) = &skeletons(&items)[0].documentation else { panic!("markdown documentation"); }; assert!(doc.value.contains("`WIDTH` = `8`"), "{}", doc.value); @@ -482,7 +858,9 @@ sub #( } #[test] - fn nothing_is_offered_in_the_middle_of_an_expression() { + fn no_skeleton_is_offered_in_the_middle_of_an_expression() { + // The other tiers answer here — a name is a name wherever it is + // written — but a fifteen-line instantiation is not. 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"), @@ -490,30 +868,31 @@ sub #( ("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}"); + let items = items(completions(&ws, &uri, position, true)); + assert!(skeletons(&items).is_empty(), "{name}: {top}\n{items:#?}"); } } #[test] - fn nothing_is_offered_inside_a_procedural_block() { + fn no_skeleton_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()); + assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty()); 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()); + assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty()); } #[test] - fn nothing_is_offered_inside_a_function_or_a_class() { + fn no_skeleton_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()); + assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty()); 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()); + assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty()); } #[test] @@ -526,41 +905,38 @@ module top; endmodule "; let (_tree, ws, uri, position) = asking("genfor", top, " su"); - assert_eq!(items(completions(&ws, &uri, position, true)).len(), 1, "{top}"); + assert_eq!(skeletons(&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); + assert_eq!(skeletons(&items(completions(&ws, &uri, position, true))).len(), 1); } #[test] - fn nothing_is_offered_outside_a_design_unit() { + fn no_skeleton_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()); + assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty()); } #[test] - fn a_prefix_that_matches_no_module_offers_nothing() { + fn a_prefix_that_matches_no_module_offers_no_skeleton() { 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()); + assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty()); } #[test] fn a_module_declared_twice_is_skipped_rather_than_guessed() { + // The index still knows the *name* — tier 2 offers it as a plain + // module — but there is no single definition to build a skeleton from. 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()); + let (_tree, ws, uri, position) = opened(tree, "module top;\n du\nendmodule\n", " du"); + let items = items(completions(&ws, &uri, position, true)); + assert!(skeletons(&items).is_empty(), "{items:#?}"); + assert_eq!(tier(find(&items, "dup").expect("the name is still known")), TIER_INDEX); } #[test] @@ -575,22 +951,17 @@ endmodule "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 (_tree, ws, uri, position) = opened(tree, top, " su"); let items = items(completions(&ws, &uri, position, true)); - assert_eq!(items.len(), 1, "{items:#?}"); + let skeletons = skeletons(&items); + assert_eq!(skeletons.len(), 1, "{items:#?}"); assert_eq!( - items[0].insert_text_format, + skeletons[0].insert_text_format, Some(InsertTextFormat::PLAIN_TEXT), "snippets were offered but the plan cannot be encoded as one" ); - let text = inserted(&items[0]); + let text = inserted(skeletons[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}"); @@ -609,4 +980,357 @@ endmodule assert_eq!(snippet_hole(3, "$bits(t)"), "${3:\\$bits(t)}"); assert_eq!(snippet_hole(4, "a}b\\c"), "${4:a\\}b\\\\c}"); } + + // ------------------------------------------------------------------ + // tier 3 — keywords + // ------------------------------------------------------------------ + + #[test] + fn every_keyword_the_lexer_knows_is_offered() { + let top = "module top;\n assign x = alw\nendmodule\n"; + let (_tree, ws, uri, position) = asking("keyword", top, "= alw"); + let items = items(completions(&ws, &uri, position, true)); + let keywords: Vec<&str> = + items.iter().filter(|i| tier(i) == TIER_KEYWORD).map(|i| i.label.as_str()).collect(); + assert_eq!(keywords, ["always", "always_comb", "always_ff", "always_latch"]); + let always = find(&items, "always").expect("`always`"); + assert_eq!(always.kind, Some(CompletionItemKind::KEYWORD)); + assert_eq!(inserted(always), "always"); + } + + #[test] + fn the_keyword_tier_is_exactly_the_lexers_list() { + let top = "module top;\n assign x = \nendmodule\n"; + let (_tree, ws, uri, position) = asking("allkeywords", top, "= "); + let items = items(completions(&ws, &uri, position, true)); + let offered: HashSet<&str> = + items.iter().filter(|i| tier(i) == TIER_KEYWORD).map(|i| i.label.as_str()).collect(); + let known: HashSet<&str> = KEYWORDS.iter().copied().collect(); + assert_eq!(offered, known, "no keyword may be missing and none invented"); + } + + // ------------------------------------------------------------------ + // comments and strings, both ways round + // ------------------------------------------------------------------ + + #[test] + fn nothing_is_offered_inside_a_comment_or_a_string() { + for (name, top, needle) in [ + ("line", "module top;\n // wid\nendmodule\n", "// wid"), + ("block", "module top;\n /* wid */\nendmodule\n", "/* wid"), + ("trailing", "module top;\n logic a; // wid\nendmodule\n", "// wid"), + ("string", "module top;\n initial $display(\"wid\");\nendmodule\n", "\"wid"), + ] { + let (_tree, ws, uri, position) = asking(&format!("in{name}"), top, needle); + assert!(completions(&ws, &uri, position, true).is_none(), "{name}: {top}"); + } + } + + #[test] + fn the_byte_after_a_block_comment_is_code_again() { + // The other half of the boundary: `/* x */w|` is not inside anything. + let top = "module top;\n /* c */ wid\nendmodule\n"; + let (_tree, ws, uri, position) = asking("afterblock", top, "*/ wid"); + assert!(completions(&ws, &uri, position, true).is_some()); + } + + #[test] + fn a_name_that_only_a_comment_or_a_string_holds_is_never_a_candidate() { + let tree = Tree::new("harvest"); + tree.write( + "other.sv", + "module other;\n // widget_in_comment\n logic widget_in_code;\n\ + initial $display(\"widget_in_string\");\nendmodule\n", + ); + let top = "module top;\n assign x = widget\nendmodule\n"; + let (_tree, ws, uri, position) = opened(tree, top, "= widget"); + let items = items(completions(&ws, &uri, position, true)); + let labels = labels(&items); + assert!(labels.contains(&"widget_in_code"), "{labels:?}"); + assert!(!labels.contains(&"widget_in_comment"), "a comment is not code: {labels:?}"); + assert!(!labels.contains(&"widget_in_string"), "a string is not code: {labels:?}"); + } + + #[test] + fn a_buffer_that_does_not_lex_is_declined_rather_than_guessed_at() { + let top = "module top;\n logic a; /* unterminated\n wid\n"; + let (_tree, ws, uri, position) = asking("nolex", top, " wid"); + assert!(completions(&ws, &uri, position, true).is_none()); + } + + // ------------------------------------------------------------------ + // tiers, ordering and dedup + // ------------------------------------------------------------------ + + #[test] + fn the_tiers_are_ordered_scope_then_project_then_keywords_then_words() { + let tree = Tree::new("tiers"); + tree.write("pkg.sv", "package w_pkg;\n localparam K = 1;\nendpackage\n"); + tree.write("other.sv", "module other;\n logic w_elsewhere;\nendmodule\n"); + let top = "module top;\n logic w_local;\n assign x = w\nendmodule\n"; + let (_tree, ws, uri, position) = opened(tree, top, "= w"); + let items = items(completions(&ws, &uri, position, true)); + + assert_eq!(tier(find(&items, "w_local").expect("in scope")), TIER_SCOPE); + assert_eq!(tier(find(&items, "w_pkg").expect("a package")), TIER_INDEX); + assert_eq!(tier(find(&items, "wire").expect("a keyword")), TIER_KEYWORD); + assert_eq!(tier(find(&items, "w_elsewhere").expect("a project word")), TIER_WORD); + + let scope = find(&items, "w_local").expect("in scope"); + let word = find(&items, "w_elsewhere").expect("a project word"); + assert!(scope.sort_text < word.sort_text, "the client sorts scope above words"); + } + + #[test] + fn a_name_that_is_both_in_scope_and_a_project_word_is_offered_once() { + let tree = Tree::new("dedup"); + // The same name, declared here and used elsewhere in the project. + tree.write("other.sv", "module other;\n logic shared_name;\nendmodule\n"); + let top = "module top;\n logic shared_name;\n assign x = shared\nendmodule\n"; + let (_tree, ws, uri, position) = opened(tree, top, "= shared"); + let items = items(completions(&ws, &uri, position, true)); + let hits: Vec<&CompletionItem> = + items.iter().filter(|i| i.label == "shared_name").collect(); + assert_eq!(hits.len(), 1, "{hits:#?}"); + assert_eq!(tier(hits[0]), TIER_SCOPE, "the semantic tier wins"); + assert_eq!(hits[0].kind, Some(CompletionItemKind::VARIABLE), "and its real kind with it"); + } + + #[test] + fn a_visible_declaration_carries_its_kind_and_the_line_it_was_written_on() { + let top = "\ +module top #(parameter int WIDTH = 8) (input logic clk); + typedef logic [1:0] pair_t; + logic [WIDTH-1:0] data; + function int f(); return 0; endfunction + assign x = +endmodule +"; + let (_tree, ws, uri, position) = asking("kinds", top, "assign x ="); + let items = items(completions(&ws, &uri, position, true)); + let kind = |label: &str| find(&items, label).unwrap_or_else(|| panic!("{label}")).kind; + assert_eq!(kind("WIDTH"), Some(CompletionItemKind::CONSTANT)); + assert_eq!(kind("clk"), Some(CompletionItemKind::FIELD)); + assert_eq!(kind("pair_t"), Some(CompletionItemKind::TYPE_PARAMETER)); + assert_eq!(kind("data"), Some(CompletionItemKind::VARIABLE)); + assert_eq!(kind("f"), Some(CompletionItemKind::FUNCTION)); + assert_eq!( + find(&items, "data").expect("data").detail.as_deref(), + Some("logic [WIDTH-1:0] data;"), + "the declaration as written" + ); + } + + #[test] + fn only_what_the_scope_chain_reaches_is_in_the_semantic_tier() { + // `inner` is declared in a block the cursor is not in, so it may only + // arrive as a project word — never as a visible declaration. + let top = "\ +module top; + initial begin : b + integer inner_only; + end + initial begin + x = inner + end +endmodule +"; + let (_tree, ws, uri, position) = asking("scopewalk", top, "x = inner"); + let items = items(completions(&ws, &uri, position, true)); + let item = find(&items, "inner_only").expect("known as a word at least"); + assert_eq!(tier(item), TIER_WORD, "{item:#?}"); + } + + // ------------------------------------------------------------------ + // `define names and the backtick + // ------------------------------------------------------------------ + + #[test] + fn a_backtick_offers_macro_names_and_only_macro_names() { + let tree = Tree::new("macro"); + tree.write("defs.svh", "`define WIDTH 8\n`define MAX(a, b) 0\n"); + tree.write("other.sv", "module other;\n logic WIDGET;\nendmodule\n"); + let top = "module top;\n assign x = `WI\nendmodule\n"; + let (_tree, ws, uri, position) = opened(tree, top, "`WI"); + let items = items(completions(&ws, &uri, position, true)); + assert_eq!(labels(&items), ["`WIDTH"], "only a macro may follow a backtick"); + assert_eq!(inserted(&items[0]), "`WIDTH"); + 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: 13 }, + "the typed backtick is replaced, not doubled" + ); + } + + #[test] + fn a_macro_name_without_a_backtick_is_offered_bare() { + // Where a macro name is written without one: `` `ifdef NAME ``. + let tree = Tree::new("macrobare"); + tree.write("defs.svh", "`define WIDTH 8\n"); + let top = "module top;\n assign x = WID\nendmodule\n"; + let (_tree, ws, uri, position) = opened(tree, top, "= WID"); + let items = items(completions(&ws, &uri, position, true)); + let item = find(&items, "WIDTH").expect("the macro name"); + assert_eq!(inserted(item), "WIDTH", "no backtick is invented"); + assert_eq!(item.detail.as_deref(), Some("`define WIDTH")); + } + + // ------------------------------------------------------------------ + // filtering, the cap, and the scope ladder + // ------------------------------------------------------------------ + + #[test] + fn the_prefix_filters_server_side() { + let tree = Tree::new("prefix"); + tree.write("other.sv", "module other;\n logic aaa_one, bbb_two;\nendmodule\n"); + let top = "module top;\n assign x = aaa\nendmodule\n"; + let (_tree, ws, uri, position) = opened(tree, top, "= aaa"); + let items = items(completions(&ws, &uri, position, true)); + assert!(!items.is_empty()); + for item in &items { + assert!( + starts_with_ignore_case(&item.label, "aaa"), + "{} does not start with the typed prefix", + item.label + ); + } + } + + #[test] + fn a_full_response_is_truncated_and_says_it_is_incomplete() { + let mut top = String::from("module top;\n"); + for i in 0..LIMIT + 40 { + top.push_str(&format!(" logic wsig{i:04};\n")); + } + top.push_str(" assign x = wsig\nendmodule\n"); + let (_tree, ws, uri, position) = asking("cap", &top, "= wsig"); + let Some(CompletionResponse::List(list)) = completions(&ws, &uri, position, true) else { + panic!("a completion list"); + }; + assert_eq!(list.items.len(), LIMIT); + assert!(list.is_incomplete, "a truncated list must say so"); + } + + #[test] + fn a_file_outside_the_filelist_contributes_no_words() { + // M1's ladder decides what "the project" is, and the word tier is + // built from exactly that list. + let tree = Tree::new("filelist"); + tree.write("listed.sv", "module listed;\n logic word_listed;\nendmodule\n"); + tree.write("unlisted.sv", "module unlisted;\n logic word_unlisted;\nendmodule\n"); + tree.write("files.f", "listed.sv\n"); + let top = "module top;\n assign x = word_\nendmodule\n"; + let path = tree.write("top.sv", top); + + let mut ws = Workspace::default(); + ws.set_client_settings(ClientSettings { + filelist: Some("files.f".to_string()), + ..Default::default() + }); + ws.open_roots(vec![tree.path.clone()]); + let uri = path_to_uri(&path).expect("uri"); + ws.set_document(uri.clone(), top.to_string()); + ws.rebuild_index(); + let offset = (top.find("= word_").expect("needle") + 7) as u32; + let position = ws.document(&uri).expect("open").positions().position(offset); + + let items = items(completions(&ws, &uri, position, true)); + let labels = labels(&items); + assert!(labels.contains(&"word_listed"), "{labels:?}"); + assert!(!labels.contains(&"word_unlisted"), "outside the project: {labels:?}"); + } + + #[test] + fn an_unsaved_edit_contributes_its_own_words_at_once() { + // The buffer's own token stream is read per request, so a name typed + // a moment ago is a candidate before anything is saved. + let top = "module top;\n logic fresh_name;\n assign x = fre\nendmodule\n"; + let (_tree, ws, uri, position) = asking("unsaved", top, "= fre"); + // The file on disk is `top` too, so make the buffer differ from it. + let edited = "module top;\n logic fresher_name;\n assign x = fre\nendmodule\n"; + let mut ws = ws; + ws.set_document(uri.clone(), edited.to_string()); + let items = items(completions(&ws, &uri, position, true)); + assert!(labels(&items).contains(&"fresher_name"), "{:?}", labels(&items)); + } + + // ------------------------------------------------------------------ + // the performance claim, measured + // ------------------------------------------------------------------ + + /// What a keystroke costs over the real corpus, and what the tables cost + /// to build. Skipped when `corpus/` is not checked out + /// (`tools/corpus_fetch.sh`), exactly like the other corpus tests. + /// + /// The budgets are deliberately loose — a debug build on a loaded machine + /// is the worst case this ever runs in — and exist to catch an *order of + /// magnitude* regression, not to pin a number. The numbers themselves are + /// in `docs/features/completion-core/README.md`. + #[test] + fn a_keystroke_over_the_whole_corpus_stays_in_budget() { + let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); + if !corpus.is_dir() { + eprintln!("corpus/ not checked out — skipping"); + return; + } + let started = std::time::Instant::now(); + let mut ws = Workspace::default(); + ws.open_roots(vec![corpus.clone()]); + let build = started.elapsed(); + + // A buffer that is not on disk: it overlays the walk, so the corpus is + // never written to. + let top = "module vfmt_probe;\n logic clk;\n assign x = pr\nendmodule\n"; + let uri = path_to_uri(&corpus.join("vfmt_probe.sv")).expect("uri"); + ws.set_document(uri.clone(), top.to_string()); + let offset = (top.find("= pr").expect("needle") + 4) as u32; + let position = ws.document(&uri).expect("open").positions().position(offset); + + // Warm, then the measurement: ten requests, worst one reported. Twice + // — once for a typed prefix, once for the empty one, which is the + // worst case there is (every tier matches, and the cap does the work). + let empty = ws.document(&uri).expect("open").positions().position(offset - 2); + let mut worst = std::time::Duration::ZERO; + let mut worst_empty = std::time::Duration::ZERO; + for round in 0..11 { + let started = std::time::Instant::now(); + let typed = items(completions(&ws, &uri, position, true)); + let after_typed = started.elapsed(); + let started = std::time::Instant::now(); + let all = items(completions(&ws, &uri, empty, true)); + let after_empty = started.elapsed(); + assert!(!typed.is_empty()); + assert_eq!(all.len(), LIMIT, "the empty prefix fills the response"); + if round > 0 { + worst = worst.max(after_typed); + worst_empty = worst_empty.max(after_empty); + } + } + eprintln!( + "corpus: {} files, {} words, {} index names; index+tables built in {build:?}; \ + worst request {worst:?} typed / {worst_empty:?} empty", + ws.index().files().len(), + ws.candidates().words("").len(), + ws.candidates().units("").len(), + ); + assert!(worst < std::time::Duration::from_millis(150), "a keystroke cost {worst:?}"); + assert!(worst_empty < std::time::Duration::from_millis(150), "{worst_empty:?}"); + } + + #[test] + fn another_open_buffer_overlays_disk_once_the_index_is_rebuilt() { + let tree = Tree::new("overlay"); + let other = tree.write("other.sv", "module other;\n logic on_disk_name;\nendmodule\n"); + let top = "module top;\n assign x = ov\nendmodule\n"; + let (_tree, mut ws, uri, position) = opened(tree, top, "= ov"); + + let other_uri = path_to_uri(&other).expect("uri"); + ws.set_document(other_uri, "module other;\n logic ov_in_buffer;\nendmodule\n".to_string()); + ws.rebuild_index(); + let items = items(completions(&ws, &uri, position, true)); + assert!(labels(&items).contains(&"ov_in_buffer"), "{:?}", labels(&items)); + } } diff --git a/crates/vfmt_server/src/main.rs b/crates/vfmt_server/src/main.rs index 98f545c..2bd1a26 100644 --- a/crates/vfmt_server/src/main.rs +++ b/crates/vfmt_server/src/main.rs @@ -6,6 +6,7 @@ //! `vlog_parser`, `vlog_semantic` or `vlog_formatter`. See //! `docs/features/vfmt-server/README.md`. +mod candidates; mod code_action; mod completion; mod convert; diff --git a/crates/vfmt_server/src/state.rs b/crates/vfmt_server/src/state.rs index 054ce9c..27ff6d8 100644 --- a/crates/vfmt_server/src/state.rs +++ b/crates/vfmt_server/src/state.rs @@ -17,6 +17,7 @@ use vlog_semantic::{analyze, resolve_external, ExternalResolutions, Semantics, W use vfmt_core::config::Discovery; use vfmt_core::walk::{collect_files, EXTENSIONS}; +use crate::candidates::Candidates; use crate::convert::Positions; use crate::settings::ClientSettings; use crate::uri::uri_to_path; @@ -86,6 +87,10 @@ pub struct Workspace { docs: HashMap, roots: Vec, index: WorkspaceIndex, + /// The project-wide completion tables, rebuilt with `index` and from the + /// same file list. Precomputed because completion fires per keystroke and + /// nothing that walks the workspace may. + candidates: Candidates, /// The last `vfmt.*` settings a client pushed. Default until it does. client: ClientSettings, } @@ -102,6 +107,11 @@ impl Workspace { &self.index } + /// The project-wide completion tables, as of the last index rebuild. + pub fn candidates(&self) -> &Candidates { + &self.candidates + } + /// Whether the client opened a workspace at all. /// /// Without one the index's scope is the open buffers' own directories, so @@ -150,8 +160,9 @@ impl Workspace { self.docs.keys().cloned().collect() } - /// Re-scan the workspace and rebuild the index, then refresh every open - /// buffer's overlay. Called on `initialize` and on every `didSave`. + /// Re-scan the workspace and rebuild the index and the completion tables, + /// then refresh every open buffer's overlay. Called on `initialize` and on + /// every `didSave`. /// /// Returns the warnings from resolving the scope — a filelist naming a /// file that is gone, say. Rendering them is `server.rs`'s job; this @@ -159,6 +170,9 @@ impl Workspace { pub fn rebuild_index(&mut self) -> Vec { let (sources, warnings) = self.collect_sources(); self.index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.clone(), t.as_str()))); + // Built here, from the same list, so a file the scope ladder excluded + // contributes no completion candidates either. + self.candidates = Candidates::build(&self.index, &sources); for doc in self.docs.values_mut() { doc.refresh_overlay(&self.index); } diff --git a/crates/vfmt_server/tests/e2e.rs b/crates/vfmt_server/tests/e2e.rs index 90e6589..0219ade 100644 --- a/crates/vfmt_server/tests/e2e.rs +++ b/crates/vfmt_server/tests/e2e.rs @@ -1197,13 +1197,18 @@ fn completion_and_signature_help_round_trip_over_the_wire() { .unwrap_or_else(|| panic!("no signatureHelpProvider in {capabilities:#?}")); assert_eq!(triggers, &["(", ","]); - // 2. One module item, inserting the whole skeleton as a snippet. + // 2. The module item, first of its tier, inserting the whole skeleton as + // a snippet — and keywords beside it, in a later tier. 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]; + let skeletons: Vec<&serde_json::Value> = items + .iter() + .filter(|item| item["sortText"].as_str().is_some_and(|s| s.starts_with('0'))) + .collect(); + assert_eq!(skeletons.len(), 1, "{items:#?}"); + let item = skeletons[0]; assert_eq!(item["label"], "hint_sub"); assert_eq!(item["kind"], 9, "CompletionItemKind.Module"); assert_eq!(item["insertTextFormat"], 2, "InsertTextFormat.Snippet"); @@ -1215,10 +1220,23 @@ fn completion_and_signature_help_round_trip_over_the_wire() { ); assert_eq!(item["textEdit"]["range"]["start"]["character"], 2, "the typed word is replaced"); assert_eq!(item["textEdit"]["range"]["end"]["character"], 8); + // `hint_s` also prefixes no keyword, but `clk` is in scope and the file's + // own words are there, so the general tiers really did run. + assert!( + items.iter().any(|i| i["sortText"].as_str().is_some_and(|s| !s.starts_with('0'))), + "the general tiers answer at the same position: {items:#?}" + ); - // 3. Inside an `always_comb` there is no module item to complete. + // 3. Inside an `always_comb` there is no *module* item to complete — but + // keywords and project names still are. let inside = messages.iter().find(|m| m["id"] == 3).expect("completion response"); - assert!(inside["result"].is_null(), "{inside:#?}"); + let inside_items = inside["result"]["items"] + .as_array() + .unwrap_or_else(|| panic!("no completion list in {inside:#?}")); + assert!( + !inside_items.iter().any(|i| i["sortText"].as_str().is_some_and(|s| s.starts_with('0'))), + "no skeleton belongs in a procedural block: {inside_items:#?}" + ); // 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"); @@ -1273,10 +1291,81 @@ fn a_client_without_snippet_support_gets_the_skeleton_as_plain_text() { 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"); + let item = items + .iter() + .find(|item| item["label"] == "hint_sub") + .unwrap_or_else(|| panic!("no module item in {items:#?}")); + assert_eq!(item["insertTextFormat"], 1, "InsertTextFormat.PlainText"); + let new_text = item["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); } + +/// The general tiers over the wire: keywords, project words and the two +/// places a completion list must not appear. +#[test] +fn keyword_and_project_completion_round_trip_over_the_wire() { + let dir = temp_dir("general"); + std::fs::write(dir.join("other.sv"), "module other;\n logic widget_elsewhere;\nendmodule\n") + .expect("write"); + std::fs::write(dir.join("defs.svh"), "`define WIDGET_MACRO 1\n").expect("write"); + // Line 2 holds the half-typed word, line 3 the same letters in a comment. + let top = "module top;\n logic widget_local;\n assign x = widget\n // widget\nendmodule\n"; + let path = dir.join("top.sv"); + std::fs::write(&path, top).expect("write"); + let root = format!("file://{}", dir.display()); + let uri = format!("file://{}", path.display()); + + let session = [ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(top).expect("json") + )), + // End of `widget` on line 2, mid-expression: no skeleton, everything else. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/completion","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":2,"character":19}}}}}}"# + )), + // End of `// widget` on line 3: inside a comment, so nothing at all. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/completion","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":3,"character":11}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(); + + let messages = talk(&session); + let completion = messages.iter().find(|m| m["id"] == 2).expect("completion response"); + let items = completion["result"]["items"] + .as_array() + .unwrap_or_else(|| panic!("no completion list in {completion:#?}")); + let labelled = |label: &str| items.iter().find(|item| item["label"] == label).cloned(); + + let local = labelled("widget_local").expect("the declaration in scope"); + assert_eq!(local["kind"], 6, "CompletionItemKind.Variable"); + assert!(local["sortText"].as_str().expect("sortText").starts_with('1'), "{local:#?}"); + + let macro_name = labelled("WIDGET_MACRO").expect("a `define name"); + assert!(macro_name["sortText"].as_str().expect("sortText").starts_with('2')); + + let elsewhere = labelled("widget_elsewhere").expect("a word used in the project"); + assert_eq!(elsewhere["kind"], 1, "CompletionItemKind.Text"); + assert!(elsewhere["sortText"].as_str().expect("sortText").starts_with('4')); + + assert!( + !items.iter().any(|item| item["sortText"].as_str().is_some_and(|s| s.starts_with('0'))), + "mid-expression is no place for an instantiation skeleton: {items:#?}" + ); + + // Inside the comment, the server declines outright. + let in_comment = messages.iter().find(|m| m["id"] == 3).expect("completion response"); + assert!(in_comment["result"].is_null(), "{in_comment:#?}"); + + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/vlog_parser/src/lib.rs b/crates/vlog_parser/src/lib.rs index 1eba214..11534a5 100644 --- a/crates/vlog_parser/src/lib.rs +++ b/crates/vlog_parser/src/lib.rs @@ -16,6 +16,7 @@ pub use lexer::{tokenize, LexError}; pub use line_index::LineIndex; pub use parser::{parse, parse_tolerant, ParseDiagnostic, ParseError}; pub use span::TextRange; +pub use token::KEYWORDS; /// Convenience: lex and parse in one step. pub fn parse_source(source: &str) -> Result { diff --git a/crates/vlog_parser/src/token.rs b/crates/vlog_parser/src/token.rs index 321d736..55932d5 100644 --- a/crates/vlog_parser/src/token.rs +++ b/crates/vlog_parser/src/token.rs @@ -110,200 +110,237 @@ impl Token { } } -/// Reserved words we treat as keywords. This covers Verilog-2001 plus the -/// SystemVerilog subset the parser understands. Words not listed here lex as -/// plain identifiers. -pub fn is_keyword(s: &str) -> bool { - matches!( - s, - "module" - | "macromodule" - | "endmodule" - | "interface" - | "endinterface" - | "package" - | "endpackage" - | "program" - | "endprogram" - | "modport" - | "clocking" - | "endclocking" - | "input" - | "output" - | "inout" - | "ref" - | "wire" - | "tri" - | "tri0" - | "tri1" - | "wand" - | "wor" - | "trireg" - | "supply0" - | "supply1" - | "uwire" - | "reg" - | "logic" - | "bit" - | "byte" - | "shortint" - | "int" - | "longint" - | "integer" - | "time" - | "realtime" - | "real" - | "shortreal" - | "string" - | "chandle" - | "event" - | "var" - | "void" - | "signed" - | "unsigned" - | "packed" - | "parameter" - | "localparam" - | "defparam" - | "specparam" - | "type" - | "typedef" - | "enum" - | "struct" - | "union" - | "assign" - | "alias" - | "always" - | "always_comb" - | "always_ff" - | "always_latch" - | "initial" - | "final" - | "begin" - | "end" - | "if" - | "else" - | "case" - | "casex" - | "casez" - // `randcase` is reserved (IEEE 1800 Table B.1) and opens a - // statement of its own; `let` is reserved too and opens an item. - // Both are here rather than matched by text so a declaration can - // never accidentally be named after one. - | "randcase" - | "let" - | "endcase" - | "default" - | "unique" - | "unique0" - | "priority" - | "for" - | "while" - | "repeat" - | "forever" - | "do" - | "foreach" - | "break" - | "continue" - | "return" - | "fork" - | "join" - | "join_any" - | "join_none" - | "disable" - | "wait" - | "posedge" - | "negedge" - | "edge" - | "or" - | "and" - | "nand" - | "nor" - | "xor" - | "xnor" - | "not" - | "buf" - | "bufif0" - | "bufif1" - | "notif0" - | "notif1" - | "pullup" - | "pulldown" - | "generate" - | "endgenerate" - | "genvar" - // Class-related reserved words. `new`, `this`, `super` and `null` - // are deliberately *not* here: they stand in expression position - // and already parse as ordinary names, so promoting them to - // keywords would break `x = new(...)` and `super.f()` for nothing. - | "class" - | "endclass" - | "extends" - | "implements" - | "virtual" - | "pure" - | "extern" - | "rand" - | "randc" - | "local" - | "protected" - | "constraint" - | "covergroup" - | "endgroup" - | "function" - | "endfunction" - | "task" - | "endtask" - | "automatic" - | "static" - | "const" - | "import" - | "export" - | "timeunit" - | "timeprecision" - | "assert" - | "assume" - | "cover" - | "property" - | "endproperty" - | "sequence" - | "endsequence" - | "inside" - | "with" - | "iff" - | "release" - | "force" - | "deassign" - | "primitive" - | "endprimitive" - | "specify" - | "endspecify" - | "table" - | "endtable" - | "small" - | "medium" - | "large" - | "scalared" - | "vectored" - | "highz0" - | "highz1" - | "strong0" - | "strong1" - | "pull0" - | "pull1" - | "weak0" - | "weak1" - | "cmos" - | "rcmos" - | "nmos" - | "pmos" - | "rnmos" - | "rpmos" - | "tran" - | "rtran" - | "tranif0" - | "tranif1" - | "rtranif0" - | "rtranif1" - ) +/// Every reserved word the lexer knows, in the order they are written +/// below. Verilog-2001 plus the SystemVerilog subset the parser understands; +/// words not listed here lex as plain identifiers. +/// +/// [`is_keyword`] and this slice are generated from the same list, so a word +/// can never be one without being the other — which is what lets a completion +/// list offer exactly what the lexer reserves. +macro_rules! keywords { + ($($word:literal),* $(,)?) => { + pub const KEYWORDS: &[&str] = &[$($word),*]; + + /// Whether `s` is one of [`KEYWORDS`]. + pub fn is_keyword(s: &str) -> bool { + matches!(s, $($word)|*) + } + }; +} + +keywords![ + "module", + "macromodule", + "endmodule", + "interface", + "endinterface", + "package", + "endpackage", + "program", + "endprogram", + "modport", + "clocking", + "endclocking", + "input", + "output", + "inout", + "ref", + "wire", + "tri", + "tri0", + "tri1", + "wand", + "wor", + "trireg", + "supply0", + "supply1", + "uwire", + "reg", + "logic", + "bit", + "byte", + "shortint", + "int", + "longint", + "integer", + "time", + "realtime", + "real", + "shortreal", + "string", + "chandle", + "event", + "var", + "void", + "signed", + "unsigned", + "packed", + "parameter", + "localparam", + "defparam", + "specparam", + "type", + "typedef", + "enum", + "struct", + "union", + "assign", + "alias", + "always", + "always_comb", + "always_ff", + "always_latch", + "initial", + "final", + "begin", + "end", + "if", + "else", + "case", + "casex", + "casez", + // `randcase` is reserved (IEEE 1800 Table B.1) and opens a + // statement of its own; `let` is reserved too and opens an item. + // Both are here rather than matched by text so a declaration can + // never accidentally be named after one. + "randcase", + "let", + "endcase", + "default", + "unique", + "unique0", + "priority", + "for", + "while", + "repeat", + "forever", + "do", + "foreach", + "break", + "continue", + "return", + "fork", + "join", + "join_any", + "join_none", + "disable", + "wait", + "posedge", + "negedge", + "edge", + "or", + "and", + "nand", + "nor", + "xor", + "xnor", + "not", + "buf", + "bufif0", + "bufif1", + "notif0", + "notif1", + "pullup", + "pulldown", + "generate", + "endgenerate", + "genvar", + // Class-related reserved words. `new`, `this`, `super` and `null` + // are deliberately *not* here: they stand in expression position + // and already parse as ordinary names, so promoting them to + // keywords would break `x = new(...)` and `super.f()` for nothing. + "class", + "endclass", + "extends", + "implements", + "virtual", + "pure", + "extern", + "rand", + "randc", + "local", + "protected", + "constraint", + "covergroup", + "endgroup", + "function", + "endfunction", + "task", + "endtask", + "automatic", + "static", + "const", + "import", + "export", + "timeunit", + "timeprecision", + "assert", + "assume", + "cover", + "property", + "endproperty", + "sequence", + "endsequence", + "inside", + "with", + "iff", + "release", + "force", + "deassign", + "primitive", + "endprimitive", + "specify", + "endspecify", + "table", + "endtable", + "small", + "medium", + "large", + "scalared", + "vectored", + "highz0", + "highz1", + "strong0", + "strong1", + "pull0", + "pull1", + "weak0", + "weak1", + "cmos", + "rcmos", + "nmos", + "pmos", + "rnmos", + "rpmos", + "tran", + "rtran", + "tranif0", + "tranif1", + "rtranif0", + "rtranif1", +]; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_slice_and_the_predicate_are_the_same_list() { + // They are generated from one `keywords!` invocation, so this can only + // fail if the macro is edited into disagreeing with itself — which is + // exactly the drift the macro exists to prevent. + assert!(KEYWORDS.iter().all(|word| is_keyword(word))); + assert!(!is_keyword("clk"), "an ordinary name is not reserved"); + assert!(!is_keyword("new"), "deliberately not a keyword, see the list"); + assert!(!KEYWORDS.contains(&"clk")); + } + + #[test] + fn no_keyword_is_listed_twice() { + let mut sorted = KEYWORDS.to_vec(); + sorted.sort_unstable(); + let mut unique = sorted.clone(); + unique.dedup(); + assert_eq!(sorted, unique, "a duplicate entry would double a completion list"); + } } diff --git a/docs/features/completion-core/README.md b/docs/features/completion-core/README.md new file mode 100644 index 0000000..75a791f --- /dev/null +++ b/docs/features/completion-core/README.md @@ -0,0 +1,658 @@ +# completion-core + +M5 of the refactoring plan (`docs/features/refactor/README.md`): **general +completion** — keywords and project-wide identifiers merged into M4's +module-hinting response — plus the **0.3.0 version bump**. + +## Goal + +Make `textDocument/completion` answer the question a user actually asks while +typing, instead of only the one M4 could answer. One response, five tiers, +sorted best-first: the instantiation skeleton where one belongs, then the +declarations visible at the cursor, then what the project declares, then every +reserved word the lexer knows, then every identifier used anywhere in the +project. A name appears once, claimed by its best tier. Nothing is offered +inside a comment or a string, and — the other half of the same promise — a name +that appears *only* inside a comment or a string is never a candidate, because +the word list is harvested from the token stream, where comments are trivia and +a string is one token. The scope of "the project" is M1's ladder, unchanged, so +a file the filelist leaves out contributes nothing. + +Completion fires on every keystroke, which is the whole design constraint: no +tier may walk the workspace. The two project-wide tables are built beside the +workspace index, from the same file list, and are replaced with it. + +## Assumptions + +- **The lexer's reserved-word list is the keyword list.** `vlog_parser::token` + now generates `KEYWORDS` (a `&[&str]`) and `is_keyword` from one + `keywords![...]` macro invocation, so a word cannot be one without being the + other. The list is unchanged — 181 words, comments and all — and the parser + suite is green, so lexing behaviour is untouched. Offering a word the parser + does not reserve, or failing to offer one it does, would both be lies; the + macro makes both unrepresentable. +- **A comment is never code and a string is never code.** The harvest takes + `Ident` and `SystemIdent` tokens only. Comments never reach the token stream + at all (the lexer detaches them as trivia), and a string literal is one + `String` token, so neither can contribute a candidate — this is a property of + the lexer, not a filter that could be forgotten. Two `Ident` shapes are + dropped on purpose: a macro usage (`` `WIDTH ``, whose text is the whole + invocation, argument list included — the macro *names* have their own table) + and an escaped identifier (`\my-port`, which needs a terminating space that a + plain word item cannot promise). +- **A buffer that does not lex gets no completions at all.** With no token + stream there is no way to tell a comment from code, and the commonest way to + break the lexer while typing is to open a string or a block comment and keep + going. Declining is the safe half of that trade, and the buffer lexes again as + soon as the quote or the `*/` is typed. Deliberate: the alternative is + offering a completion list *inside* the unterminated string. +- **The index's freshness is the tables' freshness.** The index rebuilds on + `initialize` and on `didSave`, so the project-wide tables do too. An unsaved + edit in *another* buffer is therefore not in the word table until it is + saved — exactly the rule the index has always had (`vfmt-server`'s + invalidation notes). The buffer being typed in is the exception, and needs no + rebuild: its own token stream is already computed on every change, so its + words are harvested per request and an unsaved name is a candidate + immediately. +- **A macro name is written with a backtick where it is used and without one + where it is defined or tested.** See *The backtick ruling* below. +- **`sortText` is a nudge, not a guarantee.** VS Code scores its own fuzzy match + first and uses `sortText` to break ties; a client that sorts purely on + `sortText` gets the tier order exactly. Both are correct behaviour, and the + tests assert what the server sends rather than what any client draws. +- **The response is capped at 512 items** (`LIMIT`), the module tier separately + at 64 (`MODULE_LIMIT`, M4's, unchanged). Justification under *The cap*. + +## Handshakes + +- **Widened in `vlog_parser`** — the only change outside `vfmt_server`. + `token.rs`'s keyword table became a `keywords![...]` macro invocation that + generates both `pub const KEYWORDS: &[&str]` and `pub fn is_keyword`; + `lib.rs` re-exports `KEYWORDS`. `is_keyword` is still a `matches!` over + literals, so the lexer's hot path is byte-for-byte the same code it was. + No word was added, removed or reordered. +- **Consumes `vlog_semantic`**: `Semantics::scopes`/`scope`/`symbol` for the + visible-declarations tier, `WorkspaceIndex::workspace_symbols`/`path`/ + `files`/`defines` (all once per index build, never per request) for the + project-declares tier. Read-only; nothing new is asked of it. + `SymbolKind` → `CompletionItemKind` is a new mapping in `completion.rs` + mirroring the choices `symbols::lsp_kind` already makes for the outline in + the other enum. +- **Consumes `vlog_parser`**: `tokenize` for the word harvest, `KEYWORDS` for + the keyword tier, `defines::DefineKind` to keep `` `undef`` entries out of the + macro table. +- **Consumes `vlog_refactor`** exactly as M4 did — `module_names`, + `module_definition`, `instantiation_plan`, `render_with` — through the + unchanged `module_tier`. Nothing in `vlog_refactor` was touched. +- **Duplicated deliberately, not shared**: `vlog_refactor::ports::visible_in` + answers "is this *one* name visible here" and is `pub(crate)` to that crate; + `completion::visible_symbols` answers "what is visible here". They share the + innermost-scope idea and nothing else, and lifting one to fit both would have + meant widening another crate's API for a second caller that wants a different + answer. Recorded so the lead can overrule it cheaply. +- **Promises `vfmt_server`'s own callers**: `completions` never panics, always + returns items whose `textEdit` replaces exactly the typed word (plus the + backtick, in the macro case), and never returns a module item whose text + differs from what M4 returned — the M4 tests assert the skeleton byte for + byte and still pass. +- **`editors/vscode` needs no change.** No new setting, no new capability: the + completion provider was already advertised, and `snippetSupport` is read the + same way. + +## The tiers + +`sortText` is ``, so the client sorts tier-first and +alphabetically within a tier. + +| Tier | What | `CompletionItemKind` | Where it comes from | +|---|---|---|---| +| `0` | Module instantiation skeletons | `MODULE` | M4, unchanged — module-item position only | +| `1` | Declarations the scope chain at the cursor binds | the declaration's own kind | this file's `Semantics` | +| `2` | Packages, package members, typedefs, classes, modules, `` `define`` names | the declaration's own kind, `CONSTANT` for a macro | `WorkspaceIndex`, tabled at build time | +| `3` | Every reserved word | `KEYWORD` | `vlog_parser::KEYWORDS` | +| `4` | Every identifier used anywhere in the project | `TEXT` | token harvest, tabled at build time | + +Tier 0 is first because at module-item position a fifteen-line skeleton is what +the user is reaching for, and it is the only tier that is *position*-gated at +all: M4's gate (nothing but whitespace before the word on its line, plus +`pairs::analyze`'s scope chain) is unchanged and still declines inside a +procedural block, a function, a class, a connection list and an expression. +Every other tier ignores position entirely — a name is a name wherever it is +written — which is why M4's "nothing is offered here" tests became "no +*skeleton* is offered here". + +Tier 4 deliberately includes names that are **not** visible at the cursor. That +is the point of it: it is the rope / VS Code word-completion tier, and a name +used three files away is a better guess than nothing. It is last, and it is +`TEXT`, so it never pretends to be a resolved symbol. + +Dedup is by label, first tier wins. A name that is both a local declaration and +a word used elsewhere in the project is offered once, in tier 1, with its real +kind and its declaration line as detail. + +## The backtick ruling + +`` `define`` names are the one candidate whose spelling depends on where the +cursor is, so the rule is stated rather than implied: + +- **The cursor follows a backtick** (`` `WI| ``) — the response is *only* macro + names, because nothing else may follow a backtick. Each item is labelled and + inserted as `` `NAME ``, and the replaced range starts at the backtick the + user already typed, so it is never doubled. +- **The cursor does not follow one** (`WI|`) — macro names are offered + alongside everything else, bare, and **no backtick is invented**. Inserting + punctuation the user did not type is how a completion list loses trust, and + bare is the correct text at exactly the places a macro name is written without + a backtick: `` `ifdef NAME ``, `` `ifndef NAME ``, `` `undef NAME ``, + `` `define NAME ``. + +Both spellings are tested. `` `undef`` entries are not offered: vfmt does not +preprocess and cannot say where a name stopped being defined, so a table that +listed them would be pretending to know. + +## The cap + +512 items per response, `isIncomplete` when it truncates. The arithmetic: an +*empty* prefix is the worst case, and 64 modules + 181 keywords + whatever one +scope binds still leaves room for the word tier to appear at all, which a +64-item cap (M4's) would not — the list would have ended inside the keywords. +512 small items is a payload of a few tens of kilobytes, and the tiers fill in +order, so what a truncation drops is the least useful end. + +The module tier keeps its own 64, because it is the one tier that costs +*parsing*: one parse of one defining file per item. Every other tier is a binary +search into a sorted table. + +Truncation is cheap by construction: each tier asks `Items::full()` before +building an item and breaks out of its loop when the answer is yes, so a full +response never formats a `detail` string nobody will read. Skipping that check +cost 8.5 ms on the corpus's empty-prefix request; with it, 212 µs. + +## Performance + +Measured on the 860-file corpus (4.94 MB of source: picorv32, ibex, +common_cells, OpenTitan), release build, aarch64-apple-darwin. The permanent +regression guard is +`completion::tests::a_keystroke_over_the_whole_corpus_stays_in_budget`, which +skips when `corpus/` is not checked out and asserts a deliberately loose 150 ms +per request — it is there to catch an order of magnitude, not to pin a number. + +**Build (once per index rebuild: `initialize`, `didSave`, a settings change):** + +| Step | Time | +|---|---| +| `WorkspaceIndex::build` (pre-existing) | 165 ms | +| `Candidates::build` — the new tables | **94 ms** (word harvest alone: 88 ms) | +| whole `open_roots`: walk + read + index + tables | 344 ms | + +The new tables therefore add ~57 % to what the index build already cost, and +~27 % to the whole rebuild. The word harvest is one extra `tokenize` pass over +the same sources the index reads; it is not shared with the index's own lex +because `WorkspaceIndex::build` does its lexing privately, and asking it to hand +back token streams would be a new cross-crate contract for one caller. + +Deduplicating *during* the harvest rather than after it matters more than the +lexing does: the corpus holds ~900 k identifier tokens and 16 750 distinct +identifiers, and copying every token only to sort the copies away cost 197 ms +against the 88 ms it costs now. + +**Tables and memory:** + +| Table | Entries | Heap | +|---|---|---| +| index names (units + members) | 7 728 | | +| `` `define`` names | 361 | | +| project words | 16 750 | | +| all three | | **~1.4 MiB** | + +**Per request (what a keystroke costs):** + +| Case | Worst of ten, release | Worst of ten, debug | +|---|---|---| +| typed prefix, mid-expression | **298 µs** | 1.3 ms | +| empty prefix (explicit invoke — every tier matches, the cap does the work) | **212 µs** | 1.1 ms | + +A prefix lookup itself is ~76 ns (1 000 lookups in 76 µs): the tables are +sorted case-insensitively, so a match is a `partition_point` and then a +`take_while` over one contiguous run. Nothing allocates a lowercase copy — +`lower_cmp` compares byte iterators. + +The one request that is *not* microseconds is a module-item position, which +still parses up to 64 defining files. That is M4's cost, unchanged and +separately capped. + +## Version 0.3.0 + +Every place `tools/RELEASING.md` says the version lives, plus the install +examples it does not: + +- [x] `Cargo.toml` `[workspace.package] version` → `0.3.0` (all eight crates + inherit it via `version.workspace = true`) +- [x] `Cargo.lock` regenerated by `cargo check --workspace` — eight entries +- [x] `editors/vscode/package.json` `"version"` +- [x] `editors/vscode/package-lock.json` `"version"` in **both** places (top + level and `packages[""]`) +- [x] `README.md` — the `code --install-extension dist/vfmt-0.3.0.vsix` example +- [x] `editors/vscode/README.md` — both install examples +- [x] `tools/RELEASING.md` — the `dist/` listing, the install commands, the + `git tag v0.3.0` example and the appendix's publish commands +- [x] `CHANGELOG.md` — a `0.3.0 — 2026-08-24` section in the existing voice: + one paragraph per area (filelists, rename, ports, module hinting, + completion, editors), each linking to its feature README +- [x] Verified: `target/debug/vfmt --version` → `vfmt 0.3.0`. Nothing + hard-codes a version string in Rust; `vfmt --version` and the server's + `serverInfo.version` both read `env!("CARGO_PKG_VERSION")`. +- [x] Verified: `node editors/vscode/smoke.js target/debug/vfmt-server` → + `smoke: OK` + +Deliberately **not** touched: the `0.2.0` section of `CHANGELOG.md`, +`docs/features/release-prep/README.md` and `TODO.md`'s release entry — those +record what happened at 0.2.0 and are not install instructions. The literal +`0.2.0` strings in `vfmt_core/src/cache.rs`'s and `vfmt/tests/cli.rs`'s +corrupt-cache fixtures are deliberately malformed lines whose version field is +incidental; they exercise the parser, not the version. + +## Status / TODO + +- [x] `KEYWORDS` factored out of the lexer's table without changing lexing +- [x] `candidates.rs`: the two project-wide tables, built with the index +- [x] Tier 1 — visible declarations, with kinds and declaration lines +- [x] Tier 2 — index names and `` `define`` names, with the backtick ruling +- [x] Tier 3 — keywords +- [x] Tier 4 — token-harvested project words, current buffer overlaid live +- [x] Comment/string gate, both directions +- [x] Dedup across tiers, `sortText` tier ordering, prefix filter, cap + + `isIncomplete` +- [x] Every M4 completion test green, module skeletons byte-identical +- [x] e2e stdio round trip for the new tiers +- [x] Corpus performance measured and guarded +- [x] Version 0.3.0 across the workspace, the extension and the docs +- [x] `cargo fmt --all -- --check`, `cargo clippy --all-targets`, + `cargo test --workspace` all clean; `smoke.js` OK + +## Work log + +- **2026-08-24 (dev)** — implemented. + + **Keyword list.** `vlog_parser/src/token.rs`'s `is_keyword` was a 181-arm + `matches!`. Rather than write a second copy of the list, the whole thing is + now one `keywords![...]` invocation of a local `macro_rules!` that expands to + both `pub const KEYWORDS` and `pub fn is_keyword` — so `is_keyword` is still a + `matches!` over literals (no linear scan on the lexer's hot path) and the two + cannot drift. The explanatory comments inside the list survived the move. Two + tests added in `token.rs`; the parser suite (185 → 187 lib tests, all four + targets) is green. + + **Tables (`crates/vfmt_server/src/candidates.rs`, new).** `Candidates` holds + three sorted vectors — index names, macro names, project words — built in + `Workspace::rebuild_index` from the same `collect_sources()` list the index + gets. That is what makes the scope ladder and the open-buffer-beats-disk rule + apply to completion for free, with no second walk. Lookup is + `partition_point` on a case-insensitive comparator, returning a slice. + + **Tiers (`completion.rs`).** `completions` grew a gate + (`in_comment_or_string`, plus "no tokens, no answer") and five tier functions + feeding one `Items` builder that owns dedup, the cap and `isIncomplete`. + M4's `completions` body is now `module_tier`, unchanged except that it is + conditional instead of an early return, and its item gained a `sortText`. + `typed_word` grew two fields: `backtick` (was the run preceded by one) and + `at_line_start` (M4's second gate, now used only by tier 0). + + **Decisions worth flagging to the lead:** + 1. **M4's "nothing is offered" tests had to change meaning.** Nine of them + asserted `completions(...).is_none()` at positions where general + completion is exactly what a user wants (mid-expression, inside an + `always` block, inside a function). They are now "no *skeleton* is + offered here", checked on `sortText`'s tier digit; the skeleton text and + the module gate are untouched, and the e2e assertions changed the same + way. This is the one place the milestone genuinely broadens behaviour + M4 shipped, and it is what the M5 brief asked for — recorded so it is + reviewed rather than assumed. + 2. **The cap went 64 → 512** for the response as a whole, with the module + tier keeping 64. Arithmetic under *The cap*. + 3. **The backtick ruling** — only macros after a backtick, bare macro names + without one, no backtick ever invented. Under *The backtick ruling*. + 4. **`SystemIdent` tokens (`$display`, `$clog2`) are harvested as words.** + They are identifiers used in the project and `$` is already an + identifier character as far as the typed-word scan is concerned, so + `$clo|` completes. Cheap, and it is what "identifiers used anywhere in + the project" says. + 5. **A buffer that does not lex is declined outright** rather than answered + without a comment/string gate. + + **Performance work.** Two measured fixes, both from the corpus harness rather + than from guessing: deduplicating the word harvest during collection (197 ms + → 88 ms) and checking `Items::full()` before building an item (8.5 ms → 212 µs + on the empty-prefix request). Numbers under *Performance*. + + **Version bump** per `tools/RELEASING.md`, checklist above, plus a + `CHANGELOG.md` 0.3.0 section covering M1–M5. + + **Suite**: 1 232 → 1 262 workspace tests, all green; `cargo fmt --all -- + --check` and `cargo clippy --all-targets` clean; `node + editors/vscode/smoke.js target/debug/vfmt-server` → `smoke: OK`. + +## 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, **1262** tests (summed the per-crate + `test result` lines myself rather than trusting the printed total) — + matches the Work log's `1232 → 1262` claim exactly. +- `node editors/vscode/smoke.js target/debug/vfmt-server` — `smoke: OK`. +- `cargo build -p vfmt` then `target/debug/vfmt --version` → `vfmt 0.3.0`. + +All gates: **pass, claims confirmed.** + +### Priority 1 — the keyword-table refactor (`vlog_parser::token`) + +Not eyeballed: extracted both word lists programmatically (regex over +`is_keyword`'s old `matches!` arms vs. the new `keywords![...]` invocation) +and diffed the two lists as Python sets and as ordered lists. + +- Old list: 181 words, no duplicates. New list: 181 words, no duplicates. +- `old_set == new_set` → **True**. `old_words == new_words` (order too) → + **True**. Nothing added, dropped, reordered or typo'd. +- Read the macro expansion by hand: `matches!(s, $($word)|*)` expands to + exactly the same `matches!(s, "module" | "macromodule" | ...)` chain the + old hand-written function was — confirmed textually, not just by claim — + so the lexer's hot path really is byte-for-byte the same generated code. +- `crates/vlog_parser/src/lib.rs`'s diff is the expected one-line + `pub use token::KEYWORDS;`. + +**Confirmed exactly as claimed.** + +### Priority 2 — the nine repurposed M4 tests + the module-skeleton gate + +Counted precisely rather than trusting "nine": `grep -c '.is_none()'` in the +old (`git show HEAD:.../completion.rs`) test module gives **8** call sites +across 6 functions (one of them a 4-case loop), plus **1** more in +`e2e.rs`'s `completion_and_signature_help_round_trip_over_the_wire` (the +`assert!(inside["result"].is_null())` at the always_comb position) — **9 +total**, matching the claim exactly once both files are counted together. + +Diffed the gate itself: `at_module_item`, `enclosing_scopes`, +`is_procedural`, `balanced`, and the `ITEM_SCOPES`/`NOT_ITEM_SCOPES`/ +`PROCEDURAL`/`STATEMENT_END` constants are **byte-identical** between +`git show HEAD:crates/vfmt_server/src/completion.rs` and the working tree — +only a doc comment above `completions` changed (`"module completions"` → +`"completions"`). The gate that decides *where* a skeleton may appear was +not touched. + +Confirmed each of the 9 sites was repurposed consistently: the 8 unit-test +sites now assert `skeletons(&items).is_empty()` (module-tier-only, read off +`sortText`'s digit) rather than `completions(...).is_none()`, and the +e2e site now asserts no item has a `sortText` starting with `'0'` while the +general tiers *do* answer (`items.iter().any(|i| sortText doesn't start +with '0')`) — i.e. it went from "nothing at all" to "everything except a +skeleton", which is exactly the milestone's stated broadening. + +**Confirmed exactly as claimed.** + +### Attacks — comment/string exclusion + +All of the following pass exactly as the feature promises (verified by +reading `in_comment_or_string`/`in_comment` and running the dev's own +tests, which cover every case listed in the brief): + +- Identifier only in a comment, or only in a string → not a candidate + (`a_name_that_only_a_comment_or_a_string_holds_is_never_a_candidate`, + and independently in `candidates.rs`'s + `words_come_from_tokens_so_comments_and_strings_contribute_nothing`). +- Cursor inside a `//` comment, a `/* */` comment, and a string literal → + no response (`nothing_is_offered_inside_a_comment_or_a_string`, all four + sub-cases). +- Cursor immediately after a block comment's `*/` on the same line → code + again, completions answer (`the_byte_after_a_block_comment_is_code_again`). +- An unterminated block comment mid-file → `doc.tokens.is_empty()`, decline + outright (`a_buffer_that_does_not_lex_is_declined_rather_than_guessed_at`). +- Identifier in a string in an **unsaved** buffer overlay: structurally + guaranteed rather than merely tested — `word_tier`'s live scan of + `doc.tokens` filters to `Ident | SystemIdent` (`completion.rs:250-254`), + the same `TokenKind` gate `candidates.rs::is_word` uses for the + persisted table, so a string's contents can never surface as an `Ident` + token regardless of whether the buffer is saved. + +No findings here. + +### Attacks — the backtick + +- `` `de `` completes defines with the range including the + backtick, no doubling — dev's own + `a_backtick_offers_macro_names_and_only_macro_names` pins the exact + replaced range; re-verified by hand. +- Backtick with nothing typed after it (`` ` ``, no macros defined) + → 0 items (probed). With macros defined → all of them, sorted + (probed: `` ` `` against `ALPHA`/`BETA` → `["`ALPHA", "`BETA"]`). +- Backtick inside a comment → `None` (probed: the comment gate in + `completions` runs before the backtick branch is ever reached, so this + is structural, not incidental). +- **Directive keywords (`ifdef`, `endif`, `undef`, `include`, `timescale`, + …) get no completion help anywhere — LOW, not filed as blocking.** + Probed: `` `ifd `` (typing toward `` `ifdef ``) → `None`. + Mechanism: `` `ifdef FOO `` lexes as one `TokenKind::Directive` token + (`vlog_parser/src/token.rs`), so `ifdef`/`endif`/etc. are never `Ident` + tokens (can't reach the word tier) and are deliberately absent from + `KEYWORDS` (the lexer's directive handling is a separate mechanism from + its keyword table, unchanged by this milestone). Typing a backtick then + a directive name routes into the backtick branch's macro-only answer, + which correctly finds no macro named `ifd*` and returns nothing. This + isn't a regression — there was no completion at all before M5 — and it + isn't inside this milestone's stated scope (keywords + project + identifiers), but it's a real, common gap (`` `ifdef `` is about as + frequent as any keyword) that the README's *Assumptions* and *The + backtick ruling* sections don't mention at all. Worth a line in the + README disclosing it, or a follow-up milestone; not blocking M5. + +### Attacks — tiers, dedup, case + +- A name that is both a local declaration and a project word: offered + **once**, tier 1, real kind — dev's own + `a_name_that_is_both_in_scope_and_a_project_word_is_offered_once`; + re-derived independently with a `Data`/`data` pair (see below). +- Module name at item position → skeleton (tier 0); at expression + position → offered as a plain tier-2 index item, `CompletionItemKind:: + MODULE`, `PlainText`, no snippet (probed directly: `sub` at + `assign x = su|` comes back as tier `'2sub'`, not a skeleton). Correct — + matches "a name is a name wherever it is written" for every tier but 0. +- Case-insensitive **prefix** vs. case-sensitive **identity**: probed with + `logic data;` (local) and a project file declaring `logic Data;` + elsewhere. Typing `dat` (prefix, case-insensitive) surfaces **both** + `data` and `Data` as separate items — the prefix match doesn't collapse + them, and dedup (label-keyed) correctly treats them as different SV + identifiers. Exactly as required. +- The cap keeps the **best** tiers, not an arbitrary cut: probed a + workspace where tier 2 alone (600 `localparam`s in one package) exceeds + `LIMIT` on an empty prefix — response is exactly 512 items, all from + tier 2 (`has_word_tier: false`), `isIncomplete: true`. Consistent with + the tiers being filled in strict order and each one's `Items::full()` + guard stopping it immediately; not re-derived from scratch since the + dev's own `a_full_response_is_truncated_and_says_it_is_incomplete` and + the corpus test's "empty prefix fills the response to exactly LIMIT" + already pin the same mechanism. +- Empty prefix at item position: 187 items total, 2 module skeletons + (`sub`, and — see next finding — `top` itself). + +**LOW, informational, not blocking — a module can offer itself as a +self-instantiation skeleton.** Probed: cursor at item position inside +`module top` with nothing typed → tier-0 skeletons offered are `["sub", +"top"]`. `module_tier` calls `vlog_refactor::module_names(ws.index(), "")` +unfiltered by the enclosing module, and that function is M4's, unchanged +(confirmed: `module_tier`'s body is untouched by this milestone). Not a +new bug — an M4-era gap in `vlog_refactor::module_names` — but M5 makes it +far easier to hit in practice: an explicit empty-prefix invoke +(VS Code's Ctrl+Space) at item position is a completion this milestone +specifically added support for (see *The cap*'s "empty prefix" arithmetic), +and it now surfaces "instantiate `top` inside `top`" as a real, clickable +suggestion. Filing against `vlog_refactor::module_names`/`instantiate.rs`, +not against this milestone's own code, since nothing in `completion.rs` or +`candidates.rs` introduced it. + +### Attacks — scope ladder, invalidation, cap arithmetic + +- 2-file + filelist fixture: dev's own + `a_file_outside_the_filelist_contributes_no_words` builds exactly this + (`files.f` listing only `listed.sv`) and confirms `word_unlisted` never + appears. Read the mechanism independently: `Candidates::build` is fed + the same `sources` list `rebuild_index` already restricted by the + filelist, so this is structural, not per-tier filtering. +- Which event updates candidates: confirmed by reading `server.rs` — + `reindex()` (which calls `Workspace::rebuild_index`, which rebuilds + `Candidates`) is called from `DidSaveTextDocument`, from `DidOpen` only + when there is no workspace root, and from `open_roots` at `initialize`. + `DidChangeTextDocument` does **not** call it. This matches the README's + "rebuilds on `initialize` and `didSave`" claim exactly — not "on every + edit". The buffer being typed in is still live because `word_tier` + separately re-scans `doc.tokens` (recomputed per `didChange`) on every + request, independent of the table. Probed the negative case the dev's + own test doesn't cover: edited *another* buffer without calling + `rebuild_index()` — the new word (`ov_in_buffer`) is correctly absent + (only the current buffer's own half-typed `ov` shows up, from the live + per-request scan). The dev's + `another_open_buffer_overlays_disk_once_the_index_is_rebuilt` shows the + positive half (present *after* `rebuild_index()`); together they pin + the exact rule stated in the README. +- Cap arithmetic isn't quadratic: ran the corpus budget test in release + (below). Separately probed a worst-case shape the corpus doesn't + naturally produce — sparse scope/index/keyword tiers (so `word_tier`'s + own `items.full()` guard does *not* short-circuit) against an + artificially huge word table (30 003 distinct identifiers, one file) — + 512 items, `isIncomplete: true`, in **1.66 ms** (release build). Not + quadratic (n log n from the sort, bounded well under any budget this + test would need to guard), and not a finding: `word_tier` does collect + and sort the *whole* prefix-matched slice before applying the cap + rather than stopping at remaining capacity, which is a real but minor + inefficiency (the guard only short-circuits the *whole tier*, not a + partial one) — worth knowing about, not worth blocking on at these + numbers. + +### Version 0.3.0 + +- `grep -rn "0.2.0"` over the whole tree (excluding `target/`): every hit + is one the dev's README lists as deliberately untouched — `CHANGELOG.md`'s + `0.2.0` history section, `TODO.md`'s release-prep line, + `docs/features/release-prep/README.md`'s own history, and the + malformed-cache-line fixtures in `vfmt_core/src/cache.rs` and + `vfmt/tests/cli.rs`. No stray `0.2.0` anywhere else. +- `cargo metadata` — all eight workspace crates report `0.3.0`. + `editors/vscode/package.json` and **both** places in + `package-lock.json` (top level and `packages[""]`) — `0.3.0`. + `Cargo.toml`'s `[workspace.package] version` — `0.3.0`. + `target/debug/vfmt --version` → `vfmt 0.3.0`. +- `CHANGELOG.md`'s `0.3.0` section: read against what actually shipped + (filelists, rename, ports, module hinting, completion, editors) — + accurate, no overclaiming; the completion paragraph's "860 real-world + files answer a request in about 300 µs" matches the measured number + below almost exactly. + +**Confirmed exactly as claimed.** + +### Performance + +Re-ran `a_keystroke_over_the_whole_corpus_stays_in_budget` in `--release` +against the checked-out `corpus/` (860 files): + +``` +corpus: 860 files, 16750 words, 7728 index names; +index+tables built in 344.538ms; +worst request 296.917µs typed / 222.625µs empty +``` + +Matches the README's table almost exactly (298 µs / 212 µs claimed vs. +297 µs / 223 µs measured here — within normal run-to-run noise on a +loaded machine) and the file/word/index counts match exactly (860 / 16 750 +/ 7 728). **Confirmed, not overclaimed.** + +### e2e — real server binary over stdio + +Ran the dev's own `crates/vfmt_server/tests/e2e.rs` tests as part of the +full-suite gate (both pass). Independently drove `target/debug/vfmt-server` +over stdio by hand (a small Python LSP client, not committed anywhere) for +the one case the dev's own e2e test doesn't explicitly assert on: + +- **Keyword completion over the wire** — `initialize` → `didOpen` with + `assign x = alw` → `textDocument/completion` at the cursor. Real + response: 5 items, keyword items `always`/`always_comb`/`always_ff`/ + `always_latch`, each with `"kind": 14` (LSP `Keyword`), `"sortText": + "3always"` etc., and a `textEdit.range` matching exactly the typed + `alw`. Confirms the keyword tier works correctly end-to-end. +- Project-word completion from another file, and inside-comment decline: + already covered by the dev's own + `keyword_and_project_completion_round_trip_over_the_wire`, which I + re-ran in isolation (`cargo test -p vfmt_server --test e2e + keyword_and_project_completion -- --nocapture`) — passes standalone. + +**LOW, informational — the Status/TODO line "e2e stdio round trip for the +new tiers" (plural) is slightly optimistic.** `e2e.rs` asserts scope +(tier 1), index/macro (tier 2), word (tier 4), and the comment decline +over the wire, but never asserts a keyword-tier (tier 3) item by label or +`kind` — only that no item's `sortText` starts with `'0'`. The keyword +tier itself is thoroughly unit-tested +(`every_keyword_the_lexer_knows_is_offered`, +`the_keyword_tier_is_exactly_the_lexers_list`) and, per the probe above, +does work correctly over the wire — this is a documentation-accuracy / +test-coverage nit, not a functional gap. Not fixed (adding the assertion +is a one-line addition to the dev's existing e2e test, left for the dev +or a follow-up rather than touching test files outside a small, +unambiguous fix). + +### Cleanup + +All probing was done with temporary `qa_probe_*` `#[test]` functions added +to `crates/vfmt_server/src/completion.rs`'s existing `tests` module, run +with `--nocapture`, then fully reverted. Verified clean: +`grep -rn qa_probe crates/` — zero hits; `git diff --stat` for this file +matches the pre-QA baseline exactly (898 changed lines, same as +`git status` showed before QA started); final `cargo fmt --all -- --check` ++ `cargo clippy --all-targets` + `cargo test --workspace` (1262 passed) +re-run clean after cleanup. + +### Verdict + +**Ship.** Both priority items (the keyword-list refactor and the nine +repurposed tests) are verified programmatically, not by eyeballing, and +hold up exactly as claimed. Every other claim in the Work log — the three +sorted tables, the five tiers, the backtick ruling, the cap arithmetic, +the performance numbers, the version bump — checked out under direct +attack. Three LOW/informational findings, none blocking: + +1. Preprocessor directive names (`` `ifdef ``, `` `endif ``, …) get no + completion assistance anywhere — a real, common gap, undisclosed in + the README, but out of this milestone's stated scope + (`vlog_parser::token`'s directive handling, untouched by M5). +2. A module can offer itself as a self-instantiation skeleton at an + empty-prefix, item-position completion — pre-existing to + `vlog_refactor::module_names` (M4), newly easy to trigger via M5's + empty-prefix support. +3. The e2e suite's "new tiers" coverage doesn't explicitly assert the + keyword tier by label/kind over the wire, though it works correctly + (independently verified by hand against the real binary). + +No fixes applied to feature code — nothing found rose to "small, +unambiguous" (typo/missing assertion) territory; all three are judgment +calls for the dev/lead. No commits, no edits to `TODO.md` or the umbrella +`docs/features/refactor/README.md`. + +## Review + +**2026-08-24 — lead.** Reviewed after QA's ship verdict — the first +milestone through with no rework round; gates run independently (1262 +tests, 0 failures, clippy silent). The keyword-table refactor was verified +set- and order-identical programmatically, the five-tier/sortText design is +the boring right shape, and 212–298 µs per keystroke over the 860-file +corpus with a budget test guarding it is exactly the performance story +wanted. The nine repurposed M4 tests are a genuine, intended broadening +(general completion where skeletons were rightly refused), with the +skeleton gate itself byte-identical. Dev's backtick ruling (never invent +punctuation) and decline-on-unlexable-buffer are accepted as argued. +QA's three LOW findings, ruled: (1) no completion help on preprocessor +directive words — accepted gap, now named in the umbrella backlog; +(2) self-instantiation skeletons — pre-existing M4 nit, backlog; +(3) e2e keyword-tier assertion — nice-to-have, not required. QA's +transparency note about a briefly clobbered-and-restored working file is +appreciated; the independent gate run confirms the tree. Accepted; M5 and +the 0.3.0 bump are 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 42bc3d3..91ef5fa 100644 --- a/docs/features/refactor/README.md +++ b/docs/features/refactor/README.md @@ -96,6 +96,18 @@ the work is reviewed**. Owner-priority items first (2026-08-24). - [ ] Declare-missing-signals companion action (generate `logic` decls for unconnected skeleton ports) — backlog +### Completion (owner request, 2026-08-24 evening) +- [x] **Keyword completion** — Verilog/SV keywords offered as completion + items alongside everything else → `docs/features/completion-core/README.md` (M5) +- [x] **Project-wide identifier completion** — names visible in the current + scope (semantics-ranked first) plus identifiers used anywhere in the + project scope (filelist, else workspace walk, else same-directory — + M1's ladder), harvested from *tokens* so comments and strings never + contribute candidates; no completions offered while typing inside a + comment or string → M5 +- [x] **Version 0.3.0** — workspace + extension bump with a CHANGELOG entry + covering the whole refactoring layer (M1–M5) → M5 + ### Structural refactorings (backlog, post-M4) - [ ] **Extract module** from a selected statement range (infer ports from read/driven sets) — the flagship, hardest one @@ -108,6 +120,8 @@ the work is reviewed**. Owner-priority items first (2026-08-24). `wire-reg-mixup` lint rule's fix slot) - [ ] **Move typedef/function/localparam into a package**; update imports - [ ] **Organize imports** (sort, dedupe, drop unused) +- [ ] **Completion for preprocessor directive words** (`` `ifdef`` …) and + suppressing self-instantiation skeletons — two LOW QA finds from M5 - [ ] **Rename module together with its file** (`module-filename` rule agreement; needs LSP `workspace/willRenameFiles` plumbing) @@ -169,6 +183,9 @@ commit — in order: all instantiations, exposed as code actions + `workspace/executeCommand`. 4. **M4 `refactor-instantiate`** — instantiation completion snippets, auto-connect, signature help in connection lists. +5. **M5 `completion-core`** — keyword + project-wide identifier completion + (token-harvested, comment/string-free), merged with M4's module + snippets; version bump to 0.3.0. 5. **Backlog** — the unchecked structural items above, re-planned when the first four have soaked. @@ -180,7 +197,8 @@ commit — in order: - [x] M2 refactor-rename — done, QA clean after one rework round, reviewed - [x] M3 refactor-ports — done, QA clean after one rework round, reviewed - [x] M4 refactor-instantiate — done, QA clean after one rework round, reviewed -- [ ] Backlog triage after M4 +- [x] M5 completion-core — done, QA clean first pass, reviewed +- [ ] Backlog triage after M5 ## Work log diff --git a/editors/vscode/README.md b/editors/vscode/README.md index ee89f89..b26372e 100644 --- a/editors/vscode/README.md +++ b/editors/vscode/README.md @@ -46,14 +46,14 @@ catches "the binary moved" or "the handshake broke" without launching VS Code. ```bash npm ci # installs vscode-languageclient (the only dependency) npx @vscode/vsce package -code --install-extension vfmt-0.2.0.vsix +code --install-extension vfmt-0.3.0.vsix ``` Then reload VS Code and open a `.v`/`.sv`/`.vh`/`.svh` file. `tools/release.sh` from the repo root does all of the above (plus the release binaries and checksums) and drops the `.vsix` in `dist/`, so -`code --install-extension dist/vfmt-0.2.0.vsix` is the one-command path. +`code --install-extension dist/vfmt-0.3.0.vsix` is the one-command path. `editors/vscode/LICENSE` is a copy of the repo's MIT license and is what lets `vsce package` run without `--skip-license`. If you are packaging a fork that dropped `package.json`'s `repository` field, add `--allow-missing-repository`. diff --git a/editors/vscode/package-lock.json b/editors/vscode/package-lock.json index abd4f96..da9febc 100644 --- a/editors/vscode/package-lock.json +++ b/editors/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "vfmt", - "version": "0.2.0", + "version": "0.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "vfmt", - "version": "0.2.0", + "version": "0.3.0", "license": "MIT", "dependencies": { "vscode-languageclient": "9.0.1" diff --git a/editors/vscode/package.json b/editors/vscode/package.json index ec2946d..70fc13c 100644 --- a/editors/vscode/package.json +++ b/editors/vscode/package.json @@ -2,7 +2,7 @@ "name": "vfmt", "displayName": "vfmt — Verilog/SystemVerilog", "description": "Formatting, diagnostics, navigation and semantic highlighting for Verilog and SystemVerilog, served by the vfmt language server.", - "version": "0.2.0", + "version": "0.3.0", "publisher": "REPLACE-ME", "license": "MIT", "repository": { diff --git a/tools/RELEASING.md b/tools/RELEASING.md index eee4a8d..e3b5475 100644 --- a/tools/RELEASING.md +++ b/tools/RELEASING.md @@ -12,7 +12,7 @@ Four files, one number. Keep them identical. | File | What to change | |---|---| -| `Cargo.toml` | `[workspace.package] version` — **all seven crates inherit it** via `version.workspace = true`, so this is the only Rust edit | +| `Cargo.toml` | `[workspace.package] version` — **all eight crates inherit it** via `version.workspace = true`, so this is the only Rust edit | | `Cargo.lock` | regenerated by any `cargo` command; run `cargo check --workspace` and commit the result | | `editors/vscode/package.json` | `"version"` | | `editors/vscode/package-lock.json` | `"version"` in **both** places (the top level and the `packages[""]` entry) | @@ -61,9 +61,9 @@ recreated on every run. ``` dist/ - vfmt-0.2.0-aarch64-apple-darwin - vfmt-server-0.2.0-aarch64-apple-darwin - vfmt-0.2.0.vsix + vfmt-0.3.0-aarch64-apple-darwin + vfmt-server-0.3.0-aarch64-apple-darwin + vfmt-0.3.0.vsix SHA256SUMS ``` @@ -111,11 +111,11 @@ npx @vscode/vsce package --out ../../dist/vfmt-.vsix ```bash # the CLI and the server: anywhere on PATH -install -m 755 dist/vfmt-0.2.0-aarch64-apple-darwin ~/.local/bin/vfmt -install -m 755 dist/vfmt-server-0.2.0-aarch64-apple-darwin ~/.local/bin/vfmt-server +install -m 755 dist/vfmt-0.3.0-aarch64-apple-darwin ~/.local/bin/vfmt +install -m 755 dist/vfmt-server-0.3.0-aarch64-apple-darwin ~/.local/bin/vfmt-server # the editor extension: sideload, no marketplace involved -code --install-extension dist/vfmt-0.2.0.vsix +code --install-extension dist/vfmt-0.3.0.vsix ``` Publishing the artifacts is a matter of attaching `dist/`'s contents plus @@ -123,8 +123,8 @@ Publishing the artifacts is a matter of attaching `dist/`'s contents plus gate is green: ```bash -git tag -a v0.2.0 -m 'vfmt 0.2.0' -git push origin v0.2.0 +git tag -a v0.3.0 -m 'vfmt 0.3.0' +git push origin v0.3.0 ``` ## Appendix — if the owner ever publishes to a marketplace @@ -151,10 +151,10 @@ The commands themselves, once those exist: # VS Code Marketplace: needs an Azure DevOps PAT for the publisher npx @vscode/vsce publish -p "$VSCE_TOKEN" # ... or publish an already-built package -npx @vscode/vsce publish --packagePath dist/vfmt-0.2.0.vsix -p "$VSCE_TOKEN" +npx @vscode/vsce publish --packagePath dist/vfmt-0.3.0.vsix -p "$VSCE_TOKEN" # Open VSX (VSCodium, Gitpod, Cursor): needs an Eclipse Foundation account -npx ovsx publish dist/vfmt-0.2.0.vsix -p "$OVSX_TOKEN" +npx ovsx publish dist/vfmt-0.3.0.vsix -p "$OVSX_TOKEN" ``` Both tokens are secrets. Neither belongs in this repo, in a shell history, or