Compare commits

...
5 Commits
Author SHA1 Message Date
lucio 464929262b Release 0.65.0: module instantiation syntax highlighting
release / build-and-publish (push) Successful in 3m40s
ci / corpus (push) Successful in 21s
ci / checks (push) Failing after 10s
Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both
package-lock.json spots); notes in CHANGELOG.md (## 0.65.0) and
editors/vscode/CHANGELOG.md. TODO §69.
Gates: no local cargo/tools/gates.sh run on this Windows host (the release
relies on Gitea CI). Locally: all 10 VS Code extension node tests pass
(including the new semanticTokens_test.js, 75 checks).
2026-11-19 02:40:10 -08:00
lucio e4db0ac1fc TODO §69: colour module instantiations by role, with # matching parameters
Add AST-guided semantic token overrides in lucisv_server/src/tokens/instantiation.rs
and cross-file overlay lookup in tokens.rs without changing the 14-type wire legend:
- module/interface/extends names -> class (pkg:: prefixes -> namespace)
- parameter-list # (never delays), .PARAM overrides and parameter values -> parameter
- instance names (declarations, gate instances, bind lists, hierarchical uses) -> function
- named port connections (.port, implicit .port, .*) -> property
- port connection signals -> variable

Enable editor.semanticHighlighting.enabled by default for [verilog] and
[systemverilog] in editors/vscode/package.json and contribute semanticTokenScopes
so every role renders with a distinct, non-white colour across VS Code themes.
Add editors/vscode/semanticTokens_test.js (75 checks, passing under node --test).
Rust tests/fmt/clippy deferred to Gitea CI (no cargo toolchain on this Windows host).
2026-11-19 02:38:42 -08:00
lucioandClaude Mythos 5.2 857b82d58a Release 0.64.0: completion that keeps up with typing
ci / checks (push) Successful in 1m35s
ci / corpus (push) Successful in 31s
release / build-and-publish (push) Successful in 7m3s
Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both
package-lock.json spots); notes in CHANGELOG.md (## 0.64.0) and
editors/vscode/CHANGELOG.md. TODO §68.1, §68.2.
Gates: no local tools/gates.sh run (owner's call, 2026-11-09: the release
relies on Gitea CI). Locally: every crate suite green in the lanes' dev
and QA runs, corpus 814/6, and on this commit's tree the release
lucisv-server and lucisv-mcp pass smoke.js / mcp_smoke.js (both modes)
and the node tests (9 files). Not yet seen in a running VS Code.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-17 15:46:21 -08:00
lucioandClaude Mythos 5.2 14213f6a93 TODO §68.2: an unfinished port connection stays in its own entry, and its errors wait until you pause
Parser (tolerant mode only, parser/recover_list.rs): a lone '.', a
'.name(' left open at its line end and a trailing ',' in a named list are
recovered inside their entry — always a diagnostic, never silent; strict
mode and valid code are unchanged (1 026 inputs old vs new: identical
strict results and trees, byte-identical CLI output; corpus 814/6).
Server (state/port_grace.rs): diagnostics that start inside the entry the
last edit touched, in a named-connection list of an instance, are withheld
for 1.5 s and released by the loop's timeout, an edit elsewhere or a save;
a pulling client that supports it gets workspace/diagnostic/refresh.
A trailing ',' in a named list is now reported in tolerant mode too.
Dev + QA (Opus 5.5); QA failed one gate (lucisv_mcp qa_f1), one fix
round, re-check passed: parser 521, server 1954, mcp 383, formatter 352.
Not yet seen in a running VS Code. docs/features/port-entry-grace; topo
rows for §68.1 and §68.2.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-17 15:40:58 -08:00
lucioandClaude Mythos 5.2 c1076f9405 TODO §68.1: begin+Enter writes the end, clock+reset templates, this file's names first, keyword ghosts, port items that write .name()
Server (lucisv_server only): on_type/auto_end.rs — the newline answer
adds the owed end at the owning statement's indentation (lucisv.autoEnd);
always_ff @( / always @( ghosts and popup templates lead with posedge clk
or negedge rst_n; completion tiers put names declared and used in this
buffer ahead of the index, templates and keywords (completion/buffer.rs);
inline/keywords.rs ghosts the rest of a keyword and follows the popup's
selected entry (lucisv.inlineKeywords); connection items keep connected
ports as a second group marked 'connected' and insert name($1), pre-filled
with a same-named signal (completion/connection.rs).
Extension: typing.js sends the newline on-type request itself when
editor.formatOnType is off and restores the cursor; the inline-completion
context is converted to LSP shapes.
Dev + QA (Opus 5.5) + one fix round; unit 1823, e2e 102, node 9 files,
smoke OK. Not yet seen in a running VS Code.
docs/features/completion-ux.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-17 14:39:32 -08:00
49 changed files with 6277 additions and 273 deletions

No files matched your search

+80
View File
@@ -4,6 +4,86 @@ All notable changes to lucisv 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.65.0 — 2026-11-19
### Module instantiation syntax highlighting
(`docs/features/instantiation-highlighting`; TODO §69.)
- **Every part of a module instantiation gets its own colour.** Module names,
instance names, `.PARAM` overrides, `.port` names and connected signals used
to collapse to the same default foreground colour whenever the instantiated
module lived in another file or a theme left bare semantic tokens unstyled.
The language server now layers AST-guided semantic token overrides (and
cross-file `ExternalResolutions` lookups) over the existing 14-type legend:
- **Module / interface names** (`uart_core`, `pkg::uart_core` with `pkg` as
`namespace`, and lone `bind` targets) highlight as `class`.
- **`#` and parameters share one colour** (`parameter`), distinct from `()`:
the `#` introducing a module, class, `extends`, instantiation or
parameterized-type parameter list, every `.PARAM` override (`.` and name),
and parameter values inside `#(...)` all carry `parameter`. Delay `#`
tokens (`#5`, `#(1:2:3)`) are left unemitted.
- **Instance names** (`u_uart`, gate instances, `bind` instance lists, and
hierarchical uses like `u_uart.sig`) highlight as `function`.
- **Port names** (`.clk_i` dot and name, implicit `.rst_ni`, and wildcard
`.*`), including unfinished entries being typed, highlight as `property`.
- **Port connections** (`clk`, `data_q`) stay `variable` so signals keep one
consistent colour across the file.
- **VS Code: semantic highlighting on by default with theme-safe scope maps.**
`configurationDefaults` enables `editor.semanticHighlighting.enabled` for
`[verilog]` and `[systemverilog]` (user settings still win), and
`contributes.semanticTokenScopes` maps the language's semantic token types to
distinct TextMate scopes so every role renders in colour across Dark+, Dark
Modern, Light+, GitHub Dark, One Dark Pro and Visual Studio Dark.
## 0.64.0 — 2026-11-17
### Completion that keeps up with typing
(`docs/features/completion-ux`, `docs/features/port-entry-grace`; TODO §68.)
- **`begin` + Enter writes the `end`.** The newline on-type answer, when
the line above ends in `begin` (or `begin : label`) and a block is still
open, also inserts `end` on the line after the new one, at the
indentation of the statement that owns the `begin`; the cursor stays on
the new, indented line. Nothing is added when the blocks already balance
(an `end` under the owner or under a `begin` on its own line counts), nor
for a `begin` left open inside an `ifdef` region that has an `else`.
Setting `lucisv.autoEnd` (default on). The VS Code extension sends the
request itself when `editor.formatOnType` is off.
- **`always_ff @(` and `always @(` expand with clock and reset**:
`posedge clk or negedge rst_n`, both names tab stops, as the ghost text
and as the first popup template. The clock-only forms follow.
- **This file's names rank first.** The popup's order is now: the scope at
the cursor, names declared anywhere in this buffer, words used in it,
then the workspace index, templates, keywords and project words.
- **Keyword ghosts.** Two or more letters of a keyword show the rest as
grey inline text (Tab accepts); with the popup open the ghost follows its
selected entry. A word that is exactly a name the buffer declares gets
none. A `.v` file is offered Verilog-2005 keywords only. Setting
`lucisv.inlineKeywords` (default on). The `begin` ghost now also appears
for a `begin` typed inside a block that already balances.
- **Port suggestions.** After `.` in an instance, unconnected ports come
first and already-connected ones follow, marked `connected`; they used to
be left out. Accepting a port inserts `name()` with the cursor inside,
pre-filled with a same-named signal when one is visible; parameter lists
(`#(.`) behave the same.
- **An unfinished connection stays in its own entry.** In the editor's
tolerant parse, a lone `.`, a `.name(` still open at the end of its line
and a trailing `,` are each recovered inside their entry — always with a
diagnostic — so the rest of the list and the file still parse, colour and
lint. Strict parsing, and so the formatter and the CLI, are unchanged.
- **Errors on the connection being typed wait.** Diagnostics that start
inside the entry the last edit touched, in a named-connection list of an
instance, are withheld and published after 1.5 s without typing, on an
edit elsewhere, or on save. A client that pulls diagnostics and supports
it is sent `workspace/diagnostic/refresh`. Nothing outside that entry is
ever withheld.
- **Changed: a trailing `,` in a named connection list (`.a(x),)`) is now
reported in the editor.** The formatter and the CLI always refused it;
the editor's tolerant parse used to accept it silently. Format Selection
elsewhere in such a file now works instead of refusing the whole file.
## 0.63.1 — 2026-11-11
### Sticky scroll shows every layer
Generated
+9 -9
View File
@@ -97,7 +97,7 @@ dependencies = [
[[package]]
name = "lucisv"
version = "0.63.1"
version = "0.65.0"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.63.1"
version = "0.65.0"
[[package]]
name = "lucisv_mcp"
version = "0.63.1"
version = "0.65.0"
dependencies = [
"lucisv_core",
"serde",
@@ -126,7 +126,7 @@ dependencies = [
[[package]]
name = "lucisv_server"
version = "0.63.1"
version = "0.65.0"
dependencies = [
"lsp-server",
"lsp-types",
@@ -262,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.63.1"
version = "0.65.0"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.63.1"
version = "0.65.0"
dependencies = [
"lucisv_core",
"vlog_formatter",
@@ -279,11 +279,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.63.1"
version = "0.65.0"
[[package]]
name = "vlog_refactor"
version = "0.63.1"
version = "0.65.0"
dependencies = [
"vlog_formatter",
"vlog_parser",
@@ -292,7 +292,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.63.1"
version = "0.65.0"
dependencies = [
"vlog_parser",
]
+1 -1
View File
@@ -13,7 +13,7 @@ members = [
]
[workspace.package]
version = "0.63.1"
version = "0.65.0"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
+70
View File
@@ -7193,3 +7193,73 @@ line.
- Known limit: a layer with no `begin` (a one-statement `if`, a case item
without `begin`) has no fold and so no pinned line; a `begin` written on
its own line pins that `begin` line, not the `always` above it.
## 68. Completion that keeps up with typing (planned 2026-11-17, owner's order)
Five asks from the owner, about the VS Code extension. Two serial lanes
(`lucisv_server` depends on `vlog_parser`, so they are not independent):
68.1 first, then 68.2. Each lane: one dev, then one QA, both Opus 5.5.
### 68.1 Lane A — auto-`end`, templates, ranking, keyword ghosts, port items
Feature README: `docs/features/completion-ux/README.md`. Files:
`crates/lucisv_server/src/{on_type.rs,inline.rs,templates.rs,pairs.rs,settings.rs,main.rs}`,
`crates/lucisv_server/src/completion/*`, new modules beside them where a
file is near 600 production lines, `crates/lucisv_server/tests/e2e.rs`,
`editors/vscode/{extension.js,package.json,smoke.js,README.md}` and a new
`editors/vscode/*_test.js` if the extension logic is factored out. No
parser, formatter, linter or semantic crate change.
- [x] **`begin` + Enter writes the `end`** (owner: "more like begin +
<return>, the cursor should be the next line of begin, at the correct
indentation, and ready for the first statement"). The newline on-type
answer, when the line above ends in `begin` (or `begin : label`) and
the file has an unclosed `begin`, also inserts `end` on the line after
the new one, at the indentation of the statement the `begin` belongs
to; the cursor stays on the new, indented line. No `end` when the
blocks already balance. Setting `lucisv.autoEnd` (default on). The
extension sends the request itself when `editor.formatOnType` is off
and puts the cursor back.
- [x] **`always_ff @(` / `always @(` expand with clock and reset**:
`posedge ${1:clk} or negedge ${2:rst_n}`, both tab stops, in the ghost
and as the first popup template; the clock-only form stays available
second.
- [x] **Names from the current file rank first** in the popup: declared
anywhere in this buffer, then words used in it, ahead of other files'
names and of keywords.
- [x] **Keyword ghosts**: a typed prefix of a keyword shows the rest of it
as grey inline text (Tab accepts), following the popup's selected item
when the popup is open. Setting `lucisv.inlineKeywords` (default on).
- [x] **Port items**: unconnected ports first; already-connected ports
listed after them, marked `connected` in the dimmed detail; accepting
a port writes `.name($1)` with the cursor inside the parentheses.
### 68.2 Lane B — no rushed errors on the connection being typed
Feature README: `docs/features/port-entry-grace/README.md`. Files:
`crates/vlog_parser/src/parser/instance.rs` (+ its tests),
`crates/lucisv_server/src/{diagnostics.rs,server/diagnostics.rs,state/*}`.
- [x] Parser recovery keeps an unfinished connection (`.`, `.name(` open to
the end of its line, a missing `,` before the next `.name`) inside its
own entry — still a diagnostic, never silent — so the rest of the file
parses, colours and lints as if the entry were complete.
- [x] The server withholds the diagnostics that fall inside the entry the
last edit touched, and releases them after a quiet period or when the
next edit lands elsewhere.
## 69. Module instantiation syntax highlighting (2026-11-17, owner's order)
Feature README: `docs/features/instantiation-highlighting/README.md`. Files:
`crates/lucisv_server/src/{tokens.rs,tokens/instantiation.rs}`,
`editors/vscode/{package.json,.vscodeignore,semanticTokens_test.js}`,
`docs/features/{lucisv-server,large-file-mode}/README.md`.
- [x] Distinct semantic highlights across module instantiations (14-type wire
legend unchanged): module name (`class`), `#` + `.PARAM` overrides +
parameter values (`parameter`, distinct from `()`), instance name
(`function`), `.port`/`.*` (`property`), and port connections
(`variable`), including unfinished entries while typing.
- [x] `configurationDefaults` enables `editor.semanticHighlighting.enabled` and
`semanticTokenScopes` maps `verilog`/`systemverilog` roles to distinct,
non-white TextMate scopes across themes.
@@ -0,0 +1,144 @@
//! Tiers 2 and 3: what the buffer being typed in declares, and the words it
//! uses (TODO §68.1, `completion-ux`).
//!
//! The current file first: a name this buffer declares anywhere — in another
//! module, a sibling block, a function three screens down — and then a word
//! it merely uses, both ahead of what other files declare and ahead of the
//! templates and keywords. Both are read from the buffer's own `Semantics`
//! and token stream, recomputed on every change, so an unsaved declaration
//! ranks as soon as it is typed. Tier 1 (the scope chain) still comes first:
//! what is visible at the cursor is a better answer than what is merely in
//! the file.
use std::collections::HashSet;
use lsp_types::CompletionItemKind;
use vlog_parser::token::TokenKind;
use vlog_semantic::Symbol;
use super::word::Word;
use super::{completion_kind, declaration_detail, Items, TIER_BUFFER_WORD, TIER_DECLARED};
use crate::candidates::{rank_cmp, starts_with_ignore_case, Query};
use crate::state::Document;
/// Tier 2: every declaration in the buffer, whatever scope holds it.
pub(super) fn declared_tier(items: &mut Items, doc: &Document, word: &Word, fuzzy: Option<&Query>) {
let symbols: Vec<&Symbol> = doc.semantics.symbols().iter().collect();
for symbol in matching(symbols, |symbol| symbol.name.as_str(), word, fuzzy) {
if items.full() {
break;
}
items.simple(
&symbol.name,
completion_kind(symbol.kind),
TIER_DECLARED,
declaration_detail(doc, symbol),
);
}
}
/// Tier 3: every identifier the buffer's token stream holds, except the one
/// being typed — offering the user their own half-word back is noise.
pub(super) fn buffer_word_tier(
items: &mut Items,
doc: &Document,
word: &Word,
fuzzy: Option<&Query>,
) {
if items.full() {
return;
}
let mut seen = HashSet::new();
let words: Vec<&str> =
buffer_words(doc, word.start).filter(|name| seen.insert(*name)).collect();
for name in matching(words, |name| name, word, fuzzy) {
if items.full() {
break;
}
items.simple(name, CompletionItemKind::TEXT, TIER_BUFFER_WORD, "used in this file".into());
}
}
/// The candidates `word` reaches, in the order they are offered: by prefix
/// below the fuzzy floor (in the buffer's own order), ranked by subsequence
/// score from it up — the house rule every tier applies.
fn matching<'a, T: Copy + 'a>(
candidates: Vec<T>,
name: impl Fn(T) -> &'a str,
word: &Word,
fuzzy: Option<&Query>,
) -> Vec<T> {
match fuzzy {
None => candidates
.into_iter()
.filter(|c| starts_with_ignore_case(name(*c), &word.text))
.collect(),
Some(query) => {
let mut hits: Vec<(T, _)> =
candidates.into_iter().filter_map(|c| Some((c, query.score(name(c))?))).collect();
hits.sort_by(|a, b| rank_cmp((name(a.0), a.1), (name(b.0), b.1)));
hits.into_iter().map(|(c, _)| c).collect()
}
}
}
/// Every identifier the buffer holds, as the project-word tier counts one —
/// `Ident` and `SystemIdent` only, neither a macro usage nor an escaped
/// identifier — but not the token starting at `typing`, the word under the
/// cursor.
fn buffer_words(doc: &Document, typing: u32) -> impl Iterator<Item = &str> {
doc.tokens
.iter()
.filter(move |token| token.span.start != typing)
.filter(|token| matches!(token.kind, TokenKind::Ident | TokenKind::SystemIdent))
.map(|token| token.text.as_str())
.filter(|text| !text.starts_with('`') && !text.starts_with('\\'))
}
#[cfg(test)]
mod tests {
use crate::completion::harness::*;
use crate::completion::*;
const TOP: &str = "\
module top;
logic data_q;
always_comb begin
da
end
endmodule
module other;
logic data_other;
assign data_word = 1;
always_comb al_used = 0;
endmodule
";
#[test]
fn this_files_declarations_and_words_rank_after_the_scope_and_before_other_files() {
let (_tree, ws, uri, position) = asking("bufferrank", TOP, " da");
let items = items(completions(&ws, &uri, position, true));
let tier_of = |label: &str| tier(find(&items, label).unwrap_or_else(|| panic!("{label}")));
assert_eq!(tier_of("data_q"), TIER_SCOPE, "visible at the cursor");
assert_eq!(tier_of("data_other"), TIER_DECLARED, "declared in another module of this file");
assert_eq!(tier_of("data_word"), TIER_BUFFER_WORD, "only used in this file");
assert_eq!(tier_of("data"), TIER_INDEX, "a port only `sub.sv` declares");
assert!(TIER_SCOPE < TIER_DECLARED && TIER_DECLARED < TIER_BUFFER_WORD);
assert!(TIER_BUFFER_WORD < TIER_INDEX && TIER_INDEX < TIER_TEMPLATE);
assert!(TIER_TEMPLATE < TIER_KEYWORD && TIER_KEYWORD < TIER_WORD);
}
#[test]
fn a_word_this_file_uses_sorts_ahead_of_the_keywords() {
let top = TOP.replace(" da\n", " al\n");
let (_tree, ws, uri, position) = asking("bufferkw", &top, " al");
let items = items(completions(&ws, &uri, position, true));
let sort = |label: &str| {
find(&items, label)
.and_then(|i| i.sort_text.clone())
.unwrap_or_else(|| panic!("{label}"))
};
assert!(sort("al_used") < sort("always"), "{items:#?}");
assert!(sort("al_used") < sort("always_ff"));
}
}
@@ -0,0 +1,102 @@
//! What a connection-list entry inserts (TODO §68.1, `completion-ux`).
//!
//! After the `.` of `sub u_sub (.cl|` or `sub #(.WI|`, accepting a port or a
//! parameter writes the whole entry — `.clk(|)` with the cursor inside the
//! parentheses — rather than the bare name. When the instantiating scope can
//! see a net, variable or port of the same name (a parameter, for the
//! parameter list), it is pre-filled as the placeholder: `.clk(${1:clk})`,
//! one Tab to keep it, one keystroke to replace it.
//!
//! The bare name stays the answer where the snippet would be wrong: a client
//! that never said it reads snippets, a `(` already written after the word
//! being replaced (re-editing `.clk(x)`'s name), and a name the snippet
//! grammar would have to escape (an escaped identifier).
use std::collections::HashSet;
use vlog_semantic::SymbolKind;
use super::snippet_hole;
use super::tiers::visible_symbols;
use super::word::Word;
use crate::signature;
use crate::state::Document;
/// A connection-list entry, beyond its name.
pub(super) struct Connection {
/// Whether the list already connects this port elsewhere — it sorts after
/// the rest and is marked `connected`.
pub(super) connected: bool,
/// The snippet accepting it writes, or `None` for the bare name.
pub(super) snippet: Option<String>,
}
/// Everything about the cursor's entry that every candidate's insertion
/// shares: whether to write the parentheses, and the names a placeholder may
/// be pre-filled with.
pub(super) struct EntrySite<'a> {
wrap: bool,
visible: HashSet<&'a str>,
}
impl<'a> EntrySite<'a> {
/// The entry being typed at `word`, in a list of `kind`.
pub(super) fn new(
doc: &'a Document,
word: &Word,
kind: signature::Kind,
snippets: bool,
) -> EntrySite<'a> {
let wrap = snippets && !paren_follows(&doc.text, word.start);
let admits = |symbol_kind: SymbolKind| match kind {
signature::Kind::Ports => {
matches!(symbol_kind, SymbolKind::Net | SymbolKind::Var | SymbolKind::Port)
}
signature::Kind::Params => {
matches!(symbol_kind, SymbolKind::Param | SymbolKind::LocalParam)
}
};
let visible = match wrap {
true => visible_symbols(&doc.semantics, word.start)
.into_iter()
.filter(|symbol| admits(symbol.kind))
.map(|symbol| symbol.name.as_str())
.collect(),
false => HashSet::new(),
};
EntrySite { wrap, visible }
}
/// The entry for the port or parameter `name`.
pub(super) fn connection(&self, name: &str, connected: bool) -> Connection {
let plain = name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
let snippet = (self.wrap && plain).then(|| {
let fill = if self.visible.contains(name) { name } else { "" };
format!("{name}({})", snippet_hole(1, fill))
});
Connection { connected, snippet }
}
}
/// Whether a `(` follows the identifier run that starts at `start`, past any
/// spaces or tabs — the entry is already written and only its name is being
/// re-edited.
fn paren_follows(text: &str, start: u32) -> bool {
let Some(rest) = text.get(start as usize..) else { return false };
let rest = rest.trim_start_matches(|c: char| c.is_ascii_alphanumeric() || c == '_' || c == '$');
rest.trim_start_matches([' ', '\t']).starts_with('(')
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_paren_after_the_word_means_the_entry_is_already_written() {
assert!(paren_follows(".clk(x)", 1));
assert!(paren_follows(".cl (x)", 1));
assert!(!paren_follows(".cl", 1));
assert!(!paren_follows(".cl\n (x)", 1), "only on the same line");
assert!(!paren_follows(".cl, .b(x)", 1));
}
}
+125 -38
View File
@@ -16,6 +16,7 @@ use lsp_types::CompletionResponse;
use vlog_parser::token::{Token, TokenKind};
use vlog_semantic::{MemberSite, Semantics, Surface, SymbolKind, WorkspaceIndex};
use super::connection::{self, Connection};
use super::site::balanced;
use super::tiers::innermost_scope;
use super::word::{Sep, Word};
@@ -54,6 +55,7 @@ pub(super) fn member_answer(
doc: &Document,
word: &Word,
offset: u32,
snippets: bool,
) -> Option<CompletionResponse> {
let members = match word.spine.as_ref() {
Some(spine) => {
@@ -69,7 +71,7 @@ pub(super) fn member_answer(
// question, and it is the commonest completion position in RTL there
// is: a `.` opening a connection or a parameter override.
None => match word.sep? {
Sep::Dot => connection_members(ws, doc, word)?,
Sep::Dot => connection_members(ws, doc, word, snippets)?,
Sep::Scope => return None,
},
};
@@ -77,7 +79,7 @@ pub(super) fn member_answer(
// Prefix below [`FUZZY_MIN`], subsequence from it up — the house rule, on
// the same `Query` every other tier scores with.
let fuzzy = (word.text.len() >= FUZZY_MIN).then(|| Query::new(&word.text));
let matched: Vec<Member> = match &fuzzy {
let mut matched: Vec<Member> = match &fuzzy {
None => members
.into_iter()
.filter(|member| starts_with_ignore_case(&member.name, &word.text))
@@ -95,12 +97,20 @@ pub(super) fn member_answer(
}
};
// A connection list's already-connected ports go after the rest, each
// group in the order it was matched in (`completion-ux`, TODO §68.1).
matched.sort_by_key(|member| member.connection.as_ref().is_some_and(|c| c.connected));
let mut items = Items::new(doc, word.range(offset));
for member in matched {
if items.full() {
break;
}
items.simple(&member.name, completion_kind(member.kind), TIER_MEMBER, member.detail);
let kind = completion_kind(member.kind);
match member.connection {
Some(connection) => items.connection(&member.name, kind, member.detail, connection),
None => items.simple(&member.name, kind, TIER_MEMBER, member.detail),
}
}
// **The `isIncomplete` trap, in its member form.** The request that
// matters is the one the trigger character fires, with nothing typed
@@ -132,6 +142,9 @@ struct Member {
name: String,
kind: SymbolKind,
detail: String,
/// What a connection list's entry carries beyond its name; `None` for
/// every other member.
connection: Option<Connection>,
}
/// What a member declared **in another file** shows beside its name.
@@ -225,10 +238,17 @@ fn members_at(
/// list to what may legally be written; it never offers a name the
/// resolution could not find.
///
/// Ports already connected earlier in the same list are dropped. `None` — no
/// Ports already connected elsewhere in the same list stay on offer, marked
/// (`completion-ux`, 2026-11-17 — they used to be dropped), and every entry
/// carries the `.name($1)` snippet [`connection::entry`] spells. `None` — no
/// popup — when the cursor is not in such a list at all, or is inside a
/// connected *expression* (`.clk(` opens a paren of its own).
fn connection_members(ws: &Workspace, doc: &Document, word: &Word) -> Option<Vec<Member>> {
fn connection_members(
ws: &Workspace,
doc: &Document,
word: &Word,
snippets: bool,
) -> Option<Vec<Member>> {
let dot = word.start.checked_sub(1)?;
let list = signature::enclosing_list(&doc.tokens, word.start)?;
let open = doc.tokens.get(list.open)?.span.end;
@@ -250,27 +270,33 @@ fn connection_members(ws: &Workspace, doc: &Document, word: &Word) -> Option<Vec
signature::Kind::Ports => SymbolKind::Port,
};
let taken = connected_names(&doc.tokens, list.open, dot);
let entry = connection::EntrySite::new(doc, word, list.kind, snippets);
let mut members = Members::new();
let mut push = |name: &str, kind: SymbolKind, detail: String| {
let connection = entry.connection(name, taken.contains(name));
members.push_member(Member {
name: name.to_string(),
kind,
detail,
connection: Some(connection),
});
};
match doc.semantics.instantiable_scope(&list.module) {
// This file declares the module: its own scope is the whole answer,
// and no other file's module of the same name may override it.
Some(scope) => {
let scope = doc.semantics.scope(scope)?;
for symbol in scope.symbols.iter().filter_map(|&id| doc.semantics.symbol(id)) {
if symbol.kind == wanted && !taken.contains(symbol.name.as_str()) {
members.push(&symbol.name, symbol.kind, declaration_detail(doc, symbol));
if symbol.kind == wanted {
push(&symbol.name, symbol.kind, declaration_detail(doc, symbol));
}
}
}
None => {
for (name, defs) in ws.index().members_of(&list.module) {
let Some(def) = defs.first() else { continue };
if def.kind == wanted && !taken.contains(name) {
members.push(
name,
def.kind,
indexed_detail(def.kind, def.type_name.as_deref()),
);
if def.kind == wanted {
push(name, def.kind, indexed_detail(def.kind, def.type_name.as_deref()));
}
}
}
@@ -282,12 +308,11 @@ fn connection_members(ws: &Workspace, doc: &Document, word: &Word) -> Option<Vec
/// token at `open`, except the one whose `.` sits at `skip` — the entry being
/// typed, which must stay on offer.
///
/// Dropping them is the friendlier half of a choice the other way round would
/// be simpler: in a sixty-port instantiation the fifty-five already connected
/// are the ones the user is *not* looking for, and a popup that keeps offering
/// them is a popup they scroll past. It cannot mislead — a name dropped here
/// is one the buffer already spells two lines up — and a re-edited entry is
/// still offered, because its own dot is the one `skip` names.
/// In a sixty-port instantiation the fifty-five already connected are the ones
/// the user is *not* looking for, so they sort after the rest and say so; they
/// are not dropped (`completion-ux`, 2026-11-17), because a port connected
/// twice by mistake is exactly the one a user goes looking for. A re-edited
/// entry is not marked, because its own dot is the one `skip` names.
fn connected_names(tokens: &[Token], open: usize, skip: u32) -> HashSet<&str> {
let mut taken = HashSet::new();
let mut depth = 0i32;
@@ -328,8 +353,12 @@ impl Members {
}
fn push(&mut self, name: &str, kind: SymbolKind, detail: String) {
if self.seen.insert(name.to_string()) {
self.out.push(Member { name: name.to_string(), kind, detail });
self.push_member(Member { name: name.to_string(), kind, detail, connection: None });
}
fn push_member(&mut self, member: Member) {
if self.seen.insert(member.name.clone()) {
self.out.push(member);
}
}
@@ -823,28 +852,55 @@ endmodule
assert_eq!(wiring_labels("conn_typed", ".cl"), vec!["clk"]);
}
/// The answer against [`WIRING`] in the order the client shows it — by
/// `sortText` — as `(label, marked connected)` pairs.
fn wiring_order(name: &str, hole: &str) -> Vec<(String, bool)> {
let top = WIRING.replace(" HOLE\n", &format!(" {hole}\n"));
let (_tree, ws, uri, position) = opened(Tree::new(name), &top, hole);
let mut found = items(completions(&ws, &uri, position, true));
found.sort_by(|a, b| a.sort_text.cmp(&b.sort_text));
found
.into_iter()
.map(|item| {
let marked = item
.label_details
.as_ref()
.and_then(|d| d.description.as_deref())
.is_some_and(|d| d == "connected");
(item.label, marked)
})
.collect()
}
fn pairs(list: &[(&str, bool)]) -> Vec<(String, bool)> {
list.iter().map(|(name, marked)| (name.to_string(), *marked)).collect()
}
#[test]
fn a_connection_list_answers_after_a_comma_and_across_a_newline() {
assert_eq!(wiring_labels("comma", ".clk(clk), ."), vec!["data", "ready"]);
let expected = pairs(&[("data", false), ("ready", false), ("clk", true)]);
assert_eq!(wiring_order("comma", ".clk(clk), ."), expected);
assert_eq!(
wiring_labels("newline", ".clk(clk),\n ."),
vec!["data", "ready"],
wiring_order("newline", ".clk(clk),\n ."),
expected,
"an indented continuation line is the ordinary way this is written",
);
}
/// Already-connected ports are dropped: in a sixty-port instantiation the
/// ones still to wire are the whole of what the user is looking for.
/// Already-connected ports sort after the ones still to wire and say so
/// (`completion-ux`, 2026-11-17 — they used to be dropped): in a
/// sixty-port instantiation the ones still to wire are what the user is
/// looking for, but a port connected twice by mistake is findable.
#[test]
fn a_port_already_connected_is_not_offered_again() {
fn a_port_already_connected_is_offered_last_and_marked() {
assert_eq!(
wiring_labels("taken", ".clk(clk), .data(d), ."),
vec!["ready"],
"two written, one left",
wiring_order("taken", ".clk(clk), .data(d), ."),
pairs(&[("ready", false), ("clk", true), ("data", true)]),
"two written, one left, and the two after it",
);
// …and the entry being *re-typed* is still offered, because the dot
// the cursor follows is the one that is skipped.
assert_eq!(wiring_labels("retype", ".clk(clk), .data(d), .re"), vec!["ready"]);
// …and the entry being *re-typed* is not marked, because the dot the
// cursor follows is the one that is skipped.
assert_eq!(wiring_order("retype", ".clk(clk), .data(d), .re"), pairs(&[("ready", false)]));
}
#[test]
@@ -945,17 +1001,21 @@ endmodule
}
#[test]
fn a_port_item_inserts_the_bare_name_and_shows_its_declaration() {
fn a_port_item_writes_the_whole_entry_and_shows_its_declaration() {
let top = WIRING.replace(" HOLE\n", " .\n");
let tree = Tree::new("portitem");
let (_tree, ws, uri, position) = opened(tree, &top, " .");
let answer = items(completions(&ws, &uri, position, true));
let data = find(&answer, "data").expect("the port");
assert_eq!(data.kind, Some(CompletionItemKind::FIELD));
// The user types the `(` themselves; inventing it would be guessing
// at what is connected.
assert_eq!(inserted(data), "data");
assert_eq!(data.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
// `.data(|)`: the parentheses come with it, the cursor inside
// (`completion-ux`, 2026-11-17). Nothing named `data` is visible in
// `wiring_top`, so the placeholder is empty…
assert_eq!(inserted(data), "data(${1})");
assert_eq!(data.insert_text_format, Some(InsertTextFormat::SNIPPET));
// …while `clk` is, so it is pre-filled.
let clk = find(&answer, "clk").expect("the clock");
assert_eq!(inserted(clk), "clk(${1:clk})");
// The declaration line carries the direction and the width, which is
// the whole of what a connection list needs to know.
assert_eq!(data.detail.as_deref(), Some("input logic [WIDTH-1:0] data,"));
@@ -965,6 +1025,33 @@ endmodule
}
}
#[test]
fn a_port_item_is_the_bare_name_where_a_snippet_would_be_wrong() {
// A `(` already after the word: only the name is being re-edited.
let top = WIRING.replace(" HOLE\n", " .da(d)\n");
let (_tree, ws, uri, position) = opened(Tree::new("portparen"), &top, " .da");
let answer = items(completions(&ws, &uri, position, true));
assert_eq!(inserted(find(&answer, "data").expect("the port")), "data");
// A client without snippet support gets the name, as before.
let top = WIRING.replace(" HOLE\n", " .\n");
let (_tree, ws, uri, position) = opened(Tree::new("portplain"), &top, " .");
let answer = items(completions(&ws, &uri, position, false));
let data = find(&answer, "data").expect("the port");
assert_eq!(inserted(data), "data");
assert_eq!(data.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
}
#[test]
fn a_parameter_item_is_pre_filled_from_a_visible_parameter() {
let top = WIRING
.replace("module wiring_top;\n", "module wiring_top;\n localparam int WIDTH = 16;\n")
.replace("wiring_sub u_sub (", "wiring_sub #(.) u_sub (");
let (_tree, ws, uri, position) = opened(Tree::new("paramfill"), &top, "#(.");
let answer = items(completions(&ws, &uri, position, true));
assert_eq!(inserted(find(&answer, "WIDTH").expect("the parameter")), "WIDTH(${1:WIDTH})");
assert_eq!(inserted(find(&answer, "DEPTH").expect("the other")), "DEPTH(${1})");
}
/// A **non-ANSI** port list writes its directions in the module body, so
/// the header alone names the ports and the body types them. Both halves
/// bind a `Port`, so the list is the same.
+77 -18
View File
@@ -1,7 +1,7 @@
//! `textDocument/completion` — module hinting, templates, keywords, and every
//! name the project uses.
//!
//! One response, six tiers, ordered by `sortText`:
//! One response, eight tiers, ordered by `sortText`:
//!
//! 0. **module names** — at module-item position only, every module the
//! workspace declares whose name contains what is typed. The item inserts
@@ -10,12 +10,15 @@
//! 2026-08-30);
//! 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,
//! 2. **what this file declares** — every declaration in the buffer, in any
//! scope (`buffer.rs`, `completion-ux` 2026-11-17);
//! 3. **what this file uses** — every identifier its token stream holds;
//! 4. **what the project declares** — packages, their members, typedefs,
//! classes, modules and `` `define`` names, from the workspace index;
//! 3. **templates** — `if`/`case`/`always_ff`/declaration skeletons with
//! 5. **templates** — `if`/`case`/`always_ff`/declaration skeletons with
//! tabstops, offered only where the construct may be written;
//! 4. **keywords** — every reserved word `vlog_parser` knows;
//! 5. **project words** — every identifier the in-scope files' *token
//! 6. **keywords** — every reserved word `vlog_parser` knows;
//! 7. **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
@@ -47,8 +50,9 @@
//! list included;
//! * `module` — tier 0, and the instantiation planning `inline.rs` and
//! `instantiate.rs` share;
//! * `tiers` — tiers 1 to 5, the five ordinary tiers in the order they fill
//! the response.
//! * `buffer` — tiers 2 and 3, the current file's declarations and words;
//! * `tiers` — the other ordinary tiers, in the order they fill the
//! response.
//!
//! Functions a sibling file calls are `pub(super)`; the four `pub(crate)`
//! entry points other modules of the crate use keep their paths through the
@@ -58,9 +62,9 @@
use std::collections::HashSet;
use lsp_types::{
CompletionItem, CompletionItemKind, CompletionList, CompletionResponse, CompletionTextEdit,
Documentation, InsertTextFormat, InsertTextMode, MarkupContent, MarkupKind, Position, Range,
TextEdit, Uri,
CompletionItem, CompletionItemKind, CompletionItemLabelDetails, CompletionList,
CompletionResponse, CompletionTextEdit, Documentation, InsertTextFormat, InsertTextMode,
MarkupContent, MarkupKind, Position, Range, TextEdit, Uri,
};
use vlog_parser::token::{Comment, TokenKind};
use vlog_parser::TextRange;
@@ -71,6 +75,8 @@ use crate::candidates::Query;
use crate::state::{Document, Workspace};
use crate::symbols::kind_label;
use crate::templates::Template;
use buffer::{buffer_word_tier, declared_tier};
use connection::Connection;
use member::member_answer;
use module::module_tier;
use site::{at_module_item, at_statement, enclosing_scopes};
@@ -85,6 +91,8 @@ pub(crate) use module::module_header;
pub(crate) use site::at_instantiation_site;
pub(crate) use tiers::layout_at;
mod buffer;
mod connection;
#[cfg(test)]
mod harness;
mod member;
@@ -134,11 +142,19 @@ const TIER_MODULE: char = '0';
/// would say there is a ranking against the other tiers to express, and there
/// is not.
const TIER_MEMBER: char = '0';
/// A connection list's already-connected ports: after every port still to
/// connect, inside the same exclusive answer (`completion-ux`).
const TIER_CONNECTED: char = '1';
const TIER_SCOPE: char = '1';
const TIER_INDEX: char = '2';
const TIER_TEMPLATE: char = '3';
const TIER_KEYWORD: char = '4';
const TIER_WORD: char = '5';
/// What this buffer declares anywhere, and then the words it uses — the
/// current file ahead of every other file and of the templates and keywords
/// (`completion-ux`, TODO §68.1).
const TIER_DECLARED: char = '2';
const TIER_BUFFER_WORD: char = '3';
const TIER_INDEX: char = '4';
const TIER_TEMPLATE: char = '5';
const TIER_KEYWORD: char = '6';
const TIER_WORD: char = '7';
/// What a multi-line item tells the client about its own whitespace.
///
@@ -203,7 +219,7 @@ pub fn completions(
// A `.` or a `::` admits exactly one kind of name too — a member of what
// stands before it — so the answer is only those. See [`member_answer`].
if word.sep.is_some() {
return member_answer(ws, doc, &word, offset);
return member_answer(ws, doc, &word, offset, snippets);
}
// Both position gates read the same scope chain, and neither can be true
@@ -225,10 +241,12 @@ pub fn completions(
let mut items = Items::new(doc, word.range(offset));
module_tier(&mut items, ws, doc, &word, at_item);
scope_tier(&mut items, doc, &word, fuzzy.as_ref());
declared_tier(&mut items, doc, &word, fuzzy.as_ref());
buffer_word_tier(&mut items, doc, &word, fuzzy.as_ref());
index_tier(&mut items, ws, &word, fuzzy.as_ref());
template_tier(&mut items, ws, doc, &word, snippets, at_item, at_statement);
keyword_tier(&mut items, &word);
word_tier(&mut items, ws, doc, &word, fuzzy.as_ref());
word_tier(&mut items, ws, &word, fuzzy.as_ref());
// **The `isIncomplete` trap.** VS Code asks the server again on the next
// keystroke *only* when the last answer said it was incomplete; otherwise
// it filters the list it already holds. A complete two-character prefix
@@ -307,13 +325,54 @@ impl Items {
self.push(item);
}
/// A port or parameter after a connection list's `.`: the bare name, or
/// the `name($1)` entry when the connection carries one, and a dimmed
/// `connected` beside the label when the list already connects it.
fn connection(
&mut self,
name: &str,
kind: CompletionItemKind,
detail: String,
connection: Connection,
) {
if self.full() || self.seen.contains(name) {
return;
}
let tier = if connection.connected { TIER_CONNECTED } else { TIER_MEMBER };
let format = match connection.snippet {
Some(_) => InsertTextFormat::SNIPPET,
None => InsertTextFormat::PLAIN_TEXT,
};
let item = CompletionItem {
label: name.to_string(),
kind: Some(kind),
detail: Some(detail),
label_details: connection.connected.then(|| CompletionItemLabelDetails {
detail: None,
description: Some("connected".to_string()),
}),
sort_text: Some(format!("{tier}{name}")),
insert_text_format: Some(format),
text_edit: Some(CompletionTextEdit::Edit(TextEdit {
range: self.range,
new_text: connection.snippet.unwrap_or_else(|| name.to_string()),
})),
..Default::default()
};
self.push(item);
}
/// One template: the skeleton it inserts, the word it is reached by, and
/// the shape it expands to.
///
/// A client that never said it understands snippets gets the same text
/// with every hole filled in rather than nothing at all — the M4 ruling,
/// applied to a body whose defaults were chosen so that the result parses.
fn template(&mut self, template: &Template, layout: &Layout, snippets: bool) {
///
/// `rank` is the template's place in the registry, which is what orders the
/// templates among themselves: the label alone would put `always @(*)`
/// before the clocked blocks.
fn template(&mut self, template: &Template, rank: usize, layout: &Layout, snippets: bool) {
if self.full() || self.seen.contains(template.label) {
return;
}
@@ -329,7 +388,7 @@ impl Items {
// types to reach the item — otherwise `if` would not match
// `if begin/end` at all.
filter_text: Some(template.prefix.to_string()),
sort_text: Some(format!("{TIER_TEMPLATE}{}", template.label)),
sort_text: Some(format!("{TIER_TEMPLATE}{rank:03}{}", template.label)),
insert_text_format: Some(match snippets {
true => InsertTextFormat::SNIPPET,
false => InsertTextFormat::PLAIN_TEXT,
+26 -59
View File
@@ -13,7 +13,6 @@
use std::collections::HashSet;
use lsp_types::CompletionItemKind;
use vlog_parser::token::TokenKind;
use vlog_parser::KEYWORDS;
use vlog_refactor::Layout;
use vlog_semantic::{Semantics, Symbol};
@@ -66,7 +65,7 @@ pub(super) fn scope_tier(items: &mut Items, doc: &Document, word: &Word, fuzzy:
/// 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> {
pub(super) 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);
@@ -158,7 +157,7 @@ pub(super) fn template_tier(
}
let layout = layout_at(ws, doc, word.start);
let dialect = templates::dialect(doc.path.as_deref());
for template in templates::for_dialect(dialect) {
for (rank, template) in templates::for_dialect(dialect).enumerate() {
if items.full() {
break;
}
@@ -168,7 +167,7 @@ pub(super) fn template_tier(
if !starts_with_ignore_case(template.prefix, &word.text) {
continue;
}
items.template(template, &layout, snippets);
items.template(template, rank, &layout, snippets);
}
}
@@ -205,45 +204,26 @@ pub(super) fn keyword_tier(items: &mut Items, word: &Word) {
}
}
/// Tier 5: identifiers used anywhere in the project scope.
/// Tier 7: 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.
pub(super) fn word_tier(
items: &mut Items,
ws: &Workspace,
doc: &Document,
word: &Word,
fuzzy: Option<&Query>,
) {
/// 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 by
/// tier 3 (`buffer.rs`), so an unsaved edit still contributes immediately.
pub(super) fn word_tier(items: &mut Items, ws: &Workspace, word: &Word, fuzzy: Option<&Query>) {
// 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;
}
// The buffer's own words were offered by tier 3 already, so only the
// prebuilt table is read here; a name in both is offered once anyway,
// because `Items` drops a repeated label.
let names: Vec<&str> = match fuzzy {
None => {
let mut names: Vec<&str> =
ws.candidates().words(&word.text).iter().map(String::as_str).collect();
names
.extend(buffer_words(doc).filter(|text| starts_with_ignore_case(text, &word.text)));
names.sort_unstable();
names.dedup();
names
}
None => ws.candidates().words(&word.text).iter().map(String::as_str).collect(),
Some(query) => {
// The table's hits come back ranked; the buffer's own words are
// scored here and the two are ranked together, so a name the user
// typed a moment ago sits where its match deserves rather than
// after everything the table knows.
let mut hits = ws.candidates().words_fuzzy(query, LIMIT);
let hits = ws.candidates().words_fuzzy(query, LIMIT);
// A full return is a truncation; see `index_tier`.
items.incomplete |= hits.len() >= LIMIT;
hits.extend(buffer_words(doc).filter_map(|name| Some((name, query.score(name)?))));
hits.sort_by(|a, b| rank_cmp(*a, *b));
// A name in both lists is offered once: `Items` drops the second
// by label, so no dedup is needed here.
hits.into_iter().map(|(name, _)| name).collect()
}
};
@@ -255,21 +235,6 @@ pub(super) fn word_tier(
}
}
/// Every identifier the buffer being typed in holds, as tier 5 counts one.
///
/// The live half of the tier: the prebuilt table is as of the last index
/// rebuild, and this is the buffer's own token stream, recomputed on every
/// change. The filter is `candidates::is_word`'s, in the other direction —
/// `Ident` and `SystemIdent` only, and neither a macro usage nor an escaped
/// identifier.
fn buffer_words(doc: &Document) -> impl Iterator<Item = &str> {
doc.tokens
.iter()
.filter(|token| matches!(token.kind, TokenKind::Ident | TokenKind::SystemIdent))
.map(|token| token.text.as_str())
.filter(|text| !text.starts_with('`') && !text.starts_with('\\'))
}
#[cfg(test)]
mod tests {
use super::*;
@@ -374,7 +339,7 @@ endmodule
let at_item = offering("alwitem", "top.sv", "module top;\n alw\nendmodule\n", " alw");
assert_eq!(
template_labels(&at_item),
["always_ff @(posedge clk)", "always_ff with reset", "always_comb begin/end"],
["always_ff with reset", "always_ff @(posedge clk)", "always_comb begin/end"],
"and `alw` finds every one of them"
);
@@ -419,7 +384,7 @@ endmodule
let always = offering("dialectalw", "top.v", "module top;\n alw\nendmodule\n", " alw");
assert_eq!(
template_labels(&always),
["always @(posedge clk)", "always @(posedge clk or negedge rst_n)", "always @(*)"],
["always @(posedge clk or negedge rst_n)", "always @(posedge clk)", "always @(*)"],
"and no always_ff, which a .v file's compiler would reject"
);
}
@@ -637,7 +602,8 @@ endmodule
#[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.
// arrive as one of this file's declarations (tier 2, `completion-ux`)
// — never as a visible declaration.
let top = "\
module top;
initial begin : b
@@ -650,8 +616,8 @@ 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:#?}");
let item = find(&items, "inner_only").expect("known as a declaration at least");
assert_eq!(tier(item), TIER_DECLARED, "{item:#?}");
}
// ------------------------------------------------------------------
@@ -750,12 +716,13 @@ endmodule
fn the_short_answers_are_what_they_always_were() {
let (_tree, mut ws, uri) = typing("fuzzygolden");
for (typed, expected) in [
// `c` itself is in the list because the buffer being typed in
// holds it as an `Ident` token — behaviour this round did not
// touch, pinned here because a golden that quietly lost it would
// be a change.
("c", vec!["c", "c_l_k_scatter", "celsius", "clk_osc_en_q"]),
("ce", vec!["ce", "celsius"]),
// `c` itself used to be in the list, because the buffer being
// typed in holds it as an `Ident` token. `completion-ux`
// (2026-11-17) dropped it on purpose: the buffer-word tier skips
// the token under the cursor, and offering the user their own
// half-word back is noise.
("c", vec!["c_l_k_scatter", "celsius", "clk_osc_en_q"]),
("ce", vec!["celsius"]),
] {
let found = items(after_typing(&mut ws, &uri, typed));
let named: Vec<&str> = found
+82 -25
View File
@@ -27,16 +27,19 @@
//! because the editor prepends that line's own indentation when it inserts the
//! snippet; see `render`. See `docs/features/inline-templates/README.md`.
use lsp_types::{Position, Range, Uri};
use lsp_types::{Position, Range, SelectedCompletionInfo, Uri};
use vlog_parser::token::{Token, TokenKind};
use vlog_parser::TextRange;
use vlog_refactor::{Layout, Site};
use crate::completion;
use crate::on_type;
use crate::pairs;
use crate::state::{Document, Workspace};
use crate::templates::{self, Dialect};
mod keywords;
/// One line of a body: how many indent steps it sits in, and its text. The
/// same shape `templates.rs` writes its skeletons in.
type Line = (u8, &'static str);
@@ -96,6 +99,13 @@ const BEGIN_BODY: &[Line] = &[(0, ""), (1, "$0"), (0, "end")];
const FORK_BODY: &[Line] = &[(0, ""), (1, "$0"), (0, "join")];
const GENERATE_BODY: &[Line] = &[(0, ""), (1, "$0"), (0, "endgenerate")];
/// The event control of a flop with an async active-low reset, both edges a
/// tabstop. First in both `always` families (TODO §68.1): the commoner flop.
const CLOCK_AND_RESET: &[Line] =
&[(0, "posedge ${1:clk} or negedge ${2:rst_n}) begin"), (1, "$0"), (0, "end")];
/// The clock-only event control, one cycle away.
const CLOCK_ONLY: &[Line] = &[(0, "posedge ${1:clk}) begin"), (1, "$0"), (0, "end")];
/// Every construct that offers ghost text.
///
/// The order is the order `triggered` tries them, which only matters when two
@@ -156,19 +166,16 @@ const TRIGGERS: &[Trigger] = &[
opener: EVENT,
dialect: Some(Dialect::SystemVerilog),
gate: Unclosed::Paren,
bodies: &[&[(0, "posedge ${1:clk}) begin"), (1, "$0"), (0, "end")]],
bodies: &[CLOCK_AND_RESET, CLOCK_ONLY],
},
Trigger {
keyword: "always",
opener: EVENT,
dialect: None,
gate: Unclosed::Paren,
// Two items, clocked first: `always @(` is overwhelmingly a flop, and
// the client cycles to the second with one keystroke.
bodies: &[
&[(0, "posedge ${1:clk}) begin"), (1, "$0"), (0, "end")],
&[(0, "*) begin"), (1, "$0"), (0, "end")],
],
// Three items, clocked first: `always @(` is overwhelmingly a flop,
// and the client cycles to the next with one keystroke.
bodies: &[CLOCK_AND_RESET, CLOCK_ONLY, &[(0, "*) begin"), (1, "$0"), (0, "end")]],
},
Trigger {
keyword: "begin",
@@ -237,7 +244,15 @@ pub struct InlineItems {
/// `None` rather than an empty list wherever there is nothing to say: an
/// editor treats both the same, and `null` is the cheaper answer to a request
/// that arrives on every keystroke.
pub fn inline_completions(ws: &Workspace, uri: &Uri, position: Position) -> Option<InlineItems> {
///
/// `selected` is the request's `context.selectedCompletionInfo` — the popup's
/// selected entry, when one is showing. Only the keyword ghost reads it.
pub fn inline_completions_in_context(
ws: &Workspace,
uri: &Uri,
position: Position,
selected: Option<&SelectedCompletionInfo>,
) -> Option<InlineItems> {
let doc = ws.document(uri)?;
// No token stream, no answer — the same trade `completion.rs` makes. A
// half-typed string or block comment is what breaks the lexer, and those
@@ -260,14 +275,24 @@ pub fn inline_completions(ws: &Workspace, uri: &Uri, position: Position) -> Opti
return instantiation(ws, doc, name, at);
}
let last = last_token(doc, offset)?;
match doc.tokens.get(last)?.kind {
// A name with nothing after it is not an offer (owner ruling,
// 2026-08-30): `aes` may still be growing into `aes_dft`, and the
// space is the user saying that it is not. No trigger's own last token
// is an `Ident` either, so nothing is lost by stopping here.
TokenKind::Ident => None,
_ => template(ws, doc, last, at),
// A name with nothing after it is not an instantiation offer (owner
// ruling, 2026-08-30): `aes` may still be growing into `aes_dft`, and the
// space is the user saying that it is not. No trigger's own last token is
// an `Ident` either, so only the keyword ghost is asked about one.
if doc.tokens.get(last)?.kind != TokenKind::Ident {
if let Some(items) = template(ws, doc, last, at) {
return Some(items);
}
}
// The fallback: the rest of a keyword the word is a proper prefix of.
keywords::keyword_ghost(ws, doc, last, position, selected)
}
/// [`inline_completions_in_context`] with no popup open — what every test
/// that is not about the popup asks.
#[cfg(test)]
pub fn inline_completions(ws: &Workspace, uri: &Uri, position: Position) -> Option<InlineItems> {
inline_completions_in_context(ws, uri, position, None)
}
/// The identifier the user has just finished and armed with a space: the token
@@ -299,7 +324,7 @@ fn template(ws: &Workspace, doc: &Document, last: usize, at: Range) -> Option<In
return None;
}
let (trigger, opened) = triggered(doc, last)?;
if !unfinished(doc, trigger, opened) {
if !unfinished(doc, trigger, opened, last) {
return None;
}
Some(InlineItems {
@@ -487,13 +512,20 @@ fn triggered(doc: &Document, index: usize) -> Option<(&'static Trigger, Opened)>
}
/// Whether the construct the user opened really is still waiting to be closed.
fn unfinished(doc: &Document, trigger: &Trigger, opened: Opened) -> bool {
///
/// `last` is the index of the token just typed — for `begin`, the keyword
/// itself, which is asked the auto-`end` question (`on_type::auto_end`)
/// rather than "is this span unmatched": a `begin` typed inside a balanced
/// block steals that block's `end` in the stack matcher, and would otherwise
/// get no ghost (`completion-ux` fix round, 2026-11-17).
fn unfinished(doc: &Document, trigger: &Trigger, opened: Opened, last: usize) -> bool {
let paren = || !paren_is_closed(&doc.tokens, opened.last);
let scope = || {
pairs::analyze(&doc.tokens).unmatched_open.iter().any(|open| open.span == opened.keyword)
};
match trigger.gate {
Unclosed::Paren => paren(),
Unclosed::Scope if trigger.keyword == "begin" => on_type::begin_owes_an_end(doc, last),
Unclosed::Scope => scope(),
// The paren check first: it is a flat pass over the tokens, and
// skipping `pairs::analyze` when it already says no is what keeps this
@@ -822,15 +854,16 @@ endmodule
}
#[test]
fn an_always_at_offers_the_clocked_block_first_and_the_star_second() {
fn an_always_at_offers_clock_and_reset_first_then_clock_only_then_the_star() {
let text = "module top;\n always @(\nendmodule\n";
assert_eq!(
all_offered(text, "always @("),
vec![
"posedge ${1:clk} or negedge ${2:rst_n}) begin\n\t$0\nend".to_string(),
"posedge ${1:clk}) begin\n\t$0\nend".to_string(),
"*) begin\n\t$0\nend".to_string(),
],
"clocked first: `always @(` is overwhelmingly a flop"
"clocked first: `always @(` is overwhelmingly a flop, and most flops reset"
);
}
@@ -839,7 +872,10 @@ endmodule
let text = "module top;\n always_ff @(\nendmodule\n";
assert_eq!(
offered_in("/rtl/top.sv", text, "always_ff @("),
vec!["posedge ${1:clk}) begin\n\t$0\nend"]
vec![
"posedge ${1:clk} or negedge ${2:rst_n}) begin\n\t$0\nend",
"posedge ${1:clk}) begin\n\t$0\nend"
]
);
assert!(
offered_in("/rtl/top.v", text, "always_ff @(").is_empty(),
@@ -930,6 +966,15 @@ endmodule
assert!(offered(text, "initial begin").is_some(), "this one lost its end");
}
#[test]
fn a_begin_typed_inside_a_balanced_block_still_offers_its_end() {
// The new `begin` steals the `always_comb` block's `end` in the stack
// matcher; the gate asks the auto-`end` question instead
// (`completion-ux` fix round, 2026-11-17).
let text = "module top;\n always_comb begin\n if (x) begin\n end\nendmodule\n";
assert_eq!(offered(text, "if (x) begin").as_deref(), Some("\n\t$0\nend"));
}
#[test]
fn a_scope_keyword_that_already_has_its_closer_offers_nothing() {
// The same rule as `begin`, for the three keywords that joined it.
@@ -1019,8 +1064,10 @@ endmodule
fn an_always_without_its_event_control_offers_nothing() {
// The opener is a *sequence*: both `@` and `(` must be there, in that
// order, or the user has not committed to an event-controlled block.
// A bare `always` grows no block — only the keyword ghost's `_ff`,
// which is a different feature with its own setting.
let text = "module top;\n always\nendmodule\n";
assert_eq!(offered(text, " always"), None);
assert_eq!(offered(text, " always").as_deref(), Some("_ff"));
let text = "module top;\n always @\nendmodule\n";
assert_eq!(offered(text, "always @"), None);
let text = "module top;\n always (\nendmodule\n";
@@ -1140,7 +1187,7 @@ endmodule
assert_eq!(offered(text, " if(").as_deref(), Some("${1:cond}) begin\n\t$0\nend"));
// ...and the same for a two-symbol opener written tight.
let text = "module top;\n always@(\nendmodule\n";
assert_eq!(all_offered(text, "always@(").len(), 2);
assert_eq!(all_offered(text, "always@(").len(), 3);
}
#[test]
@@ -1532,7 +1579,7 @@ endmodule
// `no_space_between_the_keyword_and_the_paren_still_triggers`, this
// pins the opposite spacing.
let text = "module top;\n always @ (\nendmodule\n";
assert_eq!(all_offered(text, "always @ (").len(), 2);
assert_eq!(all_offered(text, "always @ (").len(), 3);
}
#[test]
@@ -1588,7 +1635,7 @@ endmodule
// counterpart — both must still offer.
let text = "module top;\n if (\n always @(\nendmodule\n";
assert!(offered(text, " if (").is_some());
assert_eq!(all_offered(text, " always @(").len(), 2);
assert_eq!(all_offered(text, " always @(").len(), 3);
}
// ------------------------------------------------------------------
@@ -1629,6 +1676,16 @@ endmodule
serde_json::to_value(&items).expect("serializes"),
serde_json::json!({
"items": [
{
"insertText": {
"kind": "snippet",
"value": "posedge ${1:clk} or negedge ${2:rst_n}) begin\n\t$0\nend"
},
"range": {
"start": { "line": 1, "character": 11 },
"end": { "line": 1, "character": 11 }
}
},
{
"insertText": {
"kind": "snippet",
+519
View File
@@ -0,0 +1,519 @@
//! Keyword ghosts (TODO §68.1): a typed proper prefix of a keyword shows the
//! rest of it as grey text — `alw` grows `ays_ff`, Tab accepts.
//!
//! The fallback ghost: asked only where no template trigger answered, and
//! only for an identifier-like word of two characters or more that ends
//! exactly at the cursor. Three rules decide which keyword, in order:
//!
//! 1. **The popup's choice.** While VS Code's suggest widget is open it shows
//! an inline item only if it extends the selected entry over the selected
//! entry's range (LSP 3.18 `selectedCompletionInfo`). So with a selection,
//! the ghost is exactly that keyword when it is one, and nothing otherwise.
//! 2. **A fixed priority list** of the words an RTL designer types all day.
//! 3. **Shortest, then alphabetical**, over every keyword of the buffer's
//! dialect.
//!
//! A word that is already a keyword is only extended across an underscore:
//! `always` grows `_ff`, but `for` stays `for` and `end` stays `end` — the
//! keystroke after a finished keyword is a space or a newline far more often
//! than another letter, and a ghost there is noise a stray Tab accepts.
//! See `docs/features/completion-ux/README.md`.
use lsp_types::{Position, Range, SelectedCompletionInfo};
use vlog_parser::token::TokenKind;
use vlog_parser::KEYWORDS;
use super::{InlineItem, InlineItems, SnippetValue};
use crate::state::{Document, Workspace};
use crate::templates::{self, Dialect};
/// The shortest word worth a ghost. One letter is a prefix of half the
/// keyword list, and the ghost would change on every keystroke.
const MIN_WORD: usize = 2;
/// The keywords tried first, in this order, whenever more than one extends
/// the typed word. Everything else falls back to shortest-then-alphabetical.
const PRIORITY: &[&str] = &[
"always_ff",
"always_comb",
"always",
"assign",
"begin",
"logic",
"input",
"output",
"inout",
"module",
"endmodule",
"parameter",
"localparam",
"function",
"endfunction",
"task",
"endtask",
"generate",
"endgenerate",
"genvar",
"case",
"endcase",
"default",
"initial",
"integer",
"posedge",
"negedge",
"typedef",
"struct",
"enum",
"package",
"endpackage",
"interface",
"endinterface",
"foreach",
"forever",
"return",
"automatic",
"unique",
"wire",
"reg",
];
/// The IEEE 1364-2005 reserved words: what a `.v` buffer may be offered. The
/// lexer's list is one list for both dialects, and `logic` grown in a file a
/// Verilog compiler reads is a ghost that hands the user an error.
const VERILOG: &[&str] = &[
"always",
"and",
"assign",
"automatic",
"begin",
"buf",
"bufif0",
"bufif1",
"case",
"casex",
"casez",
"cell",
"cmos",
"config",
"deassign",
"default",
"defparam",
"design",
"disable",
"edge",
"else",
"end",
"endcase",
"endconfig",
"endfunction",
"endgenerate",
"endmodule",
"endprimitive",
"endspecify",
"endtable",
"endtask",
"event",
"for",
"force",
"forever",
"fork",
"function",
"generate",
"genvar",
"highz0",
"highz1",
"if",
"ifnone",
"incdir",
"include",
"initial",
"inout",
"input",
"instance",
"integer",
"join",
"large",
"liblist",
"library",
"localparam",
"macromodule",
"medium",
"module",
"nand",
"negedge",
"nmos",
"nor",
"noshowcancelled",
"not",
"notif0",
"notif1",
"or",
"output",
"parameter",
"pmos",
"posedge",
"primitive",
"pull0",
"pull1",
"pulldown",
"pullup",
"pulsestyle_ondetect",
"pulsestyle_onevent",
"rcmos",
"real",
"realtime",
"reg",
"release",
"repeat",
"rnmos",
"rpmos",
"rtran",
"rtranif0",
"rtranif1",
"scalared",
"showcancelled",
"signed",
"small",
"specify",
"specparam",
"strong0",
"strong1",
"supply0",
"supply1",
"table",
"task",
"time",
"tran",
"tranif0",
"tranif1",
"tri",
"tri0",
"tri1",
"triand",
"trior",
"trireg",
"unsigned",
"use",
"uwire",
"vectored",
"wait",
"wand",
"weak0",
"weak1",
"while",
"wire",
"wor",
"xnor",
"xor",
];
/// The keyword ghost for the word ending at `position`, or `None`.
///
/// `last` is the index of the token ending exactly at the cursor — the
/// caller's `last_token` — and `selected` the popup's selected entry, when
/// the client said one is showing.
pub(super) fn keyword_ghost(
ws: &Workspace,
doc: &Document,
last: usize,
position: Position,
selected: Option<&SelectedCompletionInfo>,
) -> Option<InlineItems> {
if !ws.client_settings().inline_keywords.unwrap_or(true) {
return None;
}
let (word, start) = typed_word(doc, last)?;
// A name this buffer declares is what the user is typing, not the front
// of a keyword: `in`, `re`, `out` as signals stay quiet (fix round).
if doc.semantics.symbols().iter().any(|symbol| symbol.name == word) {
return None;
}
let dialect = templates::dialect(doc.path.as_deref());
// A selection that does not cover exactly the typed word is about some
// other text, and is read as no selection at all — never echoed back.
let word_range = Range { start: doc.positions().position(start), end: position };
let selected = selected.filter(|info| info.range == word_range);
let (keyword, range) = match selected {
// An explicit selection wins over the finished-keyword rule: `end`
// with `endmodule` selected ghosts `endmodule`.
Some(info) => {
let text = info.text.as_str();
(reserved_extension(word, text, dialect).then_some(text)?, info.range)
}
None => (best_keyword(word, dialect)?, Range { start: position, end: position }),
};
// Without a selection the item inserts at the cursor, as every other
// ghost here does; with one it must replace the selection's range with
// the whole word, which is the shape the client compares against.
let value = match selected {
Some(_) => keyword.to_string(),
None => keyword[word.len()..].to_string(),
};
Some(InlineItems {
items: vec![InlineItem { insert_text: SnippetValue { kind: "snippet", value }, range }],
})
}
/// The word a keyword ghost may extend: the token at `last` when it is a
/// plain identifier or a keyword, at least [`MIN_WORD`] long, spelled with
/// identifier characters only, and not a member name after a `.` or `::`.
///
/// A macro use (`` `alw ``), an escaped identifier and a `$system` name all
/// fail the character test or the kind test; a comment and a string never
/// produce a token ending at the cursor at all.
fn typed_word(doc: &Document, last: usize) -> Option<(&str, u32)> {
let token = doc.tokens.get(last)?;
if !matches!(token.kind, TokenKind::Ident | TokenKind::Keyword) {
return None;
}
let text = token.text.as_str();
let plain = text.chars().next().is_some_and(|c| c.is_ascii_alphabetic())
&& text.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
if !plain || text.len() < MIN_WORD {
return None;
}
let after_separator = last
.checked_sub(1)
.and_then(|i| doc.tokens.get(i))
.is_some_and(|prev| prev.is_sym(".") || prev.is_sym("::") || prev.is_sym("`"));
(!after_separator).then_some((text, token.span.start))
}
/// The keyword to ghost behind `word` with no popup selection to follow.
fn best_keyword(word: &str, dialect: Dialect) -> Option<&'static str> {
if let Some(first) = PRIORITY.iter().copied().find(|kw| extends(word, kw, dialect)) {
return Some(first);
}
KEYWORDS
.iter()
.copied()
.filter(|kw| extends(word, kw, dialect))
.min_by(|a, b| a.len().cmp(&b.len()).then(a.cmp(b)))
}
/// Whether `keyword` is a reserved word of `dialect` that properly extends
/// `word` — across an underscore only, when `word` is already a keyword.
fn extends(word: &str, keyword: &str, dialect: Dialect) -> bool {
reserved_extension(word, keyword, dialect)
&& (!KEYWORDS.contains(&word) || keyword.as_bytes()[word.len()] == b'_')
}
/// Whether `keyword` is a reserved word of `dialect` that properly extends
/// `word` — the whole test for a keyword the popup has selected.
fn reserved_extension(word: &str, keyword: &str, dialect: Dialect) -> bool {
keyword.len() > word.len()
&& keyword.starts_with(word)
&& KEYWORDS.contains(&keyword)
&& (dialect == Dialect::SystemVerilog || VERILOG.contains(&keyword))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::inline::inline_completions_in_context;
use crate::settings::ClientSettings;
use lsp_types::Uri;
use std::str::FromStr;
/// The ghosts at the end of `needle` in `text`, opened as `/rtl/top.sv`,
/// as `(value, range)` pairs.
fn ghosts(
text: &str,
needle: &str,
selected: Option<SelectedCompletionInfo>,
settings: ClientSettings,
) -> Vec<(String, Range)> {
let uri = Uri::from_str("file:///rtl/top.sv").expect("uri");
let mut ws = Workspace::default();
ws.set_client_settings(settings);
ws.set_document(uri.clone(), text.to_string());
let doc = ws.document(&uri).expect("open");
let offset = (text.find(needle).expect("needle") + needle.len()) as u32;
let position = doc.positions().position(offset);
inline_completions_in_context(&ws, &uri, position, selected.as_ref())
.map(|found| {
found.items.into_iter().map(|item| (item.insert_text.value, item.range)).collect()
})
.unwrap_or_default()
}
fn plain(text: &str, needle: &str) -> Vec<String> {
ghosts(text, needle, None, ClientSettings::default())
.into_iter()
.map(|(value, _)| value)
.collect()
}
fn at(line: u32, character: u32) -> Position {
Position { line, character }
}
#[test]
fn a_keyword_prefix_grows_the_rest_of_the_keyword_at_the_cursor() {
let text = "module top;\n alw\nendmodule\n";
let found = ghosts(text, " alw", None, ClientSettings::default());
let cursor = at(1, 5);
assert_eq!(found, vec![("ays_ff".to_string(), Range { start: cursor, end: cursor })]);
assert_eq!(
plain("module top;\n logic a;\n assign a = 1;\n endm\n", " endm"),
["odule"]
);
}
#[test]
fn the_popups_selection_is_followed_over_its_own_range() {
let text = "module top;\n alw\nendmodule\n";
let range = Range { start: at(1, 2), end: at(1, 5) };
let selected = SelectedCompletionInfo { range, text: "always_comb".to_string() };
let found = ghosts(text, " alw", Some(selected), ClientSettings::default());
assert_eq!(found, vec![("always_comb".to_string(), range)]);
}
#[test]
fn a_selection_that_is_not_a_keyword_extension_silences_the_ghost() {
let text = "module top;\n logic alw_q;\n alw\nendmodule\n";
let range = Range { start: at(2, 2), end: at(2, 5) };
let selected = SelectedCompletionInfo { range, text: "alw_q".to_string() };
assert!(ghosts(text, "\n alw", Some(selected), ClientSettings::default()).is_empty());
}
#[test]
fn no_ghost_after_a_separator_in_a_comment_or_for_one_letter() {
assert!(plain("module top;\n assign x = s.al\nendmodule\n", "s.al").is_empty());
assert!(plain("module top;\n import p::al\nendmodule\n", "p::al").is_empty());
assert!(plain("module top;\n // alw\nendmodule\n", "// alw").is_empty());
assert!(plain("module top;\n a\nendmodule\n", " a").is_empty());
assert!(plain("module top;\n `alw\nendmodule\n", "`alw").is_empty());
}
#[test]
fn no_ghost_when_the_rest_of_the_line_is_written() {
assert!(plain("module top;\n alw x;\nendmodule\n", " alw").is_empty());
}
#[test]
fn the_setting_turns_keyword_ghosts_off_and_leaves_templates_on() {
let off = ClientSettings { inline_keywords: Some(false), ..Default::default() };
let text = "module top;\n alw\nendmodule\n";
assert!(ghosts(text, " alw", None, off.clone()).is_empty());
let text = "module top;\n always_comb begin\n if (\n end\nendmodule\n";
assert_eq!(ghosts(text, "if (", None, off).len(), 1, "the template ghost is untouched");
}
#[test]
fn a_template_trigger_wins_over_the_keyword_ghost() {
// `begin` is a finished keyword and a trigger: its ghost is the block.
let text = "module top;\n initial begin\nendmodule\n";
assert_eq!(plain(text, "initial begin"), ["\n\t$0\nend"]);
}
#[test]
fn the_priority_list_picks_among_several_extensions() {
let sv = Dialect::SystemVerilog;
assert_eq!(best_keyword("al", sv), Some("always_ff"));
assert_eq!(best_keyword("always_c", sv), Some("always_comb"));
assert_eq!(best_keyword("as", sv), Some("assign"));
assert_eq!(best_keyword("lo", sv), Some("logic"));
assert_eq!(best_keyword("endm", sv), Some("endmodule"));
assert_eq!(best_keyword("par", sv), Some("parameter"));
}
#[test]
fn outside_the_list_the_shortest_then_alphabetical_keyword_wins() {
assert_eq!(best_keyword("tr", Dialect::SystemVerilog), Some("tri"), "tri before tran");
assert_eq!(best_keyword("tri", Dialect::SystemVerilog), None, "`tri` is finished");
assert_eq!(best_keyword("xn", Dialect::SystemVerilog), Some("xnor"));
}
#[test]
fn a_finished_keyword_only_grows_across_an_underscore() {
let sv = Dialect::SystemVerilog;
assert_eq!(best_keyword("always", sv), Some("always_ff"));
assert_eq!(best_keyword("end", sv), None, "`end` is finished");
assert_eq!(best_keyword("for", sv), None, "`for` is finished");
assert_eq!(best_keyword("case", sv), None);
}
#[test]
fn a_verilog_buffer_is_only_offered_verilog_words() {
let v = Dialect::Verilog;
assert_eq!(best_keyword("al", v), Some("always"));
assert_eq!(best_keyword("lo", v), Some("localparam"), "no `logic` in a .v file");
assert_eq!(best_keyword("always", v), None, "no `always_ff` either");
}
#[test]
fn every_listed_word_is_a_reserved_word_the_lexer_knows() {
for word in PRIORITY {
assert!(KEYWORDS.contains(word), "{word}");
}
}
/// QA (2026-11-17): the shape an unbridged client sends — VS Code's
/// `Range` serialized by its `toJSON` as `[start, end]`, trigger kind 0 —
/// still decodes (serde reads a struct from a sequence), so the
/// extension's middleware is a spelling fix, not what keeps the request
/// alive.
#[test]
fn qa_an_array_shaped_range_and_a_zero_trigger_kind_still_decode() {
let params: lsp_types::InlineCompletionParams = serde_json::from_value(serde_json::json!({
"textDocument": { "uri": "file:///rtl/top.sv" },
"position": { "line": 1, "character": 5 },
"context": {
"triggerKind": 0,
"selectedCompletionInfo": {
"range": [{ "line": 1, "character": 2 }, { "line": 1, "character": 5 }],
"text": "always_comb"
}
}
}))
.expect("decodes");
let selected = params.context.selected_completion_info.expect("kept");
assert_eq!(selected.range, Range { start: at(1, 2), end: at(1, 5) });
}
#[test]
fn nothing_extends_a_word_that_is_no_keyword_prefix() {
assert_eq!(best_keyword("clk", Dialect::SystemVerilog), None);
assert!(extends("al", "always", Dialect::SystemVerilog));
assert!(!extends("Al", "always", Dialect::SystemVerilog), "case matters");
}
#[test]
fn a_name_this_buffer_declares_grows_no_keyword() {
let text = "module top;\n logic re, in;\n assign x = re\nendmodule\n";
assert!(plain(text, "= re").is_empty(), "`re` is a signal here, not `return`");
// An undeclared word still ghosts, expression position or not.
let text = "module top;\n assign x = ou\nendmodule\n";
assert_eq!(plain(text, "= ou"), ["tput"]);
}
#[test]
fn an_explicit_selection_wins_over_the_finished_keyword_rule() {
let text = "module top;\n logic a;\n end\nendmodule\n";
assert!(plain(text, "\n end").is_empty(), "no popup: `end` is finished");
let range = Range { start: at(2, 2), end: at(2, 5) };
let selected = SelectedCompletionInfo { range, text: "endmodule".to_string() };
let found = ghosts(text, "\n end", Some(selected), ClientSettings::default());
assert_eq!(found, vec![("endmodule".to_string(), range)]);
}
#[test]
fn a_selection_over_some_other_range_is_read_as_no_selection() {
let text = "module top;\n alw\nendmodule\n";
let cursor = at(1, 5);
for range in [
Range { start: at(1, 2), end: at(1, 4) },
Range { start: at(1, 3), end: cursor },
Range { start: at(0, 0), end: at(0, 6) },
] {
let selected = SelectedCompletionInfo { range, text: "always_comb".to_string() };
let found = ghosts(text, " alw", Some(selected), ClientSettings::default());
assert_eq!(
found,
vec![("ays_ff".to_string(), Range { start: cursor, end: cursor })],
"{range:?} is never echoed back"
);
}
}
}
+39
View File
@@ -117,6 +117,7 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
// capabilities have no field for it and drop it on the floor — see
// `ranges_formatting_support`.
let ranges_formatting = ranges_formatting_support(&params);
let diagnostic_refresh = diagnostic_refresh_support(&params);
// Read from the raw params for the same reason, and because it is not a
// capability at all: `initializationOptions` is whatever the client's
// extension put there.
@@ -133,6 +134,7 @@ fn main() -> Result<(), Box<dyn Error + Sync + Send>> {
pull_diagnostics: pull_diagnostics_support(&params),
work_done_progress: work_done_progress_support(&params),
code_lens_refresh: code_lens_refresh_support(&params),
diagnostic_refresh,
show_document: show_document_support(&params),
configuration: configuration_support(&params),
token_server_cancel: token_server_cancel_support(&params),
@@ -645,6 +647,21 @@ fn code_lens_refresh_support(params: &InitializeParams) -> bool {
.unwrap_or(false)
}
/// Whether the client can be asked to pull its diagnostics again
/// (`workspace/diagnostic/refresh`), read from the **raw** `initialize`
/// params.
///
/// Server-initiated, so the spec makes this capability the gate, exactly as
/// for the code-lens refresh. It has to be the raw JSON: the protocol's key is
/// `workspace.diagnostics`, and `lsp-types` 0.97 spells its field
/// `diagnostic` with no rename, so the typed decode never sees what VS Code
/// sends. Anything but a literal `true` means no. Sent when a connection entry
/// held back while it was typed is released
/// (`docs/features/port-entry-grace/README.md`).
fn diagnostic_refresh_support(params: &serde_json::Value) -> bool {
params["capabilities"]["workspace"]["diagnostics"]["refreshSupport"] == true
}
/// Whether the client opens a document the server asks it to.
///
/// This is what makes the instantiation lens actually navigate: an
@@ -1352,6 +1369,28 @@ mod tests {
assert!(!code_lens_refresh_support(&saying(None)), "an empty `codeLens` is not a yes");
}
#[test]
fn diagnostic_refresh_support_is_read_from_the_raw_params_and_only_when_literally_true() {
let saying = |refresh: serde_json::Value| {
serde_json::json!({
"processId": null,
"capabilities": { "workspace": { "diagnostics": { "refreshSupport": refresh } } }
})
};
assert!(diagnostic_refresh_support(&saying(serde_json::json!(true))));
assert!(!diagnostic_refresh_support(&saying(serde_json::json!(false))));
assert!(!diagnostic_refresh_support(&saying(serde_json::json!("yes"))));
assert!(!diagnostic_refresh_support(&saying(serde_json::Value::Null)));
assert!(!diagnostic_refresh_support(&serde_json::json!({ "capabilities": {} })));
assert!(!diagnostic_refresh_support(&serde_json::Value::Null));
// The protocol's key is plural; `lsp-types`' singular field name is
// not what any client sends, and is not read.
let singular = serde_json::json!({
"capabilities": { "workspace": { "diagnostic": { "refreshSupport": true } } }
});
assert!(!diagnostic_refresh_support(&singular));
}
#[test]
fn show_document_support_is_read_from_the_clients_own_capabilities() {
use lsp_types::{
+23 -10
View File
@@ -28,6 +28,10 @@ use crate::format;
use crate::pairs;
use crate::state::{first_token_from, first_token_reaching, Document};
mod auto_end;
pub(crate) use auto_end::begin_owes_an_end;
/// The character the client is told to trigger on. A newline is the one
/// keystroke that opens a line whose indentation nobody has chosen yet.
pub const NEWLINE: &str = "\n";
@@ -40,12 +44,21 @@ pub const SEMICOLON: &str = ";";
///
/// Never an `Err`: every refusal on this path — an unknown trigger, a client
/// out of step, a buffer the formatter will not touch — is the empty answer.
///
/// `auto_end` is `lucisv.autoEnd`: whether a newline typed after a `begin`
/// that still owes its `end` also writes that `end` (see `auto_end.rs`).
pub fn on_type_formatting(
doc: &Document,
position: Position,
typed: &str,
config: &Config,
auto_end: bool,
) -> Vec<TextEdit> {
if auto_end && typed == NEWLINE {
if let Some(edits) = auto_end::begin_newline_edits(doc, position, config.indent_width) {
return edits;
}
}
let edit = match typed {
NEWLINE => indent_edit(doc, position, config.indent_width),
SEMICOLON => statement_edit(doc, position, config),
@@ -715,7 +728,7 @@ mod tests {
fn newline_with(text: &str, line: u32, indent_width: usize) -> Vec<TextEdit> {
let at = Position { line, character: 0 };
with(text, |doc| on_type_formatting(doc, at, NEWLINE, &config(indent_width)))
with(text, |doc| on_type_formatting(doc, at, NEWLINE, &config(indent_width), false))
}
/// The `new_text` of the single edit a newline produced, or `None` when it
@@ -732,7 +745,7 @@ mod tests {
let content = source[line as usize].trim_end_matches('\n');
let character = content.rfind(';').expect("the line ends a statement") as u32 + 1;
let at = Position { line, character };
with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2)))
with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2), false))
}
// ------------------------------------------------------------------
@@ -793,7 +806,7 @@ mod tests {
// it means the client is not talking about a newline it just typed.
let text = "module m;\nwire a;\nendmodule\n";
let at = Position { line: 1, character: 4 };
let edits = with(text, |doc| on_type_formatting(doc, at, NEWLINE, &config(2)));
let edits = with(text, |doc| on_type_formatting(doc, at, NEWLINE, &config(2), false));
assert_eq!(edits, Vec::new());
}
@@ -955,7 +968,7 @@ mod tests {
with(text, |doc| {
for line in 1..text.lines().count() as u32 {
let at = Position { line, character: 0 };
for edit in on_type_formatting(doc, at, NEWLINE, &config(2)) {
for edit in on_type_formatting(doc, at, NEWLINE, &config(2), false) {
assert_eq!(edit.range.start, at, "always column zero of the asked-for line");
assert_eq!(edit.range.end.line, line, "and never past that line");
let source = doc.text.lines().nth(line as usize).unwrap_or("");
@@ -1178,7 +1191,7 @@ mod tests {
// buffer no longer refuses (selection-formatting, TODO §66.2).
let text = "module m;\n wire a = ;\nendmodule\n";
let at = Position { line: 1, character: 13 };
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2)));
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2), false));
assert_eq!(edits, Vec::new());
}
@@ -1192,7 +1205,7 @@ mod tests {
#[test]
fn a_semicolon_that_is_not_where_the_client_said_answers_nothing() {
let at = Position { line: 1, character: 3 };
let edits = with(MESSY, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2)));
let edits = with(MESSY, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2), false));
assert_eq!(edits, Vec::new());
}
@@ -1203,7 +1216,7 @@ mod tests {
assert_eq!(semicolon(text, 1), Vec::new());
let text = "module m;\n string s = \"a;\";\n wire a;\nendmodule\n";
let at = Position { line: 1, character: 16 };
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2)));
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2), false));
assert_eq!(edits, Vec::new(), "the `;` inside the quotes");
}
@@ -1214,7 +1227,7 @@ mod tests {
// the whole document.
let text = "module m;\n wire a;\nendmodule";
let at = Position { line: 1, character: 11 };
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2)));
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2), false));
assert_eq!(edits.len(), 1, "{edits:#?}");
// Only the statement moves: the file's tail is outside the splice, so
// the missing final newline stays missing — exactly what
@@ -1253,7 +1266,7 @@ mod tests {
// inside a string or a comment.
let text = "`define FOO x = 1;\nmodule m;\nendmodule\n";
let at = Position { line: 0, character: 19 };
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2)));
let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2), false));
assert_eq!(edits, Vec::new(), "no Symbol(;) token ends inside a Directive");
}
@@ -1281,7 +1294,7 @@ mod tests {
// guess at what it meant.
let at = Position { line: 1, character: 9 };
for typed in ["}", ")", "\t", ""] {
let edits = with(MESSY, |doc| on_type_formatting(doc, at, typed, &config(2)));
let edits = with(MESSY, |doc| on_type_formatting(doc, at, typed, &config(2), false));
assert_eq!(edits, Vec::new(), "trigger {typed:?}");
}
}
@@ -0,0 +1,581 @@
//! `begin` + Enter writes the `end` (TODO §68.1).
//!
//! The newline answer's second half. When the line above the one a `\n` just
//! opened ends in `begin` (or `begin : label`) and that block still owes an
//! `end`, the answer is two edits instead of one: the new line's body
//! indentation, as the plain newline answer would give it, and a line after
//! it holding `end` at the indentation of the statement the `begin` belongs
//! to. The cursor's line stays blank, so the user types the first statement
//! where they already are.
//!
//! **Which `begin` owes an `end`.** `pairs::analyze` is a stack matcher, so a
//! `begin` typed inside a block that already balances *steals* that block's
//! `end`: the new inner `begin` comes out matched, and the outer one is
//! reported unclosed. "Is *this* `begin` unmatched" is therefore the wrong
//! question. The one asked here is: is any `begin` at or before this one
//! unclosed — unless this `begin` is matched by an `end` that starts its line
//! at exactly the indentation this answer would have written, which is the
//! block the user already closed. See `docs/features/completion-ux/README.md`.
use lsp_types::{Position, Range, TextEdit};
use vlog_parser::token::{Token, TokenKind};
use vlog_parser::TextRange;
use super::level_at;
use crate::pairs;
use crate::state::{first_token_from, Document};
/// The keywords whose header a `begin` may be the body of. Reading backwards,
/// one of these is where the header starts.
const HEADER_KEYWORDS: &[&str] = &[
"if",
"for",
"foreach",
"while",
"repeat",
"forever",
"always",
"always_ff",
"always_comb",
"always_latch",
"initial",
"final",
];
/// The words that may stand in front of a header on the same statement:
/// `else if`, `unique case`-style qualifiers, and a bare `else` before its
/// `begin`.
const QUALIFIERS: &[&str] = &["else", "unique", "unique0", "priority"];
/// The edits for a newline typed right after a `begin` that still owes its
/// `end`, or `None` when this newline is not that — the caller then answers
/// the plain indentation question instead.
pub(super) fn begin_newline_edits(
doc: &Document,
position: Position,
indent_width: usize,
) -> Option<Vec<TextEdit>> {
let line = NewLine::at(doc, position)?;
let begin = begin_ending_line_above(doc, line.range.start)?;
let end_indent = owner_indent(doc, begin);
if !owes_an_end(doc, begin, &end_indent) {
return None;
}
let body = body_indent(level_at(doc, line.content), &end_indent, indent_width);
Some(edits(doc, &line, &body, &end_indent))
}
/// The blank line a `\n` just opened, as far as this answer needs it.
struct NewLine {
/// The whole line, its `\r` included when the file has one.
range: TextRange,
/// The end of its leading whitespace.
content: u32,
/// The line ending the file writes, read off the newline just typed.
eol: &'static str,
}
impl NewLine {
/// The line at `position`, when a newline opened it, the cursor sits in
/// its leading whitespace, and nothing but whitespace is on it — Enter
/// pressed in the middle of a line carries text down, and a body that is
/// already written owes nothing.
fn at(doc: &Document, position: Position) -> Option<NewLine> {
let range = doc.line_index.line_range(position.line.checked_add(1)?)?;
let bytes = doc.text.as_bytes();
if range.start == 0 || bytes.get(range.start as usize - 1) != Some(&b'\n') {
return None;
}
let text = doc.text.get(range.start as usize..range.end as usize)?;
let rest = text.trim_start_matches([' ', '\t']);
if !rest.trim_end_matches('\r').is_empty() {
return None;
}
let content = range.start + (text.len() - rest.len()) as u32;
if doc.positions().offset(position) > content {
return None;
}
let crlf = range.start >= 2 && bytes.get(range.start as usize - 2) == Some(&b'\r');
Some(NewLine { range, content, eol: if crlf { "\r\n" } else { "\n" } })
}
}
/// The index of the `begin` the line above `line_start` ends with — the last
/// token on it, or the one before a `: label` — when it does.
///
/// Comments are trivia, not tokens, so `begin // why` ends in `begin` here
/// without a check of its own.
fn begin_ending_line_above(doc: &Document, line_start: u32) -> Option<usize> {
let last = first_token_from(&doc.tokens, line_start).checked_sub(1)?;
let above = doc.line_index.line_col(line_start).0.checked_sub(1)?;
let on_line_above =
|index: usize| doc.tokens.get(index).is_some_and(|token| line_of(doc, token) == above);
let token = doc.tokens.get(last)?;
let begin = match token.kind {
TokenKind::Ident if last >= 2 && doc.tokens.get(last - 1)?.is_sym(":") => last - 2,
_ => last,
};
(doc.tokens.get(begin)?.is_kw("begin") && on_line_above(begin) && on_line_above(last))
.then_some(begin)
}
/// The leading whitespace of the line the statement owning the `begin` at
/// `begin` starts on, as written — tabs stay tabs.
///
/// Read backwards from the `begin` over what may stand between a statement's
/// first token and its body: a parenthesised header, an `@`/`#` control and
/// its operand, and [`HEAD_KEYWORDS`]. Anything else — a `;`, an `end`, a
/// case item's `:` — is where the statement starts. A header with no `(` to
/// match leaves the `begin`'s own line as the answer.
fn owner_indent(doc: &Document, begin: usize) -> String {
let tokens = &doc.tokens;
let mut first = begin;
// Once a header keyword is read, only a qualifier may still precede it:
// `always_comb` on the line above an `if` is the `if`'s *owner*, not part
// of its header.
let mut keyword_seen = false;
while let Some(prev) = first.checked_sub(1) {
let token = &tokens[prev];
let step = match keyword_seen {
true => is_keyword_in(token, QUALIFIERS).then_some(prev),
false => header_step(tokens, prev),
};
let Some(step) = step else { break };
keyword_seen |= is_keyword_in(token, HEADER_KEYWORDS) || is_keyword_in(token, QUALIFIERS);
first = step;
}
line_indent(doc, tokens[first].span.start)
}
/// Where reading a header backwards goes from the token at `prev`: over a
/// parenthesised group to its `(`, onto a header keyword, a qualifier, an
/// `@`/`#`, or the operand right after one — or nowhere, when `prev` is
/// already outside the header.
fn header_step(tokens: &[Token], prev: usize) -> Option<usize> {
let token = &tokens[prev];
if token.is_sym(")") {
return matching_open(tokens, prev);
}
let after_control = prev
.checked_sub(1)
.and_then(|i| tokens.get(i))
.is_some_and(|t| t.is_sym("@") || t.is_sym("#"));
let in_header = is_keyword_in(token, HEADER_KEYWORDS)
|| is_keyword_in(token, QUALIFIERS)
|| token.is_sym("@")
|| token.is_sym("#")
|| after_control;
in_header.then_some(prev)
}
fn is_keyword_in(token: &Token, words: &[&str]) -> bool {
token.kind == TokenKind::Keyword && words.contains(&token.text.as_str())
}
/// The `(` the `)` at `close` closes, counting parentheses only.
fn matching_open(tokens: &[Token], close: usize) -> Option<usize> {
let mut depth = 0u32;
for index in (0..=close).rev() {
let token = &tokens[index];
if token.is_sym(")") {
depth += 1;
} else if token.is_sym("(") {
depth = depth.checked_sub(1)?;
if depth == 0 {
return Some(index);
}
}
}
None
}
/// Whether the block the `begin` at `begin` opens still needs an `end`
/// written for it. See the module comment for why this is not "is this
/// `begin` unmatched".
///
/// Two layouts count as "already closed": the `end` under the statement (the
/// formatter's own layout) and the `end` under the `begin`'s own line (the GNU
/// layout, `begin` on a line of its own — QA finding 1, fix round
/// 2026-11-17). And an unmatched `begin` inside a `` `ifdef `` that has an
/// `` `else ``/`` `elsif `` arms nothing: two branches each opening a block
/// closed by one shared `end` are an unmatched `begin` to the stack matcher
/// and complete code to the compiler.
fn owes_an_end(doc: &Document, begin: usize, end_indent: &str) -> bool {
let span = doc.tokens[begin].span;
let own_indent = line_indent(doc, span.start);
let analysis = pairs::analyze(&doc.tokens);
let closed_here = analysis.pairs.iter().any(|pair| {
pair.open == span
&& (starts_line_at(doc, pair.close, end_indent)
|| starts_line_at(doc, pair.close, &own_indent))
});
if closed_here {
return false;
}
let branched = branched_regions(&doc.tokens);
analysis.unmatched_open.iter().any(|open| {
open.keyword == "begin"
&& open.span.start <= span.start
&& !branched.iter().any(|region| region.contains(&open.span.start))
})
}
/// Whether the `begin` at token index `begin` opens a block that still needs
/// an `end` — [`owes_an_end`] with the `end` at its owner's indentation. The
/// inline `begin` ghost asks the same question.
pub(crate) fn begin_owes_an_end(doc: &Document, begin: usize) -> bool {
owes_an_end(doc, begin, &owner_indent(doc, begin))
}
/// The byte ranges of every `` `ifdef ``/`` `ifndef `` … `` `endif `` region
/// that holds an `` `else `` or `` `elsif `` of its own. A region never closed
/// runs to the end of the buffer.
fn branched_regions(tokens: &[Token]) -> Vec<std::ops::Range<u32>> {
let mut open: Vec<(u32, bool)> = Vec::new();
let mut out = Vec::new();
for token in tokens {
match conditional(token) {
Some("`ifdef" | "`ifndef") => open.push((token.span.start, false)),
Some("`else" | "`elsif") => {
if let Some(last) = open.last_mut() {
last.1 = true;
}
}
Some("`endif") => {
if let Some((start, true)) = open.pop() {
out.push(start..token.span.end);
}
}
_ => {}
}
}
let end = tokens.last().map_or(0, |token| token.span.end);
out.extend(open.into_iter().filter(|(_, branched)| *branched).map(|(start, _)| start..end));
out
}
/// The conditional-compilation directive a token spells, by its first word.
fn conditional(token: &Token) -> Option<&str> {
let word = token.text.split_whitespace().next()?;
matches!(word, "`ifdef" | "`ifndef" | "`else" | "`elsif" | "`endif").then_some(word)
}
/// Whether `span` is the first thing on its line and that line is indented
/// by exactly `indent`.
fn starts_line_at(doc: &Document, span: TextRange, indent: &str) -> bool {
let line = doc.line_index.line_col(span.start).0;
let Some(range) = doc.line_index.line_range(line) else { return false };
doc.text.get(range.start as usize..span.start as usize) == Some(indent)
}
/// The body line's indentation: the nesting model's answer when it has one
/// that sits inside the `end`, else one step in from the `end`. A file
/// indented with tabs gets one more tab — the model speaks spaces, and mixing
/// the two on adjacent lines would be worse than either.
fn body_indent(level: Option<usize>, end_indent: &str, indent_width: usize) -> String {
if end_indent.contains('\t') {
return format!("{end_indent}\t");
}
match level {
Some(level) if level * indent_width > end_indent.len() => " ".repeat(level * indent_width),
_ => format!("{end_indent}{}", " ".repeat(indent_width)),
}
}
/// The edits themselves: re-indent the new line when it needs it, and write
/// the `end` line after it.
///
/// The `end` goes in at the **start of the following line** whenever there is
/// one, so no edit touches the cursor's own position and an editor applying
/// them leaves the cursor on the body line. The new line being the file's last
/// is the one case with nowhere else to put it, and there the two are one
/// edit.
fn edits(doc: &Document, line: &NewLine, body: &str, end_indent: &str) -> Vec<TextEdit> {
let positions = doc.positions();
let start = positions.position(line.range.start);
let indent = Range { start, end: positions.position(line.content) };
let end_line = format!("{end_indent}end");
if line.range.end as usize >= doc.text.len() {
let new_text = format!("{body}{}{end_line}", line.eol);
return vec![TextEdit {
range: Range { start, end: positions.position(line.range.end) },
new_text,
}];
}
let mut edits = Vec::new();
if doc.text.get(line.range.start as usize..line.content as usize) != Some(body) {
edits.push(TextEdit { range: indent, new_text: body.to_string() });
}
let next = positions.position(line.range.end + 1);
edits.push(TextEdit {
range: Range { start: next, end: next },
new_text: format!("{end_line}{}", line.eol),
});
edits
}
/// The 1-based line a token starts on.
fn line_of(doc: &Document, token: &Token) -> u32 {
doc.line_index.line_col(token.span.start).0
}
/// The leading whitespace of the line holding `offset`.
fn line_indent(doc: &Document, offset: u32) -> String {
let line = doc.line_index.line_col(offset).0;
let Some(range) = doc.line_index.line_range(line) else { return String::new() };
let text = doc.text.get(range.start as usize..range.end as usize).unwrap_or("");
text[..text.len() - text.trim_start_matches([' ', '\t']).len()].to_string()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::on_type::{on_type_formatting, NEWLINE};
use crate::state::Workspace;
use lsp_types::Uri;
use std::str::FromStr;
use vlog_formatter::Config;
/// The buffer after the newline answer for a `\n` that opened `line`
/// (0-based), with `lucisv.autoEnd` as given — and the edits themselves.
fn typed(text: &str, line: u32, auto_end: bool) -> (String, Vec<TextEdit>) {
let uri = Uri::from_str("file:///rtl/m.sv").expect("uri");
let mut ws = Workspace::default();
ws.set_document(uri.clone(), text.to_string());
let doc = ws.document(&uri).expect("open");
let at = Position { line, character: 0 };
let config = Config { indent_width: 2, ..Config::default() };
let edits = on_type_formatting(doc, at, NEWLINE, &config, auto_end);
(apply(doc, &edits), edits)
}
/// `edits` applied to the buffer, last first so the offsets stay true.
fn apply(doc: &Document, edits: &[TextEdit]) -> String {
let mut spans: Vec<(usize, usize, &str)> = edits
.iter()
.map(|edit| {
let start = doc.positions().offset(edit.range.start) as usize;
let end = doc.positions().offset(edit.range.end) as usize;
(start, end, edit.new_text.as_str())
})
.collect();
spans.sort_by_key(|(start, _, _)| std::cmp::Reverse(*start));
let mut text = doc.text.to_string();
for (start, end, new_text) in spans {
text.replace_range(start..end, new_text);
}
text
}
#[test]
fn a_newline_after_an_unclosed_begin_writes_the_end_under_its_statement() {
let text = "module m;\n always_ff @(posedge clk) begin\n\nendmodule\n";
let (after, edits) = typed(text, 2, true);
assert_eq!(after, "module m;\n always_ff @(posedge clk) begin\n \n end\nendmodule\n");
// Nothing lands on the cursor's own position: the `end` goes in at the
// start of the line after it, so the cursor stays on the body line.
assert!(edits
.iter()
.all(|edit| edit.range.start.line != 2 || edit.range.end.character == 0));
assert_eq!(
edits.last().map(|edit| edit.range.start),
Some(Position { line: 3, character: 0 })
);
}
#[test]
fn a_begin_typed_inside_a_balanced_block_still_gets_its_end() {
// The new `if`'s `begin` steals the `always_comb` block's `end` in the
// stack matcher, and the *outer* `begin` is what comes out unclosed.
let text =
"module m;\n always_comb begin\n x = 1;\n if (x) begin\n\n end\nendmodule\n";
let (after, _) = typed(text, 4, true);
assert_eq!(
after,
"module m;\n always_comb begin\n x = 1;\n if (x) begin\n \n end\n end\nendmodule\n"
);
}
#[test]
fn a_begin_whose_blocks_already_balance_gets_no_end() {
let text = "module m;\n always_comb begin\n\n end\nendmodule\n";
let (after, edits) = typed(text, 2, true);
assert_eq!(after, "module m;\n always_comb begin\n \n end\nendmodule\n");
assert_eq!(edits.len(), 1, "the indentation alone: {edits:?}");
}
#[test]
fn a_closed_inner_block_with_an_outer_end_missing_gets_no_second_end() {
// The outer `begin` is the unclosed one, but this `begin` already has
// its `end`, at exactly the indentation the answer would write.
let text = "module m;\n always_comb begin\n if (x) begin\n\n end\nendmodule\n";
let (_, edits) = typed(text, 3, true);
assert!(edits.iter().all(|edit| !edit.new_text.contains("end")), "{edits:?}");
}
#[test]
fn a_labelled_begin_and_a_trailing_comment_both_count() {
let text = "module m;\n initial begin : boot // first\n\nendmodule\n";
let (after, _) = typed(text, 2, true);
assert_eq!(after, "module m;\n initial begin : boot // first\n \n end\nendmodule\n");
}
#[test]
fn the_end_lines_up_with_the_first_line_of_a_wrapped_header() {
let text = "module m;\n always_comb\n if (a &&\n b) begin\n\nendmodule\n";
let (after, _) = typed(text, 4, true);
assert!(after.contains(" b) begin\n \n end\nendmodule"), "{after}");
}
#[test]
fn an_else_branch_ends_under_the_line_that_holds_the_else() {
let text = "module m;\n always_comb begin\n if (a) begin\n x = 1;\n end else begin\n\n end\nendmodule\n";
let (after, _) = typed(text, 5, true);
assert!(after.contains(" end else begin\n \n end\n end\n"), "{after}");
}
#[test]
fn a_case_item_ends_under_the_item() {
let text = "module m;\n always_comb begin\n case (s)\n 2'b01: begin\n\n endcase\n end\nendmodule\n";
let (after, _) = typed(text, 4, true);
assert!(after.contains(" 2'b01: begin\n \n end\n endcase"), "{after}");
}
#[test]
fn tabs_stay_tabs() {
let text = "module m;\n\talways_comb begin\n\nendmodule\n";
let (after, _) = typed(text, 2, true);
assert_eq!(after, "module m;\n\talways_comb begin\n\t\t\n\tend\nendmodule\n");
}
#[test]
fn a_crlf_file_gets_a_crlf_end_line() {
let text = "module m;\r\n initial begin\r\n\r\nendmodule\r\n";
let (after, _) = typed(text, 2, true);
assert_eq!(after, "module m;\r\n initial begin\r\n \r\n end\r\nendmodule\r\n");
}
#[test]
fn the_last_line_of_the_file_gets_one_edit() {
let text = "module m;\n initial begin\n";
let (after, edits) = typed(text, 2, true);
assert_eq!(after, "module m;\n initial begin\n \n end");
assert_eq!(edits.len(), 1);
}
#[test]
fn nothing_but_the_indent_when_the_setting_is_off() {
let text = "module m;\n always_ff @(posedge clk) begin\n\nendmodule\n";
let (after, _) = typed(text, 2, false);
assert_eq!(after, "module m;\n always_ff @(posedge clk) begin\n \nendmodule\n");
}
#[test]
fn no_end_where_the_line_above_does_not_end_in_begin() {
for text in [
"module m;\n initial begin x = 1;\n\nendmodule\n",
"module m;\n initial // begin\n\nendmodule\n",
"module m;\n initial $display(\"begin\");\n\nendmodule\n",
"module m;\n initial fork\n\nendmodule\n",
] {
let (_, edits) = typed(text, 2, true);
assert!(edits.iter().all(|edit| !edit.new_text.contains("end")), "{text:?}: {edits:?}");
}
}
#[test]
fn no_end_when_enter_carried_text_down_to_the_new_line() {
let text = "module m;\n initial begin\n x = 1;\nendmodule\n";
let (_, edits) = typed(text, 2, true);
assert!(edits.iter().all(|edit| !edit.new_text.contains("end")), "{edits:?}");
}
#[test]
fn a_begin_two_lines_up_is_not_the_line_above() {
let text = "module m;\n initial begin\n\n\nendmodule\n";
let (_, edits) = typed(text, 3, true);
assert!(edits.iter().all(|edit| !edit.new_text.contains("end")), "{edits:?}");
}
/// QA (2026-11-17): buffers just after an Enter on `line`, each of which
/// gets an `end`.
const QA_ARMED: &[(&str, u32)] = &[
("module m;\n always_comb begin\n x = 1;\n if (x) begin\n\n end\nendmodule\n", 4),
("module m;\n generate\n if (P) begin : g\n\n endgenerate\nendmodule\n", 3),
("module m;\n initial fork\n begin\n\n join\nendmodule\n", 3),
("module m;\n initial `MY_MACRO begin\n\nendmodule\n", 2),
("module m;\n initial #5 begin\n\nendmodule\n", 2),
("module m;\n always @* begin\n\nendmodule\n", 2),
("class c;\n function void f();\n if (a) begin\n\n endfunction\nendclass\n", 3),
("module m;\r\n always_comb begin\r\n\r\nendmodule\r\n", 2),
("module m;\n initial begin\n", 2),
];
#[test]
fn qa_asking_again_after_the_answer_is_applied_adds_no_second_end() {
for &(text, line) in QA_ARMED {
let (after, edits) = typed(text, line, true);
assert!(edits.iter().any(|edit| edit.new_text.contains("end")), "{text:?}: {edits:?}");
let (again, second) = typed(&after, line, true);
assert!(
second.iter().all(|edit| !edit.new_text.contains("end")),
"{after:?}: {second:?}"
);
assert_eq!(again, after, "the second answer changes nothing: {text:?}");
}
}
#[test]
fn qa_a_declined_newline_is_exactly_the_plain_indent_answer() {
for (text, line) in [
("module m;\n always_comb begin\n\n end\nendmodule\n", 2),
("`define OPEN begin\n\nmodule m;\nendmodule\n", 1),
("`define BLK(x) if (x) begin \\\n\nmodule m;\nendmodule\n", 1),
("module m;\n initial $display(\"begin\n\nendmodule\n", 2),
("module m;\n`ifdef A\n always_ff @(posedge clk) begin\n`else\n always_ff @(posedge clk or negedge rst_n) begin\n\n`endif\n x <= 1;\n end\nendmodule\n", 5),
("module m;\n always_comb begin\n\nend\nendmodule\n", 2),
("module m;\n initial begin end\n\nendmodule\n", 2),
("module m;\n wire \\begin \n\nendmodule\n", 2),
("module m;\n initial begin\nfoo = 1;\nendmodule\n", 2),
] {
let (_, with) = typed(text, line, true);
let (_, without) = typed(text, line, false);
assert_eq!(with, without, "{text:?}");
}
}
/// Whether any edit writes an `end`.
fn wrote_an_end(edits: &[TextEdit]) -> bool {
edits.iter().any(|edit| edit.new_text.contains("end"))
}
#[test]
fn a_gnu_style_begin_already_closed_under_itself_gets_no_end() {
// Another `begin` above is unclosed (mid-edit), and this block's `end`
// sits under the `begin`'s own line rather than under the `if`.
let text = "module m;\n initial begin\n always_comb\n if (x)\n begin\n\n y = 1;\n end\nendmodule\n";
let (_, edits) = typed(text, 5, true);
assert!(!wrote_an_end(&edits), "{edits:?}");
}
#[test]
fn qa_ifdef_branches_sharing_one_end_get_no_second_end() {
// QA finding 1: two `ifdef` branches each open the `always` block and
// one `end` after the `endif` closes whichever was compiled.
let shared = "module m;\n`ifdef A\n always @(posedge clk) begin\n`else\n always @(posedge clk or negedge rst) begin\n`endif\n if (x)\n begin\n\n y <= 1;\n end\n end\nendmodule\n";
let (_, edits) = typed(shared, 8, true);
assert!(!wrote_an_end(&edits), "after the GNU-style begin: {edits:?}");
// The cursor after the *first* branch's `begin`: that block's `end`
// is the shared one after the `endif`, so writing one would be wrong.
let first = "module m;\n`ifdef A\n always @(posedge clk) begin\n\n`else\n always @(posedge clk or negedge rst) begin\n`endif\n y <= 1;\n end\nendmodule\n";
let (_, edits) = typed(first, 3, true);
assert!(!wrote_an_end(&edits), "inside the first branch: {edits:?}");
}
#[test]
fn an_ifdef_with_no_else_still_arms_the_answer() {
let text = "module m;\n`ifdef A\n initial begin\n\n`endif\nendmodule\n";
let (_, edits) = typed(text, 3, true);
assert!(wrote_an_end(&edits), "{edits:?}");
}
}
+43 -1
View File
@@ -53,6 +53,7 @@ impl Server {
let buffers = self.dirty.len();
for (uri, text) in std::mem::take(&mut self.dirty) {
self.set_document(uri.clone(), text);
self.workspace.locate_port_entry(&uri);
crate::lint_trace::rebuild(crate::lint_trace::Rebuild::Publish, || self.publish(&uri));
}
self.timed(started, |took| {
@@ -100,7 +101,48 @@ impl Server {
// (`docs/features/semantic-lints-on/`).
let run = crate::lint::LintRun::for_document(&self.workspace, doc);
self.report_config_problems(&run);
diagnostics::all_in(doc, &run)
// Except what the connection being typed would say, while it is being
// typed (`docs/features/port-entry-grace/README.md`).
self.workspace.port_grace().withhold(uri, doc, diagnostics::all_in(doc, &run))
}
/// Say everything again about each buffer whose connection entry is no
/// longer being typed: its quiet period ran out, or an edit landed in
/// another buffer.
///
/// The generation moves first, so a pulling client's next pull gets the
/// full list rather than "unchanged" against the withheld one; a pulling
/// client that accepts `workspace/diagnostic/refresh` is asked — once per
/// release, however many buffers it covers — to make that pull now. Its
/// answer is ignorable and rides `response`'s fall-through. A pulling
/// client without the capability sees the release at its own next pull.
pub(super) fn release_port_entries(&mut self) {
let due = self.workspace.port_grace_mut().due(std::time::Instant::now());
if due.is_empty() {
return;
}
self.generation += 1;
for uri in &due {
self.publish(uri);
}
if self.abilities.pull_diagnostics && self.abilities.diagnostic_refresh {
use lsp_types::request::{Request as _, WorkspaceDiagnosticRefresh};
self.send_request(WorkspaceDiagnosticRefresh::METHOD, ());
}
}
/// How long the loop may wait for a message before it owes something: a
/// dirty buffer's quiet period, or the end of a connection entry's grace,
/// whichever comes first. `None` is "nothing is owed; wait for ever".
pub(super) fn quiet_wait(&self) -> Option<std::time::Duration> {
let debounce = (!self.dirty.is_empty()).then_some(super::CHANGE_DEBOUNCE);
let now = std::time::Instant::now();
let grace =
self.workspace.port_grace().deadline().map(|at| at.saturating_duration_since(now));
match (debounce, grace) {
(Some(a), Some(b)) => Some(a.min(b)),
(a, b) => a.or(b),
}
}
/// Say, once, what this buffer's `lucisv.toml` asked for and did not get.
+2 -1
View File
@@ -568,7 +568,8 @@ impl Server {
decode(request).and_then(|p: InlineCompletionParams| {
let at = p.text_document_position;
let (uri, position) = (at.text_document.uri, at.position);
inline::inline_completions(&self.workspace, &uri, position)
let selected = p.context.selected_completion_info.as_ref();
inline::inline_completions_in_context(&self.workspace, &uri, position, selected)
.map_or(Ok(Value::Null), to_value)
})
}
@@ -98,7 +98,9 @@ impl Server {
return to_value(Vec::<lsp_types::TextEdit>::new());
};
let settings = format::settings_for(doc, self.workspace.client_settings(), &params.options);
let edits = on_type::on_type_formatting(doc, at.position, &params.ch, &settings.config);
let auto_end = self.workspace.client_settings().auto_end.unwrap_or(true);
let edits =
on_type::on_type_formatting(doc, at.position, &params.ch, &settings.config, auto_end);
to_value(edits)
}
+19 -7
View File
@@ -88,6 +88,12 @@ pub struct ClientAbilities {
/// that said nothing is never asked, and keeps the instantiation counts it
/// last requested until it asks again for its own reasons.
pub code_lens_refresh: bool,
/// Whether the client accepts a `workspace/diagnostic/refresh` — what
/// makes a pulling client pull again when a connection entry held back
/// while it was typed is released
/// (`docs/features/port-entry-grace/README.md`). A client that said
/// nothing sees the release at its own next pull.
pub diagnostic_refresh: bool,
/// Whether the client opens a document the server asks it to
/// (`window/showDocument`). This is what lets the instantiation lens
/// navigate; a client without it still gets the sites back as the
@@ -316,7 +322,9 @@ impl Server {
///
/// A buffer sitting dirty past [`CHANGE_DEBOUNCE`] with nothing arriving is
/// flushed here rather than left waiting for a request that may never
/// come — diagnostics are the one answer the client never asks for.
/// come — diagnostics are the one answer the client never asks for. The
/// same wake-up releases a connection entry whose diagnostics were held
/// back while it was typed, once its grace has run out.
pub fn run(&mut self) -> Result<(), Box<dyn Error + Sync + Send>> {
use std::sync::mpsc::RecvTimeoutError;
loop {
@@ -338,20 +346,24 @@ impl Server {
}
continue;
}
let message = if self.dirty.is_empty() {
match self.queue.recv() {
// A connection entry whose grace ran out while messages kept
// arriving is released here, not only when the wait below times
// out (`docs/features/port-entry-grace/README.md`).
self.release_port_entries();
let message = match self.quiet_wait() {
None => match self.queue.recv() {
Ok(message) => message,
Err(_) => return Ok(()),
}
} else {
match self.queue.recv_timeout(CHANGE_DEBOUNCE) {
},
Some(wait) => match self.queue.recv_timeout(wait) {
Ok(message) => message,
Err(RecvTimeoutError::Timeout) => {
self.flush_dirty();
self.release_port_entries();
continue;
}
Err(RecvTimeoutError::Disconnected) => return Ok(()),
}
},
};
let batch = burst(&self.queue, message);
if self.process_batch(batch)? {
@@ -51,6 +51,10 @@ impl Server {
self.dirty.retain(|(pending, _)| *pending != uri);
}
}
// A buffer saved, closed or opened afresh holds nothing back any more
// (`docs/features/port-entry-grace/README.md`). Forgotten before the
// flush, so the flush below already publishes everything.
let released = self.forget_port_entry(&method, &notification);
// Everything but a `didChange` needs the buffers' analyses current —
// a `didSave` rebuilds the index on top of them — so the same flush a
// request gets happens here, with the one exception that *is* the
@@ -58,6 +62,14 @@ impl Server {
if method != DidChangeTextDocument::METHOD {
self.flush_dirty();
}
// A save of a buffer that was not dirty: nothing above said the full
// list, so it is said here, under a new generation for a pulling
// client. (The rescan the save starts says it again; that is the same
// list twice, never a stale one.)
if let Some(uri) = released {
self.generation += 1;
self.publish(&uri);
}
match method.as_str() {
DidOpenTextDocument::METHOD => {
if let Ok(p) = extract::<DidOpenTextDocumentParams>(notification) {
@@ -103,7 +115,7 @@ impl Server {
return;
}
let uri = p.text_document.uri;
let text = {
let (text, end) = {
let base = self
.dirty
.iter()
@@ -111,8 +123,12 @@ impl Server {
.map(|(_, text)| text.as_str())
.or_else(|| self.workspace.document(&uri).map(|doc| doc.text.as_str()))
.unwrap_or("");
sync::apply_changes(base, &p.content_changes)
sync::apply_changes_at(base, &p.content_changes)
};
// Where the edit ended is where someone is typing: the
// flush looks it up for a connection entry to hold back.
let now = std::time::Instant::now();
self.workspace.port_grace_mut().edited(&uri, end, now);
self.mark_dirty(uri, text);
}
}
@@ -315,6 +331,23 @@ impl Server {
}
}
/// Forget the connection entry a `didOpen`, `didSave` or `didClose` names,
/// answering the buffer whose full list a save now owes the client. An
/// open publishes on its own and a close clears, so only a save asks.
fn forget_port_entry(&mut self, method: &str, notification: &Notification) -> Option<Uri> {
let ends_typing = [
DidOpenTextDocument::METHOD,
DidSaveTextDocument::METHOD,
DidCloseTextDocument::METHOD,
];
if !ends_typing.contains(&method) {
return None;
}
let uri = document_uri(notification)?;
let held = self.workspace.port_grace_mut().forget(&uri);
(held && method == DidSaveTextDocument::METHOD).then_some(uri)
}
/// The rule selection in force, as a value two settings pushes can be
/// compared by.
///
@@ -346,6 +379,13 @@ fn closing_uri(notification: &Notification) -> Option<Uri> {
.map(|p| p.text_document.uri)
}
/// The `textDocument.uri` a document notification names, read without
/// consuming it; `None` when the params carry none that parses.
fn document_uri(notification: &Notification) -> Option<Uri> {
let uri = notification.params.get("textDocument")?.get("uri")?.as_str()?;
uri.parse().ok()
}
/// The paths behind a `didChangeWorkspaceFolders` list.
///
/// A folder whose URI is not a `file:` URI — or is not valid UTF-8 once
+41 -1
View File
@@ -121,6 +121,14 @@ pub struct ClientSettings {
/// followed by a space. Unset means on, the same way `inline_templates`
/// does — see `docs/features/inline-instantiation/README.md`.
pub inline_instantiation: Option<bool>,
/// `lucisv.inlineKeywords`: whether a typed proper prefix of a keyword
/// grows the rest of it as ghost text. Unset means on, independent of
/// `inline_templates` — see `docs/features/completion-ux/README.md`.
pub inline_keywords: Option<bool>,
/// `lucisv.autoEnd`: whether a newline typed after `begin` also writes
/// the `end` the block still owes. Unset means on — see
/// `docs/features/completion-ux/README.md`.
pub auto_end: Option<bool>,
/// `lucisv.formatOnSave`: whether `textDocument/willSaveWaitUntil` formats
/// the buffer. A plain `bool` rather than an `Option`, because unset and
/// off are the same answer here: an editor with a format-on-save of its
@@ -246,6 +254,8 @@ impl Default for ClientSettings {
uvm_utils_indent: None,
inline_templates: None,
inline_instantiation: None,
inline_keywords: None,
auto_end: None,
format_on_save: false,
max_file_size: DEFAULT_MAX_FILE_SIZE,
log_files: true,
@@ -345,6 +355,8 @@ pub fn from_payload(settings: &Value) -> ClientSettings {
uvm_utils_indent: flag(lucisv.get("format").and_then(|f| f.get("uvmUtilsIndent"))),
inline_templates: flag(lucisv.get("inlineTemplates")),
inline_instantiation: flag(lucisv.get("inlineInstantiation")),
inline_keywords: flag(lucisv.get("inlineKeywords")),
auto_end: flag(lucisv.get("autoEnd")),
// Anything that is not `true` leaves the hook declining, wrong-typed
// values included: the safe direction for a setting that rewrites the
// user's buffer on every save is the one that does nothing.
@@ -623,6 +635,8 @@ mod tests {
"filelist": "",
"inlineTemplates": true,
"inlineInstantiation": true,
"inlineKeywords": true,
"autoEnd": true,
"formatOnSave": false,
"index": {
"maxFileSize": 1048576, "logFiles": true,
@@ -838,7 +852,13 @@ mod tests {
// The two ghost-text settings are the ones whose absence resolves to
// `true` here, so a `false` default in the manifest would make the
// settings UI and the server disagree about a feature being on.
for ghost in ["lucisv.inlineTemplates", "lucisv.inlineInstantiation"] {
// `autoEnd` is the same kind of switch: absent means on.
for ghost in [
"lucisv.inlineTemplates",
"lucisv.inlineInstantiation",
"lucisv.inlineKeywords",
"lucisv.autoEnd",
] {
assert_eq!(properties[ghost]["default"], json!(true), "{ghost}");
assert_eq!(properties[ghost]["type"], json!("boolean"), "{ghost}");
}
@@ -1103,6 +1123,8 @@ mod tests {
ClientSettings {
inline_templates: Some(true),
inline_instantiation: Some(true),
inline_keywords: Some(true),
auto_end: Some(true),
..Default::default()
},
"the only difference from silence must be the settings whose \
@@ -1141,6 +1163,24 @@ mod tests {
assert_eq!(found.inline_templates, None, "the templates setting is untouched");
}
#[test]
fn inline_keywords_and_auto_end_are_booleans_and_nothing_else() {
let found = settings(json!({ "lucisv": { "inlineKeywords": false, "autoEnd": false } }));
assert_eq!((found.inline_keywords, found.auto_end), (Some(false), Some(false)));
let found = settings(json!({ "lucisv": { "inlineKeywords": true, "autoEnd": true } }));
assert_eq!((found.inline_keywords, found.auto_end), (Some(true), Some(true)));
// Absence is not `false`: both are on unless a client says no.
let found = settings(json!({ "lucisv": {} }));
assert_eq!((found.inline_keywords, found.auto_end), (None, None));
for bad in [json!("false"), json!(0), json!(null), json!([false])] {
let found = settings(json!({ "lucisv": { "inlineKeywords": bad, "autoEnd": bad } }));
assert_eq!((found.inline_keywords, found.auto_end), (None, None), "{bad} ignored");
}
// Independent of the template ghosts: one off leaves the other alone.
let found = settings(json!({ "lucisv": { "inlineKeywords": false } }));
assert_eq!(found.inline_templates, None, "the templates setting is untouched");
}
#[test]
fn format_on_save_is_off_until_a_client_asks_for_it() {
assert!(settings(json!({ "lucisv": { "formatOnSave": true } })).format_on_save);
+24
View File
@@ -30,6 +30,7 @@ mod buffers;
pub(crate) mod discover;
mod document;
mod incremental;
mod port_grace;
mod rescan;
mod scan;
mod scope;
@@ -39,6 +40,7 @@ mod views;
#[cfg(test)]
pub use document::mixed_buffer;
pub use document::{first_token_from, first_token_reaching, Document};
pub use port_grace::PortGrace;
pub use scan::{IndexEvent, Scan};
pub use views::FileView;
@@ -118,6 +120,10 @@ pub struct Workspace {
/// How many scans this workspace has run, so a session's lines can be
/// told apart — a `workspace` scope pays two (`docs/features/perf5-p4`).
scans: u32,
/// Where each buffer's last edit ended and the connection-list entry it
/// is in, while that entry's diagnostics are held back
/// (`docs/features/port-entry-grace/README.md`).
grace: PortGrace,
}
impl Workspace {
@@ -150,6 +156,24 @@ impl Workspace {
pub fn includes(&self) -> &IncludeGraph {
&self.includes
}
/// The edits whose connection-list entries are being held back.
pub fn port_grace(&self) -> &PortGrace {
&self.grace
}
/// The same, to note an edit, forget a buffer or release what is due.
pub fn port_grace_mut(&mut self) -> &mut PortGrace {
&mut self.grace
}
/// Look `uri`'s last edit up in the analysis just built for it, finding
/// the connection-list entry it is in, if any.
pub fn locate_port_entry(&mut self, uri: &Uri) {
if let Some(doc) = self.docs.get(uri) {
self.grace.locate(uri, doc);
}
}
}
#[cfg(test)]
@@ -0,0 +1,332 @@
//! The connection being typed: where each buffer's last edit ended, the
//! connection-list entry around it, and the diagnostics held back from that
//! entry while the typing goes on (`docs/features/port-entry-grace/README.md`).
//!
//! Someone typing `.po` into `sub u0 (…)` passes through a lone `.`, a `.p`
//! that names no port, a `.po(` with nothing closed — and every one of those
//! keystrokes used to draw a squiggle. While the last edit sits inside an
//! instantiation's port or parameter list, the diagnostics whose range starts
//! inside the entry around it are withheld from what is published or pulled.
//! Nothing outside that entry is ever withheld, and the entry is released —
//! the full list said again — when the next edit lands outside it, when
//! [`PORT_ENTRY_GRACE`] passes with no edit at all, or when the buffer is
//! saved, closed or reopened.
//!
//! The lookup is a token scan of the buffer just analyzed, no extra parse.
//! The parser's half — keeping the unfinished entry inside its own entry so
//! the rest of the file parses as if it were complete — is in
//! `vlog_parser`'s `recover_list.rs`, and the two agree on where an entry
//! ends: a `,` or the list's `)` at the list's own level, or the end of the
//! line when the next line opens a new `.` entry.
use std::collections::HashMap;
use std::time::{Duration, Instant};
use lsp_types::{Diagnostic, Uri};
use vlog_parser::token::{Token, TokenKind};
use vlog_parser::TextRange;
use super::Document;
use crate::signature::enclosing_list;
/// How long the diagnostics of the entry being typed are held back after the
/// last edit. Long enough to finish typing a port name and its connection,
/// short enough that a real mistake left behind is shown before the eye has
/// moved on.
pub const PORT_ENTRY_GRACE: Duration = Duration::from_millis(1500);
/// Every buffer's last edit, while it may still be withholding something.
#[derive(Default)]
pub struct PortGrace {
edits: HashMap<Uri, LastEdit>,
}
/// One buffer's last edit.
struct LastEdit {
/// Where the edit ended, in the buffer's newest text.
offset: u32,
/// When it arrived.
at: Instant,
/// Where it stands in the analysis of that text.
state: Located,
/// An edit has since landed in another buffer: release at the next
/// chance rather than when the quiet period ends.
released: bool,
}
/// Whether a buffer's last edit has been looked up in its analysis yet.
enum Located {
/// The buffer is dirty; its analysis is not the text the edit is in.
Pending,
/// The edit is inside this connection-list entry.
Entry(TextRange),
}
impl PortGrace {
/// Note a buffer's edit, `end` being where the last of its changes ended
/// in the new text — `None` for a full-document replacement, which says
/// nothing about where anyone is typing and so withholds nothing.
///
/// An edit is "elsewhere" for every other buffer, so whatever those are
/// withholding is released at the next chance.
pub fn edited(&mut self, uri: &Uri, end: Option<u32>, now: Instant) {
for (other, edit) in self.edits.iter_mut() {
if other != uri {
edit.released = true;
}
}
match end {
Some(offset) => {
let edit = LastEdit { offset, at: now, state: Located::Pending, released: false };
self.edits.insert(uri.clone(), edit);
}
None => {
self.edits.remove(uri);
}
}
}
/// Look a buffer's pending edit up in `doc`, its freshly analyzed text.
/// An edit outside every connection list is forgotten on the spot: it
/// withholds nothing and needs no release.
pub fn locate(&mut self, uri: &Uri, doc: &Document) {
let Some(edit) = self.edits.get_mut(uri) else { return };
if !matches!(edit.state, Located::Pending) {
return;
}
match entry_around(doc, edit.offset) {
Some(entry) => edit.state = Located::Entry(entry),
None => {
self.edits.remove(uri);
}
}
}
/// `diagnostics` without the ones whose range starts inside the entry
/// `uri`'s last edit is in. Everything, when there is no such entry.
pub fn withhold(
&self,
uri: &Uri,
doc: &Document,
diagnostics: Vec<Diagnostic>,
) -> Vec<Diagnostic> {
let Some(entry) = self.entry_of(uri) else { return diagnostics };
let positions = doc.positions();
diagnostics
.into_iter()
.filter(|d| !inside(entry, positions.offset(d.range.start)))
.collect()
}
/// The entry `uri`'s last edit is in, while it is withholding.
pub fn entry_of(&self, uri: &Uri) -> Option<TextRange> {
match self.edits.get(uri)?.state {
Located::Entry(entry) => Some(entry),
Located::Pending => None,
}
}
/// Drop a buffer's edit — it was saved, closed or opened afresh — and say
/// whether it was withholding anything, i.e. whether its full list is
/// owed now.
pub fn forget(&mut self, uri: &Uri) -> bool {
matches!(self.edits.remove(uri), Some(LastEdit { state: Located::Entry(_), .. }))
}
/// When the next release is due: the end of the earliest quiet period,
/// or right away for an entry an edit elsewhere released.
pub fn deadline(&self) -> Option<Instant> {
self.edits.values().filter_map(LastEdit::due_at).min()
}
/// Take every buffer whose release is due at `now`: their full lists are
/// owed to the client.
pub fn due(&mut self, now: Instant) -> Vec<Uri> {
let due: Vec<Uri> = self
.edits
.iter()
.filter(|(_, edit)| edit.due_at().is_some_and(|at| at <= now))
.map(|(uri, _)| uri.clone())
.collect();
for uri in &due {
self.edits.remove(uri);
}
due
}
}
impl LastEdit {
/// When this edit's entry is to be released; `None` while it has no
/// entry yet.
fn due_at(&self) -> Option<Instant> {
if !matches!(self.state, Located::Entry(_)) {
return None;
}
if self.released {
return Some(self.at);
}
Some(self.at.checked_add(PORT_ENTRY_GRACE).unwrap_or(self.at))
}
}
/// Whether `offset` lies in `entry`, both ends included: a diagnostic on the
/// token that ends the entry (the `,` of `.b(y),)`, the `.` that proves a
/// comma missing) is the entry's own news.
fn inside(entry: TextRange, offset: u32) -> bool {
entry.start <= offset && offset <= entry.end
}
/// The extent of the connection-list entry around `offset`, or `None` when
/// `offset` is not inside an instantiation's port or parameter list.
///
/// The entry starts at the last separator before `offset` at the list's own
/// level — a `,`, which it includes, or the list's `(`, which it does not —
/// or at a `.` that opens its own line, which is where the parser ends an
/// entry left open on the line above. It ends at the first `,`, `;` or
/// closing bracket after `offset` at the level `offset` is at, or at the end
/// of `offset`'s line — reaching on to the next line's first token when that
/// is a `.`, the token that proves a `,` is missing. A `;` ends it at any
/// level: no connection list holds one.
pub fn entry_around(doc: &Document, offset: u32) -> Option<TextRange> {
let tokens = &doc.tokens;
let list = enclosing_list(tokens, offset)?;
let next = tokens.partition_point(|t| t.span.start < offset);
// The bracket count above takes a value left open (`.po(`) for the list
// never closing, so a list "around" an edit three items further down is
// only believed when no `;` stands between them: a connection list never
// holds one, and every item after it ends in one.
if tokens.get(list.open + 1..next)?.iter().any(|t| t.is_sym(";")) {
return None;
}
// Only an instance's *named* list: `enclosing_list` also accepts a
// header's `name #(`, a positional list, a call after a block label and a
// function whose return type is a name, and none of those is typed the
// way a `.name(…)` connection is.
if !holds_a_named_entry(tokens, list.open) || in_a_declaration_header(tokens, list.open) {
return None;
}
let (start, depth) = entry_start(tokens, list.open, next);
let (line, _) = doc.line_index.line_col(offset);
let end = entry_end(&tokens[next..], depth, offset, line);
Some(TextRange::new(start, end.max(start)))
}
/// Walk from the list's `(` up to the token at `next`: where the entry there
/// starts, and how many brackets are open inside it at that point.
fn entry_start(tokens: &[Token], open: usize, next: usize) -> (u32, u32) {
let mut start = tokens[open].span.end;
let mut depth = 0u32;
for i in open + 1..next {
let t = &tokens[i];
if t.is_sym(".") && tokens[i - 1].line != t.line {
// A `.` opening its line starts an entry even inside a bracket:
// the parser ends a value left open on the line above here.
start = t.span.start;
depth = 0;
} else if is_open(t) {
depth += 1;
} else if is_close(t) {
depth = depth.saturating_sub(1);
} else if depth == 0 && t.is_sym(",") {
start = t.span.start;
}
}
(start, depth)
}
/// Walk on from `offset` (`after` being the tokens from there on, `depth`
/// the brackets open inside the entry, `line` 1-based): where the entry ends.
fn entry_end(after: &[Token], mut depth: u32, offset: u32, line: u32) -> u32 {
let mut end = offset;
for t in after {
if t.kind == TokenKind::Eof {
break;
}
if t.line != line {
return if t.is_sym(".") { t.span.start } else { end };
}
if is_close(t) {
if depth == 0 {
return t.span.start;
}
depth -= 1;
} else if is_open(t) {
depth += 1;
} else if t.is_sym(";") || (depth == 0 && t.is_sym(",")) {
return t.span.start;
}
end = t.span.end;
}
end
}
/// The keywords whose header lists (`name #(`, `name (`) are declarations,
/// never an instance's connections.
const DECLARATION_HEADERS: &[&str] = &[
"module",
"macromodule",
"interface",
"program",
"class",
"package",
"primitive",
"function",
"task",
"checker",
];
/// Whether the list opened at `open` holds an entry, at its own level, that
/// starts with `.` — the entry being typed counts. A `.` opening its own line
/// counts at any depth, as it does for [`entry_start`]: the parser ends a
/// value left open on the line above there. The walk ends at the list's `)`,
/// a `;`, or the end of the file.
fn holds_a_named_entry(tokens: &[Token], open: usize) -> bool {
let mut depth = 0u32;
for i in open + 1..tokens.len() {
let t = &tokens[i];
let prev = &tokens[i - 1];
if t.kind == TokenKind::Eof || t.is_sym(";") {
return false;
}
if t.is_sym(".") {
let entry_start = i == open + 1
|| prev.line != t.line
|| (depth == 0 && (prev.is_sym(",") || prev.kind == TokenKind::Attribute));
if entry_start {
return true;
}
} else if is_open(t) {
depth += 1;
} else if is_close(t) {
if depth == 0 {
return false;
}
depth -= 1;
}
}
false
}
/// Whether the list opened at `open` belongs to a declaration's header: a
/// [`DECLARATION_HEADERS`] keyword stands between it and the `;` that ended
/// the item before.
fn in_a_declaration_header(tokens: &[Token], open: usize) -> bool {
tokens[..open]
.iter()
.rev()
.take_while(|t| !t.is_sym(";"))
.any(|t| t.kind == TokenKind::Keyword && DECLARATION_HEADERS.contains(&t.text.as_str()))
}
/// True on `(`, `[` or `{`.
fn is_open(t: &Token) -> bool {
t.is_sym("(") || t.is_sym("[") || t.is_sym("{")
}
/// True on `)`, `]` or `}`.
fn is_close(t: &Token) -> bool {
t.is_sym(")") || t.is_sym("]") || t.is_sym("}")
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,350 @@
//! The entry bounds, the withhold/release state machine with time injected,
//! and what the parser's half buys the editor: the tokens and the findings
//! after an unfinished entry are those of the completed one.
use std::str::FromStr;
use lsp_types::{DiagnosticSeverity, SemanticToken};
use super::*;
use crate::state::Workspace;
fn uri(name: &str) -> Uri {
Uri::from_str(&format!("file:///rtl/{name}")).expect("uri")
}
/// A workspace holding `text` as `m.sv`.
fn open(text: &str) -> (Workspace, Uri) {
let uri = uri("m.sv");
let mut ws = Workspace::default();
ws.set_document(uri.clone(), text.to_string());
(ws, uri)
}
/// `text` with the `|` marking the cursor taken out, and the cursor's offset.
fn cursor(marked: &str) -> (String, u32) {
let at = marked.find('|').expect("a `|` marks the cursor");
(marked.replacen('|', "", 1), at as u32)
}
/// The text of the entry around the `|` in `marked`, or `None`.
fn entry_text(marked: &str) -> Option<String> {
let (text, at) = cursor(marked);
let (ws, uri) = open(&text);
let doc = ws.document(&uri).expect("open");
entry_around(doc, at).map(|r| text[r.as_range()].to_string())
}
// ----------------------------------------------------------------------
// Entry bounds
// ----------------------------------------------------------------------
#[test]
fn the_entry_runs_from_the_comma_before_to_the_close_after() {
let got = entry_text("module m;\n sub u0 (.a(x), .p|);\nendmodule\n");
assert_eq!(got.as_deref(), Some(", .p"));
let got = entry_text("module m;\n sub u0 (.p|, .a(x));\nendmodule\n");
assert_eq!(got.as_deref(), Some(".p"), "the list's own `(` is not the entry's");
}
#[test]
fn a_cursor_inside_a_value_takes_the_whole_entry() {
let got = entry_text("module m;\n sub u0 (.a(x), .b(y|), .c(z));\nendmodule\n");
assert_eq!(got.as_deref(), Some(", .b(y)"));
let got = entry_text("module m;\n sub u0 (.a(x), .b({p, q|}), .c(z));\nendmodule\n");
assert_eq!(got.as_deref(), Some(", .b({p, q})"), "a `,` inside a bracket is the value's");
}
#[test]
fn an_entry_left_open_ends_with_its_line_and_reaches_the_next_dot() {
// The parser's diagnostic is on the `(`; the next line opens a new entry,
// whose `.` the entry reaches to.
let got = entry_text("module m;\n sub u0 (.a(x), .po(|\n .b(y));\nendmodule\n");
assert_eq!(got.as_deref(), Some(", .po(\n "));
// Typing on the line below an entry left open: the entry is that line's.
let got = entry_text("module m;\n sub u0 (.a(x), .po(\n .b(y|));\nendmodule\n");
assert_eq!(got.as_deref(), Some(".b(y)"));
}
#[test]
fn a_missing_comma_is_inside_the_entry_typed_on_either_side_of_it() {
// Typed below: the entry starts at its own line's `.`, which is where the
// parser reports the missing `,`.
let got = entry_text("module m;\n sub u0 (.a(x)\n .b(y|));\nendmodule\n");
assert_eq!(got.as_deref(), Some(".b(y)"));
// Typed above: the entry reaches the next line's `.`.
let got = entry_text("module m;\n sub u0 (.a(x), .po|\n .b(y));\nendmodule\n");
assert_eq!(got.as_deref(), Some(", .po\n "));
}
#[test]
fn a_trailing_comma_is_inside_the_entry_after_it() {
let got = entry_text("module m;\n sub u0 (.a(x),|\n );\nendmodule\n");
assert_eq!(got.as_deref(), Some(","));
}
#[test]
fn a_parameter_list_has_entries_too() {
let got = entry_text("module m;\n sub #(.W(8), .D|) u0 (.a(x));\nendmodule\n");
assert_eq!(got.as_deref(), Some(", .D"));
let got = entry_text("module m;\n sub #(.W(|\n u0 (.a(x));\nendmodule\n");
assert_eq!(got.as_deref(), Some(".W("), "an override typed open");
}
/// The entry being typed is enough to make a list a named one, and so is
/// any other named entry when the one being typed is still empty.
#[test]
fn a_named_list_is_recognised_from_any_named_entry() {
let got = entry_text("module m;\n sub u0 (.po|);\nendmodule\n");
assert_eq!(got.as_deref(), Some(".po"));
let got = entry_text("module m;\n sub u0 (.|);\nendmodule\n");
assert_eq!(got.as_deref(), Some("."));
let got = entry_text("module m;\n sub u0 (.a(x), |);\nendmodule\n");
assert_eq!(got.as_deref(), Some(", "), "a fresh entry after a `,`");
}
/// QA's list (2026-11-17): every list `enclosing_list` accepts that is not
/// an instance's named list withholds nothing.
#[test]
fn lists_that_are_not_named_connections_withhold_nothing() {
for marked in [
// A module header's parameter list.
"module hm #(parameter W = |) (input logic a);\nendmodule\n",
"interface hi #(parameter W = 1|);\nendinterface\n",
"class hc #(type T = int|);\nendclass\n",
// A positional instance list.
"module m;\n sub u0 (x, y|, z);\nendmodule\n",
// A function declaration with a user-type return.
"module m;\n function automatic my_t f(input a|);\n endfunction\nendmodule\n",
// A call right after a block label.
"module m;\n initial begin : blk\n my_task(a, b|);\n end\nendmodule\n",
// A fresh, still empty instance list: nothing named in it yet.
"module m;\n sub u0 (|);\nendmodule\n",
] {
assert_eq!(entry_text(marked), None, "{marked}");
}
}
#[test]
fn nothing_outside_a_connection_list_is_an_entry() {
for marked in [
"module m;\n wire w|;\nendmodule\n",
"module m;\n sub u0| (.a(x));\nendmodule\n",
"module m;\n sub u0 (.a(x));|\nendmodule\n",
"module m;\n initial f(a, b|);\nendmodule\n",
"module m (input a|, input b);\nendmodule\n",
// A value left open makes the list's bracket look unclosed to the
// end of the file; the `;` after it says the list is over.
"module m;\n sub u0 (.a(x), .po(\n .b(y));\n wire w|;\nendmodule\n",
] {
assert_eq!(entry_text(marked), None, "{marked}");
}
// The next instance's own list is still found, and is its own.
let marked = "module m;\n sub u0 (.a(x), .po(\n .b(y));\n sub u1 (.c|(z));\nendmodule\n";
assert_eq!(entry_text(marked).as_deref(), Some(".c(z)"));
}
// ----------------------------------------------------------------------
// Withholding
// ----------------------------------------------------------------------
/// A module whose port list is fine, so only the instance's entries say
/// anything, plus one unrelated parse error far from the list.
const TYPING: &str =
"module m;\n logic x, y;\n sub u0 (.a(x),\n .po(\n .b(y));\n wire ;\nendmodule\n";
#[test]
fn only_the_entry_being_typed_is_withheld() {
let (mut ws, uri) = open(TYPING);
let at = TYPING.find(".po(").expect("entry") as u32 + 4;
let now = Instant::now();
ws.port_grace_mut().edited(&uri, Some(at), now);
ws.locate_port_entry(&uri);
let doc = ws.document(&uri).expect("open");
let all = crate::diagnostics::all(doc);
let errors: Vec<_> =
all.iter().filter(|d| d.severity == Some(DiagnosticSeverity::ERROR)).collect();
assert_eq!(errors.len(), 2, "the open `(` and the `wire ;`: {all:#?}");
let shown = ws.port_grace().withhold(&uri, doc, all.clone());
assert_eq!(shown.len(), all.len() - 1, "exactly the entry's one: {shown:#?}");
assert!(shown.iter().any(|d| d.range.start.line == 5), "the `wire ;` is still said");
assert!(shown.iter().all(|d| d.range.start.line != 3), "{shown:#?}");
}
#[test]
fn an_edit_outside_every_list_withholds_nothing() {
let (mut ws, uri) = open(TYPING);
let at = TYPING.find("wire ;").expect("wire") as u32 + 4;
ws.port_grace_mut().edited(&uri, Some(at), Instant::now());
ws.locate_port_entry(&uri);
let doc = ws.document(&uri).expect("open");
let all = crate::diagnostics::all(doc);
assert_eq!(ws.port_grace().withhold(&uri, doc, all.clone()), all);
assert_eq!(ws.port_grace().deadline(), None, "no release is owed");
}
#[test]
fn a_whole_document_change_withholds_nothing() {
let (mut ws, uri) = open(TYPING);
let at = TYPING.find(".po(").expect("entry") as u32 + 4;
ws.port_grace_mut().edited(&uri, Some(at), Instant::now());
ws.port_grace_mut().edited(&uri, None, Instant::now());
ws.locate_port_entry(&uri);
assert_eq!(ws.port_grace().entry_of(&uri), None);
}
// ----------------------------------------------------------------------
// The release, with time injected
// ----------------------------------------------------------------------
/// A grace with one located entry in `uri`, edited at `t0`.
fn held(ws: &mut Workspace, uri: &Uri, t0: Instant) {
let at = TYPING.find(".po(").expect("entry") as u32 + 4;
ws.port_grace_mut().edited(uri, Some(at), t0);
ws.locate_port_entry(uri);
assert!(ws.port_grace().entry_of(uri).is_some(), "premise: the edit is in an entry");
}
#[test]
fn the_entry_is_released_when_the_quiet_period_ends() {
let (mut ws, uri) = open(TYPING);
let t0 = Instant::now();
held(&mut ws, &uri, t0);
assert_eq!(ws.port_grace().deadline(), Some(t0 + PORT_ENTRY_GRACE));
let almost = t0 + PORT_ENTRY_GRACE - Duration::from_millis(1);
assert!(ws.port_grace_mut().due(almost).is_empty(), "not a moment early");
assert_eq!(ws.port_grace_mut().due(t0 + PORT_ENTRY_GRACE), vec![uri.clone()]);
assert_eq!(ws.port_grace().entry_of(&uri), None, "released means withholding nothing");
assert_eq!(ws.port_grace().deadline(), None);
}
#[test]
fn another_edit_restarts_the_quiet_period() {
let (mut ws, uri) = open(TYPING);
let t0 = Instant::now();
held(&mut ws, &uri, t0);
let t1 = t0 + Duration::from_millis(1000);
held(&mut ws, &uri, t1);
assert!(ws.port_grace_mut().due(t0 + PORT_ENTRY_GRACE).is_empty());
assert_eq!(ws.port_grace_mut().due(t1 + PORT_ENTRY_GRACE), vec![uri]);
}
#[test]
fn an_unanalyzed_edit_is_not_due() {
let (mut ws, uri) = open(TYPING);
let t0 = Instant::now();
ws.port_grace_mut().edited(&uri, Some(3), t0);
assert_eq!(ws.port_grace().deadline(), None, "pending: the flush has not looked yet");
assert!(ws.port_grace_mut().due(t0 + PORT_ENTRY_GRACE).is_empty());
}
#[test]
fn an_edit_in_another_buffer_releases_at_once() {
let (mut ws, a) = open(TYPING);
let b = uri("other.sv");
let t0 = Instant::now();
held(&mut ws, &a, t0);
let t1 = t0 + Duration::from_millis(100);
ws.port_grace_mut().edited(&b, Some(0), t1);
assert_eq!(ws.port_grace().deadline(), Some(t0), "due already");
assert_eq!(ws.port_grace_mut().due(t1), vec![a]);
}
#[test]
fn forgetting_says_whether_anything_was_held() {
let (mut ws, uri) = open(TYPING);
assert!(!ws.port_grace_mut().forget(&uri), "nothing to forget");
ws.port_grace_mut().edited(&uri, Some(3), Instant::now());
assert!(!ws.port_grace_mut().forget(&uri), "pending withholds nothing");
held(&mut ws, &uri, Instant::now());
assert!(ws.port_grace_mut().forget(&uri));
assert_eq!(ws.port_grace().entry_of(&uri), None);
}
// ----------------------------------------------------------------------
// The parser's half, as the editor sees it
// ----------------------------------------------------------------------
/// The module `sub` and an instance of it with `entry` as its second
/// connection, on a line of its own (line 4, 0-based), then more after it.
fn with_entry(entry: &str) -> String {
format!(
"module sub (input logic a, input logic po, output logic b);\nendmodule\n\
module m;\n logic x, y;\n sub u0 (.a(x),\n {entry}\n .b(y));\n \
assign x = y;\n sub u1 (.a(y), .po(x), .b());\nendmodule\n"
)
}
/// Semantic tokens as absolute `(line, start, length, type, modifiers)`.
fn absolute(tokens: &[SemanticToken]) -> Vec<(u32, u32, u32, u32, u32)> {
let (mut line, mut start) = (0u32, 0u32);
tokens
.iter()
.map(|t| {
if t.delta_line > 0 {
start = 0;
}
line += t.delta_line;
start += t.delta_start;
(line, start, t.length, t.token_type, t.token_modifiers_bitset)
})
.collect()
}
/// What the editor shows after the entry's line: the semantic tokens and the
/// diagnostics, the latter as `(line, character, message)`.
type After = (Vec<(u32, u32, u32, u32, u32)>, Vec<(u32, u32, String)>);
fn after_entry(text: &str) -> After {
let (ws, uri) = open(text);
let doc = ws.document(&uri).expect("open");
let entry_line = 5;
let tokens = absolute(&crate::tokens::semantic_tokens(doc))
.into_iter()
.filter(|t| t.0 > entry_line)
.collect();
let diags = crate::diagnostics::all(doc)
.into_iter()
.filter(|d| d.range.start.line > entry_line)
.map(|d| (d.range.start.line, d.range.start.character, d.message))
.collect();
(tokens, diags)
}
/// The owner's ask: the rest of the file colours and lints as the
/// auto-completed version (`.po` → `.po()`) would.
#[test]
fn after_an_unfinished_entry_the_file_reads_as_with_the_entry_completed() {
// An entry the parser had to recover reads on to the next `.` as though
// its `,` had been typed too.
let done = after_entry(&with_entry(".po(),"));
assert!(!done.0.is_empty(), "premise: there are tokens after the entry");
assert!(done.1.is_empty(), "premise: the completed file says nothing: {:?}", done.1);
for unfinished in [".po(", ".", ".po(x"] {
assert_eq!(after_entry(&with_entry(unfinished)), done, "after `{unfinished}`");
}
// `.po` is already a whole (implicit) connection; what it still lacks is
// the `,`, and so does its completion — the same one diagnostic, on the
// `.` of the line after, in both.
let done = after_entry(&with_entry(".po()"));
assert_eq!(done.1.len(), 1, "{:?}", done.1);
for unfinished in [".po", ".p"] {
assert_eq!(after_entry(&with_entry(unfinished)), done, "after `{unfinished}`");
}
}
/// The unfinished entry is one parse error and nothing else: the entries
/// written after it still resolve, so nothing about them is reported.
#[test]
fn an_unfinished_entry_costs_one_error_and_no_cascade() {
for unfinished in [".po(", "."] {
let (ws, uri) = open(&with_entry(unfinished));
let doc = ws.document(&uri).expect("open");
let errors: Vec<_> = crate::diagnostics::all(doc)
.into_iter()
.filter(|d| d.severity == Some(DiagnosticSeverity::ERROR))
.collect();
assert_eq!(errors.len(), 1, "`{unfinished}`: {errors:#?}");
assert_eq!(errors[0].range.start.line, 5, "on the entry's own line");
}
}
+45 -1
View File
@@ -18,13 +18,31 @@ use crate::convert::Positions;
///
/// A change with no range replaces the whole document — what a full-sync
/// client sends, and what still works if one arrives mid-batch.
///
/// `#[cfg(test)]` since the server reads where the edit ended too
/// ([`apply_changes_at`]); the tests, and the cross-check against the
/// reference implementation, come in by this door.
#[cfg(test)]
pub fn apply_changes(text: &str, changes: &[TextDocumentContentChangeEvent]) -> String {
apply_changes_at(text, changes).0
}
/// `apply_changes`, and where the last change ended in the text that
/// results: the byte offset just past what it inserted. `None` when the last
/// change replaced the whole document — that says nothing about where anyone
/// is typing (`docs/features/port-entry-grace/README.md`).
pub fn apply_changes_at(
text: &str,
changes: &[TextDocumentContentChangeEvent],
) -> (String, Option<u32>) {
let mut text = text.to_string();
let mut edit_end = None;
for change in changes {
let Some(range) = change.range else {
// The whole document. This also resets the state that the ranges
// after it in the same batch are positioned against.
text.clone_from(&change.text);
edit_end = None;
continue;
};
// A fresh line table per change: each range is positioned against the
@@ -46,8 +64,9 @@ pub fn apply_changes(text: &str, changes: &[TextDocumentContentChangeEvent]) ->
continue;
};
text = format!("{before}{}{after}", change.text);
edit_end = u32::try_from(start + change.text.len()).ok();
}
text
(text, edit_end)
}
#[cfg(test)]
@@ -84,6 +103,31 @@ mod tests {
assert_eq!(after, "module m;\n wire ab;\nendmodule\n");
}
/// Where the last change ended is the offset just past what it inserted,
/// in the text that results — the cursor's place after typing it.
#[test]
fn the_edit_end_is_just_past_the_inserted_text() {
let text = "module m;\n wire a;\nendmodule\n";
let (after, end) = apply_changes_at(text, &[edit((1, 8), (1, 8), "bc")]);
assert_eq!(after, "module m;\n wire abc;\nendmodule\n");
assert_eq!(end, Some(20), "just past the `bc`");
assert_eq!(&after[..20], "module m;\n wire abc");
let (_, end) = apply_changes_at(text, &[edit((1, 7), (1, 8), "")]);
assert_eq!(end, Some(17), "a delete ends where it started");
}
/// The last change of a batch decides, and a rangeless one — a whole
/// document — says nothing about where anyone is typing.
#[test]
fn the_edit_end_follows_the_last_change_and_a_whole_document_has_none() {
let text = "module m;\nendmodule\n";
let (_, end) = apply_changes_at(text, &[edit((0, 0), (0, 0), "x"), whole("module n;\n")]);
assert_eq!(end, None);
let (_, end) = apply_changes_at(text, &[whole("module n;\n"), edit((0, 9), (0, 9), "\n")]);
assert_eq!(end, Some(10));
assert_eq!(apply_changes_at(text, &[]), (text.to_string(), None));
}
#[test]
fn a_delete_removes_exactly_the_range() {
let text = "module m;\n wire aaa;\nendmodule\n";
+22 -14
View File
@@ -115,6 +115,11 @@ impl Template {
}
/// Every template offered in `dialect`, the shared ones first.
///
/// The order is the popup's order among templates: the tier writes each one's
/// position here into its `sortText` (`completion-ux`, 2026-11-17), so two
/// templates reached by the same prefix show in registry order rather than by
/// label.
pub fn for_dialect(dialect: Dialect) -> impl Iterator<Item = &'static Template> {
let dialect_only = match dialect {
Dialect::SystemVerilog => SYSTEMVERILOG,
@@ -198,13 +203,8 @@ const SYSTEMVERILOG: &[Template] = &[
detail: "for loop with a local loop variable",
body: &[(0, "for (int ${1:i} = 0; $1 < ${2:N}; $1++) begin"), (1, "$0"), (0, "end")],
},
Template {
label: "always_ff @(posedge clk)",
prefix: "always_ff",
gate: Gate::Item,
detail: "synchronous block, no reset",
body: &[(0, "always_ff @(posedge ${1:clk}) begin"), (1, "$0"), (0, "end")],
},
// With-reset before clock-only (TODO §68.1): a flop with an async reset is
// the commoner one to write, and the registry order is the popup order.
Template {
label: "always_ff with reset",
prefix: "always_ff",
@@ -220,6 +220,13 @@ const SYSTEMVERILOG: &[Template] = &[
(0, "end"),
],
},
Template {
label: "always_ff @(posedge clk)",
prefix: "always_ff",
gate: Gate::Item,
detail: "synchronous block, no reset",
body: &[(0, "always_ff @(posedge ${1:clk}) begin"), (1, "$0"), (0, "end")],
},
Template {
label: "always_comb begin/end",
prefix: "always_comb",
@@ -267,13 +274,7 @@ const VERILOG: &[Template] = &[
detail: "for loop over an existing variable",
body: &[(0, "for (${1:i} = 0; $1 < ${2:N}; $1 = $1 + 1) begin"), (1, "$0"), (0, "end")],
},
Template {
label: "always @(posedge clk)",
prefix: "always",
gate: Gate::Item,
detail: "synchronous block, no reset",
body: &[(0, "always @(posedge ${1:clk}) begin"), (1, "$0"), (0, "end")],
},
// With-reset first, as in the SystemVerilog list above.
Template {
label: "always @(posedge clk or negedge rst_n)",
prefix: "always",
@@ -289,6 +290,13 @@ const VERILOG: &[Template] = &[
(0, "end"),
],
},
Template {
label: "always @(posedge clk)",
prefix: "always",
gate: Gate::Item,
detail: "synchronous block, no reset",
body: &[(0, "always @(posedge ${1:clk}) begin"), (1, "$0"), (0, "end")],
},
Template {
label: "always @(*)",
prefix: "always",
+197 -30
View File
@@ -1,24 +1,30 @@
//! `textDocument/semanticTokens/full`, `/range` and `/full/delta`.
//!
//! Classification comes from the lexer's token stream, refined for plain
//! identifiers by `vlog_semantic`. The full mapping table is in
//! `docs/features/lucisv-server/README.md`; the range and delta rules are in
//! `docs/features/semantic-tokens-delta/README.md`.
//! identifiers by `vlog_semantic` + `ExternalResolutions` and for module
//! instantiations / `#(...)` parameter lists by `Document.tree`
//! (`docs/features/instantiation-highlighting/README.md`). The full mapping
//! table is in `docs/features/lucisv-server/README.md`; the range and delta
//! rules are in `docs/features/semantic-tokens-delta/README.md`.
//!
//! One tokenizer and one encoder serve all three requests: classification
//! produces [`Absolute`] tokens (line, column, length — the coordinates the
//! protocol thinks in), a range answer drops the ones it does not want, and
//! `encode` delta-encodes whatever is left from the start of the document.
use std::collections::HashMap;
use lsp_types::{
Position, Range, SemanticToken, SemanticTokenModifier, SemanticTokenType, SemanticTokensEdit,
};
use vlog_parser::token::{Token, TokenKind};
use vlog_parser::TextRange;
use vlog_semantic::{Semantics, SymbolKind};
use vlog_semantic::{Definition, ExternalResolutions, Semantics, SymbolKind};
use crate::state::Document;
mod instantiation;
/// The legend the server advertises. The index into this array is what the
/// wire format carries, so the order is part of the protocol contract and
/// must match [`Highlight`].
@@ -133,6 +139,7 @@ pub fn semantic_tokens_in_range(doc: &Document, range: Range) -> Vec<SemanticTok
/// See `docs/features/large-file-mode/README.md`.
pub fn semantic_tokens_in_window(doc: &Document, range: Range) -> Vec<SemanticToken> {
let window = crate::large::window(doc, range);
let overrides = HashMap::new();
let mut pieces = Vec::new();
// The comment spans the lexer never saw go in first; `flatten` sorts, so
// the order they are collected in cannot reach the wire.
@@ -140,16 +147,17 @@ pub fn semantic_tokens_in_window(doc: &Document, range: Range) -> Vec<SemanticTo
pieces.push(Piece { span: *span, ty: Highlight::Comment, modifiers: 0 });
}
for token in &window.tokens {
collect(token, &doc.semantics, &mut pieces);
collect(token, doc, &overrides, &mut pieces);
}
encode(&within(flatten(pieces, doc), range))
}
/// Classify the whole buffer, split at line boundaries, in wire order.
fn absolute(doc: &Document) -> Vec<Absolute> {
let overrides = instantiation::overrides(doc);
let mut pieces = Vec::new();
for token in &doc.tokens {
collect(token, &doc.semantics, &mut pieces);
collect(token, doc, &overrides, &mut pieces);
}
flatten(pieces, doc)
}
@@ -177,12 +185,17 @@ fn within(tokens: Vec<Absolute>, range: Range) -> Vec<Absolute> {
/// after it on the same line — because [`flatten`] converts the offsets with a
/// single forward cursor. Ordering is otherwise invisible: `flatten` sorts,
/// and no two pieces here can start at the same byte.
fn collect(token: &Token, semantics: &Semantics, out: &mut Vec<Piece>) {
fn collect(
token: &Token,
doc: &Document,
overrides: &HashMap<u32, Highlight>,
out: &mut Vec<Piece>,
) {
for comment in &token.leading {
out.push(Piece { span: comment.span, ty: Highlight::Comment, modifiers: 0 });
}
if let Some(ty) = classify(token, semantics) {
out.push(Piece { span: token.span, ty, modifiers: modifiers(token, semantics) });
if let Some(ty) = classify(token, doc, overrides) {
out.push(Piece { span: token.span, ty, modifiers: modifiers(token, &doc.semantics) });
}
if let Some(comment) = &token.trailing {
out.push(Piece { span: comment.span, ty: Highlight::Comment, modifiers: 0 });
@@ -190,7 +203,14 @@ fn collect(token: &Token, semantics: &Semantics, out: &mut Vec<Piece>) {
}
/// What a token is, or `None` for the ones this server does not colour.
fn classify(token: &Token, semantics: &Semantics) -> Option<Highlight> {
fn classify(
token: &Token,
doc: &Document,
overrides: &HashMap<u32, Highlight>,
) -> Option<Highlight> {
if let Some(&ty) = overrides.get(&token.span.start) {
return Some(ty);
}
match token.kind {
TokenKind::Keyword => Some(Highlight::Keyword),
TokenKind::Number => Some(Highlight::Number),
@@ -201,8 +221,8 @@ fn classify(token: &Token, semantics: &Semantics) -> Option<Highlight> {
// A macro *usage* lexes as an identifier whose text starts with a
// backtick; `is_macro` is the lexer's own public test for it.
TokenKind::Ident if token.is_macro() => Some(Highlight::Macro),
TokenKind::Ident => Some(identifier_type(token.span.start, semantics)),
// Punctuation: deliberately not emitted, see the feature README.
TokenKind::Ident => Some(identifier_type(token.span.start, &doc.semantics, &doc.external)),
// Punctuation outside `overrides`: deliberately not emitted, see the feature README.
TokenKind::Symbol | TokenKind::Eof => None,
}
}
@@ -219,16 +239,28 @@ fn modifiers(token: &Token, semantics: &Semantics) -> u32 {
}
}
/// A plain identifier, classified through the symbol table: its own
/// declaration, the declaration it resolves to, or `variable` when nothing in
/// this file knows (an external candidate, or a name a macro would produce).
fn identifier_type(offset: u32, semantics: &Semantics) -> Highlight {
let symbol = semantics
.symbol_at(offset)
.or_else(|| semantics.reference_at(offset).and_then(|r| r.resolved()))
.and_then(|id| semantics.symbol(id));
match symbol {
Some(symbol) => symbol_type(symbol.kind),
/// What symbol kind `offset` resolves to across the file and workspace overlay.
fn resolved_kind(
offset: u32,
semantics: &Semantics,
external: &ExternalResolutions,
) -> Option<SymbolKind> {
match external.definition_of(semantics, offset)? {
Definition::Local(symbol) => Some(symbol.kind),
Definition::External(defs) => defs.first().map(|def| def.kind),
}
}
/// A plain identifier, classified through the symbol table and workspace
/// overlay: its own declaration, the declaration it resolves to, or `variable`
/// when nothing resolves it.
fn identifier_type(
offset: u32,
semantics: &Semantics,
external: &ExternalResolutions,
) -> Highlight {
match resolved_kind(offset, semantics, external) {
Some(kind) => symbol_type(kind),
None => Highlight::Variable,
}
}
@@ -248,7 +280,7 @@ fn symbol_type(kind: SymbolKind) -> Highlight {
SymbolKind::Typedef => Highlight::Type,
SymbolKind::EnumVariant => Highlight::EnumMember,
SymbolKind::Param | SymbolKind::LocalParam | SymbolKind::TfArg => Highlight::Parameter,
SymbolKind::Function | SymbolKind::Task => Highlight::Function,
SymbolKind::Function | SymbolKind::Task | SymbolKind::Instance => Highlight::Function,
SymbolKind::StructMember
| SymbolKind::Constraint
| SymbolKind::Coverpoint
@@ -260,7 +292,6 @@ fn symbol_type(kind: SymbolKind) -> Highlight {
| SymbolKind::Net
| SymbolKind::Var
| SymbolKind::Genvar
| SymbolKind::Instance
| SymbolKind::Clocking
| SymbolKind::Block => Highlight::Variable,
// A property and a sequence are named, instantiated by name and take
@@ -728,9 +759,19 @@ mod tests {
}
}
/// Decoded tokens with the identifier refinement folded away.
fn coarsely(data: &[SemanticToken]) -> Vec<(u32, u32, u32, u32)> {
decode(data).into_iter().map(|(l, c, len, ty, _)| (l, c, len, coarse(ty))).collect()
/// Decoded tokens with identifier refinement and AST-only punctuation
/// (`#`, `.`, `*`) folded away so the unparsed window lexer can be compared
/// against the full pipeline.
fn coarsely(full: &Document, data: &[SemanticToken]) -> Vec<(u32, u32, u32, u32)> {
let positions = full.positions();
decode(data)
.into_iter()
.filter(|&(line, character, ..)| {
let at = positions.offset(Position { line, character });
!full.token_at(at).is_some_and(|t| t.kind == TokenKind::Symbol)
})
.map(|(l, c, len, ty, _)| (l, c, len, coarse(ty)))
.collect()
}
/// Whether any construct in `doc` crosses `offset` — a block comment, a
@@ -792,8 +833,8 @@ mod tests {
continue;
}
assert_eq!(
coarsely(&semantic_tokens_in_window(&fast, window)),
coarsely(&semantic_tokens_in_range(&full, window)),
coarsely(&full, &semantic_tokens_in_window(&fast, window)),
coarsely(&full, &semantic_tokens_in_range(&full, window)),
"{}: lines {from}..{to}",
path.display()
);
@@ -889,7 +930,8 @@ mod tests {
// Punctuation (`,`, `;`) is deliberately not classified at all, so it
// never reaches `pieces` — only the tokens `classify` keeps are
// expected on the wire.
for token in window.tokens.iter().filter(|t| classify(t, &doc.semantics).is_some()) {
let empty = HashMap::new();
for token in window.tokens.iter().filter(|t| classify(t, &doc, &empty).is_some()) {
let expected = positions.position(token.span.start);
let found = decoded
.iter()
@@ -1291,4 +1333,129 @@ mod tests {
let data = ranged(FOUR_LINES, range((3, 0), (1, 0)));
assert!(decode(&data).is_empty(), "{:?}", decode(&data));
}
// ------------------------------------------------------------------
// module instantiation and `#(...)` parameter-list highlighting
// ------------------------------------------------------------------
fn named_tokens(text: &str) -> Vec<(String, u32, u32)> {
with_document(text, |doc| {
let pos = doc.positions();
decode(&semantic_tokens(doc))
.into_iter()
.map(|(line, character, len, ty, mods)| {
let start = pos.offset(Position { line, character }) as usize;
let end = pos.offset(Position { line, character: character + len }) as usize;
(doc.text[start..end].to_string(), ty, mods)
})
.collect()
})
}
#[test]
fn module_instantiation_distinguishes_module_params_instance_ports_and_connections() {
let src = "\
module top #(
parameter int DATA_W = 32
) (
input logic clk,
input logic rst_ni
);
logic [DATA_W-1:0] data_q;
pkg::uart_core #(
.BAUD_DIV (EXT_DIV),
.WIDTH (DATA_W),
.DEPTH (16)
) u_uart (
.clk_i (clk),
.rst_ni,
.data_o (data_q),
.*
);
assign data_q = u_uart.tx_data;
endmodule
";
let out = named_tokens(src);
let find_nth = |word: &str, n: usize| {
out.iter()
.filter(|(w, ..)| w == word)
.nth(n)
.cloned()
.unwrap_or_else(|| panic!("{word} #{n} missing in {out:?}"))
};
// Both `#` tokens (header parameter port list and instantiation overrides)
// share `Parameter`, while `(` and `)` are never emitted.
assert_eq!(find_nth("#", 0), ("#".into(), Highlight::Parameter as u32, 0));
assert_eq!(find_nth("#", 1), ("#".into(), Highlight::Parameter as u32, 0));
assert!(!out.iter().any(|(w, ..)| w == "(" || w == ")"));
// Scoped module name: `pkg` is Namespace, `uart_core` is Class.
assert_eq!(find_nth("pkg", 0), ("pkg".into(), Highlight::Namespace as u32, 0));
assert_eq!(find_nth("uart_core", 0), ("uart_core".into(), Highlight::Class as u32, 0));
// Parameter overrides: `.` and parameter names share `Parameter` with `#`,
// as do local (`DATA_W`) and external (`EXT_DIV`) parameter values; `16` stays Number.
assert_eq!(find_nth(".", 0), (".".into(), Highlight::Parameter as u32, 0));
assert_eq!(find_nth("BAUD_DIV", 0), ("BAUD_DIV".into(), Highlight::Parameter as u32, 0));
assert_eq!(find_nth("EXT_DIV", 0), ("EXT_DIV".into(), Highlight::Parameter as u32, 0));
assert_eq!(find_nth(".", 1), (".".into(), Highlight::Parameter as u32, 0));
assert_eq!(find_nth("WIDTH", 0), ("WIDTH".into(), Highlight::Parameter as u32, 0));
assert_eq!(find_nth("DATA_W", 2), ("DATA_W".into(), Highlight::Parameter as u32, 0));
assert_eq!(find_nth("16", 0), ("16".into(), Highlight::Number as u32, 0));
// Instance declaration and hierarchical use both highlight as `Function`.
let fn_ty = Highlight::Function as u32;
assert_eq!(find_nth("u_uart", 0), ("u_uart".into(), fn_ty, DECLARATION));
assert_eq!(find_nth("u_uart", 1), ("u_uart".into(), fn_ty, 0));
// Port names (`.clk_i`, implicit `.rst_ni`, `.data_o`, wildcard `.*`) are `Property`,
// while connected signals (`clk`, `data_q`) stay `Variable`.
assert_eq!(find_nth(".", 3), (".".into(), Highlight::Property as u32, 0));
assert_eq!(find_nth("clk_i", 0), ("clk_i".into(), Highlight::Property as u32, 0));
assert_eq!(find_nth("clk", 1), ("clk".into(), Highlight::Variable as u32, 0));
assert_eq!(find_nth("rst_ni", 1), ("rst_ni".into(), Highlight::Property as u32, 0));
assert_eq!(find_nth("data_o", 0), ("data_o".into(), Highlight::Property as u32, 0));
assert_eq!(find_nth("data_q", 1), ("data_q".into(), Highlight::Variable as u32, 0));
assert_eq!(find_nth("*", 0), ("*".into(), Highlight::Property as u32, 0));
}
#[test]
fn delay_hashes_are_never_classified_as_parameters() {
let src = "\
module m;
wire #5 a;
assign #(1:2:3) a = 1'b0;
and #(2, 3) g0 (y, a, a);
initial #10 $finish;
endmodule
";
let out = named_tokens(src);
assert!(!out.iter().any(|(w, ..)| w == "#"), "delays keep `#` unemitted: {out:?}");
assert!(out.contains(&("g0".into(), Highlight::Function as u32, DECLARATION)));
}
#[test]
fn unfinished_port_and_param_entries_keep_their_highlights_while_typing() {
let src = "\
module m;
sub #(
.WIDTH(
) u0 (
.clk_i(
.rst_ni(rst_n)
);
endmodule
";
let out = named_tokens(src);
assert!(out.contains(&("sub".into(), Highlight::Class as u32, 0)));
assert!(out.contains(&("#".into(), Highlight::Parameter as u32, 0)));
assert!(out.contains(&("WIDTH".into(), Highlight::Parameter as u32, 0)));
assert!(out.contains(&("u0".into(), Highlight::Function as u32, DECLARATION)));
assert!(out.contains(&("clk_i".into(), Highlight::Property as u32, 0)));
assert!(out.contains(&("rst_ni".into(), Highlight::Property as u32, 0)));
assert!(out.contains(&("rst_n".into(), Highlight::Variable as u32, 0)));
reconstructs(MODULE, src);
reconstructs(src, MODULE);
}
}
@@ -0,0 +1,313 @@
//! AST-guided semantic token overrides for module instantiations and `#(...)`
//! parameter lists.
//!
//! Plain lexical + symbol-table classification leaves an external module's
//! name, its `#` parameter sigil, its `.PARAM` overrides and its `.port`
//! connections as uncoloured punctuation or generic `variable`s. Walking
//! [`Document::tree`] supplies the syntactic role of each token directly from
//! the parsed AST, even before workspace indexing finishes or when the
//! instantiated unit lives outside the indexed tree.
use std::collections::HashMap;
use vlog_parser::ast::{
BindDirective, ClassDecl, ClassExtends, Connection, Connections, DataType, Expr,
GateInstantiation, GenElse, Instantiation, Item, ItemKind, ListElem, Module, PortList, RawText,
Typedef, TypedefKind,
};
use vlog_parser::token::{Token, TokenKind};
use vlog_parser::TextRange;
use vlog_semantic::{ExternalResolutions, Semantics, SymbolKind};
use super::{resolved_kind, Highlight};
use crate::state::{first_token_from, Document};
/// Token-start byte offset -> highlight overrides derived from `doc.tree`.
pub(super) fn overrides(doc: &Document) -> HashMap<u32, Highlight> {
let mut out = HashMap::new();
if doc.tokens.is_empty() {
return out;
}
let mut ctx = Ctx {
tokens: &doc.tokens,
semantics: &doc.semantics,
external: &doc.external,
out: &mut out,
};
ctx.items(&doc.tree.items);
out
}
struct Ctx<'a> {
tokens: &'a [Token],
semantics: &'a Semantics,
external: &'a ExternalResolutions,
out: &'a mut HashMap<u32, Highlight>,
}
impl<'a> Ctx<'a> {
fn items(&mut self, items: &[Item]) {
for item in items {
self.item(item);
}
}
fn item(&mut self, item: &Item) {
match &item.kind {
ItemKind::Module(m) => self.module(m, item.span.end),
ItemKind::Package { items, .. } | ItemKind::GenerateRegion { items, .. } => {
self.items(items)
}
ItemKind::Class(c) => self.class(c, item.span.end),
ItemKind::Instantiation(inst) => self.instantiation(inst, item.span.end),
ItemKind::Bind(bind) => self.bind(bind, item.span.end),
ItemKind::GateInstantiation(gate) => self.gate(gate),
ItemKind::GenBlock(b) => self.items(&b.items),
ItemKind::GenIf(g) => {
self.items(&g.then.items);
self.gen_else(g.els.as_deref());
}
ItemKind::GenFor(g) => self.items(&g.body.items),
ItemKind::GenCase(g) => {
for arm in &g.items {
self.items(&arm.body.items);
}
}
ItemKind::DataDecl(d) => self.data_type(&d.ty),
ItemKind::PortDecl(p) => self.data_type(&p.ty),
ItemKind::ParamDecl(p) => self.data_type(&p.ty),
ItemKind::Typedef(t) => self.typedef(t),
_ => {}
}
}
fn gen_else(&mut self, els: Option<&GenElse>) {
match els {
Some(GenElse::If(_, inner)) => {
self.items(&inner.then.items);
self.gen_else(inner.els.as_deref());
}
Some(GenElse::Block(block)) => self.items(&block.items),
None => {}
}
}
fn module(&mut self, m: &Module, end: u32) {
if m.param_ports.is_some() {
let last = m.imports.last().and_then(|imp| imp.paths.last());
let from = last.map_or(m.name_span.end, |p| p.item.span.end);
self.param_hash(from, end);
}
for elem in m.param_ports.iter().flatten() {
if let Some(port) = elem.ok() {
self.data_type(&port.ty);
}
}
if let PortList::Ansi(ports) = &m.ports {
for elem in ports {
if let Some(port) = elem.ok() {
self.data_type(&port.ty);
}
}
}
self.items(&m.items);
}
fn class(&mut self, c: &ClassDecl, end: u32) {
if c.param_ports.is_some() {
self.param_hash(c.name_span.end, end);
for elem in c.param_ports.iter().flatten() {
if let Some(port) = elem.ok() {
self.data_type(&port.ty);
}
}
}
if let Some(ext) = &c.extends {
self.class_extends(ext);
}
self.items(&c.items);
}
fn class_extends(&mut self, ext: &ClassExtends) {
self.scoped_unit(ext.name_span);
if let Some(params) = &ext.params {
self.param_hash(ext.name_span.end, ext.span.end);
self.param_overrides(params);
}
}
fn typedef(&mut self, t: &Typedef) {
if let TypedefKind::Alias(ty) = &t.kind {
self.data_type(ty);
}
}
fn data_type(&mut self, ty: &DataType) {
if let Some(params) = ty.params() {
self.param_hash(params.span.start, params.span.end);
}
}
fn instantiation(&mut self, inst: &Instantiation, end: u32) {
self.scoped_unit(inst.module_span);
if let Some(params) = &inst.params {
self.param_hash(inst.module_span.end, end);
self.param_overrides(params);
}
for instance in &inst.instances {
self.ident_at(instance.name_span, Highlight::Function);
self.port_connections(&instance.conns);
}
}
fn bind(&mut self, b: &BindDirective, end: u32) {
if let [only] = &b.target[..] {
let kind = resolved_kind(only.span.start, self.semantics, self.external);
if only.index.is_none() && kind != Some(SymbolKind::Instance) {
self.ident_at(only.span, Highlight::Class);
}
}
for inst in &b.instances {
self.ident_at(inst.span, Highlight::Function);
}
self.instantiation(&b.inst, end);
}
fn gate(&mut self, g: &GateInstantiation) {
for inst in &g.instances {
if let Some(span) = inst.name_span {
self.ident_at(span, Highlight::Function);
}
}
}
fn param_overrides(&mut self, params: &[ListElem<Connection>]) {
for elem in params {
match elem {
ListElem::Ok(conn) => {
self.named_entry(conn, Highlight::Parameter);
if let Some(expr) = &conn.expr {
self.param_expr(expr);
}
}
ListElem::Error(raw) => self.recovered_entry(raw, Highlight::Parameter),
}
}
}
fn port_connections(&mut self, conns: &Connections) {
let Connections::Named(list) = conns else { return };
for elem in list {
match elem {
ListElem::Ok(conn) => self.named_entry(conn, Highlight::Property),
ListElem::Error(raw) => self.recovered_entry(raw, Highlight::Property),
}
}
}
fn named_entry(&mut self, conn: &Connection, ty: Highlight) {
if conn.name_span.is_empty() {
return;
}
for tok in self.tokens_in(TextRange::new(conn.span.start, conn.name_span.start)) {
if tok.is_sym(".") {
self.out.insert(tok.span.start, ty);
}
}
for tok in self.tokens_in(conn.name_span) {
if (tok.kind == TokenKind::Ident && !tok.is_macro()) || tok.is_sym("*") {
self.out.insert(tok.span.start, ty);
}
}
}
fn recovered_entry(&mut self, raw: &RawText, ty: Highlight) {
let mut saw_dot = false;
for tok in self.tokens_in(raw.span) {
if tok.kind == TokenKind::Attribute {
continue;
}
if !saw_dot && tok.is_sym(".") {
self.out.insert(tok.span.start, ty);
saw_dot = true;
continue;
}
if saw_dot && ((tok.kind == TokenKind::Ident && !tok.is_macro()) || tok.is_sym("*")) {
self.out.insert(tok.span.start, ty);
}
break;
}
}
fn param_expr(&mut self, expr: &Expr) {
if expr.span.is_empty() {
return;
}
let start = first_token_from(self.tokens, expr.span.start);
let slice = self.tokens.get(start..).unwrap_or(&[]);
let len = slice.partition_point(|t| t.span.end <= expr.span.end);
for (idx, tok) in slice[..len].iter().enumerate() {
if tok.kind != TokenKind::Ident || tok.is_macro() {
continue;
}
if resolved_kind(tok.span.start, self.semantics, self.external).is_some() {
continue;
}
let abs = start + idx;
let next = self.tokens.get(abs + 1);
let prev = abs.checked_sub(1).and_then(|i| self.tokens.get(i));
let ty = if next.is_some_and(|t| t.is_sym("::")) {
Highlight::Namespace
} else if next.is_some_and(|t| t.is_sym("(")) && !prev.is_some_and(|t| t.is_sym(".")) {
Highlight::Function
} else {
Highlight::Parameter
};
self.out.insert(tok.span.start, ty);
}
}
fn scoped_unit(&mut self, span: TextRange) {
let idents: Vec<&Token> = self
.tokens_in(span)
.iter()
.filter(|t| t.kind == TokenKind::Ident && !t.is_macro())
.collect();
let Some((&last, prefix)) = idents.split_last() else { return };
for &seg in prefix {
self.out.insert(seg.span.start, Highlight::Namespace);
}
self.out.insert(last.span.start, Highlight::Class);
}
fn ident_at(&mut self, span: TextRange, ty: Highlight) {
for tok in self.tokens_in(span) {
if tok.kind == TokenKind::Ident && !tok.is_macro() {
self.out.insert(tok.span.start, ty);
}
}
}
fn param_hash(&mut self, from: u32, until: u32) {
let start = first_token_from(self.tokens, from);
for tok in self.tokens.get(start..).unwrap_or(&[]) {
if tok.span.start >= until || tok.is_sym("(") || tok.is_sym(";") {
break;
}
if tok.is_sym("#") {
self.out.insert(tok.span.start, Highlight::Parameter);
break;
}
}
}
fn tokens_in(&self, span: TextRange) -> &'a [Token] {
if span.is_empty() {
return &[];
}
let start = first_token_from(self.tokens, span.start);
let slice = self.tokens.get(start..).unwrap_or(&[]);
let len = slice.partition_point(|t| t.span.end <= span.end);
&slice[..len]
}
}
+418 -16
View File
@@ -1091,6 +1091,64 @@ fn typing_a_newline_and_a_semicolon_round_trips_over_the_real_binary() {
let _ = std::fs::remove_dir_all(&dir);
}
/// `begin` + Enter writes the `end` over the wire, and a pushed
/// `lucisv.autoEnd: false` takes it back to the plain indent answer
/// (`docs/features/completion-ux`).
#[test]
fn a_newline_after_begin_writes_the_end_unless_auto_end_is_off() {
let dir = temp_dir("ontype_end");
let file = dir.join("m.sv");
let text = "module m;\n always_ff @(posedge clk) begin\n\nendmodule\n";
std::fs::write(&file, text).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
let on_type = |id: u32| {
frame(&format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/onTypeFormatting","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":2,"character":0}},"ch":"\n","options":{{"tabSize":2,"insertSpaces":true}}}}}}"#
))
};
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(text).expect("json")
)),
on_type(2),
frame(
r#"{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{"settings":{"lucisv":{"autoEnd":false}}}}"#,
),
on_type(3),
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 edits = |id: u32| {
let response = messages.iter().find(|m| m["id"] == id).expect("a response");
response["result"].as_array().expect("an array of edits").clone()
};
let with_end = edits(2);
assert_eq!(with_end.len(), 2, "{with_end:#?}");
assert_eq!(with_end[0]["newText"], " ", "the body line's indent");
assert_eq!(with_end[1]["newText"], " end\n", "the `end` under its `always_ff`");
assert_eq!(
with_end[1]["range"]["start"],
serde_json::json!({ "line": 3, "character": 0 }),
"inserted at the start of the line after the cursor's"
);
let without = edits(3);
assert_eq!(without.len(), 1, "autoEnd off: the indent alone: {without:#?}");
assert_eq!(without[0]["newText"], " ");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_pushed_exclude_rebuilds_the_index_mid_session() {
// The one link a unit test cannot check: that the notification handler
@@ -2251,14 +2309,18 @@ fn inline_templates_round_trip_over_the_wire() {
assert_eq!(item["insertText"]["value"], "${1:cond}) begin\n\t$0\nend");
assert_eq!(item["range"]["start"], item["range"]["end"], "an insertion, not a replacement");
// `always @(` is the one trigger with a list: the clocked block first, the
// combinational one second, both at the same empty range.
let two = items(5);
let two = two["items"].as_array().expect("a list");
assert_eq!(two.len(), 2, "{two:#?}");
assert_eq!(two[0]["insertText"]["value"], "posedge ${1:clk}) begin\n\t$0\nend");
assert_eq!(two[1]["insertText"]["value"], "*) begin\n\t$0\nend");
assert_eq!(two[0]["range"], two[1]["range"], "both insert at the cursor");
// `always @(` is a trigger with a list: clock and reset first, clock only
// second, the combinational block third, all at the same empty range.
let three = items(5);
let three = three["items"].as_array().expect("a list");
assert_eq!(three.len(), 3, "{three:#?}");
assert_eq!(
three[0]["insertText"]["value"],
"posedge ${1:clk} or negedge ${2:rst_n}) begin\n\t$0\nend"
);
assert_eq!(three[1]["insertText"]["value"], "posedge ${1:clk}) begin\n\t$0\nend");
assert_eq!(three[2]["insertText"]["value"], "*) begin\n\t$0\nend");
assert_eq!(three[0]["range"], three[2]["range"], "all insert at the cursor");
assert_eq!(items(4), serde_json::Value::Null, "nowhere near a trigger");
@@ -2428,14 +2490,16 @@ fn keyword_and_project_completion_round_trip_over_the_wire() {
assert_eq!(local["kind"], 6, "CompletionItemKind.Variable");
assert!(local["sortText"].as_str().expect("sortText").starts_with('1'), "{local:#?}");
// `4`, not `2`: `completion-ux` (2026-11-17) put this file's own
// declarations (`2`) and words (`3`) ahead of what other files declare.
let macro_name = labelled("WIDGET_MACRO").expect("a `define name");
assert!(macro_name["sortText"].as_str().expect("sortText").starts_with('2'));
assert!(macro_name["sortText"].as_str().expect("sortText").starts_with('4'));
let elsewhere = labelled("widget_elsewhere").expect("a word used in the project");
assert_eq!(elsewhere["kind"], 1, "CompletionItemKind.Text");
// `5`, not `4`: M6 inserted the template tier above the keywords, which
// pushed the keyword and word tiers' digits down by one.
assert!(elsewhere["sortText"].as_str().expect("sortText").starts_with('5'));
// `7`: M6 inserted the template tier above the keywords, and
// `completion-ux` the two current-file tiers above the index.
assert!(elsewhere["sortText"].as_str().expect("sortText").starts_with('7'));
assert!(
!items.iter().any(|item| item["sortText"].as_str().is_some_and(|s| s.starts_with('0'))),
@@ -2611,12 +2675,12 @@ fn a_template_completion_round_trips_over_the_wire() {
assert_eq!(template["textEdit"]["range"]["start"]["line"], 2);
assert_eq!(template["textEdit"]["range"]["start"]["character"], 4);
assert_eq!(template["textEdit"]["range"]["end"]["character"], 6);
assert!(template["sortText"].as_str().expect("sortText").starts_with('3'));
assert!(template["sortText"].as_str().expect("sortText").starts_with('5'));
// The keyword survives beside it, one tier down.
let keyword = labelled(items, "if").expect("the keyword");
assert_eq!(keyword["kind"], 14, "CompletionItemKind.Keyword");
assert!(keyword["sortText"].as_str().expect("sortText").starts_with('4'));
assert!(keyword["sortText"].as_str().expect("sortText").starts_with('6'));
// A `.v` buffer is offered Verilog's `always`, never `always_ff`.
let verilog = messages.iter().find(|m| m["id"] == 3).expect("completion response");
@@ -7298,8 +7362,16 @@ fn a_connection_list_completes_ports_over_the_wire() {
assert_eq!(edit["range"]["start"], edit["range"]["end"], "an empty range at the cursor");
}
// A port already connected is not offered again.
assert_eq!(labels(3), vec!["data", "ready"]);
// A port already connected is still offered, after the others and
// marked (`completion-ux`, 2026-11-17 — it used to be dropped).
assert_eq!(labels(3), vec!["clk", "data", "ready"]);
let partly_items = response(3)["result"]["items"].as_array().expect("a list");
let clk = partly_items.iter().find(|i| i["label"] == "clk").expect("clk");
assert!(clk["sortText"].as_str().is_some_and(|s| s.starts_with('1')), "{clk:#?}");
assert_eq!(clk["labelDetails"]["description"], "connected");
let data = partly_items.iter().find(|i| i["label"] == "data").expect("data");
assert!(data["sortText"].as_str().is_some_and(|s| s.starts_with('0')), "{data:#?}");
assert!(data.get("labelDetails").is_none(), "{data:#?}");
// And `#(.` lists the parameters instead.
assert_eq!(labels(4), vec!["WIRE_W"]);
@@ -7307,6 +7379,94 @@ fn a_connection_list_completes_ports_over_the_wire() {
let _ = std::fs::remove_dir_all(&dir);
}
/// `completion-ux` over the wire: a port item, asked by a client that reads
/// snippets, writes `.name($1)` — pre-filled where the instantiating module
/// has a same-named signal — and a typed keyword prefix grows a keyword
/// ghost, following the popup's selected entry when one is sent.
#[test]
fn port_snippets_and_keyword_ghosts_round_trip_over_the_wire() {
let dir = temp_dir("completionux");
std::fs::write(
dir.join("ux_sub.sv"),
"module ux_sub (\n input logic clk,\n input logic data\n);\nendmodule\n",
)
.expect("write");
let text = "module ux_top;\n logic clk;\n ux_sub u_sub (\n .\n );\n alw\nendmodule\n";
let top = dir.join("ux_top.sv");
std::fs::write(&top, text).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", top.display());
let inline = |id: u32, selected: &str| {
frame(&format!(
r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/inlineCompletion","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":5,"character":5}},"context":{{"triggerKind":2{selected}}}}}}}"#
))
};
let session = [
frame(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{"textDocument":{{"completion":{{"completionItem":{{"snippetSupport":true}}}}}}}}}}}}"#
)),
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(text).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/completion","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":3,"character":5}},"context":{{"triggerKind":2,"triggerCharacter":"."}}}}}}"#
)),
inline(3, ""),
inline(
4,
r#","selectedCompletionInfo":{"range":{"start":{"line":5,"character":2},"end":{"line":5,"character":5}},"text":"always_comb"}"#,
),
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 result = |id: u32| {
messages
.iter()
.find(|m| m["id"] == id)
.unwrap_or_else(|| panic!("no response {id} in {messages:#?}"))["result"]
.clone()
};
let ports = result(2);
let ports = ports["items"].as_array().expect("a list");
let port = |name: &str| ports.iter().find(|i| i["label"] == name).expect("a port").clone();
assert_eq!(port("clk")["textEdit"]["newText"], "clk(${1:clk})", "pre-filled from `logic clk`");
assert_eq!(port("data")["textEdit"]["newText"], "data(${1})");
assert_eq!(port("data")["insertTextFormat"], 2, "InsertTextFormat.Snippet");
let cursor = serde_json::json!({ "line": 5, "character": 5 });
assert_eq!(
result(3),
serde_json::json!({
"items": [{
"insertText": { "kind": "snippet", "value": "ays_ff" },
"range": { "start": cursor, "end": cursor }
}]
}),
"the rest of the keyword, inserted at the cursor"
);
assert_eq!(
result(4),
serde_json::json!({
"items": [{
"insertText": { "kind": "snippet", "value": "always_comb" },
"range": {
"start": { "line": 5, "character": 2 },
"end": { "line": 5, "character": 5 }
}
}]
}),
"the popup's selection, over the popup's range"
);
let _ = std::fs::remove_dir_all(&dir);
}
// ----------------------------------------------------------------------
// constraint-bodies (TODO.md §20)
// ----------------------------------------------------------------------
@@ -8796,3 +8956,245 @@ endmodule
let _ = std::fs::remove_dir_all(&dir);
}
// ----------------------------------------------------------------------
// The connection being typed (TODO §68.2, `docs/features/port-entry-grace`)
// ----------------------------------------------------------------------
/// `cargo test --release -p lucisv_server --test e2e a_keystroke_in_a_port_list -- --ignored --nocapture --test-threads=1`
///
/// The per-keystroke cost of finding the entry being typed, on the largest
/// corpus file with instantiations in it: a character typed into a connection
/// name in the middle of `ibex_core.sv` (2 026 lines). Prints, asserts nothing,
/// exactly like `a_keystroke_round_trip_over_the_wire`; the before/after
/// numbers are in the feature README.
#[test]
#[ignore = "perf measurement, not a correctness assertion — see docs/features/port-entry-grace"]
fn a_keystroke_in_a_port_list_round_trip_over_the_wire() {
let corpus = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/ibex/rtl/ibex_core.sv");
let Ok(source) = std::fs::read_to_string(&corpus) else {
eprintln!("no corpus checkout; nothing to measure");
return;
};
let dir = temp_dir("portkeystroke");
let file = dir.join("ibex_core.sv");
std::fs::write(&file, &source).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
// The fourth `.clk_i` connection (line 781 of the file), just after `.c`.
let line = 780u32;
let column = " .c".len() as u32;
let mut live = Live::start();
live.send(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
));
live.wait_for(|m| m["id"] == 1);
live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#);
live.send(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(&source).expect("json")
));
live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
let started = std::time::Instant::now();
live.send(&keystroke(&uri, 2, line, column));
live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
let single = started.elapsed();
let runs = 10u32;
let started = std::time::Instant::now();
for k in 0..runs {
live.send(&keystroke(&uri, 3 + k, line, column + 1 + k));
live.send(&format!(
r#"{{"jsonrpc":"2.0","id":{},"method":"textDocument/documentHighlight","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":{line},"character":4}}}}}}"#,
50 + k
));
live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
live.wait_for(|m| m["id"] == 50 + k);
}
let requested = started.elapsed() / runs;
live.finish();
eprintln!(
"port-list keystroke round trip, ibex_core.sv: one change alone {single:?}, \
one change a request follows {requested:?}"
);
let _ = std::fs::remove_dir_all(&dir);
}
/// A module with an instance whose connection list has an empty line in it,
/// for a connection to be typed on (line 3, 0-based).
const PORT_TYPING: &str =
"module m;\n logic x, y;\n sub u0 (.a(x),\n \n .b(y));\n assign x = y;\nendmodule\n";
/// Open [`PORT_TYPING`] in a fresh session (`capabilities` as the client's),
/// returning the live session and the buffer's URI.
fn port_typing_session(name: &str, capabilities: &str) -> (Live, String, PathBuf) {
let dir = temp_dir(name);
let file = dir.join("m.sv");
std::fs::write(&file, PORT_TYPING).expect("write");
let root = format!("file://{}", dir.display());
let uri = format!("file://{}", file.display());
let mut live = Live::start();
live.send(&format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{capabilities}}}}}"#
));
live.wait_for(|m| m["id"] == 1);
live.send(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#);
live.send(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(PORT_TYPING).expect("json")
));
(live, uri, dir)
}
/// `text` typed at `(line, character)` of `uri`, as an incremental edit.
fn typed(uri: &str, version: u32, line: u32, character: u32, text: &str) -> String {
format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{uri}","version":{version}}},"contentChanges":[{{"range":{{"start":{{"line":{line},"character":{character}}},"end":{{"line":{line},"character":{character}}}}},"text":{}}}]}}}}"#,
serde_json::to_string(text).expect("json")
)
}
/// The parse errors a publish or a pull report carries, as their start lines.
fn error_lines(items: &serde_json::Value) -> Vec<u64> {
items
.as_array()
.expect("diagnostics")
.iter()
.filter(|d| d["severity"] == 1)
.filter_map(|d| d["range"]["start"]["line"].as_u64())
.collect()
}
/// TODO §68.2 over the wire: `.po(` typed into a connection list is not
/// reported while it is the thing being typed, and is reported once the
/// typing has stopped for the grace period (1.5 s) — with nothing else sent.
#[test]
fn a_connection_being_typed_is_reported_only_after_the_grace_period() {
let (mut live, uri, dir) = port_typing_session("portgrace", "{}");
let opened = live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
assert!(error_lines(&opened["params"]["diagnostics"]).is_empty(), "{opened:#?}");
live.send(&typed(&uri, 2, 3, 4, ".po("));
let typing = live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
let withheld_at = std::time::Instant::now();
assert!(
error_lines(&typing["params"]["diagnostics"]).is_empty(),
"the open `(` of the entry being typed is held back: {typing:#?}"
);
let released = live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
let waited = withheld_at.elapsed();
assert_eq!(error_lines(&released["params"]["diagnostics"]), [3], "{released:#?}");
assert!(waited >= std::time::Duration::from_millis(1000), "released after {waited:?}");
live.finish();
let _ = std::fs::remove_dir_all(&dir);
}
/// The other two releases: an edit landing outside the entry says everything
/// at once, with no grace to wait for — and so does a save.
#[test]
fn a_connection_being_typed_is_reported_as_soon_as_the_typing_moves_on_or_saves() {
let (mut live, uri, dir) = port_typing_session("portmoveon", "{}");
live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
live.send(&typed(&uri, 2, 3, 4, ".po("));
let typing = live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
assert!(error_lines(&typing["params"]["diagnostics"]).is_empty(), "{typing:#?}");
// A space typed after `logic x, y;` — outside every connection list.
let started = std::time::Instant::now();
live.send(&typed(&uri, 3, 1, 13, " "));
let moved = live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
assert_eq!(error_lines(&moved["params"]["diagnostics"]), [3], "{moved:#?}");
assert!(started.elapsed() < std::time::Duration::from_millis(1000), "no grace to wait for");
// Back into the entry: held back again; then saved: said again.
live.send(&typed(&uri, 4, 3, 8, "x"));
let again = live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
assert!(error_lines(&again["params"]["diagnostics"]).is_empty(), "{again:#?}");
let started = std::time::Instant::now();
live.send(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didSave","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"#
));
let saved = live.wait_for(|m| m["method"] == "textDocument/publishDiagnostics");
assert_eq!(error_lines(&saved["params"]["diagnostics"]), [3], "{saved:#?}");
assert!(started.elapsed() < std::time::Duration::from_millis(1000), "no grace to wait for");
live.finish();
let _ = std::fs::remove_dir_all(&dir);
}
/// A pulling client: the pull made while typing leaves the entry out, and the
/// first pull after the grace has a new `resultId` and the full list — never
/// "unchanged" against the report that left it out.
#[test]
fn a_pulling_client_sees_the_entry_at_its_first_pull_after_the_grace() {
let pulls = r#"{"textDocument":{"diagnostic":{}}}"#;
let (mut live, uri, dir) = port_typing_session("portpull", pulls);
live.send(&typed(&uri, 2, 3, 4, ".po("));
live.send(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/diagnostic","params":{{"textDocument":{{"uri":"{uri}"}},"identifier":"lucisv"}}}}"#
));
let typing = live.wait_for(|m| m["id"] == 2);
assert!(error_lines(&typing["result"]["items"]).is_empty(), "{typing:#?}");
let held = typing["result"]["resultId"].as_str().expect("a result id").to_string();
std::thread::sleep(std::time::Duration::from_millis(1700));
live.send(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/diagnostic","params":{{"textDocument":{{"uri":"{uri}"}},"identifier":"lucisv","previousResultId":"{held}"}}}}"#
));
// The release happened before this pull was sent, so a refresh request —
// which this client never said it accepts — would arrive first.
let after = live.wait_for(|m| {
m["id"] == 3
|| m["method"] == "textDocument/publishDiagnostics"
|| m["method"] == "workspace/diagnostic/refresh"
});
assert_eq!(after["id"], 3, "neither pushed nor asked to refresh: {after:#?}");
assert_eq!(after["result"]["kind"], "full", "{after:#?}");
assert_eq!(error_lines(&after["result"]["items"]), [3], "{after:#?}");
live.finish();
let _ = std::fs::remove_dir_all(&dir);
}
/// A pulling client that accepts `workspace/diagnostic/refresh` — VS Code's
/// `vscode-languageclient` does — is asked to pull again when the grace runs
/// out, so the entry shows after the pause with nothing typed.
#[test]
fn a_pulling_client_that_can_refresh_is_asked_to_after_the_grace() {
let pulls =
r#"{"textDocument":{"diagnostic":{}},"workspace":{"diagnostics":{"refreshSupport":true}}}"#;
let (mut live, uri, dir) = port_typing_session("portrefresh", pulls);
live.send(&typed(&uri, 2, 3, 4, ".po("));
live.send(&format!(
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/diagnostic","params":{{"textDocument":{{"uri":"{uri}"}},"identifier":"lucisv"}}}}"#
));
let typing = live.wait_for(|m| m["id"] == 2);
assert!(error_lines(&typing["result"]["items"]).is_empty(), "{typing:#?}");
let held = typing["result"]["resultId"].as_str().expect("a result id").to_string();
let withheld_at = std::time::Instant::now();
let refresh = live.wait_for(|m| {
m["method"] == "workspace/diagnostic/refresh"
|| m["method"] == "textDocument/publishDiagnostics"
});
assert_eq!(refresh["method"], "workspace/diagnostic/refresh", "{refresh:#?}");
let waited = withheld_at.elapsed();
assert!(waited >= std::time::Duration::from_millis(1000), "asked after {waited:?}");
live.send(&format!(r#"{{"jsonrpc":"2.0","id":{},"result":null}}"#, refresh["id"]));
// What the client does on the request: pull again, and get it all.
live.send(&format!(
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/diagnostic","params":{{"textDocument":{{"uri":"{uri}"}},"identifier":"lucisv","previousResultId":"{held}"}}}}"#
));
let after = live.wait_for(|m| m["id"] == 3);
assert_eq!(after["result"]["kind"], "full", "{after:#?}");
assert_eq!(error_lines(&after["result"]["items"]), [3], "{after:#?}");
live.finish();
let _ = std::fs::remove_dir_all(&dir);
}
@@ -0,0 +1,53 @@
//! The formatter still refuses every unfinished-connection shape the tolerant
//! parser now keeps inside its own entry (TODO §68.2,
//! `docs/features/port-entry-grace/README.md`).
//!
//! The recovery is the editor's: it makes the rest of a half-typed file
//! colour and lint as if the entry were complete. The formatter never reads
//! the tolerant tree, and these pin that a buffer with a half-typed entry in
//! it is refused whole — never printed with the entry "completed".
use vlog_formatter::{format_source, Config};
const UNFINISHED: &[(&str, &str)] = &[
(
"lone dot before the next entry",
"module m;\n sub u0 (.a(x),\n .\n .b(y));\nendmodule\n",
),
("lone dot before a comma", "module m;\n sub u0 (.a(x), ., .b(y));\nendmodule\n"),
("lone dot before the close", "module m;\n sub u0 (.a(x), .);\nendmodule\n"),
(
"open value before the next entry",
"module m;\n sub u0 (.a(x), .po(\n .b(y));\nendmodule\n",
),
(
"open value with a partial name",
"module m;\n sub u0 (.a(x), .po(z\n .b(y));\nendmodule\n",
),
("open value before the close", "module m;\n sub u0 (.a(x), .po(\n );\nendmodule\n"),
("open override value", "module m;\n sub #(.W(8), .D(\n .E(1)) u0 (.a(x));\nendmodule\n"),
("missing comma across lines", "module m;\n sub u0 (.a(x)\n .b(y));\nendmodule\n"),
("missing comma on one line", "module m;\n sub u0 (.a(x) .b(y));\nendmodule\n"),
(
"implicit entry missing its comma",
"module m;\n sub u0 (.a(x), .po\n .b(y));\nendmodule\n",
),
("trailing comma", "module m;\n sub u0 (.a(x), .b(y),);\nendmodule\n"),
("trailing comma in an override list", "module m;\n sub #(.W(1),) u0 (.a(x));\nendmodule\n"),
];
#[test]
fn every_unfinished_connection_is_still_refused() {
for (name, src) in UNFINISHED {
let got = format_source(src, &Config::default());
assert!(got.is_err(), "{name}: the formatter printed a half-typed entry:\n{got:?}");
}
}
/// The completed spelling of the same entries formats — so the refusal above
/// is about the unfinished entry and nothing else in these sources.
#[test]
fn the_completed_entries_format() {
let src = "module m;\n sub u0 (.a(x), .po(), .b(y));\nendmodule\n";
assert!(format_source(src, &Config::default()).is_ok());
}
+15 -6
View File
@@ -320,12 +320,13 @@ impl<'a> Parser<'a> {
if !self.cur().is_sym(")") {
loop {
let at = self.pos;
list.push(self.element_or_recover(|p| p.parse_connection())?);
list.push(self.connection_or_recover()?);
let recovered = list.last().is_some_and(ListElem::is_error);
if let Some(ListElem::Ok(last)) = list.last_mut() {
self.take_before_sep(&mut last.meta, ",");
}
let comma = self.eat_sym(",");
self.note_trailing_comma(comma);
if let Some(ListElem::Ok(last)) = list.last_mut() {
last.comma = comma;
if comma && last.meta.trailing.is_none() {
@@ -338,7 +339,7 @@ impl<'a> Parser<'a> {
// the list, and after a directive only the closing bracket
// does — an `` `ifdef`` arm may end without a comma and
// still be followed by an `` `else`` arm.
if self.list_ends(at, comma, dirs.any, recovered) {
if self.connection_list_ends(at, comma, dirs.any, recovered) {
break;
}
}
@@ -437,12 +438,13 @@ impl<'a> Parser<'a> {
let mut conns = Vec::new();
loop {
let at = self.pos;
conns.push(self.element_or_recover(|p| p.parse_connection())?);
conns.push(self.connection_or_recover()?);
let recovered = conns.last().is_some_and(ListElem::is_error);
if let Some(ListElem::Ok(last)) = conns.last_mut() {
self.take_before_sep(&mut last.meta, ",");
}
let comma = self.eat_sym(",");
self.note_trailing_comma(comma);
if let Some(ListElem::Ok(last)) = conns.last_mut() {
last.comma = comma;
if comma && last.meta.trailing.is_none() {
@@ -450,7 +452,7 @@ impl<'a> Parser<'a> {
}
}
let dirs = self.take_list_directives(directives, conns.len());
if self.list_ends(at, comma, dirs.any, recovered) {
if self.connection_list_ends(at, comma, dirs.any, recovered) {
break;
}
}
@@ -560,8 +562,15 @@ impl<'a> Parser<'a> {
// arguments — so the greedy parse swallows the instance and the
// whole instantiation collapses into one error item. Failing the
// element here costs the one connection and keeps everything
// else. See `docs/features/small-items-3/README.md`.
if self.tolerant && self.cur().is_sym("(") && self.value_runs_into_next_instance() {
// else. See `docs/features/small-items-3/README.md`. The same
// failure covers a `.NAME(` left open at the end of its line while
// the next line goes on with the list (`.po(` ⏎ `.b(y));`): the
// entry ends with its line, and the diagnostic is on its `(`
// (`docs/features/port-entry-grace/README.md`).
if self.tolerant
&& self.cur().is_sym("(")
&& (self.value_runs_into_next_instance() || self.value_left_open())
{
return self.error("unclosed `(` in a port or parameter connection");
}
let mut close_comments = Vec::new();
+193 -6
View File
@@ -25,6 +25,7 @@
//! See `docs/features/header-recovery/README.md`.
use super::directive::{closes_conditional, continues_conditional, opens_conditional};
use super::recover::is_sync_stop;
use super::*;
impl<'a> Parser<'a> {
@@ -102,6 +103,176 @@ impl<'a> Parser<'a> {
}
}
/// One entry of a port or parameter connection list, the unfinished ones
/// included (`docs/features/port-entry-grace/README.md`).
///
/// A `.` with no name after it yet — `.a(x), .` ⏎ `.b(y)` — is the entry
/// someone is typing. In tolerant mode it becomes an error element of its
/// own, holding just the `.`, with its one diagnostic on the `.`: the
/// generic recovery would report the token *after* it, which belongs to
/// the next entry, and its skip would swallow a `.b(y)` written on the
/// same line. Strict mode, and every other entry, is
/// [`Parser::element_or_recover`] over [`Parser::parse_connection`].
pub(super) fn connection_or_recover(&mut self) -> PResult<ListElem<Connection>> {
if self.tolerant && self.at_lone_dot() {
return Ok(ListElem::Error(self.take_lone_dot()));
}
self.element_or_recover(|p| p.parse_connection())
}
/// True on a `.` that no name can follow: the next token ends the entry
/// (`,` `)` `;`), ends the file or an enclosing construct, or — on a later
/// line — is a keyword or the `.` of the next entry. A keyword or a `.` on
/// the same line (`.input(x)`, `..z (p)`) is left to the generic recovery,
/// whose skip takes the whole `.input(x)` / `..z (p)` with it: one error
/// element, which is what `lucisv_mcp`'s refusal names (`qa_f1.rs`).
fn at_lone_dot(&self) -> bool {
if !self.cur().is_sym(".") {
return false;
}
let next = self.nth(1);
let later_line = next.line != self.cur().line;
next.kind == TokenKind::Eof
|| next.is_sym(",")
|| next.is_sym(")")
|| next.is_sym(";")
|| is_sync_stop(next)
|| (later_line && (next.kind == TokenKind::Keyword || next.is_sym(".")))
}
/// Record the lone `.` at the cursor and take it as an error element.
/// The comments written before it are left pending, so the next entry
/// picks them up rather than the error leaf swallowing them.
fn take_lone_dot(&mut self) -> RawText {
let dot = self.cur();
let (span, col) = (dot.span, dot.col);
self.diagnostics.push(ParseDiagnostic {
message: "expected a name after `.`".to_string(),
line: dot.line,
col,
span,
});
self.skip();
RawText { text: self.slice(span), col, span }
}
/// [`Parser::list_ends`] for a connection list, which reads one shape on.
///
/// After an entry that had to be recovered, a missing `,` normally ends
/// the list — what follows belongs to the enclosing construct. In a
/// connection list a `.` there is the next connection instead: the entry
/// above was abandoned mid-typing (`.po(` ⏎ `.b(y)`), and the list reads
/// on. No second diagnostic: the recovered entry already has one, and it
/// is the news. Strict mode never recovers, so this is `list_ends` there.
pub(super) fn connection_list_ends(
&mut self,
start: usize,
comma: bool,
dirs_any: bool,
recovered: bool,
) -> bool {
let next_entry = self.cur().is_sym(".");
if self.tolerant && recovered && !comma && !dirs_any && self.pos != start && next_entry {
return false;
}
self.list_ends(start, comma, dirs_any, recovered)
}
/// In tolerant mode, report a connection list's `,` that only the closing
/// `)` follows — `.b(y),)`, the separator typed before the next entry.
/// Strict mode fails there on the empty entry; tolerant mode used to end
/// the list on the `)` without a word. The diagnostic sits on the `,`.
/// Called right after the `,` was consumed, so it is the token behind the
/// cursor.
pub(super) fn note_trailing_comma(&mut self, comma: bool) {
if !(self.tolerant && comma && self.cur().is_sym(")")) {
return;
}
let Some(sep) = self.pos.checked_sub(1).and_then(|i| self.tokens.get(i)) else { return };
let diag = ParseDiagnostic {
message: "expected a connection after `,`".to_string(),
line: sep.line,
col: sep.col,
span: sep.span,
};
self.diagnostics.push(diag);
}
/// True when the `(` at the cursor — the one that opens a connection's
/// value — was left open mid-typing: still open at the end of its line,
/// the next line starting something new (a `.` entry, a `)`, a `;`, a
/// keyword, or end of file), **and** the bracket never closes the way a
/// value's does.
///
/// The last clause is what keeps every file the strict parser reads
/// untouched: in a valid list a value's matching `)` is followed by a
/// `,`, the list's `)`, or a directive, so `.po(top` ⏎ `.sig)` — a legal
/// path continued on the next line — is read as written. The line clause
/// keeps the pinned ambiguous shape `.D(` ⏎ `u0 (.a(x)));` greedy
/// (`docs/features/header-recovery/README.md`): an identifier opening the
/// next line is [`Parser::value_runs_into_next_instance`]'s question.
/// Tolerant mode only; the walk ends at the first `;` or construct keyword
/// outside the value, so it is bounded by the item.
pub(super) fn value_left_open(&self) -> bool {
let open = self.pos;
let line = self.cur().line;
let mut depth = 0u32;
let mut i = open + 1;
while let Some(t) = self.tokens.get(i) {
if t.line != line || t.kind == TokenKind::Eof {
break;
}
if is_open_bracket(t) {
depth += 1;
} else if is_close_bracket(t) {
if depth == 0 {
return false;
}
depth -= 1;
}
i += 1;
}
let Some(next) = self.tokens.get(i) else { return false };
let starts_new = next.kind == TokenKind::Eof
|| next.kind == TokenKind::Keyword
|| next.is_sym(".")
|| next.is_sym(")")
|| next.is_sym(";");
starts_new && !self.value_closes(open)
}
/// Whether the bracket at token `open` is closed by a `)` that a valid
/// connection list could have written next: anything but a `;`, end of
/// file, a construct keyword, a `.` or a plain identifier after it. A
/// `;` or construct keyword reached first, outside any bracket the value
/// opened, means it is never closed at all.
fn value_closes(&self, open: usize) -> bool {
let mut depth = 0u32;
let mut i = open + 1;
while let Some(t) = self.tokens.get(i) {
if t.kind == TokenKind::Eof {
return false;
}
if is_open_bracket(t) {
depth += 1;
} else if is_close_bracket(t) {
if depth == 0 {
return self.tokens.get(i + 1).is_some_and(|after| !ends_a_value_badly(after));
}
depth -= 1;
} else if depth == 0 && (t.is_sym(";") || is_sync_stop(t)) {
return false;
}
i += 1;
}
false
}
/// True on a token that opens a bracket.
fn at_open_bracket(&self) -> bool {
is_open_bracket(self.cur())
}
/// True on a `` `ifdef `` / `` `ifndef `` / `` `else `` / `` `elsif `` /
/// `` `endif ``: a directive that opens, continues or closes a
/// conditional-compilation region.
@@ -267,12 +438,6 @@ impl<'a> Parser<'a> {
RawText { text: self.slice(span), col, span }
}
/// True on a token that opens a bracket.
fn at_open_bracket(&self) -> bool {
let t = self.cur();
t.is_sym("(") || t.is_sym("[") || t.is_sym("{")
}
/// The extent a recovery covers: from `start` through the last token it
/// took, or the empty range at `start` when it took none (the sync point
/// was already under the cursor).
@@ -340,3 +505,25 @@ impl<'a> Parser<'a> {
}
}
}
/// True on a `(`, `[` or `{`.
fn is_open_bracket(t: &Token) -> bool {
t.is_sym("(") || t.is_sym("[") || t.is_sym("{")
}
/// True on a `)`, `]` or `}`.
fn is_close_bracket(t: &Token) -> bool {
t.is_sym(")") || t.is_sym("]") || t.is_sym("}")
}
/// True on a token no valid connection list writes right after a value's
/// closing `)`: the list was never closed (`;`, end of file, a construct
/// keyword), or the next connection follows with no `,` (`.`, or a plain
/// identifier — a macro invocation is a directive's business and allowed).
fn ends_a_value_badly(t: &Token) -> bool {
t.kind == TokenKind::Eof
|| t.is_sym(";")
|| t.is_sym(".")
|| is_sync_stop(t)
|| (t.kind == TokenKind::Ident && !t.is_macro())
}
@@ -0,0 +1,298 @@
//! An unfinished connection stays inside its own entry (TODO §68.2,
//! `docs/features/port-entry-grace/README.md`).
//!
//! The four shapes someone typing a named connection leaves behind — a lone
//! `.`, a `.name(` still open at the end of its line, a missing `,` between
//! two entries, a `,` with only the `)` after it — each cost exactly one
//! diagnostic, whose span lies inside the unfinished entry (or on the single
//! token that proves it), and every other entry, the instance and the rest of
//! the file parse as if the entry were complete. The strict parser refuses
//! every one of them, as before; and no valid spelling of a list reads
//! differently in tolerant mode.
use vlog_parser::ast::*;
use vlog_parser::{parse_source, parse_source_tolerant, ParseDiagnostic};
/// The file's one module. Panics unless the file is exactly one module — the
/// shapes below must never cost the module.
fn the_module(file: &SourceFile) -> &Module {
assert_eq!(file.items.len(), 1, "the file is still one item: {:?}", file.items);
let ItemKind::Module(m) = &file.items[0].kind else { panic!("expected module m") };
m
}
/// The instantiations among `m`'s items, and how many items are anything
/// else (error items included).
fn instantiations(m: &Module) -> (Vec<&Instantiation>, usize) {
let mut insts = Vec::new();
let mut others = 0;
for item in &m.items {
match &item.kind {
ItemKind::Instantiation(inst) => insts.push(inst),
ItemKind::Error(raw) => panic!("an error item escaped the list: {:?}", raw.text),
_ => others += 1,
}
}
(insts, others)
}
/// One entry, as the tests compare it: `Ok(name)` or `Err(raw text)`.
fn entries(list: &[ListElem<Connection>]) -> Vec<Result<&str, &str>> {
list.iter()
.map(|e| match e {
ListElem::Ok(c) => Ok(c.name.as_str()),
ListElem::Error(raw) => Err(raw.text.as_str()),
})
.collect()
}
/// The named connections of the first instance of the first instantiation.
fn ports(m: &Module) -> Vec<Result<&str, &str>> {
let (insts, _) = instantiations(m);
let Connections::Named(conns) = &insts[0].instances[0].conns else { panic!("named list") };
entries(conns)
}
/// The one diagnostic `src` produces, and the source text its span covers.
fn one_diag(src: &str, diags: &[ParseDiagnostic]) -> (String, String) {
assert_eq!(diags.len(), 1, "exactly one diagnostic: {diags:?}");
(diags[0].message.clone(), src[diags[0].span.as_range()].to_string())
}
/// The strict parser — the formatter's — still refuses `src`.
fn strict_refuses(src: &str) {
assert!(parse_source(src).is_err(), "strict mode must still refuse:\n{src}");
}
// ----------------------------------------------------------------------
// (a) a lone `.`
// ----------------------------------------------------------------------
#[test]
fn a_lone_dot_on_its_own_line_keeps_the_entries_after_it() {
let src = "module m;\n sub u0 (.a(x),\n .\n .b(y));\n wire w;\nendmodule\n";
let (file, diags) = parse_source_tolerant(src);
let m = the_module(&file);
let (message, at) = one_diag(src, &diags);
assert_eq!(at, ".", "on the dot itself, not on the `.b` after it");
assert_eq!(message, "expected a name after `.`");
assert_eq!(ports(m), [Ok("a"), Err("."), Ok("b")]);
assert_eq!(instantiations(m).1, 1, "`wire w;` is still an item of the module");
strict_refuses(src);
}
#[test]
fn a_lone_dot_before_a_comma_or_the_close() {
for (src, want) in [
("module m;\n sub u0 (.a(x), ., .b(y));\nendmodule\n", vec![Ok("a"), Err("."), Ok("b")]),
("module m;\n sub u0 (.a(x), .);\nendmodule\n", vec![Ok("a"), Err(".")]),
("module m;\n sub u0 (.);\nendmodule\n", vec![Err(".")]),
] {
let (file, diags) = parse_source_tolerant(src);
let m = the_module(&file);
assert_eq!(one_diag(src, &diags).1, ".", "{src}");
assert_eq!(ports(m), want, "{src}");
strict_refuses(src);
}
}
#[test]
fn a_lone_dot_in_a_parameter_override_list() {
let src = "module m;\n sub #(.W(8), .\n .D(2)) u0 (.a(x));\nendmodule\n";
let (file, diags) = parse_source_tolerant(src);
let m = the_module(&file);
assert_eq!(one_diag(src, &diags).1, ".");
let (insts, _) = instantiations(m);
assert_eq!(entries(insts[0].params.as_ref().expect("overrides")), [Ok("W"), Err("."), Ok("D")]);
assert_eq!(insts[0].instances[0].name, "u0");
strict_refuses(src);
}
#[test]
fn a_lone_dot_at_the_end_of_the_file_keeps_the_instance() {
let src = "module m;\n sub u0 (.a(x), .\nendmodule\n";
let (file, diags) = parse_source_tolerant(src);
let m = the_module(&file);
assert_eq!(one_diag(src, &diags).1, ".");
assert_eq!(ports(m), [Ok("a"), Err(".")]);
strict_refuses(src);
}
// ----------------------------------------------------------------------
// (b) `.name(` still open at the end of its line
// ----------------------------------------------------------------------
#[test]
fn an_open_value_followed_by_the_next_entry_ends_with_its_line() {
for (src, raw) in [
("module m;\n sub u0 (.a(x), .po(\n .b(y));\n wire w;\nendmodule\n", ".po("),
("module m;\n sub u0 (.a(x), .po(z\n .b(y));\n wire w;\nendmodule\n", ".po(z"),
("module m;\n sub u0 (.a(x),\n .po(\n .b(y),\n .c(z)\n );\n wire w;\nendmodule\n", ".po("),
] {
let (file, diags) = parse_source_tolerant(src);
let m = the_module(&file);
let (message, at) = one_diag(src, &diags);
assert_eq!(at, "(", "on the entry's own `(`: {src}");
assert!(message.starts_with("unclosed `(`"), "{message}");
let got = ports(m);
assert_eq!(got[0], Ok("a"));
assert_eq!(got[1], Err(raw), "{src}");
assert_eq!(got[2], Ok("b"), "the entry after it survives: {src}");
assert_eq!(instantiations(m).1, 1, "`wire w;` is an item: {src}");
strict_refuses(src);
}
}
#[test]
fn an_open_value_followed_by_the_lists_close() {
let src = "module m;\n sub u0 (.a(x), .po(\n );\n wire w;\nendmodule\n";
let (file, diags) = parse_source_tolerant(src);
let m = the_module(&file);
assert_eq!(one_diag(src, &diags).1, "(");
assert_eq!(ports(m), [Ok("a"), Err(".po(")]);
assert_eq!(instantiations(m).1, 1);
strict_refuses(src);
}
#[test]
fn an_open_value_at_the_end_of_the_module() {
let src = "module m;\n sub u0 (.a(x), .po(\nendmodule\n";
let (file, diags) = parse_source_tolerant(src);
let m = the_module(&file);
assert_eq!(one_diag(src, &diags).1, "(");
assert_eq!(ports(m), [Ok("a"), Err(".po(")]);
strict_refuses(src);
}
#[test]
fn an_open_override_value_keeps_the_overrides_after_it_and_the_instance() {
let src = "module m;\n sub #(.W(8), .D(\n .E(1)) u0 (.a(x));\n wire w;\nendmodule\n";
let (file, diags) = parse_source_tolerant(src);
let m = the_module(&file);
assert_eq!(one_diag(src, &diags).1, "(");
let (insts, others) = instantiations(m);
assert_eq!(
entries(insts[0].params.as_ref().expect("overrides")),
[Ok("W"), Err(".D("), Ok("E")]
);
assert_eq!(insts[0].instances[0].name, "u0");
assert_eq!(others, 1);
strict_refuses(src);
}
/// The two pinned shapes of `error_recovery.rs` keep their old answers: an
/// identifier opening the next line is the next-instance lookahead's, and
/// the balanced `.D(` ⏎ `u0 (.a(x)));` stays ambiguous and greedy.
#[test]
fn an_identifier_on_the_next_line_is_not_this_rule() {
let src = "module m;\n sub #(.D(\n u0 (.a(x)));\nendmodule\n";
let (file, diags) = parse_source_tolerant(src);
assert!(diags.iter().all(|d| !d.message.contains("unclosed")), "{diags:?}");
let ItemKind::Module(m) = &file.items[0].kind else { panic!("module") };
assert!(matches!(m.items[0].kind, ItemKind::Error(_)), "still one error item");
}
// ----------------------------------------------------------------------
// (c) a missing `,` between two entries
// ----------------------------------------------------------------------
#[test]
fn a_missing_comma_keeps_both_entries() {
for src in [
"module m;\n sub u0 (.a(x)\n .b(y));\nendmodule\n",
"module m;\n sub u0 (.a(x) .b(y));\nendmodule\n",
"module m;\n sub u0 (.a(x), .po\n .b(y));\nendmodule\n",
] {
let (file, diags) = parse_source_tolerant(src);
let m = the_module(&file);
let (message, at) = one_diag(src, &diags);
assert!(message.starts_with("expected `,`"), "{message}");
assert_eq!(at, ".", "on the `.` that proves the comma missing: {src}");
assert!(ports(m).iter().all(Result::is_ok), "{:?}", ports(m));
assert_eq!(ports(m).last(), Some(&Ok("b")));
strict_refuses(src);
}
}
// ----------------------------------------------------------------------
// (d) a trailing `,`
// ----------------------------------------------------------------------
#[test]
fn a_trailing_comma_is_reported_on_the_comma() {
for src in [
"module m;\n sub u0 (.a(x), .b(y),);\nendmodule\n",
"module m;\n sub u0 (.a(x), .b(y),\n );\nendmodule\n",
"module m;\n sub #(.W(1),) u0 (.a(x));\nendmodule\n",
"module m;\n sub #(1,) u0 (.a(x));\nendmodule\n",
] {
let (file, diags) = parse_source_tolerant(src);
let m = the_module(&file);
let (message, at) = one_diag(src, &diags);
assert_eq!(at, ",", "{src}");
assert_eq!(message, "expected a connection after `,`");
assert_eq!(instantiations(m).0.len(), 1);
strict_refuses(src);
}
}
/// A positional list may end in an omitted connection — `u (a, b,)` is legal
/// — so the trailing-comma report is a named-list and override-list rule only.
#[test]
fn a_positional_lists_trailing_comma_is_still_legal() {
let src = "module m;\n sub u0 (a, b,);\nendmodule\n";
assert!(parse_source(src).is_ok());
assert!(parse_source_tolerant(src).1.is_empty());
}
// ----------------------------------------------------------------------
// Valid input is untouched
// ----------------------------------------------------------------------
/// Spellings that come close to every shape above and are legal: each parses
/// strictly, reports nothing tolerantly, and builds the identical tree.
#[test]
fn valid_lists_read_the_same_in_both_modes() {
for src in [
// A path continued on the next line: `(` open at the line's end and a
// `.` opening the next — the one valid shape rule (b) has to leave be.
"module m;\n sub u0 (.a(x),\n .po(top\n .sig), .q(r));\nendmodule\n",
"module m;\n sub u0 (.po(top\n .sig));\nendmodule\n",
// A value written over several lines, its `)` alone on the last one.
"module m;\n sub u0 (.po(\n x\n ), .q(r));\nendmodule\n",
"module m;\n sub u0 (.po(f(x\n )));\nendmodule\n",
"module m;\n sub #(.DEPTH(\n f(1)\n )) u0 (.a(x));\nendmodule\n",
// The implicit `.name` form, a `.*`, an empty `.name()`.
"module m;\n sub u0 (.a,\n .b(),\n .*);\nendmodule\n",
// A directive between entries and a macro after a value.
"module m;\n sub u0 (.a(x),\n`ifdef B\n .b(y),\n`endif\n .c(z));\nendmodule\n",
"module m;\n sub u0 (.a(x) `COMMA_B\n );\nendmodule\n",
// Attributes on an entry.
"module m;\n sub u0 ((* keep *) .a(x),\n (* keep *)\n .b(y));\nendmodule\n",
] {
let strict = match parse_source(src) {
Ok(tree) => tree,
Err(e) => panic!("premise: {src:?} is valid, got {e}"),
};
let (tolerant, diags) = parse_source_tolerant(src);
assert!(diags.is_empty(), "{src}: {diags:?}");
assert_eq!(format!("{strict:?}"), format!("{tolerant:?}"), "{src}");
}
}
/// A `.` followed by another `.` on the same line is not a lone dot: the
/// generic recovery keeps `..z (p)` as one error element, whose text is what
/// a refusal downstream names (`lucisv_mcp`'s `qa_f1.rs`).
#[test]
fn two_dots_on_one_line_stay_one_error_element() {
for (src, want) in [
("module m;\n sub u0 (.a(x), ..z (p));\nendmodule\n", vec![Ok("a"), Err("..z (p)")]),
("module m;\n sub u0 (.a(x), . .b(y));\nendmodule\n", vec![Ok("a"), Err(". .b(y)")]),
] {
let (file, diags) = parse_source_tolerant(src);
let m = the_module(&file);
assert_eq!(diags.len(), 1, "{src}: {diags:?}");
assert_eq!(ports(m), want, "{src}");
strict_refuses(src);
}
}
@@ -0,0 +1,154 @@
//! QA, TODO §68.2 (`docs/features/port-entry-grace/README.md`): the tolerant
//! parser's new connection-list recovery against a wider sweep than the dev's
//! own tests — multi-line connection values that are legal (each must read
//! exactly as the strict parser reads it, with no diagnostic) and unfinished
//! entries in every position QA could think of (each must stay refused by the
//! strict parser and cost at least one tolerant diagnostic, none of them
//! outside the source).
use vlog_parser::{parse_source, parse_source_tolerant};
/// Legal multi-line connections: an operand on the line after `(`, a
/// keyword-led operand, a macro, a comment line, a dotted name, overrides,
/// `.*`, attributes, generate loops, instance arrays, gates, `bind`, UDPs,
/// conditional compilation.
const VALID: &[&str] = &[
"module m;\n sub u0 (.a(\n foo\n ), .b(y));\nendmodule\n",
"module m;\n sub u0 (.a({\n x, y\n }), .b(y));\nendmodule\n",
"module m;\n sub u0 (.a(x ?\n y : z), .b(y));\nendmodule\n",
"module m;\n sub u0 (.a(\n signed'(x)), .b(y));\nendmodule\n",
"module m;\n sub u0 (.a(\n this.x), .b(y));\nendmodule\n",
"module m;\n sub u0 (.a(\n null), .b(y));\nendmodule\n",
"module m;\n sub u0 (.a(\n super.x), .b(y));\nendmodule\n",
"module m;\n sub u0 (.a(\n $bits(x)), .b(y));\nendmodule\n",
"module m;\n sub u0 (.a(\n `MACRO(x)), .b(y));\nendmodule\n",
"module m;\n sub u0 (.a(\n // comment\n x), .b(y));\nendmodule\n",
"module m;\n sub u0 (.a(\n intf.sig), .b(y));\nendmodule\n",
"module m;\n sub u0 (.a(intf\n .sig), .b(y));\nendmodule\n",
"module m;\n sub #(.W(\n 8)) u0 (.a(x));\nendmodule\n",
"module m;\n sub u0 (.a(\n x)\n );\nendmodule\n",
"module m;\n sub u0 (.a(\n ));\nendmodule\n",
"module m;\n sub u0 (.a(x), .*);\nendmodule\n",
"module m;\n sub u0 ((* keep *) .a(\n x), .b(y));\nendmodule\n",
"module m;\n for (genvar i = 0; i < 4; i++) begin : g\n sub u (.a(\n x[i]), .b(y));\n end\nendmodule\n",
"module m;\n sub u [3:0] (.a(\n x), .b(y));\nendmodule\n",
"module m;\n and g1 (o,\n a, b);\nendmodule\n",
"module m;\n bind sub chk u_chk (.a(\n x), .b(y));\nendmodule\n",
"module m;\n intf u_if (.clk(\n clk));\n prog u_p (.a(\n x));\nendmodule\n",
"module m;\n sub u0 (.a(\n x)\n`ifdef FOO\n , .b(y)\n`endif\n );\nendmodule\n",
"module m;\n sub u0 (.a(\n x)\n `ifdef FOO , .b(y) `endif\n );\nendmodule\n",
"module m;\n sub u0 (.a(x[\n 3:0]), .b(y));\nendmodule\n",
"module m;\n sub u0 (.a(f(\n x)), .b(y));\nendmodule\n",
"module m;\n sub u0 (.a(\n x\n ), .b(\n y\n ));\nendmodule\n",
"module m;\n sub u0 (x,\n y, z);\nendmodule\n",
"module m;\n sub u0 (.a(\n new));\nendmodule\n",
"module m;\n sub #(\n .W(8),\n .T(\n logic [3:0])\n ) u0 (.a(x));\nendmodule\n",
"module m;\n sub #(.T(\n int)) u0 (.a(x));\nendmodule\n",
"module m;\n sub u0 (.a(\n 1'b0), .b(\n '0));\nendmodule\n",
"module m;\n sub u0 (.a(\n {8{1'b0}}), .b(y));\nendmodule\n",
"module m;\n sub u0 (.a(\n x)) ;\nendmodule\n",
"module m;\n sub u0 (.a(\n x)), u1 (.a(y));\nendmodule\n",
"module m;\n sub u0 (.a(\n x)) /* c */;\nendmodule\n",
"module m;\n sub u0 (.a(\n x)\n // trailing\n );\nendmodule\n",
"module m;\n sub u0 (.a(\n std::randomize(x)), .b(y));\nendmodule\n",
"module m;\n sub u0 (.a(\n x inside {1, 2}), .b(y));\nendmodule\n",
"module m;\n sub u0 (.a(\n pkg::x), .b(y));\nendmodule\n",
"module m;\n sub u0 (.a(\n (x)), .b(y));\nendmodule\n",
"module m;\n sub u0 (.a(\n ), .b(y));\nendmodule\n",
"module m;\n sub u0 (.a(\n\n x), .b(y));\nendmodule\n",
"module m;\n sub u0 (.a(x\n ), .b(y\n ));\nendmodule\n",
"module m;\n sub u0 (.a(x),\n .b(\n y\n )\n );\n sub u1 (.a(x));\nendmodule\n",
"module m;\n sub u0 (.a(\n x)\n `ifdef FOO\n ,.b(y)\n `endif\n );\nendmodule\n",
"module m;\n sub u0 (.a(\n x));\n checker_t c0 (.a(\n x));\nendmodule\n",
"module m;\n myudp u (out,\n in1, in2);\nendmodule\n",
"module m;\n sub u0 (.a(\n x), .b(y)); sub u1 (.a(\n x));\nendmodule\n",
"module m;\n sub #(\n .A(\n 1\n )\n ) u0 ();\nendmodule\n",
// Not here: "sub #(8,\n 16) u0 (x,\n y,);" — a positional list's
// trailing omitted connection. Strict keeps it as an empty entry and
// tolerant drops it, at c1076f9 already (QA log 2026-11-17, NOTE).
"module m;\n sub #(8,\n 16) u0 (x,\n y, z);\nendmodule\n",
"module m;\n sub u0 (.a(\n x)\n ) ;\nendmodule\nmodule n;\nendmodule\n",
];
/// Unfinished entries: first, last, only, repeated, at end of file, in `#(`,
/// in generate and `` `ifdef `` regions, with nested open brackets, a comma
/// inside an open value, trailing commas, keywords after the `(`.
const UNFINISHED: &[&str] = &[
"module m;\n sub u0 (.\n .b(y));\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x),\n .);\n wire w;\nendmodule\n",
"module m;\n sub u0 (.);\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x),\n .\n .\n .b(y));\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x),\n .po(\n .pq(\n .b(y));\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x),\n .",
"module m;\n sub u0 (.a(x),\n .po(",
"module m;\n sub #(.W(\n .D(1)) u0 (.a(x));\n wire w;\nendmodule\n",
"module m;\n generate if (1) begin : g\n sub u0 (.a(x),\n .po(\n .b(y));\n end endgenerate\n wire w;\nendmodule\n",
"module m;\n`ifdef FOO\n sub u0 (.a(x),\n .po(\n .b(y));\n`endif\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x),\n .po(f(\n .b(y));\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x),\n .po(x[\n .b(y));\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x),\n .po({\n .b(y));\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x),\n .po(a,\n .b(y));\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x),\n .\n );\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x),",
"module m;\n sub u0 (.a(x), .b(y),\n );\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x),,.b(y));\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x) .b(y) .c(z));\n wire w;\nendmodule\n",
"module m;\n sub u0 (.po(\n .b(y));\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x),\n .po(\n );\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x),\n .po(\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x),\n .po(\nendmodule\nmodule n;\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x),\n .po(\n .b(y)\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x),\n .po(\n .b(y),\n .c(\n .d(z));\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x), .po(z\n .b(y));\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x), .po(z)\n .b(y));\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x), .po\n .b(y));\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x), .po(\n );\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x), .po(\n ;\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x), .input(\n .b(y));\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x), .\n input w2;\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x), .po(\n u1 (.a(x)));\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x),\n .po((\n .b(y));\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x),\n .po(\n .b(y)), u1 (.a(x));\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x),\n .po(\n .b(y)) /*c*/;\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x), // c1\n . // c2\n .b(y)); // c3\n wire w;\nendmodule\n",
"module m;\n sub #(.W(1),) u0 (.a(x),);\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x),\n .po(\n`ifdef X\n .b(y)\n`endif\n );\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x),\n .po(\n .b(y))\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x),\n .po(\n .b(y)) .c(z);\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x),\n .po(\n .b(y)) foo;\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x),\n .po(\n .b(y)) `M;\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x), .po(\n .b(y)), .c(z));\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x),\n .po(\n .b(\n .c(\n .d(\n .e(y));\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x),\n .\n .\n .\n .\n .\n .\n .\n .\n .\n .\n .b(y));\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x), .po(\n endmodule\n",
"module m;\n sub u0 (.a(x), .po(\n end\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x), .po( .b(y));\n wire w;\nendmodule\n",
"module m;\n sub u0 (.a(x),\n .po(\n .b(y));\n sub u1 (.a(x),\n .\n .b(y));\n assign q = ;\nendmodule\n",
];
#[test]
fn qa_legal_multi_line_connections_read_the_same_in_both_modes() {
for src in VALID {
let strict = match parse_source(src) {
Ok(tree) => tree,
Err(e) => panic!("premise: {src:?} is valid, got {e}"),
};
let (tolerant, diags) = parse_source_tolerant(src);
assert!(diags.is_empty(), "{src}: {diags:?}");
assert_eq!(format!("{strict:?}"), format!("{tolerant:?}"), "{src}");
}
}
#[test]
fn qa_every_unfinished_entry_is_refused_strictly_and_reported_tolerantly() {
for src in UNFINISHED {
assert!(parse_source(src).is_err(), "strict mode must refuse:\n{src}");
let (_, diags) = parse_source_tolerant(src);
assert!(!diags.is_empty(), "never silent:\n{src}");
let lines = src.lines().count();
assert!(diags.len() <= lines, "no diagnostic explosion ({}):\n{src}", diags.len());
for d in &diags {
assert!(d.span.end as usize <= src.len(), "{d:?} outside the source:\n{src}");
}
}
}
+448
View File
@@ -0,0 +1,448 @@
# completion-ux
## Goal
Completion that keeps up with typing (TODO §68.1, owner's order 2026-11-17).
Five changes to the editing loop the VS Code extension drives, all served by
`lucisv-server` so other LSP clients get them too:
1. **`begin` + Enter writes the `end`.** The newline on-type answer, when the
line above ends in `begin` / `begin : label` and the block still owes an
`end`, also writes `end` on the line after the new one, at the owning
statement's indentation; the cursor stays on the indented body line. The
extension sends that request itself when `editor.formatOnType` is off.
2. **Clock and reset in the `always` templates.** `always_ff @(` and
`always @(` ghost `posedge ${1:clk} or negedge ${2:rst_n}) begin … end`
first; the clock-only form stays as the second choice, in the ghost and in
the popup.
3. **Current-file names rank first** in the popup: what this buffer declares
(any scope), then the words it uses, ahead of other files' names, the
templates and the keywords.
4. **Keyword ghosts.** A typed proper prefix of a keyword shows the rest as
grey inline text, following the popup's selected item while the popup is
open.
5. **Port items.** After the `.` of a connection, unconnected ports first,
connected ones after them marked `connected`; accepting one writes
`.name($1)` with the cursor inside the parentheses, pre-filled with a
same-named signal when the instantiating scope has one.
## Assumptions
- **Auto-`end` — which `begin` owes an `end`.** `pairs::analyze` is a stack
matcher, so a `begin` typed inside a balanced block steals that block's
`end` and the *outer* `begin` comes out unmatched. The rule
(`on_type/auto_end.rs::owes_an_end`): no `end` if this `begin` is matched by
an `end` that is first on its line at exactly the indentation the answer
would write; otherwise an `end` iff any `begin` at or before this one is in
`unmatched_open`. Fix round: the `begin` also counts as closed when its
matched `end` starts its line at the `begin`'s **own** line's indentation
(GNU layout, `begin` on its own line), and an unmatched `begin` inside a
`` `ifdef ``/`` `ifndef `` region that has an `` `else ``/`` `elsif ``
arms nothing. Consequence: an unrelated unclosed `begin` earlier in the
file still arms it (accepted heuristic, lead's ruling); a hand-mis-indented
`end` belonging to an outer block at either column disarms it.
- **Auto-`end` and `` `ifdef `` branches (QA finding 1).** Two branches that
each open the same block (`` `ifdef A always … begin `else always … begin
`endif `` and one shared `end`) are complete code that the stack matcher
reads as one unmatched `begin`. What is right after the *first* branch's
`begin` is **no `end`**: the block's `end` is the shared one after the
`` `endif ``, and a second would break the other branch. The cheap rule —
an unmatched `begin` inside a branched conditional region never arms the
answer — gets that right. Known limit it buys: a genuinely new `begin`
typed inside such a region whose only unmatched `begin` is itself gets no
`end` (the plain indent answer instead). The region scan is by directive
word over the token stream; a region never closed runs to end of buffer.
- **Auto-`end` — the owner line.** Read backwards from the `begin` over a
parenthesised header, `@`/`#` and its operand, one header keyword (`if`,
`for`, `foreach`, `while`, `repeat`, `forever`, the `always` family,
`initial`, `final`) and the qualifiers in front of it (`else`, `unique`,
`unique0`, `priority`). Anything else ends the walk. The `end` takes that
line's leading whitespace *as written* (tabs stay tabs). An unmatched `)`
leaves the `begin`'s own line as the answer.
- **Auto-`end` — the body line.** The nesting model's level (spaces, as the
plain newline answer) when it lies deeper than the `end`; else the `end`'s
indent plus one `lucisv.indent`-width step; a tab-indented `end` gets one
more tab.
- **Auto-`end` — only on a blank new line.** Enter pressed mid-line carries
text down, and that line gets the plain indent answer only. The previous
line must *end* in `begin` / `begin : label`; comments are trivia and do not
count. Only `begin` — not `fork`, `case`, `module`.
- **Auto-`end` edit shape.** Two edits: the new line's leading whitespace
(omitted when already right) and an insertion of `<indent>end<eol>` at
column 0 of the line *after* the new one, so no edit touches the cursor
position. When the new line is the file's last line there is nowhere else to
put it: one edit replaces the new line with `body<eol><indent>end`. The
line ending is the one just typed (`\r\n` files stay `\r\n`).
- **Extension path.** `editors/vscode/typing.js` acts on an
`onDidChangeTextDocument` event with exactly one content change, no
`reason` (undo/redo are skipped), `rangeLength` 0, text matching
`^\r?\n[ \t]*$`, a line before it ending in `begin`/`begin : label`
(a `//` comment stripped), `editor.formatOnType` **not** on for the
document (language overrides honoured via `getConfiguration('editor',
document)`), and `lucisv.autoEnd` not `false`. The request goes out on the
next tick (`setTimeout 0`) so the language client's own `didChange` for the
same event is sent first. The answer is applied only if the document
version is unchanged and the answer writes an `end` (an indent-only answer
is formatting the user never turned on). Applied with `editor.edit(…,
{ undoStopBefore: false, undoStopAfter: true })`, then the cursor is put at
the end of the new line.
- **Undo.** The edit has no undo stop before it, so VS Code should fold it
into the Enter's own undo step: one `Ctrl+Z` removes the `end`, the indent
and the newline together. Not verified in a running VS Code (see QA).
- **Templates.** Popup template `sortText` is now `5` + three-digit registry
rank + label, so templates reached by the same prefix show in registry order;
the with-reset `always_ff` / Verilog `always @(posedge … or negedge …)` were
moved ahead of the clock-only ones. Labels unchanged.
- **Ranking — the final tier table** (`completion/mod.rs`; the first
character of every `sortText`, a label follows, so the order is total):
| digit | tier | source |
|---|---|---|
| `0` | module names (item position) / members (exclusive answer) | index / site |
| `1` | visible at the cursor (scope chain); in a connection list: already-connected ports | `Semantics` |
| `2` | declared anywhere in this buffer | `Semantics::symbols()` |
| `3` | identifiers used in this buffer (not the token under the cursor) | token stream |
| `4` | what the project declares (units, members, `` `define ``s) | index |
| `5` | templates (`5` + rank + label) | `templates.rs` |
| `6` | keywords | `vlog_parser::KEYWORDS` |
| `7` | project words | candidate tables |
Dedup by label is unchanged: the first (best) tier wins. VS Code sorts by
its own fuzzy score first and uses `sortText` among equal scores, so the
tier order decides between equally good matches only.
- **Ranking — the typed word itself.** The buffer-word tier skips the token
starting at the cursor's word, so a half-typed `c` is no longer offered
back as `c` (it used to be, by the old word tier). A saved copy of the same
file still contributes it through the project-word table.
- **Keyword ghosts.** `inline/keywords.rs`. Asked only when no template
trigger answered and the rest of the line is blank (the existing ghost rule).
The word: the token ending exactly at the cursor, `Ident` or `Keyword`,
ASCII identifier characters starting with a letter, length ≥ 2, not after
`.`/`::`, and not exactly a name this buffer declares (fix round: `in`,
`re`, `out` as signals stay quiet; an undeclared word ghosts in any
position, expressions included). A word that is already a keyword only
extends across `_`
(`always` → `always_ff`; `end`, `for`, `case` get nothing — a ghost after a
finished keyword is noise a stray Tab accepts) — unless the popup has
that keyword selected: an explicit selection wins (`end` with `endmodule`
selected ghosts `endmodule`). Choice: the popup's
`selectedCompletionInfo.text` when present and its range is exactly the
typed word (start of the word to the cursor; any other range is read as no
selection and never echoed back) — ghost exactly it, over that range, if
it is a reserved word of the dialect extending the word, otherwise no
ghost, since VS Code would hide a disagreeing one; else the first of a fixed priority
list (`PRIORITY`); else shortest-then-alphabetical over `KEYWORDS`. A `.v`
buffer is limited to the IEEE 1364-2005 reserved words. Item shape: with
no selection, empty range at the cursor and the suffix as a snippet value
(the existing ghosts' shape); with a selection, the selection's range and
the whole keyword (LSP 3.18: "must extend the text of the selected item and
use the same range").
- **Extension bridge (corrected in the fix round, QA finding 2).**
`vscode-languageclient` 9 passes VS Code's `selectedCompletionInfo` through
unconverted, so a `vscode.Range` goes out in its `toJSON` array shape and
the trigger kind as VS Code's 0/1 rather than LSP's 1/2. **Nothing was
broken by this**: serde decodes the server's `Range` struct from a
two-element sequence and the trigger kind is an `i32` newtype, so the
request decoded and the template ghosts kept working (pinned by
`qa_an_array_shaped_range_and_a_zero_trigger_kind_still_decode`). The
`middleware.provideInlineCompletionItems` re-spelling both
(`typing.protocolInlineContext`) is correctness hygiene: the spec's
spelling on the wire, and correct trigger kinds for any server that reads
them.
- **Port items.** `completion/connection.rs`. Applies to both connection
lists — ports after `inst (` and parameters after `#(`. Connected entries
are those `connected_names` finds (the entry being re-typed excluded); they
get `sortText` `1<name>` and `labelDetails.description = "connected"`.
Within each group the order is the match order, as before (`sortText` is
alphabetical by name within a digit, also as before). Snippet
`name(${1:fill})` / `name(${1})` only for a client with snippet support, no
`(` after the identifier run being replaced (same line, spaces/tabs
skipped), and a plain-identifier name. Pre-fill when the scope chain at the
cursor binds a `Net`/`Var`/`Port` (ports) or `Param`/`LocalParam`
(parameters) of the same name. **An auto-closed `)` is not handled**: the
popup is reached after a `.`, where no paren has been typed yet; if the user
had typed `.cl(` and gone back, the `(` check already gives the bare name.
- **Known limits accepted by the lead (QA notes 6–11).**
- *LIMIT starvation moved* (6): with ≥ 512 names in this file matching a
one-letter prefix (a synthetic 600-`logic aN;` buffer), templates and
keywords fall out of the one-letter answer; `isIncomplete` is true, so
the second letter re-asks and gets them. Largest real case seen: 220
items (`r` in `ibex_core.sv`).
- *Token under the cursor* (7): tier 3 skips it even mid-word, so a word
this file uses exactly once and declares nowhere drops out while the
cursor is inside it.
- *Body indent inside `fork`* (8): the body line's indent is the existing
nesting model's answer (identical to the plain newline answer), so
`initial fork\n begin` + Enter gives an 8-space body over a 4-space
`end`.
- *Pre-fill* (9) accepts a same-named signal declared after the instance —
the scope chain binds it either way.
- *Last line under formatOnType* (11): there the answer is one edit whose
range contains the cursor, so VS Code probably leaves the cursor after
the `end`; the extension path puts it back itself.
## Handshakes
- **Consumes** `pairs::analyze` (unchanged), `on_type::level_at` (unchanged,
called from the child module), `Semantics::symbols()` / `scopes()`,
`signature::enclosing_list`, `candidates::{Query, rank_cmp}`.
- **Changed, crate-internal:** `on_type::on_type_formatting` takes a fifth
argument `auto_end: bool` (one caller, `server/formatting.rs`). The inline
entry point is now `inline::inline_completions_in_context(ws, uri,
position, selected)`; the old three-argument `inline_completions` survives
as a `#[cfg(test)]` wrapper so `instantiate.rs`'s test (outside this lane's
files) compiles unchanged. `completion::member_answer` takes `snippets`.
`tiers::visible_symbols` is `pub(super)`. Fix round: `on_type::begin_owes_an_end(doc, begin_index)`
(`pub(crate)`, re-exported from `on_type/auto_end.rs`) is what
`inline.rs`'s `begin` ghost gate now asks.
- **Changed, protocol-visible:** popup `sortText` digits (table above) — any
client or test that pinned `2`/`3`/`4`/`5` for index/template/keyword/word
sees `4`/`5`/`6`/`7`; template `sortText` gains a rank; connection items
gain `labelDetails` and snippet `textEdit`s. Settings `lucisv.autoEnd`,
`lucisv.inlineKeywords` (both boolean, default true, absent = on).
- **Outside the file list, flagged:** `editors/vscode/.vscodeignore` gained
`typing_test.js` (and `typing.js` in its comment), as the lane brief's
pointer to the restart.js/.vscodeignore pattern implied.
- No request to the parser, semantic or formatter crates.
## Status / TODO
- [x] auto-`end` on Enter: server (`on_type/auto_end.rs`, setting, wire) and
extension (`typing.js`, `extension.js`, `package.json`)
- [x] clock+reset templates (ghost + popup order)
- [x] current-file ranking (`completion/buffer.rs`, tier table)
- [x] keyword ghosts (`inline/keywords.rs`, setting, extension bridge fix)
- [x] port items (`completion/connection.rs`, `member.rs`)
- [x] unit, e2e and node tests; VS Code README; TODO §68.1 ticked
- [ ] confirmed in a running VS Code (see QA log — nobody has seen it yet)
## Work log
- **2026-11-17 (dev, Opus 5.5).** All five deliverables.
- `on_type/auto_end.rs` (new child module of `on_type.rs`): the begin-newline
answer; `on_type_formatting` tries it first when `auto_end` and falls back
to the unchanged indent answer. Old on-type tests pass `false`, so their
pins are untouched; 15 new tests (steal case, balanced, inner-closed with
outer missing, label + comment, wrapped header, `end else begin`, case
item, tabs, CRLF, last line, setting off, non-begin lines, text carried
down, begin two lines up).
- `templates.rs`/`inline.rs`/`completion`: with-reset first; template
`sortText` by registry rank (the label alone sorted `always @(*)` first).
- `completion/buffer.rs` (new): tiers 2 and 3; `word_tier` reads only the
table now. Decision: the typed token itself is not offered back (golden
`the_short_answers_are_what_they_always_were` updated, reasoned in place).
- `inline/keywords.rs` (new): keyword ghosts. Deviation from the brief's
"proper prefix of a keyword": a finished keyword only extends across `_`.
Found and fixed the `selectedCompletionInfo`/trigger-kind serialization
gap in the client bridge.
- `completion/connection.rs` (new) + `member.rs`: connected ports kept and
marked, snippet entries, pre-fill; parameters treated the same way.
- Extension: `typing.js` + `typing_test.js` (35 checks), wired in
`extension.js` (middleware + change listener), two settings in
`package.json`, README feature table and settings.
- `smoke.js` not changed: no existing probe's expectation moved (smoke run
recorded in the report).
- **2026-11-17 — fix round 2026-11-17 (dev, Opus 5.5)**, after QA and the
lead's rulings:
1. `owes_an_end`: closed also when the matched `end` sits at the `begin`'s
own line's indentation; an unmatched `begin` in a branched `` `ifdef ``
region arms nothing (`branched_regions`). Tests:
`a_gnu_style_begin_already_closed_under_itself_gets_no_end`,
`qa_ifdef_branches_sharing_one_end_get_no_second_end` (both QA repro
cases), `an_ifdef_with_no_else_still_arms_the_answer`.
2. "Extension bridge" assumption reworded: nothing was broken.
3. Keyword ghost: none for a word that is exactly a name the buffer
declares (`Semantics::symbols()` scan).
4. An explicit popup selection skips the finished-keyword rule
(`reserved_extension`).
5. A selection whose range is not exactly the typed word is read as absent.
6. `typing.js` strips trailing `/* … */` comments too (4 new checks).
7. The inline `begin` ghost gate asks `on_type::begin_owes_an_end` (new
`pub(crate)` re-export), so the stealing case ghosts its `end`; test
`a_begin_typed_inside_a_balanced_block_still_offers_its_end`.
Known limits 6–11 written into Assumptions.
## QA log
- **2026-11-17 (QA, Opus 5.5).** Verdict: **pass with findings** — no
MUST-FIX. Two SHOULD-FIX, the rest NOTEs for the lead.
**Gates (re-run by QA).** `cargo fmt --check` clean. Guarded `cargo clippy
-p lucisv_server --all-targets`: 0 warnings. Guarded `cargo test -p
lucisv_server`: 1813 unit passed / 36 ignored, e2e 102 / 2 ignored, grammar
3, opentitan_references 0 / 2 ignored (guard exit 0); after the QA tests
below, 1816 unit. `node --test editors/vscode/*_test.js`: 9 files pass
(typing_test 35 checks, 48 with QA's). Release build +
`node editors/vscode/smoke.js target/release/lucisv-server`: OK, 67
messages.
**Scope.** Diff touches only the §68.1 file list plus the flagged
`.vscodeignore` line; no parser/formatter/linter/semantic change.
(`gemini_review.md` at the root is untracked but dated 2026-10-19 — not
this lane's.) Production lines (before `mod tests`): `auto_end.rs` 184,
`keywords.rs` 242 (125 of them the Verilog word table), `buffer.rs` 68,
`connection.rs` 55, `inline.rs` 331 (was 319), `on_type.rs` 361 (354),
`completion/mod.rs` 287 (245), `member.rs` 209 (187), `tiers.rs` 162 (186),
`settings.rs` 240 (234), `templates.rs` 326 — none near 600; no new
function over 80 lines. No `unwrap`/`expect`/`panic!` in added non-test
code; `auto_end.rs` indexes `tokens[...]` with indices bounded by
construction (`prev < first <= begin < len`).
**How.** A Python stdio LSP driver against the release binary, and the same
driver against a release build of `HEAD` (exported with `git archive`, own
target dir) for before/after; sabotage-free throwaway copy for the corpus
sweep. Scripts and outputs: the QA scratchpad `qaA/` (`autoend.py`,
`ghosts.py`, `ports.py`, `perf.py`, `labels.py`, `starve.py`).
**Auto-`end`.** 46 hand cases applied to the buffer and read: nested
stealing inside a balanced `always_comb`, case items, generate `if`/nested
`for … begin : g`, function/task/class method, `fork … join`, `begin :
label` (any spacing), `begin // c`, `begin /* c */`, `else begin`, `end
else begin`, wrapped `else if (b &&\n c) begin`, `@*`, `@(*)`, `#5 begin`,
`assert … else begin`, `unique if`, `blk: begin`, header on the line above
the `begin`, tabs, CRLF, last line with and without a final newline,
whitespace-only new line with the cursor mid-indent — all write the right
`end` at the right column. Declines (and **the declined answer is
byte-identical to `HEAD`'s indent answer** in every case): balanced block,
`begin` in a comment / string / escaped identifier / attribute, `` `define
`` line (with and without `\` continuation), `begin end` on one line, text
carried down, two blank lines, a buffer that does not lex. `autoEnd=false`
equals `HEAD` in all 46. Idempotence: applying each answer and asking again
at the same spot never writes a second `end`. **Corpus sweep** (860 files,
every one of 8 235 lines ending in `begin`, Enter simulated after it):
**0 spurious `end`s**; positive control (file truncated after its first
`begin`): 512/525 armed; 0 corpus files have a permanently unmatched
`begin`. Timing: < 1 ms per answer.
**Ghost/popup templates.** `always_ff @(` ghosts with-reset then clock-only;
`always @(` with-reset, clock-only, `*`; popup `alw` in `.sv`: `always_ff
with reset`, `always_ff @(posedge clk)`, `always_comb begin/end`; in `.v`:
with-reset, clock-only, `@(*)`. Snippet syntax well-formed, tab stops 1, 2
(mirrored `$2` in the popup body), 3/4, `$0`.
**Ranking.** Tier digits match the table; dedup by first push. Labels
offered at 68 positions in `ibex_core.sv` (mid-word and word-end): **none
lost** against `HEAD`. Timing per completion (20 requests, minus an empty
session; two runs each), HEAD → NEW: `picorv32.v` `a` 0.25/0.29 →
0.43/0.35 ms, `r` 0.36/0.33 → 0.50/0.58; `ibex_core.sv` `a` 0.09/0.22 →
0.27/0.33, `r` 0.65/0.63 → 0.71/0.74. Sub-millisecond either way.
**Keyword ghosts.** None in a line/block comment, an unterminated string,
after `.`/`::`/backtick, for `$dis`, or mid-word; `.v` gets `always` /
`localparam` (no `logic`); each setting off independently. Selection
present with a keyword → that keyword over its range; with a non-keyword →
nothing. **The extension bridge is real**: `vscode-languageclient` 9.0.1
`asInlineCompletionParams` passes `context` through
(`InlineCompletionContext.create(triggerKind, selectedCompletionInfo)`),
and `middleware.provideInlineCompletionItems(document, position, context,
token, next)` is the hook it calls.
**Port items.** Unconnected first, connected after with `connected`
(including a port connected *after* the cursor and a port connected twice);
`.name(${1})`, pre-filled only from a visible net/var/port (a same-named
`localparam` is not used for a port; a `clk` in a named block or another
module of the file is not used); `#(.` pre-fills from a `localparam`;
escaped port → bare name; `.*` present → fine; unknown module → empty;
`.cl|(x)` → bare; no snippet support → bare everywhere.
**Findings.**
1. **SHOULD-FIX — a second `end` in complete code when the file holds
another unmatched `begin` and this block's `end` is not at the owner's
column.** The accepted heuristic, but the GNU layout makes it reachable
in valid code: `` module m;\n`ifdef A\n always @(posedge clk) begin\n`else\n always @(posedge clk or negedge rst) begin\n`endif\n if (x)\n begin\n|\n y <= 1;\n end\n end\nendmodule `` → ` end` written under the `if`, so the file
now has one `end` too many. Same with the cursor after the *first*
`` `ifdef `` branch's `begin` (an `end` lands inside branch A). Any
mid-edit unmatched `begin` above has the same effect on a GNU-style
block below. Corpus exposure measured at 0 (no corpus file is
permanently unbalanced). Suggested: also treat the `begin` as closed
when its matched `end` starts its line at the `begin`'s own line
indentation. Lead to rule.
2. **SHOULD-FIX (docs) — the "Extension bridge" assumption overstates the
bug it fixes.** The server *does* decode VS Code's array-shaped range and
trigger kind 0 (serde reads a struct from a sequence); before the bridge
the request did not fail and the template ghosts did not die. The bridge
is still right (spec spelling, correct trigger kinds). Pinned by
`qa_an_array_shaped_range_and_a_zero_trigger_kind_still_decode`. The
README paragraph should say so.
3. NOTE — keyword ghosts with no popup open fire on declared names and in
expression position: `assign out = in` → `put`, `x = re` → `turn`
(`return` is ahead of `reg` in `PRIORITY`; `.sv` only), `x = ou` →
`tput`, `x = al` → `ways_ff`. With the popup open VS Code's selection
is normally the exact-match signal, which silences the ghost. Lead to
rule whether an exact declared name or a non-statement position should
suppress it.
4. NOTE — the finished-keyword rule also applies to an explicit popup
selection: typed `end` with `endmodule` selected → no ghost (spec says
the ghost follows the selected item). Preview only; the popup accepts
it anyway.
5. NOTE — a `selectedCompletionInfo` whose range is elsewhere is echoed
back as the item range (VS Code would drop it); one missing `text`
fails the whole request with -32602 (pre-existing decode behaviour).
6. NOTE — `LIMIT` starvation moved: with ≥ 512 names in *this file*
matching a one-letter prefix (synthetic: 600 `logic aN;` in another
module), templates and keywords fall out of the answer (`HEAD` kept
them; `isIncomplete` is true, so the second letter re-asks). Not seen on
real files (largest: 220 items for `r` in `ibex_core.sv`).
7. NOTE — the typed token itself is skipped by tier 3 even mid-word, so a
word the file uses exactly once and declares nowhere drops out while the
cursor is inside it (68-position check found no case in `ibex_core.sv`).
8. NOTE — `fork … join` body: `initial fork\n begin` + Enter gives an
8-space body over a 4-space `end`; the body indent is the nesting
model's (identical to `HEAD`'s plain answer), not the lane's.
9. NOTE — pre-fill accepts a signal declared *after* the instance
(`sub u (.);\n logic clk;` → `clk(${1:clk})`).
10. NOTE — `typing.js` strips `//` comments only: `begin /* c */` + Enter
gets an `end` with `editor.formatOnType` on (server answers) but not
with it off (extension never asks).
11. NOTE (unverifiable here) — the last-line answer is one edit whose
range contains the cursor; with `editor.formatOnType` on, VS Code will
likely leave the cursor after the `end`, not on the body line (the
extension path puts it back itself). Needs a running VS Code, as do:
the one-step undo, the extension's `didChange`-before-request ordering
(reading `vscode-languageclient` 9.0.1 it holds: the incremental
`didChange` is sent from microtasks before the `setTimeout(0)` task),
and the ghost following the popup.
**QA tests added.** `on_type/auto_end.rs`:
`qa_asking_again_after_the_answer_is_applied_adds_no_second_end` (9
armed shapes), `qa_a_declined_newline_is_exactly_the_plain_indent_answer`
(9 declining shapes, incl. `` `define ``, `` `ifdef `` both branches,
string, escaped `\begin`). `inline/keywords.rs`:
`qa_an_array_shaped_range_and_a_zero_trigger_kind_still_decode`.
`editors/vscode/typing_test.js`: `qaEdges` (13 checks: multi-cursor, redo,
no editor, refused edit, CRLF position, pastes, context without a range).
## Review
### 2026-11-17 — lead (after dev, QA, one fix round)
Accepted. QA found no corruption, crash or spec violation; both SHOULD-FIX
items and the rulings below went into the fix round, and the dev's gates
after it are green (unit 1 823, e2e 102, node 9 files, smoke OK).
Rulings recorded:
- **Auto-`end` is armed by any unclosed `begin` at or before this one**, not
by this `begin`'s own span (the stack matcher lets a new inner `begin`
steal the outer `end`). Closed means: matched by an `end` that starts its
line at the indentation the answer would write, or at the `begin`'s own
line's (GNU layout). A `begin` unclosed inside an `ifdef` region with an
`else`/`elsif` arms nothing — the shared `end` after `endif` is its `end`.
- **No keyword ghost for a word that is exactly a name this buffer
declares** (`in`, `re`, `out` as signals stay quiet). Anything else that
is a keyword prefix ghosts, in any position — the owner asked for
"always".
- **An explicit popup selection wins** over the "finished keyword only
extends across `_`" rule; a selection whose range is not the typed word
is ignored.
- Accepted limits (in Assumptions): LIMIT 512 can drop templates/keywords
in a 600-same-prefix buffer; the token under the cursor is not offered
back; port pre-fill accepts a later declaration; the last-line answer is
one edit that contains the cursor.
**Not verified by anyone:** every behaviour in a running VS Code — the
cursor after `begin` + Enter (formatOnType on and off), one-step undo, the
ghost following the popup selection, the dimmed `connected` detail. The
list is in the dev's report and the QA log; it is the owner's acceptance.
+4
View File
@@ -282,6 +282,10 @@ signatures.
costs 1 and 1. `docs/features/header-recovery/README.md` is the feature;
the mechanism in *this* README — item and statement lists — is
unchanged and still handles everything outside a header.
- [x] **2026-11-17, `docs/features/port-entry-grace/README.md`:** an
unfinished connection (`.`, a `.name(` left open at the end of its line,
a trailing `,`) costs one diagnostic inside its own entry and the list
reads on to the entries after it.
## Work log
@@ -0,0 +1,126 @@
# instantiation-highlighting
## Goal
Give module and interface instantiations distinct, recognizable syntax colours
instead of painting every part of an instantiation with the default variable
foreground. Borrowing the roles other languages assign to constructor and
component calls (C++, Rust, TypeScript/JSX), each syntactic piece of an
instantiation takes its own semantic token class and theme-safe TextMate scope:
1. **Module / interface name** (`uart_core` in `uart_core #(...) u_uart (...)`,
`pkg::uart_core` with `pkg` as `namespace`, and lone `bind` targets) →
`class` (`entity.name.type.class`).
2. **`#` sign and parameters** (`#` before parameter port or override lists,
`.BAUD_DIV` dot + parameter-port name, `parameter`/`localparam` symbols, and
unresolved constant identifiers inside `#(...)`) → `parameter`
(`keyword.control` / `constant.language` / `variable.parameter`), sharing
one colour that stays distinct from bracket-pair-coloured `()`.
3. **Instance name** (`u_uart`, gate instances, `bind` target instances, and
uses of `SymbolKind::Instance` such as `u_uart.sig`) → `function`
(`entity.name.function`).
4. **Port name** (`.clk_i` dot + port name, implicit `.clk_i`, and wildcard
`.*` in an instance's connection list) → `property`
(`entity.name.tag.css` / `entity.other.attribute-name` /
`variable.other.property`).
5. **Port connection** (`clk` inside `.clk_i(clk)` or positional `(clk)`) →
`variable` (`support.variable` / `entity.other.attribute-name` /
`variable.other.readwrite`), keeping signal colouring consistent across the
file and non-white in themes that leave bare `variable` uncoloured.
## Assumptions
- **The 14-type wire legend is unchanged.** Every role above maps onto the
existing `SemanticTokenType` indices (`namespace`, `class`, `parameter`,
`variable`, `property`, `function`), so `token_types().len() == 14` and
`token_modifiers().len() == 1` stay untouched on the wire.
- **AST spans decide instantiation structure; single-file + overlay semantics
decide expressions.** A buffer opened before workspace indexing finishes, a
standalone file, or an instantiation of an unindexed vendor macro still
highlights its module name, `#`, `.PARAM`, instance name, and `.port` from
`Document.tree` alone. Identifiers that resolve through `Document.external`
also take their cross-file `SymbolKind` instead of degrading to `variable`.
- **Parameter `#` only, never delay `#`.** Only the `#` introducing a parameter
port list, parameter override list, or parameterized `DataType` receives
`Highlight::Parameter`; `#5` and `#(1:2:3)` net, assignment, gate, and
procedural delays remain unemitted punctuation.
- **Large-file fast path (`Document::large`) stays lexer-only.** Because the
fast path builds no AST or symbol table, AST-driven `#`, `.`, and `.*` tokens
are emitted only by the full pipeline, alongside identifier refinement.
- **Editor defaults remain user-overridable.** Setting
`editor.semanticHighlighting.enabled = true` in `configurationDefaults` for
`[verilog]` and `[systemverilog]` activates semantic tokens in themes whose
own `semanticHighlighting` flag is unset or `false`, while any explicit user
or workspace setting still wins.
## Handshakes
- **Consumed from `vlog_parser`:** `SourceFile`, `Item`/`ItemKind`, `Module`,
`Instantiation`, `Instance`, `Connections`, `Connection`, `BindDirective`,
`GateInstantiation`, `ClassDecl`, `ClassExtends`, `DataType::params`,
`ListElem`, `RawText`, `Token`, `TokenKind`, `TextRange`. No parser changes.
- **Consumed from `vlog_semantic`:** `Semantics`, `SymbolKind`,
`ExternalResolutions::definition_of`, `Definition`. No semantic changes.
- **Promised to LSP clients (`crates/lucisv_server/src/tokens.rs`):** identical
14-entry `token_types` legend and 1-entry `token_modifiers` legend; sorted,
non-overlapping single-line UTF-16 tokens; exact `full/delta` round-trip.
- **Shared with `editors/vscode/package.json`:** `contributes.semanticTokenScopes`
keys for `verilog` and `systemverilog` are a subset of `tokens::token_types()`,
checked by `editors/vscode/semanticTokens_test.js`.
## Status / TODO
- [x] Add `crates/lucisv_server/src/tokens/instantiation.rs` for AST-guided
instantiation and parameter-header highlight overrides.
- [x] Update `crates/lucisv_server/src/tokens.rs` to apply overrides, consult
`Document.external` via `definition_of`, map `SymbolKind::Instance` to
`Highlight::Function`, and add unit tests covering instantiation shapes,
delay `#` exclusion, recovered entries, and `large-file-mode` window
agreement.
- [x] Configure `editor.semanticHighlighting.enabled` and
`contributes.semanticTokenScopes` for `verilog` and `systemverilog` in
`editors/vscode/package.json`, with headless verification in
`editors/vscode/semanticTokens_test.js` (and `.vscodeignore` exclusion).
- [x] Update `docs/features/lucisv-server/README.md` and
`docs/features/large-file-mode/README.md` for the refined mapping.
## Work log
### 2026-11-17 — dev
- Audited `tokens.rs`, `editors/vscode/package.json`, and VS Code theme scope
tables across Dark Modern/Dark+, Light Modern/Light+, GitHub Dark, One Dark
Pro, Monokai, and Visual Studio Dark. Found two root causes for flat white
instantiations: (1) `tokens.rs` consulted only single-file `Semantics`
(leaving external module names, `.PARAM` overrides, `.port` names, and
`SymbolKind::Instance` all on `Highlight::Variable`, and leaving `#`
unemitted); (2) `package.json` neither defaulted
`editor.semanticHighlighting.enabled` on nor mapped semantic token types to
distinct TextMate scopes for themes where `variable`/`parameter`/`property`
collapse to white or one shared colour.
- Added `crates/lucisv_server/src/tokens/instantiation.rs` (~280 total lines)
and wired `crates/lucisv_server/src/tokens.rs` without changing the 14-type
wire legend:
- Module/interface/`extends` names → `Highlight::Class` (`pkg::` prefixes →
`Highlight::Namespace`);
- Parameter-list `#` (headers, instantiations, parameterized `DataType`s,
never delays), `.PARAM` overrides (`.` + name), and unresolved constant
identifiers inside `#(...)` → `Highlight::Parameter`;
- `SymbolKind::Instance`, `Instance.name_span`, gate instances, and `bind`
instance lists → `Highlight::Function`;
- Named port connections (`.` + name, implicit `.name`, wildcard `.*`),
including recovered unfinished entries while typing → `Highlight::Property`;
- Port connection expressions stay on `identifier_type` (`Highlight::Variable`
for signals), now backed by `ExternalResolutions::definition_of`.
- Added `editor.semanticHighlighting.enabled: true` under
`configurationDefaults` and `semanticTokenScopes` for `verilog` and
`systemverilog` in `editors/vscode/package.json`; added
`editors/vscode/semanticTokens_test.js` (75 checks, all green under `node`)
and listed it in `editors/vscode/.vscodeignore`.
- Cargo/Rust toolchain is not installed on this Windows host; Rust formatting
(`use_small_heuristics = "Max"`, ≤100 cols), clippy rules, and test
invariants were audited manually for Gitea CI execution.
## QA log
## Review
+6 -5
View File
@@ -184,11 +184,12 @@ documented difference below.
### What it gets wrong, honestly
- **A plain identifier is always `variable`, with no `declaration` modifier.**
There is no `Semantics` to refine it with, so a module name is not a `class`
and a parameter is not a `parameter`. Keywords, numbers, strings, comments,
directives, macro uses, `$system` tasks and attributes are all exactly what
the full pipeline says.
- **A plain identifier is always `variable`, with no `declaration` modifier, and
AST-only instantiation punctuation (`#`, `.`, `.*`) is unemitted.** There is
no `Semantics` or `Document.tree` to refine them with, so a module name is
not a `class` and a parameter or `#` is not a `parameter`. Keywords, numbers,
strings, comments, directives, macro uses, `$system` tasks and attributes are
all exactly what the full pipeline says.
- **A `/*` inside a string or after a `//` fools the backward scan**, and so
does a block comment whose opener is more than 64 KiB back — the documented
answer there is "code", so a multi-megabyte block comment mis-highlights.
+24 -14
View File
@@ -573,25 +573,35 @@ Modifiers: `0 declaration`.
| `TokenKind::SystemIdent` (`$display`) | `function` |
| `TokenKind::Attribute` (`(* ... *)`) | `decorator` |
| `Comment` trivia (leading and trailing, incl. on the EOF token) | `comment` |
| `TokenKind::Symbol` | **not emitted** |
| `TokenKind::Ident`, otherwise | from `Semantics`, below |
| `TokenKind::Symbol` (`#` before parameter lists; `.` / `.*` on named connections) | `parameter` / `property` |
| `TokenKind::Symbol`, otherwise | **not emitted** |
| `TokenKind::Ident`, otherwise | from `Document.tree` + `Semantics` + `ExternalResolutions`, below |
A plain identifier is looked up in the file's `Semantics` at its start offset:
a declaration (`symbol_at`) gets its symbol's type **plus the `declaration`
modifier**; a use (`reference_at`) that resolved in-file gets the resolved
symbol's type; anything else — an external candidate, a not-found name, a name
a macro would have produced — falls back to `variable`.
A plain identifier first checks the AST overrides built by
`tokens/instantiation.rs` (`docs/features/instantiation-highlighting/README.md`):
an instantiated module or `extends` base takes `class` (`pkg::` prefixes take
`namespace`), an instance name takes `function`, a `.PARAM` override and any
unresolved constant identifier inside `#(...)` take `parameter` alongside `#`,
and a `.port` connection takes `property`. Otherwise it is looked up through
`ExternalResolutions::definition_of` (`Semantics` first, then the workspace
overlay): a declaration (`symbol_at`) carries the `declaration` modifier, a
resolved local or external reference takes its target's `SymbolKind`, and
anything else falls back to `variable`.
`SymbolKind` → type: `Module`→`class`, `Package`→`namespace`,
`Typedef`→`type`, `EnumVariant`→`enumMember`, `Param`/`TfArg`→`parameter`,
`Function`/`Task`→`function`, `StructMember`→`property`, and
`Port`/`Net`/`Var`/`Genvar`/`Instance`/`Block`→`variable`.
`SymbolKind` → type: `Module`/`Interface`/`Modport`/`Class`/`Covergroup`→`class`,
`Package`→`namespace`, `Typedef`→`type`, `EnumVariant`→`enumMember`,
`Param`/`LocalParam`/`TfArg`→`parameter`,
`Function`/`Task`/`Instance`/`Property`/`Sequence`→`function`,
`StructMember`/`Constraint`/`Coverpoint`/`Cross`→`property`, and
`Port`/`Net`/`Var`/`Genvar`/`Clocking`/`Block`→`variable`.
Two rules that are easy to get wrong and are tested:
- **Punctuation is not emitted.** Every editor already colors brackets from
its TextMate grammar, and emitting one token per `;` roughly triples the
payload for no visible gain.
- **Ordinary punctuation (including `()`) is not emitted.** Every editor
already colours brackets from its bracket-pair colorizer or TextMate grammar,
and emitting one token per `;` roughly triples the payload for no visible
gain; only the parameter-list `#` and named-connection `.`/`.*` carry AST
highlights.
- **No token ever spans a line break.** The spec requires it, and Verilog has
three multi-line token shapes that would violate it — a block comment, a
continued `` `define``, and a multi-line macro invocation. Every span is
+538
View File
@@ -0,0 +1,538 @@
# port-entry-grace
## Goal
The owner (TODO §68.2): "don't rush to show the syntax error when the user is
editing the port, help auto complete the port syntax, like `.po...()`, and use
the auto-completed, syntax correct version to run syntax highlighting and
lint." Lane A (§68.1) makes accepting a port write `.name()`. This lane makes
the editor calm while a named connection is being typed inside an instance's
port list or `#(` parameter list. Two halves:
1. **Parser recovery** (`vlog_parser`, tolerant mode only): an unfinished
entry — a lone `.`, a `.name(` left open at the end of its line, a missing
`,`, a trailing `,` — stays inside its own entry. It still costs exactly one
diagnostic, whose span lies inside the entry (or on the one token that
proves it), and the rest of the list, the instance and the file parse,
colour and lint as if the entry were complete.
2. **The server withholds the entry being typed** (`lucisv_server`): while the
last edit of a buffer sits inside a connection list, the diagnostics
(parse *and* lint) whose range starts inside the entry around it are left
out of what is published or pulled, and said again when the next edit lands
outside the entry, when `PORT_ENTRY_GRACE` (1500 ms) passes with no edit, or
when the buffer is saved, closed or reopened.
## Assumptions
- **Tolerant mode only.** The whole-file formatter parses strictly, so every
shape here is refused by `format_source` exactly as before
(`crates/vlog_formatter/tests/port_entry_refusal.rs`), and no file the
strict parser accepts reads differently in tolerant mode
(`valid_lists_read_the_same_in_both_modes`,
`tolerant_parse_equals_strict_parse_on_valid_sources`; QA: 911 repo files
identical). **Corrected after QA:** the formatter *does* read the tolerant
tree in two places — Format Selection (`vlog_formatter/src/selection/mod.rs`,
`Tree::parse` falls back to it) and fences (`fence.rs`) — and the tolerant
diagnostic count is compared before/after by `vlog_refactor`'s check
(`check/mod.rs`) and the MCP placement check (`place/verify.rs`). The one
rule that changes what they see is (d), the trailing `,` now being
reported. QA measured the consequence (accepted by the lead): Format
Selection over 673 single-line selections in 113 files — 55
refused→formatted (selections clear of the instance in files whose only
fault is a trailing `,`, which used to be "not a tree to trust"), 0
formatted→refused, 0 changed outputs; the refactor check and the MCP
placement check now catch an edit that leaves `.a(x),)`; corpus
`picorv32/scripts/smtbmc/mulcmp.v` (two named lists ending in `,`, which
yosys accepts) is now flagged in the editor.
- **The unfinished entry is an error element, not a fabricated connection.**
`ListElem::Error` with the entry's raw text — the marker header recovery
already has. A synthesized `.po()` would make the tolerant tree claim a `)`
the source never wrote, and the MCP placement check compares tolerant trees
of two texts (`lucisv_mcp/src/tools/place/verify.rs`): `.po(` and `.po()`
must not compare equal. No new AST variant.
- **"The entry being typed" is where the last edit ended.** Incremental sync
only: the byte offset just past the last change's inserted text, in the new
text. A full-document sync (rangeless change) remembers nothing and
withholds nothing.
- **One buffer is being typed in at a time.** An edit in buffer B releases
whatever buffer A was withholding at once, rather than after A's grace.
- **1500 ms is a constant**, not a setting (same reasoning as
`CHANGE_DEBOUNCE`): long enough to finish a port name and its connection,
short enough that a real mistake left behind shows before attention moves.
- **The withheld window rides the generation.** Every change of what
`diagnostics_of` answers moves `generation` (the pull `resultId`): the edit
itself (flush), the release (grace or edit elsewhere), the save. A pull
answered while withholding can never be "unchanged" against a later full
list.
- **During a running scan the loop is the scan's**, so a grace that ends mid
scan is released when the scan hands the loop back (the same holds for the
change debounce today).
## The exact rules
### Half 1 — parser (`parser/recover_list.rs`, call sites in `parser/instance.rs`)
Applied in both the `#(` override list and a named connection list.
- **(a) lone `.`** — a `.` followed by `,` `)` `;` EOF, a construct
keyword (`endmodule`…), or — on a later line — a keyword or a `.`. A `.`
or keyword on the same line (`..z (p)`, `.input(x)`) keeps the generic
recovery: one error element holding the whole of it. It becomes an error
element holding just the `.`; diagnostic `expected a name after \`.\`` on
the `.`. (A same-line keyword, `.input(x)`, keeps the generic recovery,
whose skip takes the whole `.input(x)`.)
- **(b) open value** — at a `.name(`'s `(`, the value is abandoned when all
three hold: (1) the `(` is still open at the end of its line; (2) the next
line begins with `.`, `)`, `;`, a keyword, or EOF; (3) the bracket is not
closed the way a value's is — no matching `)` before a `;`/construct
keyword/EOF, or the matching `)` is followed by `;`, EOF, a construct
keyword, `.`, or a plain (non-macro) identifier. Valid lists always follow a
value's `)` with `,`, `)` or a directive/macro, so (3) is false on every
valid file — `.po(top` ⏎ `.sig), .q(r)` reads as written. The existing
error `unclosed \`(\` in a port or parameter connection` is raised at the
`(`, and the existing element recovery takes the `(` and skips to the end of
its line — at the value's own level. A bracket opened *inside* the
abandoned value (`.c(f(`, `.c(z[`, `.c({`, `.c((`) is skipped
bracket-balanced, so the element swallows the entries below it and the
list's `)` (`.c(f(\n .b(y))`). Same at c1076f9; a known limit. Condition (2) keeps the pinned ambiguous shape `.D(` ⏎
`u0 (.a(x)));` exactly as it was (an identifier opening the next line is
`value_runs_into_next_instance`'s question).
- **List continuation after a recovered entry** — `connection_list_ends`: in
tolerant mode, after an error element with no `,` behind it, a `.` at the
cursor is the next connection and the list reads on, silently (the
recovered entry already has its diagnostic). Any other token still ends the
list as `list_ends` always did.
- **(c) missing `,`** — unchanged from header recovery: both entries are
`Ok`, one `expected \`,\`` on the `.` of the second entry — the token that
proves the comma missing. After a recovered entry, (b) above applies
instead (no second diagnostic).
- **(d) trailing `,`** — a `,` that only the list's `)` follows, in a named
list or an override list: `expected a connection after \`,\`` on the `,`.
Tolerant mode used to end the list there *silently* while strict mode
refused — a gap this closes. A positional list's trailing `,` is an omitted
connection and stays legal.
- `.name(z);` on one line (both `)` already typed, list unclosed) is
unchanged: `Ok(.name(z))` plus `expected \`)\`` on the `;`.
### Half 2 — entry bounds (`state/port_grace.rs`, `entry_around`)
The list is `signature::enclosing_list`'s, but only believed when (1) no `;`
stands between its `(` and the edit (the bracket count takes a value left open
for the list never closing; a connection list never holds a `;`); (2) it is
a **named** list — it holds an entry at its own level that starts with `.`
(the one being typed counts; a `.` opening its own line counts at any depth);
and (3) it is not a declaration header's — no `module`, `macromodule`,
`interface`, `program`, `class`, `package`, `primitive`, `function`, `task`
or `checker` keyword between it and the `;` before. So positional instance
lists, call arguments, a function declaration with a user return type, a call
after `begin : label` and every header `#(` withhold nothing. Then:
- **start** — walking from the list's `(` to the edit: the last `,` at the
list's level (included), else the list's `(` (excluded); a `.` that opens
its own line always starts an entry (depth reset) — where the parser ends a
value left open on the line above.
- **end** — walking on from the edit at the depth the edit is at: the first
`,` at that level or any `;` (excluded, its start), the first closing
bracket that would go below that level, or the end of the edit's line —
reaching on to the next line's first token when that is a `.` (the token
that proves a `,` missing).
- A diagnostic is withheld iff its range **starts** in `[start, end]`, both
ends included.
Agreement with Half 1: (a) on the `.` — inside; (b) on the `(` — inside;
(c) on the next entry's `.` — inside whether the user typed the entry below
(the entry starts at its line's `.`) or above (the entry reaches the next
line's `.`), and on one line (no `,` between); (d) on the `,` — inside the
entry after it (start includes the `,`).
### Half 2 — when (`state/port_grace.rs` `PortGrace`, `server/*`)
- `didChange` → `sync::apply_changes_at` gives the edit end →
`PortGrace::edited` (pending; other buffers marked released).
- flush (`flush_dirty`) → after `set_document`, `locate_port_entry` looks the
edit up in the fresh tokens; outside any list it is forgotten.
- `diagnostics_of` (push and both pulls) → `PortGrace::withhold`.
- The loop (`Server::run`) waits `min(CHANGE_DEBOUNCE if dirty, time to the
earliest grace deadline)`; on the timeout, and at the top of every
iteration, `release_port_entries` bumps the generation and republishes each
due buffer. No thread, no new wake-up mechanism.
- `didSave` / `didClose` / `didOpen` forget the buffer's entry before the
flush; a save of a non-dirty buffer that was withholding republishes it.
- Formatting, semantic tokens, completion: untouched. The formatter refuses
on the real parse; the tokens after an unfinished entry equal those with
the entry completed (`after_an_unfinished_entry_the_file_reads_as_with_the_entry_completed`).
### Known limits (accepted by the lead, 2026-11-17)
- On a list that never closes, the entry runs on to the `;`, so a
diagnostic on the same line after it (`sub u0 (.a(x), .b(y) assign q = ;`)
waits out the grace too. The inclusive end also holds back an existing
diagnostic on the next line's `.` while the line above is typed.
- `.b(y)` ⏎ `.,` costs two diagnostics on one `.` (missing `,` and lone
dot).
- `.po(` before an `` `ifdef `` reports on the list's `;`, outside the
entry.
- A release republishes even when the entry held nothing back (one extra,
identical publish ~1.5 s after a keystroke in a complete entry).
- A nested bracket opened in an abandoned value swallows the rest of the
list (above).
## Handshakes
- **Consumes** `signature::enclosing_list` (unchanged) and
`vlog_parser`'s tolerant tree. **Promises** to everything reading the
tolerant tree: an unfinished connection is a `ListElem::Error` whose raw
text is the entry's own source; the entries after it are ordinary `Ok`
elements. `vlog_semantic`/`vlog_linter` already filter error elements
(`filter_map(ListElem::ok)`); verified no panic and no cascade
(`an_unfinished_entry_costs_one_error_and_no_cascade`).
- **New parser diagnostics** (tolerant only): `expected a name after \`.\``,
`expected a connection after \`,\``; the unclosed-`(` message is reused.
- **`sync::apply_changes` is `#[cfg(test)]` now**; the server calls
`apply_changes_at`, which also returns the edit end.
- **GRANTED by the lead, 2026-11-17: `workspace/diagnostic/refresh`.**
`ClientAbilities.diagnostic_refresh` (server/mod.rs), read in main.rs by
`diagnostic_refresh_support` from the **raw** params at
`capabilities.workspace.diagnostics.refreshSupport` — `lsp-types` 0.97
names its typed field `diagnostic` (singular, no rename), so the typed
decode never sees what VS Code sends. `release_port_entries` sends the
request once per release (not per buffer) when the client pulls and
accepts it; the answer is ignored (`response`'s fall-through).
`vscode-languageclient` 9 advertises the capability and re-pulls visible
documents on the request, so in VS Code the entry shows after the 1.5 s
pause. A pulling client without it still sees the release at its own next
pull, under a new generation.
## Status / TODO
- [x] Half 1: (a) lone `.`, (b) open value, list continuation, (d) trailing
`,`; (c) already held. Unit tests + valid-unchanged + formatter-refuses.
- [x] Half 2: edit end from incremental sync, entry bounds, withhold in push
and pull, release on edit elsewhere / grace / save / close / reopen,
generation bump on release.
- [x] Server unit tests (bounds, state machine with injected time, tokens and
findings after the entry) and e2e over stdio (grace, edit elsewhere,
save, pull).
- [x] Perf: didChange→publish before/after, two runs each.
- [x] `workspace/diagnostic/refresh` for pulling clients that accept it —
Handshake granted, main.rs read, e2e both ways.
## Work log
### 2026-11-17 — dev agent (Opus 5.5)
- Surveyed today's tolerant parse of every shape with a scratch probe:
`.` ⏎ `.b(y)` and `.po(` ⏎ `.b(y)` cost the rest of the list (the recovered
entry with no `,` ended it; `.b(y));` became an error item, two
diagnostics, the second on the next entry); `.po(z` ⏎ `.b(y))` read as
`.po(z.b(y))` with the diagnostic on the `;`; `.b(y),)` was **silent** in
tolerant mode though strict refuses it; the missing `,` already kept both
entries.
- Half 1 lives in `recover_list.rs` (the list-recovery module) rather than in
`instance.rs`: `instance.rs` is at 564 production lines and CLAUDE.md sends
new code near 600 to another module. `instance.rs` only changes its two
list loops' calls (`connection_or_recover`, `note_trailing_comma`,
`connection_list_ends`) and ORs `value_left_open` into the existing
unclosed-`(` test. `at_open_bracket` became a wrapper over a free
`is_open_bracket` shared with the new lookahead.
- Half 2: the state lives in the `Workspace` (`state/port_grace.rs`, field
`grace`), not in `Server`: `Server` is built by a struct literal in
`startup.rs` and `ClientAbilities` by one in `main.rs`, neither this lane's
file; `Workspace` is `Default`-built, so a field costs nothing outside
`state/`. Same reason the new module is `state/port_grace.rs` and not a
crate-root module (that would need a `mod` line in `main.rs`).
- Found and fixed: `enclosing_list`'s naive bracket count reads a list as
still open after an abandoned `.po(`, so an edit three items down was
"inside" it and its `wire ;` error was withheld. A `;` between the list's
`(` and the edit now rules the list out (unit-tested).
- Pull mode: no refresh path exists (`docs/features/pull-diagnostics/README.md`
says so explicitly), so per the brief nothing was invented; the generation
bump makes the next pull full. Handshake request filed above.
- Perf, `didChange` → `publishDiagnostics` over stdio, release build, two runs
each (ms; "alone" includes the 150 ms debounce timer, "+request" is a
keystroke a request follows, mean of ten):
| probe | before run 1 | before run 2 | after run 1 | after run 2 |
|---|---|---|---|---|
| ibex_core.sv (2 026 lines), keystroke in a `.clk_i` connection, alone | 170.5 | 158.8 | 165.2 | 157.6 |
| same, + request | 4.87 | 4.25 | 5.05 | 4.26 |
| generated 1 000 lines, alone | 168.5 | 165.9 | 164.6 | 164.7 |
| generated 1 000 lines, + request | 3.85 | 4.14 | 3.97 | 3.71 |
| generated 10 000 lines, alone | 200.0 | 202.3 | 204.8 | 198.7 |
| generated 10 000 lines, + request | 37.5 | 38.1 | 37.9 | 37.1 |
Probe: `cargo test --release -p lucisv_server --test e2e a_keystroke --
--ignored --nocapture --test-threads=1` (the new
`a_keystroke_in_a_port_list_round_trip_over_the_wire` plus the existing
`a_keystroke_round_trip_over_the_wire`). Flat within run-to-run noise:
the entry lookup is one token walk per flush, no extra parse.
- Gates: `cargo fmt`, clippy `--all-targets` (vlog_parser, lucisv_server)
clean; suites green (vlog_parser 518, vlog_semantic 418, vlog_linter 673,
vlog_formatter 352, vlog_refactor 743, lucisv_server 1 950, every guard
exit 0); corpus gate 814/820 pass; release build + `smoke.js` OK.
- Handshake granted (lead): main.rs reads `refreshSupport` from the raw
params (the typed field is misnamed in `lsp-types` 0.97 — found while
wiring it); `release_port_entries` asks a capable pulling client to pull
again, once per release. Tests: a unit test of the capability read
(plural key only, literal `true` only), e2e
`a_pulling_client_that_can_refresh_is_asked_to_after_the_grace`, and the
no-capability pull test now proves no refresh is sent. VS Code README line
restored to "after a short pause, or once you edit elsewhere or save".
### 2026-11-17 — fix round (dev agent, Opus 5.5)
- MUST-FIX 1: rule (a)'s `.` follower now counts only on a later line;
`..z (p)` is one error element again, so `lucisv_mcp`'s `qa_f1`
(unmodified) passes. Test `two_dots_on_one_line_stay_one_error_element`.
- SHOULD-FIX 2: `entry_around` requires a named list
(`holds_a_named_entry`) and rejects declaration headers
(`in_a_declaration_header`). Tests for QA's cases (header `#(parameter W =
|)`, interface and class headers, positional list, function declaration,
call after a labelled begin, a fresh empty instance list) and the positive
ones (`.po`, `.`, a fresh entry after `,`, `#(.W(|` on an instance).
- README: the tolerant-tree claim rewritten with QA's measured consequence;
the nested-bracket skip described as it is; known limits listed.
## QA log
### 2026-11-17 — QA agent (Opus 5.5)
Verdict: **fail on one gate (MUST-FIX 1), otherwise pass with findings.**
Experiments ran in throwaway copies under the session scratchpad (`base/` =
`git archive c1076f9`, `copy/` = this working tree, each with its own target
dir); nothing in the working tree was rewritten. Only added file:
`crates/vlog_parser/tests/qa_port_entry_grace.rs`.
**A. Gates (re-run by QA, every suite through `tools/guard.sh -m 6 -t 1200`).**
`cargo fmt --all --check` 0; clippy `--all-targets -p vlog_parser -p
lucisv_server` 0, no warnings. Suites (passed/failed/ignored, guard exit):
vlog_parser 518/0/2 (0), vlog_semantic 418/0/4 (0), vlog_linter 673/0/0 (0),
vlog_formatter 352/0/0 (0), vlog_refactor 743/0/6 (0), lucisv_server
1 952/0/41 (0), lucisv 143/0/0 (0), **lucisv_mcp 124/1/3 (101)**.
`tools/gates.sh --only corpus`: PASS, 814/6. Release build 0;
`smoke.js target/release/lucisv-server`: OK (67 messages). With the QA file:
vlog_parser +2 tests, green.
**B. Scope / size.** verify.rs, formatter source, AST, semantic, linter
untouched. Edited beyond TODO §68.2's file list: `parser/recover_list.rs`
(reasoned in the work log), `server/notification.rs`, `sync.rs`,
`tests/e2e.rs` (plus the granted main.rs / server/mod.rs). Production lines
(non-blank, non-comment, before `mod tests`): recover_list.rs 169 → 287,
instance.rs 564 → 569, port_grace.rs 162 (new), notification.rs 206 → 230,
server/diagnostics.rs 158 → 183. No `unwrap`/`expect`/`panic!`/`unsafe` in
new non-test code; slice indexing in `entry_start`/`entry_end` is bounded.
**C. Parser.** (1) 1 023 inputs — all 911 `.sv/.v/.svh/.vh` files in the repo
(corpus + fixtures) + 60 QA legal shapes + 52 QA broken shapes — dumped as
strict result + tolerant diagnostics + tolerant tree (`{:#?}`) by both
binaries: **every strict result identical; every file the strict parser
accepts reads identically**. The 43 differences are all strict-refused
inputs (41 QA broken shapes, QA `v57`, and corpus
`picorv32/scripts/smtbmc/mulcmp.v`, whose two named lists end in `,` — see
C4). `lucisv --stdout` over all 1 023: byte-identical outputs and exit codes;
`lucisv check`: identical except QA `b09` (a generate label lint now reached
past the recovered entry — intended). (2) Legal multi-line connections
(next-line operand, `signed'(…)`, `this.`, `super.`, `null`, `new`, `$bits`,
`` `MACRO(x) ``, comment line, `intf.sig`, `.a(intf` ⏎ `.sig)`, `#(.W(` ⏎
`8))`, `.*`, `(* *)`, generate-for, instance arrays, gates, `bind`, program /
interface / checker instances, UDP, `` `ifdef `` arms, `{n{…}}`, `inside`,
`tagged`, `pkg::`, `std::randomize`, two instances per item, …): zero
diagnostics, tree == strict tree; pinned in `qa_port_entry_grace.rs`. A
mutation dropping condition (3) (`starts_new && !self.value_closes(open)` →
`starts_new`) is caught by `tolerant_parse_equals_strict_parse_on_valid_sources`
and `valid_lists_read_the_same_in_both_modes`. (3) 50 unfinished shapes
(first / last / only / repeated / at EOF / in `#(` / in generate / in
`` `ifdef `` / nested open bracket / `.po(a,` / `.` ⏎ `);` / trailing `,` +
EOF / keyword after `(` / ten lone dots): never silent, strict refuses all, no
panic, no hang, at most one diagnostic per line; pinned in the same file
(fails on c1076f9: the silent trailing comma). (4) Consumers of the new
trailing-`,` diagnostic: see SHOULD-FIX 3. (5) `format_selection`, every
single line of 113 files (the QA shapes + mulcmp.v), 673 selections, base vs
new: 0 OK→refused, 0 OK with a different output, 55 refused→OK (all on
files whose new tolerant parse now has a diagnostic: b17 b22 b33 b39 b41 b46
mulcmp.v), every OK output keeps every non-whitespace character of the input;
whole-file `format_source` refusal set identical.
**D. Server** (python stdio client against the release binary; scripts in
the scratchpad `qaB/d2.py`). (1) A pre-existing lone `.` in another entry of
the same list, an `assign q = ;` elsewhere and lints elsewhere publish while
`.po(` is held. (2) Release: push +1 501–1 516 ms after the keystroke;
pull + `refreshSupport`: one `workspace/diagnostic/refresh` at +1 501 ms,
next pull full under a new resultId, no repeat refresh in 2 s; pull without
it: no server message, next pull full (resultId 3 → 4); `workspace/diagnostic`
likewise; edit elsewhere +162 ms (the debounce); edit in another buffer +1 ms;
save +1 ms (also when sent before the debounce flush); close clears, reopen
says everything. (3) No permanent hide found: hover + completion every 200 ms
for 5 s → released at +1 507 ms; two changes in one notification (last one
decides, both orders); full-document sync withholds nothing; undo; deleting
the whole instance; lines inserted above (edit elsewhere → release).
(5) `.b` → `.bx(y)` in a project: `unknown-port` withheld, shown at +1 507 ms;
`.a(undef…)` likewise. (6) ibex_core.sv keystroke in `.clk_i`, two runs per
arm: base 167.6 / 167.6 ms alone, 5.64 / 5.50 ms + request; new 168.5 /
168.3, 5.64 / 5.64 — flat. CPU over 5 idle s after a release: 0.000 s.
(7) Semantic tokens after the entry (`.po`, `.po(`, `.`, `.po(x`, `.po,` vs
`.po(),`): identical (also on c1076f9 — tokens are lexical there).
**MUST-FIX**
1. **`lucisv_mcp` suite red**:
`crates/lucisv_mcp/tests/qa_f1.rs:447`
`qa_r_only_an_affected_instances_unreadable_connection_refuses` fails
(passes on c1076f9). `..z (p)` is now a lone-`.` error element `.` plus an
`Ok` connection `.z (p)` (rule (a) takes any `.` followed by `.`, same line
included), so `add_port` still refuses and writes nothing, but says "holds
`.`" instead of "holds `..z (p)`". Repro: `cargo test -p lucisv_mcp --test
qa_f1`. The lane's gate list omitted lucisv_mcp. Either restrict (a)'s
`.` follower to a later line, or (lead's ruling, file outside the lane)
update the expectation.
**SHOULD-FIX**
2. **Module/class header `#(` lists are treated as instance lists.**
`signature::list_at` reads `name #(` as an override list, so typing in
`module hm #(parameter W = |) (input logic a);` withholds the header's
diagnostics for 1.5 s (over the wire: `expected expression` at 0:26 shown
only at +1 503 ms). The brief says a header must withhold nothing.
`port_grace.rs:192` (`entry_around` takes `enclosing_list` as is).
3. **README Assumption "the formatter … never reads the tolerant tree" is
false.** `vlog_formatter/src/selection/mod.rs:87` (`Tree::parse`) falls
back to the tolerant tree, and `fence.rs:110` reads it. Consequence of (d):
a file whose only fault is a trailing `,` (corpus `mulcmp.v`) used to be
refused whole by Format Selection (tolerant parse had no diagnostic → "not
a tree to trust"); now selections clear of the instance format (verified
output, text preserved — C5) and the instance itself is refused. Also
new: the editor flags `mulcmp.v` (yosys accepts the trailing comma). Other
consumers: `vlog_refactor` `check/mod.rs:324` and MCP `place/verify.rs:62`
compare tolerant diagnostic *counts* before/after — an engine edit that
leaves `.a(x),)` is now caught (tighter, no test changed); `lucisv check`
does not print parse diagnostics (unchanged output). Correct behaviour as
far as QA can tell; the README should say so.
4. **Nested open bracket in the abandoned value swallows the rest of the
list.** `.c(f(` / `.c(z[` / `.c({` / `.c((` ⏎ `.b(y));`: the error element
is `.c(f(\n .b(y))` — the next entry and the list's `)` go with it (rule
(b) fires, but the element recovery's skip is bracket-balanced, not "to
the end of its line" as the README says). Over the wire a lint outside the
entry (`` `y` is read but never driven `` at 1:11) appears at once while
typing `.c(f(`, and not while typing `.c(`. Same as c1076f9, so not a
regression, but the README's promise doesn't hold for it.
**NOTE**
5. Other lists `enclosing_list` accepts, withheld for 1.5 s: positional
instance lists (`sub u0 (x, y|, z)` → `, y`); function declarations with a
user-type return (`function automatic my_t f(input a|` → `input a`); a
call right after a block label (`begin : blk` ⏎ `my_task(a, b|)` → `, b`).
Not covered (nothing withheld): instance arrays `sub u0 [1:0] (…)`, gates.
6. On an unclosed list, `entry_end` runs to the `;`: `sub u0 (.a(x), .b(y) |
assign q = ;` withholds both `assign` diagnostics (1.5 s). The inclusive
end also withholds a pre-existing diagnostic on the next line's `.` when
typing on the line above it.
7. "Exactly one diagnostic" has exceptions: `.b(y)` ⏎ `.,` costs two on one
`.` (missing `,` + lone dot). `.po(` ⏎ `.b(y)), .c(z));` now loses the
whole instance to an error item (c1076f9 kept it) — contrived, not a typing
shape. `.po(` ⏎ `` `ifdef `` … → diagnostic on the list's `;`, outside the
entry.
8. Pre-existing, not this lane: a positional list's trailing omitted
connection (`u0 (x, y,)`) is an empty `Ok` entry strictly and absent
tolerantly — strict ≠ tolerant on valid input (same at c1076f9).
9. A release republishes even when the entry held nothing back (one extra
identical publish ~1.5 s after a keystroke in a complete entry). Harmless.
10. Only a running VS Code confirms: the squiggle actually disappears and
reappears with `vscode-languageclient` 9.0.1 pull + refresh (the
capability is advertised: `diagnostic.js:784`), and how it feels.
### 2026-11-17 — QA re-check of the fix round (Opus 5.5)
Verdict: **pass.** MUST-FIX 1 and SHOULD-FIX 2 are fixed; nothing new found
that blocks. Fresh scratch snapshot of the working tree; the old-vs-new
comparison is against the same c1076f9 baseline.
- **Gates** (QA's own runs, each suite guarded, exit 0): `cargo fmt --check`
clean; clippy `--all-targets -p vlog_parser -p lucisv_server` clean, 0
warnings; vlog_parser 521/0/2 (includes `qa_port_entry_grace.rs`, 2/2),
lucisv_server 1 954/0/41, **lucisv_mcp 383/0/4** (full suite;
`git status crates/lucisv_mcp` empty), vlog_formatter 352/0/0;
`gates.sh --only corpus` PASS 814/6.
- **MUST-FIX 1.** `sub u0 (.a(x), ..z (p));` and `sub u0 (.a(x), . .b(y));`:
one error element (`..z (p)`, `. .b(y)`) and one `expected identifier`
diagnostic, the same tree and diagnostics as c1076f9. `.` ⏎ `.b(y)` still
recovers: error `.`, one `expected a name after \`.\``, the list reads on.
- **SHOULD-FIX 2, over the wire** (release binary, error typed, first
publish vs ~1.5 s later). Withholding nothing; the error arrives with
the debounce: the module `#(parameter W = |)` and interface headers, the
class `#(type T = …)` header, a positional instance list, a function
declaration with a user return type, and `my_task(a, |b)` after
`begin : blk`. Still withheld, released at +1 502–1 512 ms: `.po(`, `.`,
`.p(` after a `,`, `#(.W(|` on an instance, and `.` in a fresh empty
`sub u0 (|)`. Attacks on `in_a_declaration_header`. Every instance below
is still withheld, so none is wrongly taken for a header: after
`function void f(); endfunction`, after `task t; endtask`, after
`endclass` and after `endpackage`; after `always_comb begin end` and after
`function int f(int a); return a; endfunction`; inside
`generate if (X) begin`; after `else` and after `` `ifdef ``; after
`(* keep *)`; in a `bind`; in interface and program bodies; as the first
item after `module m (input a);`; on the header's own line
(`module m; sub u0 (…`); and for checker and interface instances. Lists
that might be wrongly included: none are withheld for
`extern function my_t f(`, `import "DPI-C" function my_t f(`,
`virtual intf vif(`, `new(.x(…))`, a modport or a clocking block. Two are
withheld, both instance-shaped and both accepted per the brief:
`t(.a(|=1))` after `begin : blk`, and `my_t v (.a(…))`, which is an
instance.
- **Valid-code identity** (1 026 inputs: the 1 023 from before plus the
three two-dot shapes). Every strict result is identical. The tolerant
trees differ only on strict-refused inputs: 41 QA broken shapes, `v57`
and `mulcmp.v`. `lucisv --stdout` outputs and exit codes are
byte-identical. `lucisv check` output is identical except QA `b09`, as
before.
- **README.** The tolerant-tree readers, the nested-bracket limit, the
named-list and header rules and the known limits all match the code.
NOTE (new, minor):
11. In README rule (a), the sentence "It becomes an error element holding
just the `.`…" now follows the same-line exception, so it reads as if
it described the exception. The `.input(x)` parenthetical is repeated,
and one line of rule (b) is not wrapped. Wording only.
12. `holds_a_named_entry` counts a `.` that opens a line at any depth. A
positional list that continues a hierarchical name on the next line
(`sub u0 (top` ⏎ `.sig, b)`) therefore counts as named and is withheld
for 1.5 s. Rare and harmless.
## Review
### 2026-11-17 — lead (after dev, QA fail on one gate, one fix round, QA re-check pass)
Accepted. The first QA verdict was a fail on one gate: `lucisv_mcp`'s
`qa_f1` — rule (a) read `..z (p)` on one line as a lone dot. The lead's
dev brief had left `lucisv_mcp` and `lucisv` out of the gate list; that
omission is the lead's, and both crates are in every later list. One Opus
fix round; the re-check passed (parser 521, server 1 954, mcp 383,
formatter 352, corpus 814/6).
Rulings recorded:
- **A following `.` makes a lone dot only on a later line.** Two dots on
one line keep the generic recovery, so the MCP refusal message is the one
it was.
- **Only a named-connection list of an instance withholds.** The list holds
an entry at its own level that starts with `.`, and no declaration keyword
stands between it and the `;` before it. Headers, positional lists, call
arguments withhold nothing. A named-argument call and `my_t v (.a(…))`
still do; accepted (same syntax as an instance).
- **A trailing `,` in a named list is now a tolerant-mode diagnostic**, as it
always was in strict mode. Consequences measured by QA and accepted:
Format Selection away from that instance now formats (55 refused →
formatted, none the other way, no output changed); the refactor check and
the MCP placement check catch an edit that leaves one; one yosys-style
corpus file is flagged in the editor.
- **`workspace/diagnostic/refresh`** on release for a pulling client that
advertises it (handshake granted to the dev: `main.rs`).
- Valid code: 1 026 inputs old vs new, every strict result and every
strictly-accepted tree identical, CLI output byte-identical.
Open, minor: QA notes 11 (rule (a) wording in this README) and 12 (a
positional list continuing a hierarchical name on the next line counts as
named). **Not verified by anyone:** the squiggle's timing in a running VS
Code with the pull + refresh client, and whether 1.5 s feels right.
+2
View File
@@ -430,6 +430,8 @@ graph LR
| `range-formatting ──▶ format-fences` | depends | A range is "an inverted fence": reuses `Doc::Verbatim`, `fence::collect`/`region_at`, and two helpers widened to `pub(crate)` (`line_start`, `with_trailing_comments`) — the only fence.rs change. |
| `range-formatting ──▶ spans` | depends | The planner selects items by span/line. |
| `selection-formatting ──▶ range-formatting / format-fences / lucisv-server` | depends | (2026-11-09, TODO §66.2) `format_selection` lays out the smallest run of sibling items/statements a line span covers at its written indentation and splices it in; defers to `format_range` for a module/package-level target; consumes `fence::collect`/`with_trailing_comments` and `Fmt::item_seq`/`stmt_seq`; adds `Printer::print_at` and `FormatError::Selection`. `verify.rs`, `range.rs`, `fence.rs` untouched. The server's range, ranges and on-type `;` requests all go through it. |
| `completion-ux ──▶ on-type-formatting / inline-templates / completion-core / member-completion` | depends | (2026-11-17, TODO §68.1) the newline on-type answer writes an owed `end` (`on_type/auto_end.rs`, `begin_owes_an_end` shared with the `begin` ghost); keyword ghosts after the template triggers (`inline/keywords.rs`, follows `selectedCompletionInfo`); sortText tiers 2/3 are this buffer's declared names and used words (`completion/buffer.rs`); connection items keep connected ports and insert `name($1)` (`completion/connection.rs`). Extension `typing.js` sends the on-type request when `editor.formatOnType` is off. Server crate only. |
| `port-entry-grace ──▶ header-recovery / pull-diagnostics / change-debounce` | depends | (2026-11-17, TODO §68.2) tolerant-mode recovery of an unfinished named connection in `parser/recover_list.rs` (lone `.`, value left open at its line end, trailing `,` — always a diagnostic inside the entry; strict mode and valid code unchanged); `state/port_grace.rs` withholds the diagnostics of the entry the last edit touched for `PORT_ENTRY_GRACE` (1.5 s) in a named-connection list of an instance, released by the main loop's timeout, an edit elsewhere, or a save; `workspace/diagnostic/refresh` for pulling clients. A trailing `,` in a named list is now a tolerant diagnostic — read by Format Selection, the refactor check and the MCP placement check. |
| `alignment ──▶ spans` (+ name-spans) | depends | Anchor columns are derived from `name_span` byte offsets + the source text; deliberately **no** token-level representation of spacing. `doc.rs`/`printer.rs`/`verify.rs` untouched. |
| `alignment ──▶ format-fences` | depends | `fence::region_at` (via `Fmt::is_fenced`) keeps fenced items out of alignment groups. |
| `shared-fence-filter ◀──▶ linter-core / server-lint` | handshake | Closes server-lint Handshake 3: `fence::protected_regions` + `is_protected` become the **one** answer to "what may an automatic fix not touch"; CLI `--fix` and server quick fixes both call it; `vlog_linter` itself deliberately stays fence-blind. |
+3 -1
View File
@@ -1,5 +1,5 @@
# The checks are pre-publish/developer checks, not part of the shipped
# extension. `restart.js`, `mcp.js` and the `hierarchy*`/`references*` modules
# extension. `restart.js`, `typing.js`, `mcp.js` and the `hierarchy*`/`references*` modules
# themselves ARE shipped — `extension.js` requires them.
smoke.js
mcp_smoke.js
@@ -11,5 +11,7 @@ hierarchySections_test.js
hierarchyView_test.js
referencesModel_test.js
referencesView_test.js
typing_test.js
semanticTokens_test.js
.vscode/**
.gitignore
+33
View File
@@ -5,6 +5,39 @@ for you. The extension and its bundled language server share one version
number; the full engineering notes live in the
[project changelog](https://git.luci.ooo/lucio/lucisv/src/branch/master/CHANGELOG.md).
## 0.65.0 — 2026-11-19
- **Module instantiations are now colour-coded by role.** Module names
(`class`), instance names (`function`), port names (`.clk_i` and `.*`,
`property`), and connected signals (`variable`) each take a distinct colour
instead of blending together in white.
- **`#` shares the parameter colour**, separate from `()`: the `#` before a
parameter header or override list, `.PARAM` names, and parameter values
highlight together as `parameter`, while `#5` delays stay untouched.
- **Semantic highlighting works out of the box across themes.** The extension
now enables `editor.semanticHighlighting.enabled` by default for Verilog and
SystemVerilog and provides distinct TextMate fallback scopes for every role.
## 0.64.0 — 2026-11-17
- **`begin` + Enter writes the `end`.** The cursor lands on the indented
line between them, ready for the first statement. Turn it off with
`lucisv.autoEnd`.
- **`always_ff @(` and `always @(` expand with clock and reset** —
`posedge clk or negedge rst_n` — and Tab jumps between the two names.
- **Suggestions put this file's names first**, ahead of names from other
files and keywords.
- **Keywords appear as grey ghost text** after two letters; Tab accepts.
Turn it off with `lucisv.inlineKeywords`.
- **Port suggestions list unconnected ports first**; ports you already
connected follow, marked `connected`. Accepting one writes `.name()` with
the cursor inside, filled in with a same-named signal when there is one.
- **No rushed errors while you type a connection.** The error on a
half-typed `.port` waits until you pause for a moment, edit elsewhere or
save, and the rest of the file keeps its colours and lint meanwhile.
- A trailing comma before the closing `)` of a named connection list is now
flagged in the editor (the formatter always refused it).
## 0.63.1 — 2026-11-11
- **Sticky scroll shows where you are, layer by layer.** The first line of
+33 -3
View File
@@ -30,7 +30,7 @@ Install **lucisv — Verilog/SystemVerilog** from the VS Code Extensions view,
then open a Verilog or SystemVerilog file. There is no separate server or CLI
setup.
The current release is **0.63.1**. Its platform packages include
The current release is **0.65.0**. Its platform packages include
`lucisv-server`, the `lucisv` command-line tool and `lucisv-mcp` (see
[Agents (MCP)](#agents-mcp)):
@@ -80,7 +80,16 @@ Most features work as soon as a supported file opens:
workspace-aware and verifies its target before opening the rename box.
- Type `if (`, `case (`, `begin`, `fork`, `generate`, or `module` at the end of
a line to get structural ghost text. Press `Tab` to accept it; use `Alt+]` to
cycle when several shapes fit.
cycle when several shapes fit. `always_ff @(` offers a clock-and-reset block
first and the clock-only one second.
- Press `Enter` after a `begin` that has no `end` yet and the `end` is written
on the line below, lined up with its statement, with the cursor on the
indented line in between.
- Start typing a keyword (`alw`, `endm`) and the rest of it appears as grey
text; `Tab` accepts it.
- After the `.` of a port connection the ports still to connect come first;
accepting one writes `.name()` with the cursor inside, pre-filled with a
same-named signal when there is one.
- Run **Format Document** or **Format Selection** through the standard VS Code
commands.
@@ -106,11 +115,13 @@ enabling both paths formats twice.
| Document formatting | Width-aware, deterministic formatting with inferred alignment for ports, connections, and parameter tables |
| Range and multi-range formatting | Formats selected constructs while leaving the rest of the file byte-for-byte unchanged |
| On-type formatting | Reindents after a newline and formats a completed statement after `;` when `editor.formatOnType` is enabled |
| Auto `end` | `Enter` after an unclosed `begin` writes its `end` below the cursor at the statement's indentation, with or without `editor.formatOnType` (`lucisv.autoEnd`) |
| Keyword ghosts | A typed prefix of a keyword shows the rest as grey text that follows the popup's selection (`lucisv.inlineKeywords`) |
| Format on save | Works through VS Code's native format-on-save flow; a separate LSP save hook is available for other editors |
| Safe output | Token equivalence, comment preservation, convergence checks, and all-or-nothing fallback protect source code |
| Format fences | `// verilog_format: off` / `on` preserves deliberately hand-formatted regions |
| Inline templates | Context-sensitive ghost text completes blocks, cases, processes, generate regions, and modules |
| Smart completion | Context-aware statement/declaration templates plus complete module-instantiation snippets from the workspace index |
| Smart completion | Context-aware statement/declaration templates plus complete module-instantiation snippets from the workspace index. Names from the current file rank first; after a connection's `.` the unconnected ports come first, connected ones follow marked `connected`, and accepting one writes `.name()` |
| Static snippets | Dialect-specific file-level templates for modules, interfaces, packages, classes, functions, tasks, FSMs, assertions, testbenches, guards, and generate loops |
| Signature help | Names active ports or parameters in named and ordered instantiations |
| Linked editing | Keeps opening and closing labels synchronized for modules, classes, functions, tasks, blocks, forks, and other named scopes |
@@ -121,6 +132,7 @@ enabling both paths formats twice.
| Feature | What you get |
|---|---|
| Live parse diagnostics | Error-tolerant parsing keeps useful feedback flowing while code is half typed |
| Quiet while you connect a port | The connection being typed (`.po(` in an instance's port or `#(` list) is not flagged while you type it, only after a short pause, or once you edit elsewhere or save; the rest of the file colours and lints as if it were finished |
| Live lint diagnostics | The same lint registry as `lucisv check`, delivered through push or modern pull diagnostics |
| Severity per rule | Every rule is `error`, `warning` or `style`, and the squiggle is painted red, yellow or blue to match |
| Per-rule toggles | One setting per rule and one per severity class, all under `lucisv.lint.*`; changing any of them re-checks every open file immediately |
@@ -307,6 +319,8 @@ Server-side templates add `if`, `if/else`, `else if`, `case`, `for`, `while`,
| `lucisv.references.fullLineView` | `true` | `Shift+Alt+F12` in a Verilog/SystemVerilog editor opens lucisv's full-line References view instead of VS Code's, whose previews start a few characters before the match. `false` gives the key back to the built-in command; the context-menu entry works either way, and `Shift+F12` peek is never changed |
| `lucisv.rainbowBeginEnd` | `true` | Color nested block pairs and unmatched keywords; updates immediately |
| `lucisv.inlineTemplates` | `true` | Show context-aware structural ghost text; requires `editor.inlineSuggest.enabled` |
| `lucisv.inlineKeywords` | `true` | Ghost the rest of a keyword while its first letters are typed; follows the popup's selected entry; requires `editor.inlineSuggest.enabled` |
| `lucisv.autoEnd` | `true` | Write the `end` when `Enter` is pressed after a `begin` that has none |
| `lucisv.inlineInstantiation` | `true` | Ghost the full instantiation (parameters and ports) once a module's name is typed exactly and followed by a space; requires `editor.inlineSuggest.enabled` |
| `lucisv.lineLength` | unset | Maximum formatter width, 40–400; built-in default is 100 |
| `lucisv.indent` | unset | Indent width, 1–8; falls back to the editor tab size, then 2 |
@@ -407,6 +421,22 @@ Every nesting color is a proper VS Code theme color:
}
```
## Release 0.65.0 highlights
Version 0.65.0 gives module instantiations distinct syntax colours across
themes: module names (`class`), instance names (`function`), port names
(`.port` / `.*`, `property`), and connected signals (`variable`) each stand
out, and parameter-list `#` signs share the `parameter` colour separately from
parentheses.
## Release 0.64.0 highlights
Version 0.64.0 makes typing quicker: `begin` + Enter writes the `end`,
`always_ff @(` expands with clock and reset, the suggestion list puts this
file's names first, keywords appear as grey ghost text, and port suggestions
list unconnected ports first and write `.name()` — while the errors on a
connection you are still typing wait until you pause.
## Release 0.63.1 highlights
Version 0.63.1 makes sticky scroll pin the first line of every block you are
+48 -1
View File
@@ -16,6 +16,7 @@ const { createRestarter } = require('./restart');
const { executeCommand } = require('./extract');
const { HierarchyView } = require('./hierarchyView');
const { ReferencesView } = require('./referencesView');
const typing = require('./typing');
const mcp = require('./mcp');
/** The single client, kept only so `deactivate` can stop it. */
@@ -200,6 +201,11 @@ function activate(context) {
// advertises, so a second registration of the same id would collide with
// it at activation.
middleware: {
// `selectedCompletionInfo` as LSP spells it — the keyword ghost follows
// the popup's selected entry, and the client would otherwise send VS
// Code's own Range shape (docs/features/completion-ux, `typing.js`).
provideInlineCompletionItems: (document, position, context, token, next) =>
next(document, position, typing.protocolInlineContext(context), token),
executeCommand: (command, args, next) =>
executeCommand(
{ showInputBox: (options) => vscode.window.showInputBox(options) },
@@ -267,7 +273,12 @@ function activate(context) {
// Typing moves every range after the cursor, so the answer is stale the
// moment it arrives; debounce rather than ask on every keystroke.
vscode.workspace.onDidChangeTextDocument((event) => {
if (isVerilog(event.document)) scheduleRepaint();
if (!isVerilog(event.document)) return;
scheduleRepaint();
// `begin` + Enter writes the `end` (docs/features/completion-ux). Next
// tick, so the language client's own listener has sent this change
// before the request about it goes out.
setTimeout(() => typing.handleChange(autoEndDeps, event), 0);
}),
vscode.workspace.onDidChangeConfiguration((event) => {
// A spawn argument can only change by spawning again, so this one
@@ -310,6 +321,42 @@ function deactivate() {
return restarter ? restarter.dispose() : undefined;
}
/**
* What `typing.handleChange` needs from VS Code and the client. The edits are
* applied with no undo stop before them, so they join the Enter's own undo
* step where VS Code allows it.
*/
const autoEndDeps = {
editorFor: (document) =>
vscode.window.visibleTextEditors.find((editor) => editor.document === document),
formatOnType: (document) =>
vscode.workspace.getConfiguration('editor', document).get('formatOnType') === true,
autoEnd: (document) => vscode.workspace.getConfiguration('lucisv', document).get('autoEnd') !== false,
request: (document, position, editor) =>
client.sendRequest('textDocument/onTypeFormatting', {
textDocument: { uri: document.uri.toString() },
position,
ch: '\n',
options: {
tabSize: Number(editor.options.tabSize) || 2,
insertSpaces: editor.options.insertSpaces !== false,
},
}),
apply: async (editor, edits) => {
const converted = await client.protocol2CodeConverter.asTextEdits(edits);
return editor.edit(
(builder) => {
for (const edit of converted || []) builder.replace(edit.range, edit.newText);
},
{ undoStopBefore: false, undoStopAfter: true },
);
},
placeCursor: (editor, line) => {
const end = editor.document.lineAt(line).range.end;
editor.selection = new vscode.Selection(end, end);
},
};
/** True for the documents this extension knows about. */
function isVerilog(document) {
return LANGUAGES.includes(document.languageId);
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "lucisv",
"version": "0.63.1",
"version": "0.65.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "lucisv",
"version": "0.63.1",
"version": "0.65.0",
"license": "MIT",
"dependencies": {
"vscode-languageclient": "9.0.1"
+117 -1
View File
@@ -2,7 +2,7 @@
"name": "lucisv",
"displayName": "lucisv — Verilog/SystemVerilog",
"description": "Fast Verilog/SystemVerilog formatting, linting, navigation, refactoring, semantic highlighting and RTL design intelligence.",
"version": "0.63.1",
"version": "0.65.0",
"publisher": "guoliangchen",
"author": "Guoliang Chen",
"license": "MIT",
@@ -193,15 +193,121 @@
"configurationDefaults": {
"[verilog]": {
"editor.defaultColorDecorators": "never",
"editor.semanticHighlighting.enabled": true,
"editor.stickyScroll.defaultModel": "foldingProviderModel",
"editor.stickyScroll.maxLineCount": 10
},
"[systemverilog]": {
"editor.defaultColorDecorators": "never",
"editor.semanticHighlighting.enabled": true,
"editor.stickyScroll.defaultModel": "foldingProviderModel",
"editor.stickyScroll.maxLineCount": 10
}
},
"semanticTokenScopes": [
{
"language": "verilog",
"scopes": {
"namespace": [
"entity.name.namespace",
"entity.name.type.namespace",
"entity.name.type"
],
"class": [
"entity.name.type.class",
"entity.name.type",
"support.class"
],
"type": [
"entity.name.type",
"support.type"
],
"enumMember": [
"variable.other.enummember",
"variable.other.constant",
"constant.other"
],
"parameter": [
"keyword.control",
"constant.language",
"variable.parameter"
],
"variable": [
"support.variable",
"entity.other.attribute-name",
"variable.other.readwrite"
],
"property": [
"entity.name.tag.css",
"entity.other.attribute-name",
"variable.other.property"
],
"function": [
"entity.name.function",
"support.function"
],
"macro": [
"entity.name.function.preprocessor",
"meta.preprocessor"
],
"decorator": [
"entity.name.function.decorator",
"meta.attribute"
]
}
},
{
"language": "systemverilog",
"scopes": {
"namespace": [
"entity.name.namespace",
"entity.name.type.namespace",
"entity.name.type"
],
"class": [
"entity.name.type.class",
"entity.name.type",
"support.class"
],
"type": [
"entity.name.type",
"support.type"
],
"enumMember": [
"variable.other.enummember",
"variable.other.constant",
"constant.other"
],
"parameter": [
"keyword.control",
"constant.language",
"variable.parameter"
],
"variable": [
"support.variable",
"entity.other.attribute-name",
"variable.other.readwrite"
],
"property": [
"entity.name.tag.css",
"entity.other.attribute-name",
"variable.other.property"
],
"function": [
"entity.name.function",
"support.function"
],
"macro": [
"entity.name.function.preprocessor",
"meta.preprocessor"
],
"decorator": [
"entity.name.function.decorator",
"meta.attribute"
]
}
}
],
"languages": [
{
"id": "verilog",
@@ -392,6 +498,16 @@
"default": true,
"markdownDescription": "Show grey ghost text that finishes a module instantiation once you have typed the module's whole name **followed by a space**, somewhere an instantiation may be written: every parameter override and every port connection, with a port that matches a signal already in scope connected for you. Tab accepts it as a snippet and steps through the values left to fill in. The space is what says the name is finished — `aes` alone offers nothing, because `aes_dft` may still be coming — and the name must match an indexed module exactly, capitals included; the completion popup is what helps you get there. A module two files declare expands from the copy nearest your own file. The accepted text is indented with the editor's own `editor.tabSize`/`editor.insertSpaces`, not with `#lucisv.indent#`. Requires `editor.inlineSuggest.enabled`."
},
"lucisv.inlineKeywords": {
"type": "boolean",
"default": true,
"markdownDescription": "Show the rest of a keyword as grey ghost text while you type its first letters: `alw` suggests `always_ff`, `endm` suggests `endmodule`; Tab accepts it. While the completion popup is open the ghost follows the popup's selected entry. A word that is already a keyword only grows across an underscore (`always` → `always_ff`), so `end` and `for` stay as typed. A `.v` file is only offered Verilog-2005 keywords. Independent of `#lucisv.inlineTemplates#`. Requires `editor.inlineSuggest.enabled`."
},
"lucisv.autoEnd": {
"type": "boolean",
"default": true,
"markdownDescription": "When you press Enter after a line ending in `begin` (or `begin : label`) and that block has no `end` yet, write the `end` on the line below, lined up with the statement the `begin` belongs to, and leave the cursor on the indented line in between. Works whether or not `#editor.formatOnType#` is on. A block that already has its `end` gets none."
},
"lucisv.formatOnSave": {
"type": "boolean",
"default": false,
+106
View File
@@ -0,0 +1,106 @@
// Checks for the VS Code semantic-highlighting manifest contract:
// `configurationDefaults` enables semantic highlighting for both language ids,
// `semanticTokenScopes` covers both language ids identically, every mapped key
// exists in `crates/lucisv_server/src/tokens.rs`'s legend, and the five module
// instantiation roles map to distinct primary TextMate scopes.
//
// node semanticTokens_test.js
//
// See docs/features/instantiation-highlighting/README.md.
const fs = require('fs');
const path = require('path');
let checks = 0;
function fail(what) {
console.error(`semanticTokens_test: FAIL — ${what}`);
process.exit(1);
}
function ok(condition, what) {
checks += 1;
if (!condition) fail(what);
}
const manifestPath = path.join(__dirname, 'package.json');
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
const vscodeignore = fs.readFileSync(path.join(__dirname, '.vscodeignore'), 'utf8');
const tokensRust = fs.readFileSync(
path.join(__dirname, '..', '..', 'crates', 'lucisv_server', 'src', 'tokens.rs'),
'utf8',
);
// 1. `.vscodeignore` keeps this test out of packaged `.vsix` archives.
ok(
vscodeignore.split(/\r?\n/).includes('semanticTokens_test.js'),
'semanticTokens_test.js is listed in .vscodeignore',
);
// 2. Both language ids turn semantic highlighting on by default so themes with
// `semanticHighlighting: false` or unset still render server tokens.
const defaults = manifest.contributes.configurationDefaults;
ok(defaults && typeof defaults === 'object', 'configurationDefaults exists');
for (const lang of ['[verilog]', '[systemverilog]']) {
ok(
defaults[lang] && defaults[lang]['editor.semanticHighlighting.enabled'] === true,
`${lang} sets editor.semanticHighlighting.enabled = true`,
);
}
// 3. Extract the advertised legend names from `tokens.rs::token_types()`.
const legendMap = {
NAMESPACE: 'namespace',
CLASS: 'class',
TYPE: 'type',
ENUM_MEMBER: 'enumMember',
PARAMETER: 'parameter',
VARIABLE: 'variable',
PROPERTY: 'property',
FUNCTION: 'function',
MACRO: 'macro',
KEYWORD: 'keyword',
COMMENT: 'comment',
STRING: 'string',
NUMBER: 'number',
DECORATOR: 'decorator',
};
const fnBody = tokensRust.split('pub fn token_types()')[1].split('}')[0];
const advertised = [...fnBody.matchAll(/SemanticTokenType::([A-Z_]+)/g)].map(([, id]) => {
ok(legendMap[id], `known SemanticTokenType::${id}`);
return legendMap[id];
});
ok(advertised.length === 14, `legend stays at 14 types, got ${advertised.length}`);
// 4. `semanticTokenScopes` is registered identically for `verilog` and `systemverilog`,
// and every key is in the server's advertised legend.
const entries = manifest.contributes.semanticTokenScopes;
ok(Array.isArray(entries) && entries.length === 2, 'two semanticTokenScopes entries');
ok(entries[0].language === 'verilog', 'first entry is verilog');
ok(entries[1].language === 'systemverilog', 'second entry is systemverilog');
ok(
JSON.stringify(entries[0].scopes) === JSON.stringify(entries[1].scopes),
'verilog and systemverilog share identical semanticTokenScopes',
);
const scopes = entries[0].scopes;
for (const [tokenType, chain] of Object.entries(scopes)) {
ok(advertised.includes(tokenType), `${tokenType} is in tokens::token_types()`);
ok(Array.isArray(chain) && chain.length > 0, `${tokenType} has a non-empty scope fallback chain`);
for (const scope of chain) {
ok(typeof scope === 'string' && scope.length > 0, `${tokenType} scope is non-empty string`);
}
}
// 5. All five module-instantiation roles map to pairwise-distinct primary scopes.
const instantiationRoles = ['class', 'parameter', 'function', 'property', 'variable'];
const primaryScopes = instantiationRoles.map((role) => {
ok(Array.isArray(scopes[role]) && scopes[role].length > 0, `${role} is mapped`);
return scopes[role][0];
});
ok(
new Set(primaryScopes).size === instantiationRoles.length,
`instantiation roles have distinct primary scopes: ${primaryScopes.join(', ')}`,
);
console.log(`semanticTokens_test: ${checks} checks passed`);
+141
View File
@@ -0,0 +1,141 @@
// Two things the extension does while the user types (TODO §68.1,
// docs/features/completion-ux):
//
// 1. **`begin` + Enter writes the `end`** even with `editor.formatOnType` off,
// which is VS Code's default. The server answers the ordinary
// `textDocument/onTypeFormatting` request for "\n" with the body line's
// indent and the `end` line; VS Code only sends that request itself when
// `editor.formatOnType` is on. So when it is off, this watches for the one
// change that matters — a single newline typed after a line ending in
// `begin` / `begin : label` — sends the request itself, and applies the
// answer only if it writes an `end` and the buffer has not moved on since.
// When `editor.formatOnType` is on, VS Code sends the request and this does
// nothing, so the request is never sent twice.
// 2. **The inline-completion context, made serializable.** The language
// client passes VS Code's `selectedCompletionInfo` through as it is, and a
// `vscode.Range` serializes as a two-element array — not the LSP `Range` the
// server decodes — and VS Code's trigger kinds are numbered from 0 where
// LSP's start at 1. `protocolInlineContext` re-spells both.
//
// Nothing here requires `vscode`: the decisions are pure functions and the
// flow takes its dependencies as an object, so `typing_test.js` drives all of
// it headlessly.
/** A line that ends in `begin` or `begin : label`, comments aside. */
const ENDS_IN_BEGIN = /(^|[^A-Za-z0-9_$`])begin(\s*:\s*[A-Za-z_][A-Za-z0-9_$]*)?$/;
/** The text a single Enter inserts: one newline and the indent after it. */
const NEWLINE_ONLY = /^\r?\n[ \t]*$/;
/**
* Whether one content change is a newline typed right after `begin`.
*
* `lineBefore` is the text of the line the newline was typed on, as it reads
* *after* the change — everything left of the insertion point, since Enter
* carries whatever followed the cursor down to the new line.
*/
function isBeginNewline(change, lineBefore) {
if (!change || change.rangeLength !== 0 || !NEWLINE_ONLY.test(change.text)) return false;
return ENDS_IN_BEGIN.test(withoutTrailingComments(lineBefore));
}
/**
* A line with its `//` comment and any trailing `/* … *\/` comments cut off,
* so `begin /* why *\/` counts as ending in `begin` here exactly as it does
* in the server, which reads tokens (the formatOnType-on path).
*/
function withoutTrailingComments(line) {
let code = String(line).replace(/\/\/.*$/, '').trimEnd();
while (code.endsWith('*/')) {
const open = code.lastIndexOf('/*');
if (open < 0) break;
code = code.slice(0, open).trimEnd();
}
return code;
}
/**
* The position the server is asked about: the new line, at the end of the
* indent the editor itself wrote there.
*/
function newLinePosition(change) {
const indent = change.text.slice(change.text.lastIndexOf('\n') + 1);
return { line: change.range.start.line + 1, character: indent.length };
}
/**
* Whether the server's answer writes an `end`. Without one it is only the new
* line's indentation — on-type formatting the user has not turned on, so it is
* not applied.
*/
function writesAnEnd(edits) {
return Array.isArray(edits) && edits.some((edit) => /(^|\s)end\r?\n?$/.test(edit.newText || ''));
}
/** An LSP range from anything with `start`/`end` positions. */
function plainRange(range) {
const position = (p) => ({ line: p.line, character: p.character });
return { start: position(range.start), end: position(range.end) };
}
/**
* The inline-completion context as LSP 3.18 spells it: trigger kinds 1/2
* rather than VS Code's 0/1, and the selected popup entry's range as a plain
* `Range` object.
*/
function protocolInlineContext(context) {
const out = { triggerKind: (context && context.triggerKind === 0) ? 1 : 2 };
const selected = context && context.selectedCompletionInfo;
if (selected && selected.range) {
out.selectedCompletionInfo = { range: plainRange(selected.range), text: String(selected.text) };
}
return out;
}
/**
* Handle one `onDidChangeTextDocument` event. Resolves to `true` when an `end`
* was written.
*
* `deps`:
* - `editorFor(document)` — the visible editor showing it, or `undefined`;
* - `formatOnType(document)` / `autoEnd(document)` — the two settings;
* - `request(document, position, editor)` — the on-type request, resolving to
* LSP `TextEdit[]` or `null`;
* - `apply(editor, edits)` — apply them as one edit, resolving to a boolean;
* - `placeCursor(editor, line)` — put the cursor at the end of that line.
*/
async function handleChange(deps, event) {
// An undo or a redo replays a newline the user already had answered.
if (event.reason !== undefined && event.reason !== null) return false;
const changes = event.contentChanges || [];
if (changes.length !== 1) return false;
const document = event.document;
const change = changes[0];
if (deps.formatOnType(document) || !deps.autoEnd(document)) return false;
const lineBefore = document.lineAt(change.range.start.line).text;
if (!isBeginNewline(change, lineBefore)) return false;
const editor = deps.editorFor(document);
if (!editor) return false;
const version = document.version;
const position = newLinePosition(change);
let edits;
try {
edits = await deps.request(document, position, editor);
} catch {
return false; // a server restarting or gone: Enter stays a plain Enter
}
// The answer is about the buffer as it was; one more keystroke and every
// offset in it may be wrong.
if (document.version !== version || !writesAnEnd(edits)) return false;
if (!(await deps.apply(editor, edits))) return false;
deps.placeCursor(editor, position.line);
return true;
}
module.exports = {
isBeginNewline,
newLinePosition,
writesAnEnd,
protocolInlineContext,
handleChange,
};
+204
View File
@@ -0,0 +1,204 @@
// Checks for `typing.js`: the begin-newline decision, the auto-`end` flow and
// the inline-completion context the server is sent.
//
// node typing_test.js
//
// Exits 0 on success, 1 on any failure. Plain node, no dependencies and no
// test runner — the same style as `restart_test.js` next to it. The fakes
// script only what `typing.js` depends on; nothing here re-implements VS Code.
// See docs/features/completion-ux/README.md.
const {
isBeginNewline,
newLinePosition,
writesAnEnd,
protocolInlineContext,
handleChange,
} = require('./typing');
let checks = 0;
function ok(condition, what) {
checks += 1;
if (!condition) fail(what);
}
function equal(got, want, what) {
checks += 1;
const a = JSON.stringify(got);
const b = JSON.stringify(want);
if (a !== b) fail(`${what}\n got: ${a}\n want: ${b}`);
}
function fail(what) {
console.error(`FAIL: ${what}`);
process.exit(1);
}
/** A newline typed at the end of line `line`, column `character`. */
function enter(line, character, text = '\n') {
return { range: { start: { line, character }, end: { line, character } }, rangeLength: 0, text };
}
// --- the decision ----------------------------------------------------------
ok(isBeginNewline(enter(1, 20), ' always_comb begin'), 'a bare begin');
ok(isBeginNewline(enter(1, 20, '\n '), ' if (x) begin'), 'auto-indent may ride along');
ok(isBeginNewline(enter(1, 20, '\r\n'), ' if (x) begin'), 'a CRLF newline');
ok(isBeginNewline(enter(1, 20), 'begin : blk'), 'a labelled begin');
ok(isBeginNewline(enter(1, 20), ' end else begin // why'), 'a comment after it');
ok(!isBeginNewline(enter(1, 20), ' x = 1;'), 'not after a statement');
ok(isBeginNewline(enter(1, 20), ' if (x) begin /* why */'), 'a block comment after it');
ok(isBeginNewline(enter(1, 20), ' begin /* a */ /* b */ '), 'two block comments after it');
ok(!isBeginNewline(enter(1, 20), ' begin /* a */ x /* b */'), 'code between the comments');
ok(!isBeginNewline(enter(1, 20), ' x = 1; /* begin */'), 'a begin inside the comment');
ok(!isBeginNewline(enter(1, 20), ' my_begin'), 'not a word ending in begin');
ok(!isBeginNewline(enter(1, 20), ' `begin'), 'not a macro');
ok(!isBeginNewline(enter(1, 20, 'x'), ' begin'), 'not a letter');
ok(!isBeginNewline(enter(1, 20, '\n\n'), ' begin'), 'not two newlines (a paste)');
ok(!isBeginNewline({ ...enter(1, 20), rangeLength: 3 }, ' begin'), 'not a replacement');
equal(newLinePosition(enter(4, 13, '\n ')), { line: 5, character: 4 }, 'the new line, past its indent');
equal(newLinePosition(enter(4, 13)), { line: 5, character: 0 }, 'an unindented new line');
ok(writesAnEnd([{ newText: ' ' }, { newText: ' end\n' }]), 'the two-edit answer');
ok(writesAnEnd([{ newText: ' \n end' }]), 'the last-line answer');
ok(!writesAnEnd([{ newText: ' ' }]), 'the indent alone is not applied');
ok(!writesAnEnd(null), 'no answer');
// --- the inline context ----------------------------------------------------
equal(protocolInlineContext({ triggerKind: 1 }), { triggerKind: 2 }, 'automatic is 2 on the wire');
equal(protocolInlineContext({ triggerKind: 0 }), { triggerKind: 1 }, 'invoked is 1 on the wire');
// A `vscode.Range`-alike whose JSON form is an array, as the real one's is.
const vsRange = {
start: { line: 3, character: 2, extra: true },
end: { line: 3, character: 5 },
toJSON() {
return [this.start, this.end];
},
};
equal(
protocolInlineContext({ triggerKind: 1, selectedCompletionInfo: { range: vsRange, text: 'always_ff' } }),
{
triggerKind: 2,
selectedCompletionInfo: {
range: { start: { line: 3, character: 2 }, end: { line: 3, character: 5 } },
text: 'always_ff',
},
},
'the selected entry as a plain LSP range',
);
// --- the flow --------------------------------------------------------------
function documentWith(lines, version = 7) {
return { version, lineAt: (line) => ({ text: lines[line] }) };
}
function deps(overrides = {}) {
const log = [];
const base = {
editorFor: () => ({ id: 'editor' }),
formatOnType: () => false,
autoEnd: () => true,
request: async (_document, position) => {
log.push(['request', position]);
return [{ newText: ' ' }, { newText: ' end\n' }];
},
apply: async (_editor, edits) => {
log.push(['apply', edits.length]);
return true;
},
placeCursor: (_editor, line) => log.push(['cursor', line]),
};
return { deps: { ...base, ...overrides }, log };
}
async function flow() {
const document = documentWith(['module m;', ' always_comb begin', '']);
const event = { document, contentChanges: [enter(1, 19)] };
let { deps: d, log } = deps();
equal(await handleChange(d, event), true, 'the end is written');
equal(
log,
[['request', { line: 2, character: 0 }], ['apply', 2], ['cursor', 2]],
'asked about the new line, applied, cursor put back on it',
);
({ deps: d, log } = deps({ formatOnType: () => true }));
equal(await handleChange(d, event), false, 'formatOnType on: VS Code asks, not us');
equal(log, [], 'and nothing is sent twice');
({ deps: d, log } = deps({ autoEnd: () => false }));
equal(await handleChange(d, event), false, 'lucisv.autoEnd off');
equal(log, [], 'nothing sent');
({ deps: d, log } = deps());
equal(await handleChange(d, { ...event, reason: 1 }), false, 'an undo is not typing');
equal(log, [], 'nothing sent on undo');
({ deps: d, log } = deps({ request: async () => [{ newText: ' ' }] }));
equal(await handleChange(d, event), false, 'an indent-only answer');
equal(log, [], 'is not applied');
// The user typed again while the request was in flight.
const moving = documentWith(['module m;', ' always_comb begin', '']);
({ deps: d, log } = deps({
request: async () => {
moving.version += 1;
return [{ newText: ' end\n' }];
},
}));
equal(await handleChange(d, { document: moving, contentChanges: [enter(1, 19)] }), false, 'stale');
equal(log, [], 'a stale answer is dropped');
({ deps: d, log } = deps({
request: async () => {
throw new Error('server gone');
},
}));
equal(await handleChange(d, event), false, 'a failed request is a plain Enter');
const plain = { document: documentWith(['module m;', ' x = 1;', '']), contentChanges: [enter(1, 8)] };
({ deps: d, log } = deps());
equal(await handleChange(d, plain), false, 'not after begin');
equal(log, [], 'nothing sent for an ordinary Enter');
}
// QA (completion-ux, 2026-11-17): the edges the dev's checks left open.
async function qaEdges() {
const document = documentWith(['module m;', ' always_comb begin', '', '']);
let { deps: d, log } = deps();
const two = { document, contentChanges: [enter(1, 19), enter(2, 0)] };
equal(await handleChange(d, two), false, 'QA: multi-cursor Enter is left alone');
equal(log, [], 'QA: nothing sent for several changes');
({ deps: d, log } = deps());
equal(await handleChange(d, { document, contentChanges: [enter(1, 19)], reason: 2 }), false, 'QA: a redo');
equal(log, [], 'QA: nothing sent on redo');
({ deps: d, log } = deps({ editorFor: () => undefined }));
equal(await handleChange(d, { document, contentChanges: [enter(1, 19)] }), false, 'QA: no visible editor');
equal(log, [], 'QA: nothing sent without an editor');
({ deps: d, log } = deps({ apply: async () => false }));
equal(await handleChange(d, { document, contentChanges: [enter(1, 19)] }), false, 'QA: a refused edit');
ok(!log.some((entry) => entry[0] === 'cursor'), 'QA: the cursor is not moved after a refused edit');
equal(newLinePosition(enter(4, 13, '\r\n ')), { line: 5, character: 2 }, 'QA: CRLF newline position');
ok(!isBeginNewline(enter(1, 20, '\nfoo;'), ' begin'), 'QA: a pasted line is not Enter');
ok(!isBeginNewline(enter(1, 20, '\n \n'), ' begin'), 'QA: a pasted blank pair is not Enter');
equal(protocolInlineContext(undefined), { triggerKind: 2 }, 'QA: no context at all');
equal(
protocolInlineContext({ triggerKind: 0, selectedCompletionInfo: { text: 'x' } }),
{ triggerKind: 1 },
'QA: a selection without a range is dropped, not sent malformed',
);
}
flow()
.then(qaEdges)
.then(() => console.log(`typing_test: ${checks} checks passed`))
.catch((error) => fail(error && error.stack));