diff --git a/TODO.md b/TODO.md index 0abdf57..22f6620 100644 --- a/TODO.md +++ b/TODO.md @@ -7240,10 +7240,10 @@ 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/*}`. -- [ ] Parser recovery keeps an unfinished connection (`.`, `.name(` open to +- [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. -- [ ] The server withholds the diagnostics that fall inside the entry the +- [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. diff --git a/crates/lucisv_server/src/main.rs b/crates/lucisv_server/src/main.rs index 7fea135..09813b5 100644 --- a/crates/lucisv_server/src/main.rs +++ b/crates/lucisv_server/src/main.rs @@ -117,6 +117,7 @@ fn main() -> Result<(), Box> { // capabilities have no field for it and drop it on the floor — see // `ranges_formatting_support`. let ranges_formatting = ranges_formatting_support(¶ms); + let diagnostic_refresh = diagnostic_refresh_support(¶ms); // 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> { pull_diagnostics: pull_diagnostics_support(¶ms), work_done_progress: work_done_progress_support(¶ms), code_lens_refresh: code_lens_refresh_support(¶ms), + diagnostic_refresh, show_document: show_document_support(¶ms), configuration: configuration_support(¶ms), token_server_cancel: token_server_cancel_support(¶ms), @@ -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::{ diff --git a/crates/lucisv_server/src/server/diagnostics.rs b/crates/lucisv_server/src/server/diagnostics.rs index 5ec6209..6a63c1b 100644 --- a/crates/lucisv_server/src/server/diagnostics.rs +++ b/crates/lucisv_server/src/server/diagnostics.rs @@ -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 { + 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. diff --git a/crates/lucisv_server/src/server/mod.rs b/crates/lucisv_server/src/server/mod.rs index 85bef8e..9ab645b 100644 --- a/crates/lucisv_server/src/server/mod.rs +++ b/crates/lucisv_server/src/server/mod.rs @@ -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> { 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)? { diff --git a/crates/lucisv_server/src/server/notification.rs b/crates/lucisv_server/src/server/notification.rs index 1af9c5d..7d1aa00 100644 --- a/crates/lucisv_server/src/server/notification.rs +++ b/crates/lucisv_server/src/server/notification.rs @@ -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, ¬ification); // 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::(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 { + 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 { .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 { + 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 diff --git a/crates/lucisv_server/src/state/mod.rs b/crates/lucisv_server/src/state/mod.rs index 1495148..80fc646 100644 --- a/crates/lucisv_server/src/state/mod.rs +++ b/crates/lucisv_server/src/state/mod.rs @@ -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)] diff --git a/crates/lucisv_server/src/state/port_grace.rs b/crates/lucisv_server/src/state/port_grace.rs new file mode 100644 index 0000000..6e40142 --- /dev/null +++ b/crates/lucisv_server/src/state/port_grace.rs @@ -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, +} + +/// 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, 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, + ) -> Vec { + 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 { + 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 { + 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 { + let due: Vec = 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 { + 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 { + 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; diff --git a/crates/lucisv_server/src/state/port_grace/tests.rs b/crates/lucisv_server/src/state/port_grace/tests.rs new file mode 100644 index 0000000..01392b1 --- /dev/null +++ b/crates/lucisv_server/src/state/port_grace/tests.rs @@ -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 { + 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"); + } +} diff --git a/crates/lucisv_server/src/sync.rs b/crates/lucisv_server/src/sync.rs index 7113445..ec9fa82 100644 --- a/crates/lucisv_server/src/sync.rs +++ b/crates/lucisv_server/src/sync.rs @@ -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) { 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"; diff --git a/crates/lucisv_server/tests/e2e.rs b/crates/lucisv_server/tests/e2e.rs index 1eb51af..1d538f1 100644 --- a/crates/lucisv_server/tests/e2e.rs +++ b/crates/lucisv_server/tests/e2e.rs @@ -8956,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 { + 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); +} diff --git a/crates/vlog_formatter/tests/port_entry_refusal.rs b/crates/vlog_formatter/tests/port_entry_refusal.rs new file mode 100644 index 0000000..16476f1 --- /dev/null +++ b/crates/vlog_formatter/tests/port_entry_refusal.rs @@ -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()); +} diff --git a/crates/vlog_parser/src/parser/instance.rs b/crates/vlog_parser/src/parser/instance.rs index fceb5d4..4a8a2b3 100644 --- a/crates/vlog_parser/src/parser/instance.rs +++ b/crates/vlog_parser/src/parser/instance.rs @@ -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(); diff --git a/crates/vlog_parser/src/parser/recover_list.rs b/crates/vlog_parser/src/parser/recover_list.rs index 47de9e9..48eecd0 100644 --- a/crates/vlog_parser/src/parser/recover_list.rs +++ b/crates/vlog_parser/src/parser/recover_list.rs @@ -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> { + 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()) +} diff --git a/crates/vlog_parser/tests/port_entry_recovery.rs b/crates/vlog_parser/tests/port_entry_recovery.rs new file mode 100644 index 0000000..b571209 --- /dev/null +++ b/crates/vlog_parser/tests/port_entry_recovery.rs @@ -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]) -> Vec> { + 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> { + 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); + } +} diff --git a/crates/vlog_parser/tests/qa_port_entry_grace.rs b/crates/vlog_parser/tests/qa_port_entry_grace.rs new file mode 100644 index 0000000..9e8c9d1 --- /dev/null +++ b/crates/vlog_parser/tests/qa_port_entry_grace.rs @@ -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}"); + } + } +} diff --git a/docs/features/error-recovery/README.md b/docs/features/error-recovery/README.md index aa019b4..0de10ca 100644 --- a/docs/features/error-recovery/README.md +++ b/docs/features/error-recovery/README.md @@ -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 diff --git a/docs/features/port-entry-grace/README.md b/docs/features/port-entry-grace/README.md new file mode 100644 index 0000000..c1d07cc --- /dev/null +++ b/docs/features/port-entry-grace/README.md @@ -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. diff --git a/docs/topo.md b/docs/topo.md index f3ec28d..1f84e2f 100644 --- a/docs/topo.md +++ b/docs/topo.md @@ -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. | diff --git a/editors/vscode/README.md b/editors/vscode/README.md index 0d90688..2e66a45 100644 --- a/editors/vscode/README.md +++ b/editors/vscode/README.md @@ -132,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 |