LSP §9c: textDocument/onTypeFormatting — two triggers, one engine
';' range-formats exactly the finished statement's line through the existing verified all-or-nothing engine — no new formatting authority, gated on one lexer fact (the token ending at the offset is a real ';', so string/comment/macro semicolons decline). '\n' re-indents only the line the newline opened, via a token-stream nesting model whose edit is confined by construction to that line's leading whitespace — a model bug can be a wrong indent, never a moved byte. The path never speaks: no popups on refusal (it fires per keystroke), and the config warning is deliberately not raised here — its dedup re-arms on the didChange every keystroke produces, so it would fire per character; pinned in both directions (silent on keystrokes, still warning on requests). The nesting model was derived against the formatter itself: a corpus anchor test (77,528 lines answered, 67.9% coverage floor, 0 disagreements) forced nine of its ten rules and caught a real unconditional-pop bug mid-round. The anchor stays a normally-running test by lead ruling — it is the correctness gate over the one piece of formatting logic outside the verified engine. 49 tests added (dev 43 + QA 6: CRLF confinement, mixed tab/space, macro-body and EOF semicolons, format-off fence riding through, whole-file ifdef). verify.rs untouched; formatter suites untouched and green. docs/features/on-type-formatting/README.md Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
01c76067e8
commit
3bc61f9eab
8 files changed
+2247
-32
No files matched your search
@@ -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.
|
||||
|
||||
@@ -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]
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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)
|
||||
|
||||
@@ -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<Value, Failure> {
|
||||
let at = params.text_document_position;
|
||||
let Some(doc) = self.workspace.document(&at.text_document.uri) else {
|
||||
return to_value(Vec::<lsp_types::TextEdit>::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`
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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` |
|
||||
|
||||
@@ -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<usize>`, 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, <the `;`'s own line>)`. 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<usize>`, not `Option<Range>`), 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.
|
||||
Reference in new issue
Block a user