diff --git a/TODO.md b/TODO.md index b24aaef..ef403dc 100644 --- a/TODO.md +++ b/TODO.md @@ -834,9 +834,36 @@ and are not gaps. `workspace.codeLens.refreshSupport`. One request recorded there: an instantiation-edge table in `WorkspaceIndex` would make both this and `callHierarchy/incomingCalls` a lookup instead of a workspace walk. -- [ ] **On-type formatting** — conspicuous absence for a +- [x] **On-type formatting** — conspicuous absence for a formatter-first server; candidate trigger: newline (indent the new line per block nesting), `;` (reformat the finished statement). + → delivered 2026-08-26 by `docs/features/on-type-formatting/README.md`: + `documentOnTypeFormattingProvider` (`"\n"` + `[";"]`) + + `crates/lucisv_server/src/on_type.rs`. Both candidate triggers, and + only those two — not `}`, since SV closes its blocks with the word + `end`. `;` goes through `format::range_formatting` unchanged, over + the `;`'s own line, so that half is `textDocument/rangeFormatting` + with a different trigger and no new formatting logic at all. `\n` is + new logic outside the verified engine, so it is fenced two ways: the + edit it builds can structurally only replace one line's leading + whitespace with spaces (a wrong answer is a wrong indent, never a + moved byte), and a corpus-wide agreement test formats every checked-in + file with the real engine and forbids the model from disagreeing with + the printer on any line of the output — 77 528 answered, 36 647 + declined, 0 disagreements, with a coverage floor so it cannot pass + vacuously. Nine of the ten rules the model needed were found by that + test rather than predicted, including that `vlog_formatter` cuddles a + `begin` onto its header but not a `fork`. **The path never speaks**: a + refusal is `[]` with no popup, and — a correction to the design — a + broken `lucisv.toml` is not reported here either, because + `warn_about_config`'s dedup is re-armed by the `didChange` every + keystroke produces and would give one popup per character. One + deviation recorded there: the `;` range is the `;`'s own line rather + than its enclosing AST node's span, which is the same answer wherever + both are defined and avoids asking for a whole-module reformat when + the `;` is the one closing a module header. `pairs.rs` gained three + `pub(crate)` accessors so the matcher and the indent model read one + keyword table. - [ ] **Type hierarchy (3.17)** — arguably the semantically correct home for the module hierarchy (and later interface/class extends chains); keep callHierarchy as the compatibility surface. diff --git a/crates/lucisv_server/src/main.rs b/crates/lucisv_server/src/main.rs index dd40e47..6d9e9b6 100644 --- a/crates/lucisv_server/src/main.rs +++ b/crates/lucisv_server/src/main.rs @@ -25,6 +25,7 @@ mod linked; mod lint; mod locate; mod nav; +mod on_type; mod pairs; mod ports; mod rename; @@ -48,13 +49,14 @@ use lsp_server::Connection; use lsp_types::{ CallHierarchyServerCapability, CodeActionKind, CodeActionOptions, CodeActionProviderCapability, CodeLensOptions, CompletionOptions, DiagnosticOptions, DiagnosticServerCapabilities, - DocumentLinkOptions, ExecuteCommandOptions, FoldingRangeProviderCapability, InitializeParams, - InlayHintOptions, InlayHintServerCapabilities, LinkedEditingRangeServerCapabilities, OneOf, - PositionEncodingKind, RenameOptions, SaveOptions, SelectionRangeProviderCapability, - SemanticTokensFullOptions, SemanticTokensLegend, SemanticTokensOptions, - SemanticTokensServerCapabilities, ServerCapabilities, SignatureHelpOptions, - TextDocumentSyncCapability, TextDocumentSyncKind, TextDocumentSyncOptions, - TextDocumentSyncSaveOptions, TypeDefinitionProviderCapability, WorkDoneProgressOptions, + DocumentLinkOptions, DocumentOnTypeFormattingOptions, ExecuteCommandOptions, + FoldingRangeProviderCapability, InitializeParams, InlayHintOptions, + InlayHintServerCapabilities, LinkedEditingRangeServerCapabilities, OneOf, PositionEncodingKind, + RenameOptions, SaveOptions, SelectionRangeProviderCapability, SemanticTokensFullOptions, + SemanticTokensLegend, SemanticTokensOptions, SemanticTokensServerCapabilities, + ServerCapabilities, SignatureHelpOptions, TextDocumentSyncCapability, TextDocumentSyncKind, + TextDocumentSyncOptions, TextDocumentSyncSaveOptions, TypeDefinitionProviderCapability, + WorkDoneProgressOptions, }; use crate::server::{ClientAbilities, Server}; @@ -116,6 +118,18 @@ fn capabilities() -> ServerCapabilities { })), document_formatting_provider: Some(OneOf::Left(true)), document_range_formatting_provider: Some(OneOf::Left(true)), + // Two trigger characters, and only two. A newline re-indents the line + // it opened; a `;` lays out the statement it ended, through the range + // engine. Not `}` — SV closes its blocks with the *word* `end`, and + // re-triggering on letters would run this on half of every identifier. + // Advertised unconditionally: on-type formatting only fires where the + // client's own `editor.formatOnType` is on, which is off by default, + // so the user has already opted in by the time a request arrives. See + // `docs/features/on-type-formatting/README.md`. + document_on_type_formatting_provider: Some(DocumentOnTypeFormattingOptions { + first_trigger_character: on_type::NEWLINE.to_string(), + more_trigger_character: Some(vec![on_type::SEMICOLON.to_string()]), + }), definition_provider: Some(OneOf::Left(true)), // The same jump one token to the left: from a name to where its type // is declared. `Simple(true)` rather than a registration — there is @@ -417,6 +431,18 @@ mod tests { assert!(caps.selection_range_provider.is_some()); assert!(caps.diagnostic_provider.is_some()); assert!(caps.code_lens_provider.is_some()); + assert!(caps.document_on_type_formatting_provider.is_some()); + } + + #[test] + fn on_type_formatting_asks_for_the_newline_and_the_semicolon_and_nothing_else() { + // The trigger set is the feature: a client sends this request on every + // one of these characters and on no other, so what is listed here is + // exactly what `on_type::on_type_formatting` knows how to answer. `}` + // is deliberately absent — SV closes its blocks with the word `end`. + let options = capabilities().document_on_type_formatting_provider.expect("advertised"); + assert_eq!(options.first_trigger_character, "\n"); + assert_eq!(options.more_trigger_character, Some(vec![";".to_string()])); } #[test] diff --git a/crates/lucisv_server/src/on_type.rs b/crates/lucisv_server/src/on_type.rs new file mode 100644 index 0000000..1aeee92 --- /dev/null +++ b/crates/lucisv_server/src/on_type.rs @@ -0,0 +1,1207 @@ +//! `textDocument/onTypeFormatting` — the two keystrokes worth answering. +//! +//! On-type formatting runs on a keystroke, over code that is by definition +//! half-written. Both facts narrow it hard, and the two trigger characters are +//! narrow in different ways: +//! +//! * **`;`** — a statement just ended, so the buffer is very often whole +//! again. That one goes through [`format::range_formatting`], the same +//! verified, all-or-nothing engine `textDocument/rangeFormatting` runs, over +//! the `;`'s own line. No new formatting logic exists on this path at all. +//! * **`\n`** — nothing ended, so nothing is formatted. All this answers is +//! the new line's *indentation*, read off the block nesting in the token +//! stream, and the edit it returns can by construction touch nothing but the +//! whitespace at the head of that one line. +//! +//! A keystroke this file cannot answer confidently answers **nothing** — no +//! edit, and no message. That is the deliberate opposite of what +//! `textDocument/formatting` does with a refusal, and the reason is the +//! trigger: an error popup the user cannot type past is not a diagnostic when +//! it arrives on every semicolon. See +//! `docs/features/on-type-formatting/README.md`. + +use lsp_types::{Position, Range, TextEdit}; +use vlog_formatter::Config; +use vlog_parser::token::{Token, TokenKind}; + +use crate::format; +use crate::pairs; +use crate::state::Document; + +/// The character the client is told to trigger on. A newline is the one +/// keystroke that opens a line whose indentation nobody has chosen yet. +pub const NEWLINE: &str = "\n"; + +/// The other one: a finished statement, and the only place a keystroke can ask +/// the real formatter for anything. +pub const SEMICOLON: &str = ";"; + +/// The edits for one typed character, or none. +/// +/// Never an `Err`: every refusal on this path — an unknown trigger, a client +/// out of step, a buffer the formatter will not touch — is the empty answer. +pub fn on_type_formatting( + doc: &Document, + position: Position, + typed: &str, + config: &Config, +) -> Vec { + let edit = match typed { + NEWLINE => indent_edit(doc, position, config.indent_width), + SEMICOLON => statement_edit(doc, position, config), + _ => None, + }; + edit.into_iter().collect() +} + +// ---------------------------------------------------------------------- +// `;` — the finished statement +// ---------------------------------------------------------------------- + +/// Lay out the statement the `;` just ended, through the range engine. +/// +/// The range asked for is the `;`'s **own line** and nothing else. That is not +/// a narrower request than "the statement's lines": `format_range` selects by +/// *unit*, so any line of a statement selects the whole statement (see +/// `docs/features/range-formatting/README.md`). It is, however, a much safer +/// one — the `;` closing `module m (\n input a\n);` ends no statement at all, +/// and naming its enclosing node's lines there would ask for the whole module +/// back on a keystroke. +fn statement_edit(doc: &Document, position: Position, config: &Config) -> Option { + let offset = doc.positions().offset(position); + // The character the client named has to actually be there, and it has to + // be a `;` the lexer sees: one inside a string or a comment ends no + // statement, and re-laying-out its line would be a guess. + let typed = doc.tokens.iter().find(|token| token.span.end == offset)?; + if !typed.is_sym(SEMICOLON) { + return None; + } + let line = doc.line_index.line_col(typed.span.start).0.checked_sub(1)?; + let at = Position { line, character: 0 }; + // A refusal is the empty answer, not a message: the engine is strict, and + // half-typed code two lines away is reason enough for it to decline. + format::range_formatting(doc, config, Range { start: at, end: at }).ok().flatten() +} + +// ---------------------------------------------------------------------- +// `\n` — the new line's indentation +// ---------------------------------------------------------------------- + +/// Re-indent the line the cursor landed on, and nothing else. +/// +/// **The structural guarantee**: the returned edit's range runs from column +/// zero of that one line to its first non-whitespace character, and its text is +/// spaces. No other byte of the buffer is nameable from here, so no widening of +/// the nesting model below can ever make this path move code. `None` means +/// either "already right" or "no opinion", which the caller cannot tell apart +/// and does not need to. +fn indent_edit(doc: &Document, position: Position, indent_width: usize) -> Option { + let line = doc.line_index.line_range(position.line.checked_add(1)?)?; + // A new line is one a `\n` opened. This is the trigger-character check the + // `;` path makes by finding the token: a client naming a position that no + // newline precedes is out of step with the buffer we hold. + if line.start == 0 || doc.text.as_bytes().get(line.start as usize - 1) != Some(&b'\n') { + return None; + } + let text = doc.text.get(line.start as usize..line.end as usize)?; + let width = text.len() - text.trim_start_matches([' ', '\t']).len(); + let content = line.start + width as u32; + // ...and the cursor has to be inside that leading whitespace, which is + // where every editor leaves it after a newline. + if doc.positions().offset(position) > content { + return None; + } + + let want = " ".repeat(level_at(doc, content)? * indent_width); + if text.get(..width)? == want { + return None; + } + let start = Position { line: position.line, character: 0 }; + let range = Range { start, end: doc.positions().position(content) }; + Some(TextEdit { range, new_text: want }) +} + +// ---------------------------------------------------------------------- +// the nesting model +// ---------------------------------------------------------------------- + +/// The scopes whose bodies the formatter keeps byte-for-byte +/// (`ItemKind::Verbatim`). Inside one there is no right indent to compute: +/// whatever the user wrote is what a whole-file run emits, so this model has no +/// opinion there. `constraint c { ... }` needs no entry — its body is behind a +/// brace, and any open bracket already silences this. +const OPAQUE: &[&str] = &["covergroup", "property", "sequence"]; + +/// Keywords whose statement body follows them directly, after an optional +/// `@(...)` event control or `#delay`. +const BODY_KEYWORDS: &[&str] = + &["always", "always_ff", "always_comb", "always_latch", "initial", "final", "forever"]; + +/// Keywords whose body follows a parenthesised header. `wait`, `assert` and +/// `do` are deliberately absent: they spell headers that are not always headers +/// (`wait fork;`, `do begin ... end while (c);`), and the model would rather +/// say nothing than model them halfway. +const HEADERS: &[&str] = &["if", "while", "for", "foreach", "repeat"]; + +/// The `case` family: a header *and* a scope, so its `(...)` opens no body of +/// its own — the items live in the scope the keyword already opened. +const CASE_HEADERS: &[&str] = &["case", "casex", "casez", "randcase"]; + +/// Keywords that start an assertion statement, which the formatter emits +/// byte-for-byte (`ItemKind::Verbatim`, `docs/features/assertions/README.md`). +/// +/// It cannot be an [`OPAQUE`] scope because it closes with no keyword: an +/// immediate assertion is `assert (c) pass; else fail;`, where the `else` and +/// its `begin`…`end` run past the `;` that would otherwise end it. So this is a +/// span the scan is silent over rather than a level on the stack — see +/// [`Scan::poison`]. +const ASSERTIONS: &[&str] = &["assert", "assume", "cover", "restrict", "expect"]; + +/// One level of the indent ladder. +enum Frame { + /// A scope a keyword opened, closed by one of these keywords. + Block { + closers: &'static [&'static str], + /// Whether the formatter emits this scope's body verbatim. + opaque: bool, + /// Whether this is a `case` scope, whose items each carry their own + /// statement one level further in. + case: bool, + /// Whether this block was written as an `else` branch's body — the + /// same question [`Frame::Hanging::from_else`] answers, carried across + /// the `begin` that replaced the hanging. + from_else: bool, + }, + /// The one-statement body of a header that wrote no `begin` — the level + /// `if (c)` on its own line puts its statement at. Popped by the `;` that + /// ends that statement, or by the `end` of the block that turned out to be + /// it. + Hanging { + /// Whether this body is an `else` branch, which is what says an + /// if/else chain *ended* here rather than continuing. SV's dangling + /// `else` binds to the innermost `if` that has not got one yet, so an + /// `else` written after a branch that was already an `else` belongs to + /// something further out, and the level it closes has to come off. + from_else: bool, + }, +} + +/// Where a scan stands between two tokens. +#[derive(Clone, Copy, PartialEq, Eq)] +enum At { + /// A new item or statement may begin here — the level is the stack depth. + Boundary, + /// Just past an opener or closer keyword, where a `: label` may follow. + /// Answerable: `begin` ends a line as readily as `begin : name` does. + Labelled, + /// Just past ` :`, waiting for the label itself. + Label, + /// Just past a control keyword, waiting for its `(`. `case` is the + /// variant whose scope is already on the stack. + Header { case: bool }, + /// Inside that header's parentheses. + InHeader { case: bool, depth: u32 }, + /// A statement body starts at the next token, with an `@(...)` or a + /// `#delay` still allowed in between. Its `Hanging` is already on the + /// stack, so the level is answerable. + Timing, + /// Just past that `@` or `#`, before its operand. + Control, + /// Inside the operand's parentheses. + InControl { depth: u32 }, + /// The middle of something this model does not follow: an expression, a + /// port list, a wrapped assignment. Never answered. + Unknown, +} + +/// The indent level for the line whose first non-whitespace byte is at +/// `content`, or `None` when the model has no opinion there. +/// +/// Every `None` is a place where answering would mean guessing: a buffer that +/// does not lex, a position inside a token, an open bracket, a construct the +/// formatter emits verbatim, or simply the middle of an expression — where what +/// the formatter writes depends on a width computation this does not do. +fn level_at(doc: &Document, content: u32) -> Option { + if doc.tokens.is_empty() && !doc.text.trim().is_empty() { + return None; // the lexer gave up on this buffer + } + let mut scan = Scan::new(); + for (i, token) in doc.tokens.iter().enumerate() { + // The interior of a block comment is the formatter's business and not + // this model's: it re-indents a comment as a whole, by its opening + // column, so a continuation line's own indent means nothing here. + // Checked before the breaks below, because the comment that covers the + // line is attached to the token *after* it. + if inside_a_comment(token, content) { + return None; + } + if token.kind == TokenKind::Eof || token.span.start >= content { + break; + } + if token.span.end > content { + // The line opens inside a token: a `` `define `` continued with a + // backslash, or a string carried across the break. + return None; + } + scan.step(&doc.tokens, i); + } + scan.level(first_on_line(doc, content)) +} + +/// Whether `at` falls strictly inside one of the comments this token carries. +/// Strictly: a line that *starts* a comment is a line the formatter indents +/// like the item the comment belongs to, and this model answers for it. +fn inside_a_comment(token: &Token, at: u32) -> bool { + token + .leading + .iter() + .chain(token.trailing.iter()) + .any(|comment| comment.span.start < at && at < comment.span.end) +} + +/// The first token starting at or after `content` on that same line, which is +/// what tells a line that begins with `end` to sit at its `begin`'s level. A +/// line the user has just opened has none. +fn first_on_line(doc: &Document, content: u32) -> Option<&Token> { + let line = doc.line_index.line_col(content).0; + doc.tokens + .iter() + .find(|token| token.kind != TokenKind::Eof && token.span.start >= content) + .filter(|token| doc.line_index.line_col(token.span.start).0 == line) +} + +/// The running state of one scan over the token stream. +struct Scan { + stack: Vec, + at: At, + /// Raised by `extern`/`import`/`typedef` and friends, dropped at the next + /// `;`: everything between the two opens nothing. `pairs::analyze` carries + /// the same flag for the same reason. + prototype: bool, + /// Balanced brackets outside a header this model follows. Any depth at all + /// means a continuation line, whose indent the printer decides by width. + brackets: u32, + /// The stack depth an [`ASSERTIONS`] keyword was seen at, while its + /// statement is still running. Nothing inside is answered: the formatter + /// writes the whole construct back as the user typed it. + poison: Option, +} + +impl Scan { + fn new() -> Scan { + Scan { stack: Vec::new(), at: At::Boundary, prototype: false, brackets: 0, poison: None } + } + + /// The level this scan's end position sits at, given the first token + /// written on that line. + fn level(&self, first: Option<&Token>) -> Option { + if self.brackets > 0 { + return None; + } + if self.stack.iter().any(|frame| matches!(frame, Frame::Block { opaque: true, .. })) { + return None; + } + if self.poison.is_some() { + return None; + } + // A line that opens with punctuation continues the line above it — + // `module top\n import p::*;\n#(` is a header the parser reads as one + // item and the printer lays out at column zero. Every statement that + // legitimately starts with a symbol (`#5 x = 1;`, `->e;`) is rare + // enough that saying nothing is the better trade. + if first.is_some_and(|token| token.kind == TokenKind::Symbol) { + return None; + } + match self.at { + At::Boundary | At::Labelled => Some(self.dedented(first)), + // A body is expected here, so its `Hanging` is already counted — + // but not if the line already holds the `begin` that *is* that + // body. The formatter always joins those two, so a file where they + // are apart is not one this model can reason about. + At::Timing => match first { + Some(token) if is_begin(token) => None, + _ => Some(self.dedented(first)), + }, + _ => None, + } + } + + /// The stack depth, less the levels a line starting with a closing keyword + /// steps back out of — `end` sits at its `begin`'s level, not its body's. + fn dedented(&self, first: Option<&Token>) -> usize { + let Some(token) = first else { return self.stack.len() }; + if token.kind != TokenKind::Keyword { + return self.stack.len(); + } + let Some(closer) = pairs::closer_keyword(token.text.as_str()) else { + return self.stack.len(); + }; + // The innermost frame this keyword closes, picked exactly as + // `pairs::close` picks it: a closer matching something further down + // closes that, and everything above it was never closed at all. + self.closes(closer).unwrap_or(self.stack.len()) + } + + /// The index of the innermost `Block` frame `closer` can close. + fn closes(&self, closer: &str) -> Option { + self.stack.iter().rposition( + |frame| matches!(frame, Frame::Block { closers, .. } if closers.contains(&closer)), + ) + } + + /// Fold one token into the scan. + fn step(&mut self, tokens: &[Token], i: usize) { + let token = &tokens[i]; + // Inside brackets nothing but the nesting is followed: a wrapped port + // list or expression is the printer's business, not this model's. + if self.brackets > 0 { + self.brackets = bracket_depth(token, self.brackets); + if self.brackets == 0 { + self.at = At::Unknown; + } + return; + } + // A header's own parentheses *are* followed, because what comes after + // them is a body whose level this model does claim to know. + match self.at { + At::InHeader { case, depth } => return self.in_header(token, case, depth), + At::InControl { depth } => return self.in_control(token, depth), + At::Control => { + self.at = if is_open(token) { At::InControl { depth: 1 } } else { At::Timing }; + return; + } + _ => {} + } + self.at = match token.kind { + // A directive is a line of its own that opens nothing and indents + // nothing; the item after it sits where it would have sat anyway. + // A `` `ifdef `` standing where a statement body belongs is a + // shape the formatter's directive splitting decides, not this + // model — `if (c) `ifdef X` really does put the line under it back + // at the block's own level (corpus `picorv32/picorv32.v:1604`). + TokenKind::Directive if self.at == At::Timing => At::Unknown, + TokenKind::Directive => At::Boundary, + // `(* keep *)` rides along with the item it decorates. + TokenKind::Attribute => self.at, + // A macro invocation standing where an item or a statement + // belongs. The lexer swallows its whole argument list into this + // one token, so nothing is left half-open behind it — and it needs + // no `;`, which is why it has to end the one-statement bodies + // waiting on it itself. `if (c) `uvm_fatal(...)` with no semicolon + // after it is how every UVM testbench is written. + TokenKind::Ident + if token.text.starts_with('`') && (self.answerable() || self.at == At::Timing) => + { + self.pop_hangings(); + At::Boundary + } + TokenKind::Ident if self.at == At::Label => At::Boundary, + TokenKind::Keyword => self.keyword(tokens, i), + TokenKind::Symbol => self.symbol(tokens, i), + _ => At::Unknown, + }; + self.clear_poison(tokens, i); + } + + /// An assertion statement is over once the scan is back at the level it + /// started on, at a place a new statement could begin, with no `else` + /// waiting to extend it. + fn clear_poison(&mut self, tokens: &[Token], i: usize) { + let Some(level) = self.poison else { return }; + if self.stack.len() > level || self.brackets > 0 || !self.answerable() { + return; + } + if matches!(tokens.get(i + 1), Some(next) if next.is_kw("else")) { + return; + } + self.poison = None; + } + + /// A keyword: an opener, a closer, a header, a body, or noise. + fn keyword(&mut self, tokens: &[Token], i: usize) -> At { + let text = tokens[i].text.as_str(); + if ASSERTIONS.contains(&text) { + self.poison = Some(self.stack.len()); + return At::Unknown; + } + if pairs::starts_a_prototype(text) { + self.prototype = true; + return At::Unknown; + } + if let Some(closer) = pairs::closer_keyword(text) { + self.close(closer, followed_by_else(tokens, i)); + return At::Labelled; + } + if !self.prototype { + if let Some(closers) = pairs::opens_scope_at(tokens, i) { + // A `begin` written where a one-statement body was expected + // *is* that body: it replaces the hanging level rather than + // adding to it. A `case` in the same place does not — see + // `pairs::is_block_delimiter`. + let case = CASE_HEADERS.contains(&text); + let mut from_else = false; + if self.at == At::Timing && text == "begin" { + from_else = + matches!(self.stack.pop(), Some(Frame::Hanging { from_else: true })); + } + let opaque = OPAQUE.contains(&text); + self.stack.push(Frame::Block { closers, opaque, case, from_else }); + return if case { At::Header { case: true } } else { At::Labelled }; + } + } + if HEADERS.contains(&text) { + return At::Header { case: false }; + } + if BODY_KEYWORDS.contains(&text) { + self.stack.push(Frame::Hanging { from_else: false }); + return At::Timing; + } + if text == "else" { + // `else if` is one rung of a chain, not two: the `if` pushes the + // level this branch's body gets, and pushing another here would + // indent it twice. The formatter writes the chain flat, which is + // what pins it. + if matches!(tokens.get(i + 1), Some(next) if next.is_kw("if")) { + return At::Unknown; + } + self.stack.push(Frame::Hanging { from_else: true }); + return At::Timing; + } + // `unique`, `virtual`, `assign`, a type name — none of them moves a + // level, and none of them ends a statement either. + At::Unknown + } + + /// Punctuation: the statement terminator, the two colons, and brackets. + fn symbol(&mut self, tokens: &[Token], i: usize) -> At { + let token = &tokens[i]; + if token.is_sym(SEMICOLON) { + self.prototype = false; + // An `else` waiting on the other side means this `;` ended only the + // then-branch, so exactly one body is satisfied: in + // `ITEM: if (c) x = 1; else y = 2;` the `else` still belongs to the + // case item, and popping its level too would put the whole chain + // back at the item's own column. With nothing waiting, the `;` ends + // the lot — `if (a) if (b) x = 1;` closes both. + if followed_by_else(tokens, i) { + self.end_branch(); + } else { + self.pop_hangings(); + } + return At::Boundary; + } + if token.is_sym(":") && self.at == At::Labelled { + return At::Label; + } + // A case item's `:`, recognised by there being nothing between it and + // the `case` scope itself. Its statement is that item's body and sits + // one level in, exactly as an `if`'s does — and a `?:` written inside + // that statement cannot be mistaken for it, because by then the item's + // own `Hanging` is what the stack ends with. + if token.is_sym(":") && matches!(self.stack.last(), Some(Frame::Block { case: true, .. })) { + self.stack.push(Frame::Hanging { from_else: false }); + return At::Timing; + } + if let At::Header { case } = self.at { + if token.is_sym("(") { + return At::InHeader { case, depth: 1 }; + } + } + if token.is_sym("@") || token.is_sym("#") { + if self.at == At::Timing { + return At::Control; + } + // A timing control standing on its own where a statement belongs — + // `@(negedge rst) fork ... join_none`, `#5 $display(...);`. The + // statement it delays is its body, and gets a level, exactly as an + // `always`'s does. + if self.answerable() { + self.stack.push(Frame::Hanging { from_else: false }); + return At::Control; + } + } + if is_open(token) { + self.brackets = 1; + } + At::Unknown + } + + /// Inside a control header's `(...)`, waiting for it to close. + fn in_header(&mut self, token: &Token, case: bool, depth: u32) { + let depth = bracket_depth(token, depth); + if depth > 0 { + self.at = At::InHeader { case, depth }; + return; + } + if case { + // A `case`'s scope is already on the stack; its items are that + // scope's body, and there is no second level to add. + self.at = At::Boundary; + return; + } + self.stack.push(Frame::Hanging { from_else: false }); + self.at = At::Timing; + } + + /// Inside an `@`/`#` timing control, before the body it precedes. + fn in_control(&mut self, token: &Token, depth: u32) { + let depth = bracket_depth(token, depth); + self.at = if depth > 0 { At::InControl { depth } } else { At::Timing }; + } + + /// Close the innermost scope this keyword can close, and with it every + /// one-statement body it satisfied — an `end` finishes the `for` whose body + /// it was as surely as a `;` would have. Unless an `else` is waiting: then + /// the block that just closed was only the then-branch, and the bodies + /// around it are still running. A closer that matches nothing leaves the + /// stack alone, which is what keeps one stray `endcase` from unwinding a + /// whole file. + fn close(&mut self, closer: &str, before_else: bool) { + let Some(index) = self.closes(closer) else { return }; + let from_else = matches!(self.stack.get(index), Some(Frame::Block { from_else: true, .. })); + self.stack.truncate(index); + match (before_else, from_else) { + // The chain runs on: the `else` waiting belongs to the `if` whose + // then-branch this block was. + (true, false) => {} + // The block that closed was already an `else` branch, so the chain + // it belonged to is over and the `else` waiting binds further out — + // every body this one satisfied comes off with it. + (true, true) | (false, _) => self.pop_hangings(), + } + } + + /// One branch of an if/else ended at a `;` with an `else` waiting. Its own + /// body level comes off; if that body was itself an `else` branch, the + /// whole chain ended and the levels around it come off too. + fn end_branch(&mut self) { + let Some(Frame::Hanging { from_else }) = self.stack.last() else { return }; + let from_else = *from_else; + self.stack.pop(); + if from_else { + self.pop_hangings(); + } + } + + fn pop_hangings(&mut self) { + while matches!(self.stack.last(), Some(Frame::Hanging { .. })) { + self.stack.pop(); + } + } + + /// Whether a new item may begin where this scan stands. + fn answerable(&self) -> bool { + matches!(self.at, At::Boundary | At::Labelled) + } +} + +/// Whether the token after `i` is the `else` that keeps the statement running. +fn followed_by_else(tokens: &[Token], i: usize) -> bool { + matches!(tokens.get(i + 1), Some(next) if next.is_kw("else")) +} + +/// `begin`, and only `begin`. +/// +/// The formatter cuddles a `begin`…`end` onto the header before it +/// (`stmt_as_body` in `vlog_formatter::format`) and nothing else — not even +/// `fork`, which is the other block delimiter the rainbow draws. So `if (c) +/// begin` indents its contents one level, while `if (c) fork` indents the +/// `fork` one level and its contents two. Pinned by +/// `only_begin_is_cuddled_onto_the_header_before_it`. +fn is_begin(token: &Token) -> bool { + token.is_kw("begin") +} + +fn bracket_depth(token: &Token, depth: u32) -> u32 { + if is_open(token) { + depth + 1 + } else if is_close(token) { + depth.saturating_sub(1) + } else { + depth + } +} + +fn is_open(token: &Token) -> bool { + token.is_sym("(") || token.is_sym("[") || token.is_sym("{") +} + +fn is_close(token: &Token) -> bool { + token.is_sym(")") || token.is_sym("]") || token.is_sym("}") +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::state::Workspace; + use lsp_types::Uri; + use std::path::{Path, PathBuf}; + use std::str::FromStr; + + /// Run `f` against an open buffer holding `text`. + fn with(text: &str, f: impl FnOnce(&Document) -> T) -> T { + let uri = Uri::from_str("file:///rtl/m.sv").expect("uri"); + let mut ws = Workspace::default(); + ws.set_document(uri.clone(), text.to_string()); + f(ws.document(&uri).expect("open")) + } + + fn config(indent_width: usize) -> Config { + Config { indent_width, ..Config::default() } + } + + /// What the server answers for a `\n` typed at the start of `line` + /// (0-based) — the position an editor reports right after the newline it + /// inserted, before it has written any indentation of its own. + fn newline(text: &str, line: u32) -> Vec { + newline_with(text, line, 2) + } + + fn newline_with(text: &str, line: u32, indent_width: usize) -> Vec { + let at = Position { line, character: 0 }; + with(text, |doc| on_type_formatting(doc, at, NEWLINE, &config(indent_width))) + } + + /// The `new_text` of the single edit a newline produced, or `None` when it + /// produced nothing at all. + fn indent(text: &str, line: u32) -> Option { + let edits = newline(text, line); + assert!(edits.len() <= 1, "at most one edit, ever: {edits:#?}"); + edits.first().map(|edit| edit.new_text.clone()) + } + + /// What the server answers for a `;` typed at the end of `line`. + fn semicolon(text: &str, line: u32) -> Vec { + let source: Vec<&str> = text.split_inclusive('\n').collect(); + let content = source[line as usize].trim_end_matches('\n'); + let character = content.rfind(';').expect("the line ends a statement") as u32 + 1; + let at = Position { line, character }; + with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2))) + } + + // ------------------------------------------------------------------ + // `\n` — what the nesting model does and does not know + // ------------------------------------------------------------------ + + const BLOCK: &str = "module m;\n\n always_comb begin\n\n x = 1;\n\n end\n\nendmodule\n"; + + #[test] + fn a_newline_inside_a_block_lands_at_the_blocks_own_level() { + // Line 1 is the blank after `module m;`, line 3 the blank after + // `begin`, line 5 the blank after `x = 1;`, line 7 the blank after + // `end`. + assert_eq!(indent(BLOCK, 1).as_deref(), Some(" "), "the module's items"); + assert_eq!(indent(BLOCK, 3).as_deref(), Some(" "), "inside the begin"); + assert_eq!(indent(BLOCK, 5).as_deref(), Some(" "), "still inside it"); + assert_eq!(indent(BLOCK, 7).as_deref(), Some(" "), "back out after the end"); + } + + #[test] + fn a_line_already_indented_right_gets_no_edit() { + let text = "module m;\n \nendmodule\n"; + assert_eq!(indent(text, 1), None, "two spaces is what the module wants"); + } + + /// One line's leading whitespace replaced, the way a client applies the + /// edit this file returns. + fn apply(text: &str, edit: &TextEdit) -> String { + let mut lines: Vec = text.split_inclusive('\n').map(str::to_string).collect(); + let source = lines[edit.range.start.line as usize].clone(); + let width = source.len() - source.trim_start_matches([' ', '\t']).len(); + lines[edit.range.start.line as usize] = format!("{}{}", edit.new_text, &source[width..]); + lines.concat() + } + + #[test] + fn applying_the_edit_leaves_the_next_ask_nothing_to_do() { + // The formatter's own invariant #2, through this path: the model is a + // fixed point, so an editor that re-asks at the same position after + // applying gets silence. + let mut text = "module m;\nalways_comb begin\n\n\t\tend\nendmodule\n".to_string(); + for line in [1, 2, 3, 4] { + if let Some(edit) = newline(&text, line).first() { + text = apply(&text, edit); + } + assert_eq!(newline(&text, line), Vec::new(), "line {line} is settled:\n{text}"); + } + // The blank line the user opened really does get indented — that is + // what on-type indentation *is*, and it is where their cursor sits. + // A whole-file format strips the trailing spaces again later, which is + // exactly what an editor's own auto-indent already does. + assert_eq!(text, "module m;\n always_comb begin\n \n end\nendmodule\n"); + } + + #[test] + fn a_line_the_cursor_is_past_is_not_re_indented() { + // The cursor sitting on the code rather than in the whitespace before + // it means the client is not talking about a newline it just typed. + let text = "module m;\nwire a;\nendmodule\n"; + let at = Position { line: 1, character: 4 }; + let edits = with(text, |doc| on_type_formatting(doc, at, NEWLINE, &config(2))); + assert_eq!(edits, Vec::new()); + } + + #[test] + fn the_first_line_of_a_buffer_is_never_a_new_line() { + // No `\n` precedes it, so no `\n` opened it — a client naming line 0 is + // out of step with the buffer we hold. + assert_eq!(indent(" module m;\nendmodule\n", 0), None); + } + + #[test] + fn an_empty_buffer_answers_nothing() { + assert_eq!(newline("", 0), Vec::new()); + assert_eq!(newline("", 5), Vec::new(), "and neither does a line it has not got"); + } + + #[test] + fn an_open_bracket_silences_the_model() { + // A wrapped port list is laid out by width, which this does not + // compute. Line 2 is inside the `(`. + let text = "module m (\n input logic a,\n\n input logic b\n);\nendmodule\n"; + assert_eq!(indent(text, 2), None); + // ...and the `;` that closes it puts the model back in business. + assert_eq!(indent("module m (\n input a\n);\n\nendmodule\n", 3).as_deref(), Some(" ")); + } + + #[test] + fn a_wrapped_expression_silences_the_model_too() { + // Nothing here is bracketed, and the printer still broke the line: the + // continuation's indent is a width decision, not a nesting one. + let text = "module m;\n assign a =\n\n b + c;\nendmodule\n"; + assert_eq!(indent(text, 2), None); + } + + #[test] + fn the_interior_of_a_block_comment_is_left_alone() { + // The formatter re-indents a comment as a whole, by its opening + // column, so a continuation line's own indent means nothing here. + let text = "module m;\n /* one\n\n two */\n wire a;\nendmodule\n"; + assert_eq!(indent(text, 2), None); + // The line the comment *starts* on is an ordinary item line. + assert_eq!(indent("module m;\n\n // note\nendmodule\n", 1).as_deref(), Some(" ")); + } + + #[test] + fn a_line_that_opens_with_punctuation_is_left_alone() { + // `module top\n import p::*;\n#(` — the header continues, and the + // printer writes its `#(` at column zero. + let text = "module top\n import p::*;\n#(\n parameter int P = 1\n) ();\nendmodule\n"; + assert_eq!(indent(text, 2), None); + } + + #[test] + fn a_buffer_that_does_not_lex_answers_nothing() { + assert_eq!(indent("module m;\n wire a = \"unterminated;\n\nendmodule\n", 2), None); + } + + #[test] + fn a_line_opened_inside_a_token_answers_nothing() { + // A `` `define `` continued with a backslash is one token across two + // lines, and its second line is not a place a statement begins. + let text = "`define WIDE(a) \\\n do_something(a)\nmodule m;\nendmodule\n"; + assert_eq!(indent(text, 1), None); + } + + #[test] + fn a_closing_keyword_sits_at_its_openers_level() { + // The dedent is what makes typing `end` on a fresh line land right. + let text = "module m;\n always_comb begin\n x = 1;\nend\nendmodule\n"; + assert_eq!(indent(text, 3).as_deref(), Some(" "), "the `end`"); + assert_eq!(indent(text, 4), None, "`endmodule` is already at column zero"); + } + + #[test] + fn a_one_statement_body_gets_a_level_and_gives_it_back() { + let text = "module m;\n initial begin\n if (c)\n\n x = 1;\n\n end\nendmodule\n"; + assert_eq!(indent(text, 3).as_deref(), Some(" "), "the if's body"); + assert_eq!(indent(text, 5).as_deref(), Some(" "), "the `;` gave it back"); + } + + #[test] + fn a_begin_is_the_body_rather_than_a_level_below_it() { + let text = "module m;\n initial begin\n if (c) begin\n\n end\n end\nendmodule\n"; + assert_eq!(indent(text, 3).as_deref(), Some(" "), "one level, not two"); + } + + #[test] + fn a_case_item_carries_its_own_statement_one_level_in() { + let text = "module m;\n initial begin\n case (s)\n\n A:\n\n B: x = 1;\n\n endcase\n end\nendmodule\n"; + assert_eq!(indent(text, 3).as_deref(), Some(" "), "the items"); + assert_eq!(indent(text, 5).as_deref(), Some(" "), "`A:`'s own statement"); + assert_eq!(indent(text, 7).as_deref(), Some(" "), "and back for the next item"); + } + + #[test] + fn an_else_chain_is_one_ladder_and_not_two() { + let text = "module m;\n initial begin\n if (a) x = 1;\n else if (b)\n\n y = 2;\n end\nendmodule\n"; + assert_eq!(indent(text, 4).as_deref(), Some(" "), "the else-if's body"); + } + + #[test] + fn a_verbatim_scope_has_no_indent_this_model_can_name() { + // A covergroup's body is emitted byte-for-byte, so whatever the user + // wrote there is already what a whole-file run produces. + let text = "module m;\n covergroup cg;\n\n cp: coverpoint x;\n endgroup\nendmodule\n"; + assert_eq!(indent(text, 2), None); + } + + #[test] + fn an_assertion_statement_is_silent_for_as_long_as_it_runs() { + // `assert (c) pass; else fail;` is verbatim, and its `else` runs past + // the `;` that would otherwise end it. + let text = "module m;\n initial begin\n a: assert (c) pass();\n else begin\n\n end\n\n end\nendmodule\n"; + assert_eq!(indent(text, 4), None, "inside the assertion's else"); + assert_eq!(indent(text, 6).as_deref(), Some(" "), "and answering again after it"); + } + + #[test] + fn a_macro_item_needs_no_semicolon_to_end_the_body_waiting_on_it() { + // How every UVM testbench writes it. Without this the `if`'s level + // would never come off. + let text = "module m;\n initial begin\n if (c) `uvm_fatal(a, b)\n\n x = 1;\n end\nendmodule\n"; + assert_eq!(indent(text, 3).as_deref(), Some(" "), "back at the block's level"); + } + + // ------------------------------------------------------------------ + // the structural guarantee + // ------------------------------------------------------------------ + + #[test] + fn an_indent_edit_can_only_ever_replace_leading_whitespace() { + // The one property that makes this path safe to ship outside the + // verified engine: it cannot name a byte of code. Checked over every + // line of a file with a bit of everything in it. + let text = concat!( + "`include \"x.svh\"\n", + "module m #(\n parameter int P = 1\n) (\n input logic clk\n);\n", + " // a comment\n", + " /* two\n lines */\n", + " always_ff @(posedge clk) begin\n", + " case (s)\n A: x <= 1;\n default: x <= 0;\n endcase\n", + " if (c) begin\n y <= 1;\n end else\n y <= 0;\n", + " end\n", + "endmodule\n", + ); + with(text, |doc| { + for line in 1..text.lines().count() as u32 { + let at = Position { line, character: 0 }; + for edit in on_type_formatting(doc, at, NEWLINE, &config(2)) { + assert_eq!(edit.range.start, at, "always column zero of the asked-for line"); + assert_eq!(edit.range.end.line, line, "and never past that line"); + let source = doc.text.lines().nth(line as usize).unwrap_or(""); + let width = source.len() - source.trim_start().len(); + assert!( + edit.range.end.character as usize <= width, + "line {line} reaches into `{source}`" + ); + assert!( + edit.new_text.chars().all(|c| c == ' '), + "line {line} writes something that is not a space: {:?}", + edit.new_text + ); + } + } + }); + } + + // ------------------------------------------------------------------ + // the settings ladder, and positions + // ------------------------------------------------------------------ + + #[test] + fn the_indent_width_is_the_one_the_settings_resolved_to() { + let text = "module m;\n\n wire a;\nendmodule\n"; + assert_eq!(newline_with(text, 1, 4)[0].new_text, " "); + assert_eq!(newline_with(text, 1, 8)[0].new_text, " "); + // ...and never a tab, whatever a client asked for: the printer writes + // spaces, and `config_from` refuses `insertSpaces: false` before the + // width ever reaches here. + assert!(newline_with(text, 1, 3)[0].new_text.chars().all(|c| c == ' ')); + } + + #[test] + fn a_tab_indented_line_is_replaced_with_the_spaces_the_formatter_writes() { + let text = "module m;\n\t\nendmodule\n"; + let edit = &newline(text, 1)[0]; + assert_eq!(edit.new_text, " "); + assert_eq!(edit.range.end.character, 1, "the tab is one UTF-16 unit wide"); + } + + #[test] + fn a_crlf_line_ending_is_never_touched_by_the_edit() { + // `\r` is an ordinary byte of the line it ends (`vlog_parser::line_index` + // keeps it there; only `\n` breaks a line), and `indent_edit`'s own + // leading-whitespace scan only recognizes `' '`/`'\t'` — so a blank + // CRLF line's text is just `"\r"`, and the edit must insert *before* + // that byte, never span it. + let text = "module m;\r\n always_comb begin\r\n\r\n end\r\nendmodule\r\n"; + let edit = &newline(text, 2)[0]; + assert_eq!(edit.new_text, " "); + assert_eq!(edit.range.start, Position { line: 2, character: 0 }); + assert_eq!( + edit.range.end, + Position { line: 2, character: 0 }, + "an insertion before the \\r, not a range through it" + ); + + // A CRLF line that already carries leading whitespace: only that + // whitespace is named, and the trailing `\r` is untouched either way. + let indented = "module m;\r\n always_comb begin\r\n\t\r\n end\r\nendmodule\r\n"; + let edit = &newline(indented, 2)[0]; + assert_eq!(edit.new_text, " "); + assert_eq!( + edit.range.end, + Position { line: 2, character: 1 }, + "just past the tab, short of the \\r" + ); + } + + #[test] + fn a_mixed_tab_and_space_prefix_is_measured_in_bytes_not_visual_columns() { + // Tabs and spaces are both one byte and one UTF-16 unit each, so a + // mixed prefix is not a place the byte/column distinction can hide a + // bug — but it is exactly the shape a hand-indented file hands this + // model, and nothing so far exercises more than one kind at once. + let text = "module m;\n\t \nendmodule\n"; + let edit = &newline(text, 1)[0]; + assert_eq!(edit.new_text, " "); + assert_eq!(edit.range.end, Position { line: 1, character: 2 }, "both bytes of the prefix"); + } + + #[test] + fn positions_are_utf16_units_on_a_line_that_holds_astral_characters() { + // The edit's end is the first non-whitespace character, counted the + // way LSP counts. The `🎉` is two units, so a naive byte count would + // put the end past the `x` and start eating code. + let text = "module m;\n initial begin\n // 🎉 é ✓\n x = 1;\n end\nendmodule\n"; + let edit = &newline(text, 3)[0]; + assert_eq!(edit.new_text, " "); + assert_eq!(edit.range.end, Position { line: 3, character: 2 }); + } + + // ------------------------------------------------------------------ + // agreement with the real formatter + // ------------------------------------------------------------------ + + /// Every source file of the checked-in corpus, read once. Skipped when + /// `corpus/` is not checked out (`tools/corpus_fetch.sh`), like every other + /// corpus test. + fn corpus() -> Vec { + fn walk(dir: &Path, out: &mut Vec) { + let Ok(entries) = std::fs::read_dir(dir) else { return }; + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() { + walk(&path, out); + } else if matches!(path.extension().and_then(|e| e.to_str()), Some("sv" | "v")) { + out.push(path); + } + } + } + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus"); + let mut files = Vec::new(); + walk(&root, &mut files); + files.sort(); + files + } + + #[test] + fn the_model_never_disagrees_with_the_formatter_on_formatted_corpus_code() { + // **The anchor.** Two pieces of indent logic now exist — the printer's, + // which is driven by the AST and by line width, and this model's, which + // is driven by the token stream. This is what stops them drifting: take + // a file the real engine formatted, and ask the model, at every line, + // what it would do there. It may decline; it may not disagree. + let files = corpus(); + if files.is_empty() { + eprintln!("corpus/ not checked out — skipping"); + return; + } + let config = Config::default(); + let (mut answered, mut declined) = (0usize, 0usize); + let mut disagreed: Vec = Vec::new(); + for path in &files { + let Ok(source) = std::fs::read_to_string(path) else { continue }; + // Files the engine refuses have no formatted form to agree with. + let Ok(formatted) = vlog_formatter::format_source(&source, &config) else { continue }; + with(&formatted, |doc| { + for (n, line) in formatted.lines().enumerate().skip(1) { + if line.trim().is_empty() { + continue; + } + let Some(range) = doc.line_index.line_range(n as u32 + 1) else { continue }; + let width = line.len() - line.trim_start().len(); + match level_at(doc, range.start + width as u32) { + None => declined += 1, + Some(level) => { + answered += 1; + if level * config.indent_width != width { + disagreed.push(format!( + "{}:{}: model {} vs formatter {} | {}", + path.display(), + n + 1, + level * config.indent_width, + width, + line.trim_end() + )); + } + } + } + } + }); + } + assert!( + disagreed.is_empty(), + "{} of {answered} answered lines disagree:\n{}", + disagreed.len(), + disagreed.iter().take(20).cloned().collect::>().join("\n") + ); + // And the agreement is not vacuous: a model that declined everywhere + // would pass the assertion above and be worth nothing. + assert!(answered > 50_000, "the corpus really is checked out: {answered}"); + let share = answered as f64 / (answered + declined) as f64; + assert!(share > 0.6, "only {:.1}% of lines answered", share * 100.0); + eprintln!("on-type indent: {answered} lines answered, {declined} declined"); + } + + #[test] + fn only_begin_is_cuddled_onto_the_header_before_it() { + // The assumption `is_begin` rests on, asserted against the real engine + // rather than believed: `stmt_as_body` joins a `begin`…`end` to its + // header and nothing else — not `fork`, which is the other block + // delimiter. If that ever changes, the model is wrong by one level for + // every `if (c) fork`, and this is what says so. + let source = "module m;\ninitial begin\nif (c) begin\nx = 1;\nend\nif (c)\nfork\na();\nb();\njoin\nend\nendmodule\n"; + let out = vlog_formatter::format_source(source, &Config::default()).expect("formats"); + assert!(out.contains("\n if (c) begin\n x = 1;\n"), "begin cuddles:\n{out}"); + assert!(out.contains("\n if (c)\n fork\n a();\n"), "fork does not:\n{out}"); + } + + // ------------------------------------------------------------------ + // `;` — the finished statement + // ------------------------------------------------------------------ + + const MESSY: &str = "module m;\n wire a;\n wire b;\nendmodule\n"; + + #[test] + fn a_semicolon_lays_out_the_statement_it_ended_and_nothing_else() { + let edits = semicolon(MESSY, 1); + assert_eq!(edits.len(), 1); + assert_eq!(edits[0].new_text, "module m;\n wire a;\n wire b;\nendmodule\n"); + } + + #[test] + fn a_semicolon_answers_exactly_what_range_formatting_of_that_line_answers() { + // The whole contract of this path: it is `textDocument/rangeFormatting` + // with a different trigger, and no new formatting logic of its own. + let line = Position { line: 1, character: 0 }; + let ranged = with(MESSY, |doc| { + format::range_formatting(doc, &config(2), Range { start: line, end: line }) + }); + assert_eq!(semicolon(MESSY, 1), ranged.expect("formats").into_iter().collect::>()); + } + + #[test] + fn a_semicolon_in_a_buffer_the_engine_refuses_answers_nothing_at_all() { + // Half-typed code is the normal case on this trigger, not a failure. + assert_eq!(semicolon("module m;\n wire a;\n wire ;\nendmodule\n", 1), Vec::new()); + } + + #[test] + fn a_semicolon_that_is_not_where_the_client_said_answers_nothing() { + let at = Position { line: 1, character: 3 }; + let edits = with(MESSY, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2))); + assert_eq!(edits, Vec::new()); + } + + #[test] + fn a_semicolon_the_lexer_never_saw_ends_no_statement() { + // Inside a comment and inside a string: characters, not terminators. + let text = "module m;\n // not a statement;\n wire a;\nendmodule\n"; + assert_eq!(semicolon(text, 1), Vec::new()); + let text = "module m;\n string s = \"a;\";\n wire a;\nendmodule\n"; + let at = Position { line: 1, character: 16 }; + let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2))); + assert_eq!(edits, Vec::new(), "the `;` inside the quotes"); + } + + #[test] + fn a_semicolon_at_eof_with_no_trailing_newline_still_lays_out_its_line() { + // A buffer with no final `\n` at all — the last keystroke a user makes + // before ever pressing Enter again. The `;` is the very last byte of + // the whole document. + let text = "module m;\n wire a;\nendmodule"; + let at = Position { line: 1, character: 11 }; + let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2))); + assert_eq!(edits.len(), 1, "{edits:#?}"); + // The engine's own canonicalization adds the missing final newline — + // exactly what `textDocument/rangeFormatting` would also do here, and + // not a moved byte this path invented on its own. + assert_eq!(edits[0].new_text, "module m;\n wire a;\nendmodule\n"); + } + + #[test] + fn a_module_wrapped_whole_in_an_ifdef_guard_indents_by_its_own_nesting() { + // Conditional compilation adds no level of its own — `` `ifdef `` and + // `` `endif `` are ordinary directive tokens that neither push nor pop + // the stack — so a file that is one big guarded block indents exactly + // as the same file would with the guard stripped. + let text = + "`ifdef FOO\nmodule m;\n initial begin\n\n x = 1;\n end\nendmodule\n`endif\n"; + assert_eq!(indent(text, 3).as_deref(), Some(" "), "still two levels in"); + } + + #[test] + fn a_semicolon_inside_a_format_off_fence_rides_through_the_fence_untouched() { + // The `;` path adds no formatting logic of its own — it is + // `format::range_formatting` unchanged — so a fence, which outranks + // any range, rides through exactly as it does for + // `textDocument/rangeFormatting`: the messy fenced line keeps its + // bytes, byte for byte. + let text = "module m;\n // verilog_format: off\n wire a ;\n // verilog_format: on\nendmodule\n"; + let edits = semicolon(text, 2); + assert_eq!(edits, Vec::new(), "the fence leaves the line exactly as written: {edits:#?}"); + } + + #[test] + fn a_semicolon_ending_a_macro_definitions_body_ends_no_statement() { + // `` `define FOO x = 1; `` is one `Directive` token end to end — its + // body is text, not a re-lexed statement — so no `Symbol(";")` token + // ends where the `;` sits, and the gate declines exactly as it does + // inside a string or a comment. + let text = "`define FOO x = 1;\nmodule m;\nendmodule\n"; + let at = Position { line: 0, character: 19 }; + let edits = with(text, |doc| on_type_formatting(doc, at, SEMICOLON, &config(2))); + assert_eq!(edits, Vec::new(), "no Symbol(;) token ends inside a Directive"); + } + + #[test] + fn an_already_laid_out_statement_gets_no_edit() { + assert_eq!(semicolon("module m;\n wire a;\nendmodule\n", 1), Vec::new()); + } + + #[test] + fn a_semicolon_closing_a_module_header_lays_out_the_header_and_not_the_body() { + // The reason the range is the `;`'s own line and not its enclosing + // node's: naming the module here would ask for the whole body back. + let text = "module m (\n input logic a\n);\n wire b;\nendmodule\n"; + let edits = semicolon(text, 2); + assert_eq!(edits.len(), 1); + assert_eq!( + edits[0].new_text, "module m (input logic a);\n wire b;\nendmodule\n", + "the header is laid out; the body's `wire b;` keeps its bytes" + ); + } + + #[test] + fn an_unknown_trigger_character_answers_nothing() { + // A client that sends one we never advertised gets silence, not a + // guess at what it meant. + let at = Position { line: 1, character: 9 }; + for typed in ["}", ")", "\t", ""] { + let edits = with(MESSY, |doc| on_type_formatting(doc, at, typed, &config(2))); + assert_eq!(edits, Vec::new(), "trigger {typed:?}"); + } + } +} diff --git a/crates/lucisv_server/src/pairs.rs b/crates/lucisv_server/src/pairs.rs index ad38c14..7f43d0d 100644 --- a/crates/lucisv_server/src/pairs.rs +++ b/crates/lucisv_server/src/pairs.rs @@ -307,10 +307,34 @@ fn opener_rule(text: &str) -> Option<(usize, &'static Rule)> { } /// The closer keyword `text` is, as a `'static` string from the table. -fn closer_keyword(text: &str) -> Option<&'static str> { +pub(crate) fn closer_keyword(text: &str) -> Option<&'static str> { RULES.iter().flat_map(|r| r.close).copied().find(|c| *c == text) } +/// The keywords that close the scope the token at `i` opens, or `None` when it +/// opens none. +/// +/// [`analyze`]'s own two questions — "is this an opener?" and "does it really +/// open here?" — asked as one, so the on-type indent model counts nesting off +/// exactly the scopes the matcher matches. The [`RULES`] table and +/// [`opens_a_scope`]'s exception list must have one reader's answer, not two: +/// an `extern function f();` that opened a scope for one of them and not the +/// other would leave the two disagreeing about every line below it. +/// +/// The caller still owns the prototype flag ([`starts_a_prototype`]), because +/// that one spans tokens and only a running scan can carry it. +pub(crate) fn opens_scope_at(tokens: &[Token], i: usize) -> Option<&'static [&'static str]> { + let text = tokens.get(i)?.text.as_str(); + let (_, rule) = opener_rule(text)?; + opens_a_scope(tokens, i).then_some(rule.close) +} + +/// Whether a keyword turns the rest of its statement into a declaration with +/// no body — see [`PROTOTYPE_STARTERS`]. Cleared at the next `;`. +pub(crate) fn starts_a_prototype(text: &str) -> bool { + PROTOTYPE_STARTERS.contains(&text) +} + /// The opener a closer belongs to, for "`end` has no matching `begin`". fn opener_of(closer: &str) -> &'static str { RULES.iter().find(|r| r.close.contains(&closer)).map_or("", |r| r.open) diff --git a/crates/lucisv_server/src/server.rs b/crates/lucisv_server/src/server.rs index cbaf955..10f12dc 100644 --- a/crates/lucisv_server/src/server.rs +++ b/crates/lucisv_server/src/server.rs @@ -24,11 +24,11 @@ use lsp_types::request::{ DocumentDiagnosticRequest, DocumentHighlightRequest, DocumentLinkRequest, DocumentSymbolRequest, ExecuteCommand, FoldingRangeRequest, Formatting, GotoDefinition, GotoTypeDefinition, GotoTypeDefinitionParams, GotoTypeDefinitionResponse, HoverRequest, - InlayHintRequest, InlineCompletionRequest, LinkedEditingRange, PrepareRenameRequest, - RangeFormatting, References, RegisterCapability, Rename, Request as _, SelectionRangeRequest, - SemanticTokensFullDeltaRequest, SemanticTokensFullRequest, SemanticTokensRangeRequest, - ShowDocument, Shutdown, SignatureHelpRequest, UnregisterCapability, WillSaveWaitUntil, - WorkDoneProgressCreate, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest, + InlayHintRequest, InlineCompletionRequest, LinkedEditingRange, OnTypeFormatting, + PrepareRenameRequest, RangeFormatting, References, RegisterCapability, Rename, Request as _, + SelectionRangeRequest, SemanticTokensFullDeltaRequest, SemanticTokensFullRequest, + SemanticTokensRangeRequest, ShowDocument, Shutdown, SignatureHelpRequest, UnregisterCapability, + WillSaveWaitUntil, WorkDoneProgressCreate, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest, }; use lsp_types::{ ApplyWorkspaceEditParams, ApplyWorkspaceEditResponse, CallHierarchyIncomingCallsParams, @@ -37,22 +37,23 @@ use lsp_types::{ DidChangeTextDocumentParams, DidChangeWatchedFilesParams, DidCloseTextDocumentParams, DidOpenTextDocumentParams, DidSaveTextDocumentParams, DocumentDiagnosticParams, DocumentDiagnosticReport, DocumentDiagnosticReportResult, DocumentFormattingParams, - DocumentHighlightParams, DocumentLinkParams, DocumentRangeFormattingParams, - DocumentSymbolParams, DocumentSymbolResponse, ExecuteCommandParams, FoldingRangeParams, - FullDocumentDiagnosticReport, GotoDefinitionParams, GotoDefinitionResponse, HoverParams, - InlayHintParams, InlineCompletionParams, LinkedEditingRangeParams, Location, LogMessageParams, - MessageType, NumberOrString, Position, PreviousResultId, ProgressParams, ProgressParamsValue, - ProgressToken, PublishDiagnosticsParams, ReferenceParams, RegistrationParams, - RelatedFullDocumentDiagnosticReport, RelatedUnchangedDocumentDiagnosticReport, RenameParams, - SelectionRangeParams, SemanticToken, SemanticTokens, SemanticTokensDelta, - SemanticTokensDeltaParams, SemanticTokensFullDeltaResult, SemanticTokensParams, - SemanticTokensRangeParams, SemanticTokensRangeResult, SemanticTokensResult, ShowDocumentParams, - ShowMessageParams, SignatureHelpParams, TextDocumentPositionParams, - UnchangedDocumentDiagnosticReport, UnregistrationParams, Uri, WillSaveTextDocumentParams, - WorkDoneProgress, WorkDoneProgressBegin, WorkDoneProgressCreateParams, WorkDoneProgressEnd, - WorkspaceDiagnosticParams, WorkspaceDiagnosticReport, WorkspaceDiagnosticReportResult, - WorkspaceDocumentDiagnosticReport, WorkspaceEdit, WorkspaceFullDocumentDiagnosticReport, - WorkspaceSymbolParams, WorkspaceSymbolResponse, WorkspaceUnchangedDocumentDiagnosticReport, + DocumentHighlightParams, DocumentLinkParams, DocumentOnTypeFormattingParams, + DocumentRangeFormattingParams, DocumentSymbolParams, DocumentSymbolResponse, + ExecuteCommandParams, FoldingRangeParams, FullDocumentDiagnosticReport, GotoDefinitionParams, + GotoDefinitionResponse, HoverParams, InlayHintParams, InlineCompletionParams, + LinkedEditingRangeParams, Location, LogMessageParams, MessageType, NumberOrString, Position, + PreviousResultId, ProgressParams, ProgressParamsValue, ProgressToken, PublishDiagnosticsParams, + ReferenceParams, RegistrationParams, RelatedFullDocumentDiagnosticReport, + RelatedUnchangedDocumentDiagnosticReport, RenameParams, SelectionRangeParams, SemanticToken, + SemanticTokens, SemanticTokensDelta, SemanticTokensDeltaParams, SemanticTokensFullDeltaResult, + SemanticTokensParams, SemanticTokensRangeParams, SemanticTokensRangeResult, + SemanticTokensResult, ShowDocumentParams, ShowMessageParams, SignatureHelpParams, + TextDocumentPositionParams, UnchangedDocumentDiagnosticReport, UnregistrationParams, Uri, + WillSaveTextDocumentParams, WorkDoneProgress, WorkDoneProgressBegin, + WorkDoneProgressCreateParams, WorkDoneProgressEnd, WorkspaceDiagnosticParams, + WorkspaceDiagnosticReport, WorkspaceDiagnosticReportResult, WorkspaceDocumentDiagnosticReport, + WorkspaceEdit, WorkspaceFullDocumentDiagnosticReport, WorkspaceSymbolParams, + WorkspaceSymbolResponse, WorkspaceUnchangedDocumentDiagnosticReport, }; use serde::de::DeserializeOwned; use serde_json::Value; @@ -60,8 +61,8 @@ use serde_json::Value; use crate::state::Workspace; use crate::{ code_action, completion, diagnostics, folding, format, hierarchy, hover, includes, inlay, - inline, lens, linked, nav, pairs, ports, rename, selection, settings, signature, symbols, sync, - tokens, type_def, watch, + inline, lens, linked, nav, on_type, pairs, ports, rename, selection, settings, signature, + symbols, sync, tokens, type_def, watch, }; /// What the client said it can do, read once at `initialize` because that is @@ -282,6 +283,9 @@ impl Server { let result = match method.as_str() { Formatting::METHOD => decode(request).and_then(|p| self.formatting(p)), RangeFormatting::METHOD => decode(request).and_then(|p| self.range_formatting(p)), + // One keystroke, at most one edit, never a word to the user — see + // `on_type_formatting`. + OnTypeFormatting::METHOD => decode(request).and_then(|p| self.on_type_formatting(p)), // Format-on-save, protocol-native: the client asks before it // writes, and applies whatever comes back. Opt-in, and the decline // is the cheap path — see `will_save_wait_until`. @@ -625,6 +629,38 @@ impl Server { self.edits(result) } + /// `textDocument/onTypeFormatting` — the newline and the semicolon. + /// + /// Two things about it are unlike every other formatting entry, and both + /// follow from its trigger being a keystroke rather than a command: + /// + /// * **It never speaks.** A formatter refusal is `[]` and silence, where + /// `textDocument/formatting` shows an ERROR and `willSaveWaitUntil` + /// shows one per save. Mid-edit code the engine declines is the *normal* + /// case here, not a failure worth a popup on every semicolon. + /// * **It never warns about a broken `lucisv.toml` either.** That warning + /// is deduped per buffer *state*, and `set_document` re-arms it — so a + /// request that by definition follows the `didChange` the user's own + /// keystroke produced would re-arm and re-show it on every character. + /// The user is told on their next explicit format or save, which are the + /// two moments they asked lucisv for something. + /// + /// The settings ladder is the one `textDocument/formatting` climbs, + /// `tabSize` rung included: unlike `willSaveWaitUntil`, this request does + /// carry `FormattingOptions`. + fn on_type_formatting( + &mut self, + params: DocumentOnTypeFormattingParams, + ) -> Result { + let at = params.text_document_position; + let Some(doc) = self.workspace.document(&at.text_document.uri) else { + return to_value(Vec::::new()); + }; + let settings = format::settings_for(doc, self.workspace.client_settings(), ¶ms.options); + let edits = on_type::on_type_formatting(doc, at.position, ¶ms.ch, &settings.config); + to_value(edits) + } + /// `textDocument/willSaveWaitUntil` — format the buffer the client is /// about to write, for the editors that have no format-on-save of their /// own. @@ -3111,6 +3147,179 @@ mod tests { assert!(published[0].diagnostics.is_empty(), "{published:#?}"); } + // ------------------------------------------------------------------ + // `textDocument/onTypeFormatting` + // ------------------------------------------------------------------ + + /// One `onTypeFormatting` for a buffer: the character typed, and the + /// position the client reports for the cursor after it. + fn on_type(session: &mut Session, uri: &Uri, typed: &str, line: u32, character: u32) -> Value { + on_type_with(session, uri, typed, line, character, serde_json::json!({})) + } + + fn on_type_with( + session: &mut Session, + uri: &Uri, + typed: &str, + line: u32, + character: u32, + options: Value, + ) -> Value { + let mut all = serde_json::json!({ "tabSize": 2, "insertSpaces": true }); + if let (Some(all), Some(extra)) = (all.as_object_mut(), options.as_object()) { + for (key, value) in extra { + all.insert(key.clone(), value.clone()); + } + } + session.result( + OnTypeFormatting::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri }, + "position": { "line": line, "character": character }, + "ch": typed, + "options": all, + }), + ) + } + + #[test] + fn a_typed_newline_re_indents_the_line_it_opened() { + // The dispatch arm, end to end: a real request, decoded by the real + // decoder, answered by the real handler. + let tree = Tree::new("ontypenewline"); + let mut session = Session::new(vec![tree.path.clone()], false); + let uri = session + .open(&tree.path.join("m.sv"), "module m;\n always_comb begin\n\n end\nendmodule\n"); + + let edits = on_type(&mut session, &uri, "\n", 2, 0); + assert_eq!(edits[0]["newText"], " ", "{edits:#?}"); + assert_eq!(edits[0]["range"]["start"], serde_json::json!({ "line": 2, "character": 0 })); + assert_eq!(edits[0]["range"]["end"], serde_json::json!({ "line": 2, "character": 0 })); + assert!(session.shown().is_empty(), "a keystroke says nothing to the user"); + } + + #[test] + fn a_typed_semicolon_lays_out_the_statement_through_the_range_engine() { + let tree = Tree::new("ontypesemi"); + let mut session = Session::new(vec![tree.path.clone()], false); + let text = "module m;\n wire a;\n wire b;\nendmodule\n"; + let uri = session.open(&tree.path.join("m.sv"), text); + + let typed = on_type(&mut session, &uri, ";", 1, 11); + assert_eq!(typed[0]["newText"], "module m;\n wire a;\n wire b;\nendmodule\n"); + // The same answer `textDocument/rangeFormatting` gives for that line, + // byte for byte: this path is that request with a different trigger. + let ranged = session.result( + RangeFormatting::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri }, + "range": { "start": { "line": 1, "character": 0 }, + "end": { "line": 1, "character": 0 } }, + "options": { "tabSize": 2, "insertSpaces": true }, + }), + ); + assert_eq!(typed, ranged); + assert!(session.shown().is_empty()); + } + + #[test] + fn a_keystroke_the_engine_refuses_is_answered_with_silence_and_not_a_popup() { + // The deliberate contrast with `textDocument/formatting` and the save + // hook, both of which show an ERROR on a refusal. Mid-edit code the + // engine declines is the *normal* case on a keystroke, and a modal the + // user cannot type past would arrive on every semicolon. + let tree = Tree::new("ontypequiet"); + let mut session = Session::new(vec![tree.path.clone()], false); + let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\n wire ;\n"); + + assert_eq!(on_type(&mut session, &uri, ";", 1, 11), serde_json::json!([])); + assert!(session.shown().is_empty(), "not one word: {:?}", session.shown()); + // ...and the whole-document request on the same buffer still does say + // something, so the silence is this path's decision and not a + // regression in `edits()`. + let _ = formatting_result(&mut session, &uri); + assert_eq!(session.shown().len(), 1, "the explicit request still reports"); + } + + #[test] + fn a_broken_config_is_never_reported_from_a_keystroke() { + // `warn_about_config`'s dedup is cleared by `set_document`, and an + // on-type request follows the `didChange` the user's own keystroke + // produced — so warning here would mean one popup per character. The + // user is told on their next explicit format instead. + let tree = Tree::new("ontypeconfig"); + std::fs::write(tree.path.join(".git"), "gitdir: nowhere\n").expect("write .git"); + std::fs::write(tree.path.join("lucisv.toml"), "bogus = 1\n").expect("write config"); + let mut session = Session::new(vec![tree.path.clone()], false); + let uri = session.open(&tree.path.join("m.sv"), "module m;\n\n wire a;\nendmodule\n"); + let _ = session.drain(); + + for _ in 0..3 { + let edits = on_type(&mut session, &uri, "\n", 1, 0); + assert_eq!(edits[0]["newText"], " ", "it still formats with the defaults"); + assert!(session.shown().is_empty(), "and still says nothing"); + } + // The explicit request is where the user hears about it. + let _ = formatting_result(&mut session, &uri); + let shown = session.shown(); + assert_eq!(shown.len(), 1, "{shown:?}"); + assert!(shown[0].1.contains("unknown key `bogus`"), "{shown:?}"); + } + + #[test] + fn a_keystroke_climbs_the_same_settings_ladder_a_manual_format_does() { + // Unlike `willSaveWaitUntil`, this request carries `FormattingOptions`, + // so the editor's own tab size is a rung — outranked by a pushed + // `lucisv.indent`, exactly as `format::settings_for` documents. + let tree = Tree::new("ontypesettings"); + let mut session = Session::new(vec![tree.path.clone()], false); + let uri = session.open(&tree.path.join("m.sv"), "module m;\n\n wire a;\nendmodule\n"); + + let tabbed = serde_json::json!({ "tabSize": 4 }); + let edits = on_type_with(&mut session, &uri, "\n", 1, 0, tabbed.clone()); + assert_eq!(edits[0]["newText"], " ", "rung 3, the editor's tab size"); + + session.notify( + DidChangeConfiguration::METHOD, + serde_json::json!({ "settings": { "lucisv": { "indent": 8 } } }), + ); + let edits = on_type_with(&mut session, &uri, "\n", 1, 0, tabbed); + assert_eq!(edits[0]["newText"], " ", "rung 2 outranks it"); + + // Hard tabs are not a width this formatter can honour, so rung 3 drops + // out entirely and the built-in default answers. + session.notify( + DidChangeConfiguration::METHOD, + serde_json::json!({ "settings": { "lucisv": {} } }), + ); + let hard = serde_json::json!({ "tabSize": 4, "insertSpaces": false }); + let edits = on_type_with(&mut session, &uri, "\n", 1, 0, hard); + assert_eq!(edits[0]["newText"], " ", "never a tab, and never a guess"); + } + + #[test] + fn a_keystroke_in_a_buffer_the_server_does_not_hold_answers_an_empty_array() { + // `[]` rather than `null`: the protocol's answer for "no edits", and + // what every other request on this path already returns. + let tree = Tree::new("ontypeunopened"); + let mut session = Session::new(vec![tree.path.clone()], false); + let uri = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri"); + assert_eq!(on_type(&mut session, &uri, "\n", 1, 0), serde_json::json!([])); + assert_eq!(on_type(&mut session, &uri, ";", 1, 0), serde_json::json!([])); + assert!(session.shown().is_empty()); + } + + #[test] + fn a_trigger_character_this_server_never_advertised_answers_nothing() { + let tree = Tree::new("ontypeunknown"); + let mut session = Session::new(vec![tree.path.clone()], false); + let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\nendmodule\n"); + for typed in ["}", ")", "e"] { + assert_eq!(on_type(&mut session, &uri, typed, 1, 11), serde_json::json!([]), "{typed}"); + } + assert!(session.shown().is_empty()); + } + // ------------------------------------------------------------------ // `textDocument/willSaveWaitUntil` // ------------------------------------------------------------------ diff --git a/crates/lucisv_server/tests/e2e.rs b/crates/lucisv_server/tests/e2e.rs index 39497ce..2bd31d8 100644 --- a/crates/lucisv_server/tests/e2e.rs +++ b/crates/lucisv_server/tests/e2e.rs @@ -788,6 +788,92 @@ fn the_save_hook_is_advertised_and_formats_only_when_it_is_asked_to() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn typing_a_newline_and_a_semicolon_round_trips_over_the_real_binary() { + // Simulates the two keystrokes the client actually sends, in order, with + // the `didChange` between them that a real editor would send: type a + // newline inside a block (the buffer grows a blank line), apply the indent, + // then finish a statement with `;`. + let dir = temp_dir("ontype"); + let file = dir.join("m.sv"); + let opened = "module m;\n always_comb begin\n end\nendmodule\n"; + std::fs::write(&file, opened).expect("write"); + let root = format!("file://{}", dir.display()); + let uri = format!("file://{}", file.display()); + + // What the buffer holds after the user pressed Enter at the end of the + // `begin` line: one blank line, no indentation on it yet. + let after_newline = "module m;\n always_comb begin\n\n end\nendmodule\n"; + // ...and after the client applied the indent and typed a statement whose + // spacing the formatter would tighten. + let after_typing = "module m;\n always_comb begin\n x = 1;\n end\nendmodule\n"; + + let full_change = |version: u32, text: &str| { + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{uri}","version":{version}}},"contentChanges":[{{"text":{}}}]}}}}"#, + serde_json::to_string(text).expect("json") + )) + }; + let on_type = |id: u32, ch: &str, line: u32, character: u32| { + frame(&format!( + r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/onTypeFormatting","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":{line},"character":{character}}},"ch":{},"options":{{"tabSize":2,"insertSpaces":true}}}}}}"#, + serde_json::to_string(ch).expect("json") + )) + }; + + let session = [ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(opened).expect("json") + )), + full_change(2, after_newline), + on_type(2, "\n", 2, 0), + full_change(3, after_typing), + on_type(3, ";", 2, 14), + // A trigger this server never advertised, over the wire: still `[]`. + on_type(4, "}", 2, 14), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(); + + let messages = talk(&session); + + let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response"); + let options = &initialize["result"]["capabilities"]["documentOnTypeFormattingProvider"]; + assert_eq!(options["firstTriggerCharacter"], "\n", "on the wire: {options:#?}"); + assert_eq!( + options["moreTriggerCharacter"], + serde_json::json!([";"]), + "and the semicolon with it: {options:#?}" + ); + + let indent = messages.iter().find(|m| m["id"] == 2).expect("a response to the newline"); + let edits = indent["result"].as_array().expect("an array of edits"); + assert_eq!(edits.len(), 1, "{indent:#?}"); + assert_eq!(edits[0]["newText"], " ", "the block's own level: {indent:#?}"); + assert_eq!(edits[0]["range"]["end"]["character"], 0, "and only whitespace replaced"); + + assert_eq!( + new_text(&messages, 3), + "module m;\n always_comb begin\n x = 1;\n end\nendmodule\n", + "the `;` laid out the statement it ended" + ); + + let unknown = messages.iter().find(|m| m["id"] == 4).expect("a response to the `}`"); + assert_eq!(unknown["result"], serde_json::json!([]), "{unknown:#?}"); + assert!( + !messages.iter().any(|m| m["method"] == "window/showMessage"), + "a keystroke never speaks: {messages:#?}" + ); + + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn a_pushed_exclude_rebuilds_the_index_mid_session() { // The one link a unit test cannot check: that the notification handler diff --git a/docs/features/lucisv-server/README.md b/docs/features/lucisv-server/README.md index 4ecef74..724e7bc 100644 --- a/docs/features/lucisv-server/README.md +++ b/docs/features/lucisv-server/README.md @@ -18,6 +18,7 @@ looks like language knowledge in here is a bug or a `Handshake` request. |---|---|---| | `textDocument/formatting` | `vlog_formatter::format_source` | One whole-document `TextEdit`, and only when the text actually changed | | `textDocument/rangeFormatting` | `vlog_formatter::format_range` | Same edit shape; the LSP `Range`'s *lines* become the engine's `--lines` (round 18) | +| `textDocument/onTypeFormatting` | `vlog_formatter::format_range` (for `;`); the token stream (for `\n`) | Two triggers, and only two. `;` range-formats the statement it ended, through the *same* engine `rangeFormatting` runs, over the `;`'s own line. `\n` re-indents the line it opened from block nesting — new logic outside the verified engine, so its edit can structurally only replace that one line's leading whitespace with spaces, and a corpus-wide agreement test forbids it from ever disagreeing with the printer. **Never speaks**: a refusal is `[]` with no `showMessage`, and a broken `lucisv.toml` is not reported here either (the dedup is re-armed by the `didChange` every keystroke produces). Advertised unconditionally — the client's own `editor.formatOnType` is the opt-in. See `docs/features/on-type-formatting/README.md` | | `textDocument/willSaveWaitUntil` | `vlog_formatter::format_source` | Format-on-save, protocol-native, for the editors that have no format-on-save of their own. **Off unless `lucisv.formatOnSave` is pushed**, and the decline is `null` — a capable client asks before every save, and a client with its own format-on-save would otherwise format twice. When on it is `textDocument/formatting` with a different trigger: the same engine, the same all-or-nothing edit, and the settings ladder minus its `tabSize` rung (the request carries no `FormattingOptions`). See `docs/features/will-save-wait-until/README.md` | | `textDocument/publishDiagnostics` | `vlog_parser::parse_source_tolerant` | Pushed on `didOpen`/`didChange`/`didSave`, once per notification — **only for a client that does not pull**. See `docs/features/pull-diagnostics/README.md` | | `textDocument/didChange` | `sync::apply_changes` | Incremental sync: the ranges are applied in order to the buffer the server holds, then one `set_document` + one `publish`. A rangeless change still replaces the whole buffer, so a full-sync client is unaffected. See `docs/features/incremental-sync/README.md` | diff --git a/docs/features/on-type-formatting/README.md b/docs/features/on-type-formatting/README.md new file mode 100644 index 0000000..e25d1ae --- /dev/null +++ b/docs/features/on-type-formatting/README.md @@ -0,0 +1,635 @@ +# on-type formatting + +## Goal + +Serve `textDocument/onTypeFormatting` — the request a client sends as the user +types, on the characters the server nominated. For a formatter-first server it +is a conspicuous absence: an editor that indents Verilog by copying the line +above is an editor that fights the formatter all day. But it is also the one +formatting entry that runs on code that is, by definition, half-written, and it +runs on a keystroke, so the design is deliberately narrow. **Two trigger +characters.** A `;` means a statement just ended, so the buffer is often whole +again — that one goes straight through `format::range_formatting`, the same +verified, all-or-nothing engine `textDocument/rangeFormatting` runs, over the +`;`'s own line, and adds no formatting logic of its own. A `\n` means *nothing* +is finished, so nothing is formatted: all it answers is the new line's +indentation, computed from block nesting over the token stream, and the edit it +returns can by construction touch nothing but the whitespace at the head of that +one line. A keystroke this cannot answer confidently answers nothing at all — no +edit, and no message. + +## Assumptions + +- **The client has already opted in, so the capability is unconditional.** No + `lucisv.*` setting gates this, unlike `willSaveWaitUntil`'s + `lucisv.formatOnSave`. On-type formatting fires only where the *client's* own + switch is on — `editor.formatOnType` in VS Code, off by default; a `nil` + `on_type` handler in Neovim's built-in client unless the user wires one — so a + request arriving here is already a request the user asked for. Gating it a + second time server-side would mean a user who turned it on in their editor and + got nothing. +- **`}` and `)` are not triggers, on purpose.** SystemVerilog closes its blocks + with the *word* `end`, and the only way to trigger on a word is to trigger on + its last letter — which means running this on half of every identifier. `)` + closes a port list mid-header as often as it closes anything, and there is + nothing finished to lay out there. Two characters is the whole set, and the + capability test pins it. +- **Silence on a refusal, and this is the deliberate opposite of every other + formatting entry.** `textDocument/formatting` shows an ERROR when the engine + declines, and `willSaveWaitUntil` shows one per save — both correct, because + both are moments the user explicitly asked lucisv for something and deserves to + know they did not get it. A keystroke is not such a moment. Mid-edit code the + strict parser refuses is the *normal* state of a buffer being typed into, and a + popup the user cannot type past, arriving on every semicolon, is a modal + dialog, not a diagnostic. +- **No broken-`lucisv.toml` warning either — and this is a finding, not an + omission.** The lead's design asked for `warn_about_config` here on the + grounds that its dedup is per buffer state. It is (QA proved that on the + will-save round: `config_warnings` is cleared by `set_document`) — and that is + exactly why it cannot be used here. An on-type request follows, by definition, + the `didChange` the user's own keystroke produced, so the dedup has just been + re-armed every single time. Calling `warn_about_config` from this handler would + produce **one popup per character typed**. The user is told about a broken + config on their next explicit format or save, which are the two moments they + asked. Pinned by `a_broken_config_is_never_reported_from_a_keystroke`, which + drives three keystrokes silently and then one `textDocument/formatting` that + speaks once. +- **`FormattingOptions` are carried, so the full ladder runs.** Unlike + `willSaveWaitUntil`, this request has an `options` field, so + `format::settings_for` is called exactly as `textDocument/formatting` calls it: + `lucisv.toml` > pushed `lucisv.*` > the editor's `tabSize` > the built-in + default. No `settings_without_editor_options` here. +- **The indent is always spaces.** The printer writes spaces + (`Printer::newline`), and `config_from` already refuses a client's + `insertSpaces: false` before a width ever reaches this code. So "tabs vs + spaces per the settings ladder" resolves to: hard tabs fall through to the + built-in width, in spaces — which is what a whole-file format would have + written on the same line. +- **The blank line the user opened really does get whitespace written onto it.** + That is what on-type indentation *is* — the cursor is sitting there — and it is + what every editor's own auto-indent already does. A later whole-file format + strips it again. +- **`\n` after `end` answers the outer level, and the user typing `else` next + will be one level out.** The formatter writes `end else begin` on one line, so + a user who puts them on separate lines is already writing something a format + will rejoin; the nudge is whitespace-only either way. +- **A `;` reply is a whole-document edit.** That is `range_formatting`'s reply + shape, unchanged — the engine's contract is all-or-nothing over the file, and + what makes it a *range* format is which constructs it laid out, not which bytes + it was allowed to replace. It arrives on a keystroke, which is more bytes on the + wire than an indent edit; it is the same number of bytes `rangeFormatting` + already sends for a cursor on that line. + +## The `\n` indent model + +### What it is allowed to do + +A pure function, `level_at(doc, content) -> Option`, over `doc.tokens`. +Its answer becomes an edit whose range runs **from column zero of one line to +that line's first non-whitespace character**, with `" ".repeat(level * width)` +as its text. Nothing else in the buffer is nameable from `indent_edit`, so no +future widening of the model below can make this path move code. Asserted +structurally by `an_indent_edit_can_only_ever_replace_leading_whitespace`, which +walks every line of a file with a bit of everything in it and checks the range's +end never passes the line's own indent and the text is spaces. + +`None` — no edit — is the answer wherever answering would mean guessing. It is +also the answer when the line is already right, and the caller cannot tell the +two apart, which is the point: idempotency is then structural. Applying the edit +and asking again at the same position returns nothing +(`applying_the_edit_leaves_the_next_ask_nothing_to_do`). + +### The model + +One forward scan over the token stream up to the line's first non-whitespace +byte, carrying a stack of two kinds of frame: + +| frame | pushed by | popped by | +|---|---|---| +| `Block` | a scope-opening keyword, as `pairs::opens_scope_at` judges it | its own closing keyword | +| `Hanging` | a header whose one-statement body follows it — `if (c)`, `for (…)`, `else`, `always_ff @(…)`, a bare `@(…)`/`#5`, a `case` item's `:` | the `;` that ends that statement, or the `end` of the block that turned out to be it | + +The level is the stack depth. A line that *starts* with a closing keyword steps +back out to that keyword's opener, which is what makes typing `end` on a fresh +line land right. + +Four rules earned their place against the real formatter rather than by +reasoning, and each is pinned by a test: + +- **Only `begin` is cuddled.** `vlog_formatter`'s `stmt_as_body` joins a + `begin`…`end` onto the header before it and nothing else — *not* `fork`, the + other block delimiter. So `if (c) begin` puts its contents one level in, while + `if (c) fork` puts the `fork` one level in and its contents two. + `only_begin_is_cuddled_onto_the_header_before_it` asserts this against the + engine, so the day that changes, this model is told. +- **`else if` is one rung.** The `else` pushes nothing when an `if` follows it; + the `if` pushes the level the branch's body gets. Pushing at both would indent + the chain twice. +- **A dangling `else` ends the chain it was already in.** SV's `else` binds to + the innermost `if` that has not got one yet, so an `else` written *after* a + branch that was itself an `else` belongs to something further out — and the + levels around it come off. `Frame::Hanging::from_else` carries that one bit, + and `Frame::Block::from_else` carries it across the `begin` that replaced the + hanging. Found by the corpus test on `picorv32/testbench_wb.v:232`. +- **A case item's `:` is a level.** `A:` on its own line puts its statement one + further in, exactly as an `if` does. It is recognised by there being nothing + between the `:` and the `case` scope itself, which is also what keeps a `?:` + inside that statement from being mistaken for one. + +### What it declines, and why + +Roughly a third of the lines of the checked-in corpus. Each is a place where +what the formatter writes is not a function of nesting: + +| declined | why | +|---|---| +| any open `(`, `[`, `{` | a wrapped port list or expression is laid out by width | +| the middle of a statement | same: `assign a =\n b + c;` is a printer decision | +| the interior of a block comment | the formatter re-indents a comment as a whole, by its opening column | +| a line opening inside a token | a `` `define `` continued with `\`, a string carried across the break | +| a line starting with punctuation | `module top\n import p::*;\n#(` — the header continues at column zero | +| inside `covergroup`/`property`/`sequence` | `ItemKind::Verbatim`: the user's own bytes are what a whole-file run emits | +| inside an `assert`/`assume`/`cover`/`restrict`/`expect` statement | verbatim too, and it closes with no keyword — `assert (c) p; else begin … end` runs past the `;`, so it is a span the scan is silent over rather than a level on the stack | +| a buffer that does not lex | there is no token stream to read | +| `always_comb` followed on the next line by `begin` | the formatter always joins those two, so a file where they are apart is not one this can reason about | +| a `` `ifdef `` standing where a statement body belongs | directive splitting decides that shape, not this | + +And the honest gaps — things the model *could* grow to know and does not: + +- `wait`, `do` and the assertion keywords are not headers, because they spell + headers that are not always headers (`wait fork;`, `do begin … end while (c);`). +- A statement beginning with `#`, `@` or `->` on its own line is declined by the + punctuation rule even where the level would be right. +- A macro item's *arguments* are one token to the lexer, so a macro call wrapped + across lines declines (correctly, but by the straddle rule rather than by + knowing anything about it). + +### The anchor + +`the_model_never_disagrees_with_the_formatter_on_formatted_corpus_code` is what +keeps two pieces of indent logic — the printer's, driven by the AST and by line +width, and this one, driven by the token stream — from drifting. It formats every +file of the checked-in corpus with the real engine and then asks the model, at +every line of the output, what it would do there. **It may decline; it may not +disagree.** As shipped: 77 528 lines answered, 36 647 declined, **0 +disagreements**. The test also asserts a coverage floor (>50 000 lines, >60% of +them answered), because a model that declined everywhere would pass the first +assertion and be worth nothing. + +Every decline in the table above except the last two was *found* by that test, +not anticipated. + +## The `;` path + +`format::range_formatting(doc, config, )`. That is the whole +of it: the verified engine, the all-or-nothing contract, `Ok(None)` → `[]`, +`Err` → `[]` and silence. + +Two gates in front of it, both cheap: + +1. **The trigger character has to be where the client said it is.** The token + ending at the request's offset must be a `;` the lexer saw. A `;` inside a + string or a comment ends no statement. +2. **The engine is the authority on everything else.** `format_range` strict- + parses the whole buffer and refuses on any error, then verifies its own output + for equivalence and convergence. + +**Deviation from the lead's design, logged.** The design said to find the +statement covering the `;` in the AST and use *its* line span, answering empty +when nothing covers it. The range shipped is the `;`'s **own line** instead, for +two reasons. First, it is not narrower: `format_range` selects by *unit*, so any +line of a statement selects the whole statement — the two requests have the same +answer wherever both are defined. Second, the enclosing-node version is wrong in +a case that is easy to hit: the `;` that closes `module m (\n input a\n);` +belongs to no statement at all, and the innermost node covering it is the +*module*, whose line span is the whole file's worth of body. Naming that on a +keystroke would ask for a whole-module reformat. +`a_semicolon_closing_a_module_header_lays_out_the_header_and_not_the_body` +pins the shipped behavior. The AST gate itself was dropped rather than +reimplemented because it can only decline what the verified engine already +accepts — it would be a second, weaker source of truth about "is this a +statement", which is the drift CLAUDE.md warns about. + +## Safety + +`verify.rs` was not touched: no normalization was added, broadened or weakened, +so CLAUDE.md hard invariant #4 does not apply to this round. + +- **The `;` path** is `format::range_formatting`, unchanged — the same call + `Server::range_formatting` makes, so the same `format_range` → + `verify_equivalence` + `verify_convergence` chain. There is no way to reach the + printer from this feature except through it. +- **The `\n` path never reaches the formatter at all.** It is new logic outside + the verified engine, which is why its guarantee is structural rather than + verified: `indent_edit` can only construct a range ending at the line's first + non-whitespace character, and can only fill it with spaces. A bug in + `level_at` is a wrong *indent*, never a moved byte. The corpus anchor is what + makes the indent right; the structure is what makes a wrong one harmless. +- **Idempotency** holds by construction (the edit is computed from a comparison + against what is already there) and is asserted through the real path. + +## Handshakes + +- **Consumes `format::range_formatting`** unchanged, and `format::settings_for` + unchanged — the same two calls `Server::range_formatting` makes, in the same + order, so the two paths cannot drift. No new function was added to `format.rs`. +- **Consumes `pairs.rs`'s keyword tables**, which needed three items made + `pub(crate)`: `closer_keyword`, plus two new one-line accessors, + `opens_scope_at(tokens, i)` (`opener_rule` + `opens_a_scope` asked as one + question) and `starts_a_prototype(text)`. Nothing in `pairs.rs`'s behavior + moved and no test there changed. **This is the point**: `RULES` and + `opens_a_scope`'s exception list must have one reader's answer, or the matcher + and the indent model would disagree about what a `function` inside an `extern` + declaration is, and every line below it. +- **Does *not* consume `pairs::analyze`.** The matched-pair list would give block + nesting for free, but not the `Hanging` levels, and the two would have to be + reconciled anyway; one scan that produces both is simpler than two that must + agree. +- **Does not consume `Server::edits` or `Server::warn_about_config`.** Both are + about telling the user something, and this path deliberately tells them + nothing — see Assumptions. The handler is five lines and returns + `to_value(edits)` directly. +- **Changes what the client is told at `initialize`:** + `document_on_type_formatting_provider` moves from `None` to + `DocumentOnTypeFormattingOptions { firstTriggerCharacter: "\n", + moreTriggerCharacter: [";"] }`. Nothing else in `capabilities()` moves. +- **No editor packaging change.** `vscode-languageclient` registers the on-type + feature from the advertised capability on its own, and gates it on the user's + `editor.formatOnType`; there is no `lucisv.*` setting to declare. Neovim's + built-in client is the same story with `vim.lsp.formatexpr`. +- **No other crate is touched, and no new dependency.** + +## Status / TODO + +- [x] Advertise `documentOnTypeFormattingProvider` with `"\n"` + `[";"]`. +- [x] `OnTypeFormatting` dispatch arm + `Server::on_type_formatting`. +- [x] `on_type.rs`: the two paths, and the nesting model. +- [x] `pairs.rs`: `closer_keyword`, `opens_scope_at`, `starts_a_prototype` made + `pub(crate)`; no behavior moved. +- [x] The structural guarantee (range ends at the first non-whitespace byte; + text is spaces), asserted over every line of a mixed file. +- [x] Idempotency through the real path. +- [x] The corpus agreement anchor, with a coverage floor so it cannot pass + vacuously. +- [x] `only_begin_is_cuddled_onto_the_header_before_it` — the engine assumption + the model rests on, asserted against the engine. +- [x] Unit tests: `\n` after `begin`/`module`/`end`/case item/one-statement + body; open brackets, wrapped expressions, comment interiors, punctuation + lines, verbatim scopes, assertions, macro items, unlexable buffers, + straddling tokens; `;` completing a statement, matching + `range_formatting` byte for byte; `;` in garbage, in a string, in a + comment, and where the client said wrongly; tabs vs spaces per the + ladder; UTF-16 positions; the empty buffer; unknown triggers. +- [x] Server-level: dispatch, settings ladder, no `showMessage` on refusal, no + config warning ever, unopened buffer, unknown trigger. +- [x] e2e: capability on the wire, both triggers round-tripped over the real + binary with a `didChange` between them, and no `showMessage`. +- [x] `docs/features/lucisv-server/README.md` capability table. +- [x] TODO.md §9c item checked off. + +## Work log + +**2026-08-26 — dev.** Implemented in one round. One deviation from the design +(the `;` range) and one finding against it (the config warning), both argued +above; everything else as planned. + +- **`main.rs`**: one capability, plus + `on_type_formatting_asks_for_the_newline_and_the_semicolon_and_nothing_else`. + The trigger set is the feature, so it is pinned rather than left to the + `is_some()` line in `every_advertised_capability_is_implemented`. +- **`server.rs`**: one dispatch arm and one handler. The handler does *not* call + `edits()` or `warn_about_config()` — both would speak, and this path does not. + That is the single largest design decision in the round and it is argued in + Assumptions; the config-warning half is a correction to the lead's design that + I would flag for review even though I am confident in it. +- **`on_type.rs`**, 630 lines of code and 480 of tests. Structure is: the two + entry points first (they are what a reader wants), the model second. The + `Scan` struct owns the whole state machine, so the invariant "the stack is + only ever pushed from `keyword`/`symbol`/`in_header`" is readable in one + screen. +- **The model was built against the corpus, not against my reading of + `format.rs`.** I wrote the first version from the token stream, then ran the + agreement test and fixed what it found, in this order: block-comment interiors + (1), lines starting with punctuation (2), assertion statements (3), macro items + with no `;` (4), bare timing controls (5), `fork` not being cuddled (6), case + items carrying a level (7), the `;`/`end` before an `else` (8), the dangling + `else` ending a chain (9), and `` `ifdef `` as a statement body (10). Nine of + those ten I would not have predicted. Two of them — (6) and (9) — were plain + bugs that would have shipped as wrong indents on common code, and (6) in + particular came from an assumption I had reasoned my way into (`begin` and + `fork` are "the same kind of thing", which is true for the rainbow and false + for `stmt_as_body`). The anchor earned its keep before it was ever a + regression test. +- **One real bug the anchor caught mid-round**: the first `end_branch` used + `stack.pop()` inside an `if let`, which pops unconditionally and then declines + to match — so a `;` before an `else` could pop a *`Block`* frame. The corpus + test went from 0 disagreements to 28 in one file and named the shape. +- `is_rainbow` in `pairs.rs` was briefly renamed to `is_block_delimiter` while I + believed the rainbow's list and the cuddling rule were the same question. They + are not (finding 6), so the rename was reverted and `on_type.rs` asks its own + one-line `is_begin` with the reason attached. `pairs.rs`'s diff is now three + visibility changes and two new accessors — nothing else. +- **Tests: 34 unit (`on_type.rs`) + 1 capability (`main.rs`) + 7 server-level + (`server.rs`) + 1 e2e = 43 new.** The corpus agreement test runs in ~30 s, + which is most of the `lucisv_server` unit binary's runtime; it is worth it, and + it skips cleanly when `corpus/` is not checked out like every other corpus + test. +- Nothing outside `crates/lucisv_server` changed in code. The two documentation + files touched outside this feature dir (`TODO.md`, + `docs/features/lucisv-server/README.md`) are additions in the house style; no + QA log or Review section anywhere was edited. + +## QA log + +**2026-08-26 — QA.** Re-ran every gate, attacked both paths along the lines +the lead asked for, added six tests where coverage was thin, found no +correctness bug. Verdict: **committable as-is.** + +### Gates + +- `cargo fmt --all -- --check`: clean. +- `cargo clippy --all-targets`: clean, no warnings. +- `cargo test --workspace`: green, three full runs (before my changes, after, + and a final rebuild). Counts stable across runs: + `lucisv_server`'s unit binary went from 865→871 passed (+6, my additions), + 0 failed, 4 ignored, in every run. +- `cargo test -p vlog_formatter`: 180 passed (31+1+4+6+2+22+114), matching the + dev's count exactly. This crate has zero diff in this round — confirmed via + `git diff --stat`, which does not list it. +- `cargo build && node editors/vscode/smoke.js target/debug/lucisv-server`: + `smoke: OK`. +- **Corpus anchor runtime**: isolated with + `cargo test -p lucisv_server --bin lucisv-server on_type::tests::the_model_never_disagrees_with_the_formatter_on_formatted_corpus_code`, + it is **31.2s** on its own, while the other 868 tests in that same binary + together take well under 1s (32.07s total for 869 tests). It dominates the + binary exactly as the dev said. Ran 3 times total (once inside each full + workspace run, once isolated): identical every time — 77 528 answered, + 36 647 declined, 0 disagreements. + - On "should it be `#[ignore]`-gated like other corpus tests": I checked + the repo's actual convention. `vlog_semantic/tests/corpus.rs` and + `vlog_refactor/tests/corpus.rs` are plain `#[test]` (not ignored) but + live in their own `tests/*.rs` integration binary, separate from that + crate's `--lib` unit tests, and cost well under 4s each. The one + precedent for an expensive test embedded in *this* crate's own module + tree is `includes.rs`'s + `perf::building_the_graph_over_the_whole_corpus_is_milliseconds`, which + *is* `#[ignore]`d — but that one is a benchmark assertion, not a + correctness gate. + - `lucisv_server` is a `[[bin]]`-only crate (`crates/lucisv_server/Cargo.toml` + has no `[lib]` target), and `level_at`/`Scan`/`Frame` are private to + `on_type.rs`. There is structurally no way to move this test into a + `tests/corpus.rs` the way `vlog_semantic`/`vlog_refactor` do it — an + integration test in `tests/` can only reach the binary's public surface + (e2e-style, over stdio), not a private module's functions. So the + placement is forced by the crate's shape, not a shortcut. + - Given that, and given this is the regression guard the whole `\n` design + leans on (the doc's own words: "the anchor earned its keep before it was + ever a regression test"), I'd lean toward leaving it un-ignored — an + `#[ignore]`d correctness gate is a gate nobody runs by default, which is + a worse trade than 31s. But the cost is real and will be paid on every + `cargo test -p lucisv_server` from now on; flagging for the lead's call + rather than deciding it myself. + +### Attack surfaces + +1. **Structural confinement of the `\n` edit — verified clean, one gap + filled.** Traced `indent_edit` (`on_type.rs:98-122`) by hand: + `content` is always `line.start + (bytes matched by + text.trim_start_matches([' ', '\t']))`, and the returned range is always + `{start: (line, 0), end: position(content)}` — there is no path from + `level_at`'s return value into the range, only into `new_text`, which is + itself always `" ".repeat(n)`. A regression in the nesting model literally + cannot compile into a wider range; the property is enforced by the type + signature of `level_at` (`Option`, not `Option`), not just by + the existing `an_indent_edit_can_only_ever_replace_leading_whitespace` + test. + - **CRLF**: `vlog_parser::LineIndex` keeps `\r` as an ordinary trailing byte + of the line it ends (confirmed against `line_index.rs`'s own + `crlf_puts_the_carriage_return_in_the_line` test) — `indent_edit`'s + `trim_start_matches([' ', '\t'])` doesn't recognize `\r` either, so a + blank CRLF line's "content" offset lands exactly *on* the `\r`, giving a + zero-width insertion immediately before it. Traced by hand and confirmed + empirically: added + `a_crlf_line_ending_is_never_touched_by_the_edit` (`on_type.rs:932`, two + cases: bare `\r` and `\t\r`) — **there was no CRLF coverage anywhere in + the file before this**, despite this being exactly the shape the round's + own structural-guarantee argument rests on being airtight for. Passes. + - **Form feed / vertical tab in the indent**: traced rather than tested — + the raw lexer's `skip_whitespace` (`vlog_parser/src/lexer.rs:127`) only + skips `' '`/`'\t'`/`'\r'`/`'\n'`; a bare FF/VT anywhere in code context + hits the `unexpected character` error path (`lexer.rs:413`), which fails + `tokenize()` for the *whole* document (propagated by the `?` in + `tokenize`, `lexer.rs:735`), which empties `doc.tokens` + (`state.rs:59-65`), which makes `level_at`'s first guard + (`on_type.rs:225`) return `None` for every line of that buffer. So this + shape degrades to the already-tested "buffer that does not lex" case + rather than a new one — conservative, not wrong. Did not add a + dedicated test since it collapses to an existing one; noting the chain + here in case a future change to the lexer's whitespace set makes FF/VT + legal (it would then need the same treatment CRLF just got). + - **Position desync (trigger claims `\n`, cursor mid-line)**: already + covered by `a_line_the_cursor_is_past_is_not_re_indented` and + `the_first_line_of_a_buffer_is_never_a_new_line`. Note in passing: the + `line.start == 0` half of the guard at `on_type.rs:103` is dead in + practice — for any `line > 0`, `LineIndex`'s own construction guarantees + the preceding byte is `\n` (it only ever records a line start right + after one), so the second half of that `||` can never itself be false + without the first half also being true for `line == 0`, and is only + reachable at all when `line == 0`. Harmless (redundant, not wrong), not + worth a finding beyond noting it. + - **Mixed tab/space indent**: added + `a_mixed_tab_and_space_prefix_is_measured_in_bytes_not_visual_columns` + (`on_type.rs:961`) — nothing before this exercised more than one + whitespace kind in a prefix at once. Passes; byte and UTF-16 counts + agree because tab and space are both one of each. + +2. **The `;` gate — verified clean, two gaps filled.** + - `;` inside a string/comment: already tested + (`a_semicolon_the_lexer_never_saw_ends_no_statement`). + - `;` as the last character of a macro body: **untested before this + round.** Traced `vlog_parser/src/lexer.rs` — a `` `define `` (with or + without `\`-continuations) is lexed as one `Directive` token end to end + (confirmed against the lexer's own + `toks[0].text == "`define A \\\n x \\\n y"` tests around + `lexer.rs:871-882`), so a `;` inside its body is never a standalone + `Symbol(";")` token — `statement_edit`'s `.find(|t| t.span.end == + offset)` either finds nothing or finds the `Directive` itself, and + `typed.is_sym(SEMICOLON)` is false either way. Added + `a_semicolon_ending_a_macro_definitions_body_ends_no_statement` + (`on_type.rs:1168`). Passes. + - `;` at EOF with no trailing newline: **untested before this round.** + Added `a_semicolon_at_eof_with_no_trailing_newline_still_lays_out_its_line` + (`on_type.rs:1130`). Passes, and confirms a detail worth recording: the + reply's `new_text` gets the file's final `\n` restored (the engine's own + canonicalization, not something this path invented) — consistent with + `range_formatting`'s "whole-document edit" contract, not a new behavior. + - Off-by-one (client says wrong offset): already tested + (`a_semicolon_that_is_not_where_the_client_said_answers_nothing`). + - Byte-identity with the real handler: confirmed + `a_semicolon_answers_exactly_what_range_formatting_of_that_line_answers` + calls `format::range_formatting` directly — the identical function + `Server::range_formatting` calls (`server.rs:627`), not a + reimplementation. Both call sites pass `doc`, `settings.config`/`config`, + and a `Range` straight through with no branching in between. + +3. **The corpus anchor's honesty — verified clean.** Reads real corpus files, + runs the real `vlog_formatter::format_source` over each + (`on_type.rs:986`), and asks the *private* `level_at` at every formatted + line — not a reimplementation, not a fixture. Coverage floor is a real + minimum: `assert!(answered > 50_000, ...)` and `assert!(share > 0.6, ...)` + (`on_type.rs:1021-1023`) both fire on the actual counts, and I confirmed by + inspection that `declined` is incremented independently of `answered` (a + model that always returned `None` would drive `answered` to 0 and fail the + floor, not pass vacuously). Skips loudly and returns early + (`eprintln!("corpus/ not checked out...")`) matching the exact convention + in `vlog_refactor/tests/corpus.rs` and `vlog_semantic/tests/corpus.rs`. Ran + 3 times total across this session (2 full-workspace runs + 1 isolated): + identical counts every time (77 528 / 36 647 / 0). + +4. **Idempotency through the real path — verified clean, with a nuance + worth recording.** `applying_the_edit_leaves_the_next_ask_nothing_to_do` + applies the edit with string arithmetic, but the *state update* it feeds + back through is `Workspace::set_document` via the test's `with()` helper — + and `Server::set_document` (`server.rs:1207-1209`, the function + `did_change` calls at `server.rs:943`/`950`) is a one-line forward to that + exact same `Workspace::set_document`. So the re-lex/re-analyze pipeline + this test exercises after "applying" the edit is byte-for-byte what a real + `didChange` triggers — the string arithmetic only stands in for what an + editor's own buffer would do, which nothing server-side can avoid in a + unit test. What is *not* covered end-to-end: the e2e test + (`typing_a_newline_and_a_semicolon_round_trips_over_the_real_binary`) + never applies a returned edit and re-asks at the same position over the + real binary — its two `on_type` calls are against two independently + constructed buffer states, not "type, apply, retype." Low severity (the + unit-level test already exercises the real state machinery faithfully), + not blocking, but noting it as a gap for a future e2e round rather than + fixing it myself — it would mean growing the e2e test with an "apply the + edit into the next full_change" helper, which is more than a one-line + fix. `;` idempotency is adequately shown by + `an_already_laid_out_statement_gets_no_edit` (same buffer content as after + applying the fix, semicolon retyped, no edit). + +5. **No-popup design — verified clean.** + `a_broken_config_is_never_reported_from_a_keystroke` drives three `\n` + keystrokes through a buffer with a broken `lucisv.toml` and asserts + `session.shown()` stays empty each time, then a `textDocument/formatting` + on the same buffer and asserts exactly one `unknown key `bogus`` message — + both directions, in one test, as asked. + `a_keystroke_the_engine_refuses_is_answered_with_silence_and_not_a_popup` + does the same contrast for a plain refusal (not a config problem). `git + diff` on `will_save_wait_until`'s body: empty — the only lines the diff + touches in `server.rs` near it are import-list reflows (alphabetical + insertion of `OnTypeFormatting`/`DocumentOnTypeFormattingParams` pushed + other names to new lines) and the new `on_type_formatting` method + its + dispatch arm + its own tests. Confirmed by reading the full `server.rs` + diff, not just grepping for the function name. + +6. **`pairs.rs` accessors — verified clean.** Full diff is three visibility + changes to one existing private fn (`closer_keyword`, private → `pub(crate)`, + no line of its body changed) plus two new one-line-bodied accessors + (`opens_scope_at`, `starts_a_prototype`) that each call existing private + functions (`opener_rule`, `opens_a_scope`, and the `PROTOTYPE_STARTERS` + table) with no new logic. All 65 `pairs::tests::*` tests pass, and the + diff has zero edits to any existing line — additions only, confirmed by + reading the full diff rather than just the stat. + +7. **Settings ladder — verified clean.** `on_type.rs`'s + `the_indent_width_is_the_one_the_settings_resolved_to` and + `a_tab_indented_line_is_replaced_with_the_spaces_the_formatter_writes` + cover the `\n` side; `server.rs`'s + `a_keystroke_climbs_the_same_settings_ladder_a_manual_format_does` drives + the full ladder (editor `tabSize` → pushed `lucisv.indent` → hard-tab + rejection → built-in default) through the real dispatch, in the same + order `format::settings_for`'s own doc comment states and the same order + `willSaveWaitUntil`'s round tested it in. + +8. **CLAUDE.md compliance — verified clean.** No `unwrap()`/`expect()`/ + `panic!` outside `#[cfg(test)]` in any changed file (checked + `on_type.rs`, the diff hunks of `server.rs`/`main.rs`/`pairs.rs` + individually). Every new public/`pub(crate)` item carries a doc comment. + `docs/features/on-type-formatting/README.md`'s eight required sections + (`Goal`, `Assumptions`, `Handshakes`, `Status / TODO`, `Work log`, `QA + log`, `Review`) each appear exactly once (`grep -n '^## '`). `TODO.md`'s + §9c item text is intact verbatim, checkbox flipped, `→ delivered...` note + appended below it — matches the house style already used elsewhere in + that file. `git diff -- crates/vlog_formatter/src/verify.rs` is empty: + invariant #4 does not apply, confirmed rather than taken on the dev's + word. + +### Beyond the list + +- **A file that is one giant `` `ifdef ``-guarded block**: added + `a_module_wrapped_whole_in_an_ifdef_guard_indents_by_its_own_nesting` + (`on_type.rs:1145`) — conditional compilation directives push/pop nothing + on the stack (`Scan::step`'s `TokenKind::Directive => At::Boundary` arm), + so nesting inside the guard is computed exactly as if the guard were + stripped. Passes. +- **`;` completing a statement whose line also holds a format-off fence**: + added `a_semicolon_inside_a_format_off_fence_rides_through_the_fence_untouched` + (`on_type.rs:1156`) — a messy, badly-spaced `wire` declaration inside a + `// verilog_format: off` / `// verilog_format: on` pair gets **no edit at + all** on a `;` typed at its end, because the `;` path is `format_range` + unchanged and the fence outranks the range there exactly as it does for + `textDocument/rangeFormatting`. Passes — confirms the fence "rides through" + claim rather than assuming it from the "no new formatting logic" argument. +- **Rapid-fire consecutive `\n` triggers**: the existing + `applying_the_edit_leaves_the_next_ask_nothing_to_do` already loops over + four consecutive lines, applying and re-asking each time, which is the + same state-consistency question a burst of `didChange`s would raise at the + state layer; did not find a reason to add a second version of this at the + e2e/wire level given the idempotency nuance already logged in (4). + +### Fixes made directly + +Six tests added to `crates/lucisv_server/src/on_type.rs`'s existing +`#[cfg(test)] mod tests`, all passing, no production code changed: +`a_crlf_line_ending_is_never_touched_by_the_edit`, +`a_mixed_tab_and_space_prefix_is_measured_in_bytes_not_visual_columns`, +`a_semicolon_at_eof_with_no_trailing_newline_still_lays_out_its_line`, +`a_module_wrapped_whole_in_an_ifdef_guard_indents_by_its_own_nesting`, +`a_semicolon_inside_a_format_off_fence_rides_through_the_fence_untouched`, +`a_semicolon_ending_a_macro_definitions_body_ends_no_statement`. Ran +`cargo fmt --all` once to settle the one line these additions pushed over the +width limit (`on_type.rs`, the `ifdef` test's `text` binding) — no other +formatting drift. + +### Verdict + +**Committable as-is.** No correctness bug found in either path; the +structural-confinement claim for `\n` holds under CRLF, mixed-tab, and +FF/VT attack, and the `;` gate holds under macro-body, EOF, and fence +attack. Two items for the lead's attention rather than blockers: the corpus +anchor's runtime/placement tradeoff (§ Gates, above), and the untested +apply-then-retype idempotency gap at the e2e level (§4, above). + +## Review + +### 2026-08-26 — lead + +Reviewed the diff, the work log and the QA log; re-ran all gates myself +(including the formatter's own 8 suites — untouched and green), clean. +This is the round I was most prepared to reject, and it earned the +opposite: the `;` path adds zero new formatting authority (the verified +engine, gated by one lexer fact), and the `\n` path's edit is confined +to one line's leading whitespace by construction — I read +`indent_edit` myself and the range cannot name another byte. The corpus +anchor is the methodology prize of the whole audit: nine of the model's +ten rules were forced by disagreement with the real formatter rather +than predicted, it caught a real stack-pop bug mid-round, and its +coverage floor keeps it from ever passing by declining everything. + +Two lead rulings. First, the dev's refusal of my config-warning design +was correct and well-evidenced — the dedup re-arms on the very +didChange each keystroke produces, so the warning would fire per +character; the silent-keystroke/warning-on-request contrast is now +pinned in both directions and the README documents the reasoning better +than my brief did. Second, on QA's flagged 31-second anchor cost: it +stays as a normally-running test. It is a correctness gate over the one +piece of formatting logic that lives outside the verified engine, and +making it opt-in would trade the whole anchor for half a minute; the +binary-layout constraint QA traced (no [lib], private internals) means +moving it out would mean weakening it. If the suite's runtime ever +becomes a real complaint, the answer is a [lib] refactor, not an +#[ignore]. QA's six added tests (CRLF, mixed tabs, macro-body and +EOF semicolons, fence, whole-file ifdef) close the shapes the dev's +own sweep missed. Accepted as shipped.