From 2ba995d1c96c61813ab7dc0cae0dc208038b7208 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Wed, 19 Aug 2026 11:11:23 -0700 Subject: [PATCH] Add server-lint: lint diagnostics and quick fixes in vfmt-server Lint warnings (code = rule name, source = vfmt) merge with parse errors into ONE publishDiagnostics through the single publish path -- the two-publish flicker bug is structurally impossible, pinned by an e2e asserting notification count. textDocument/codeAction offers a quickfix per Safe fix (byte-identical to vfmt check --fix, verified live) and source.fixAll.vfmt as one honest pass with no converge loop (the client's edit/re-lint cycle converges, verified at 3 rounds) and no claimed-resolved diagnostics list. context.only honored; tab width from vfmt.toml; module-filename speaks via the URI; waived violations never published; Unsafe fixes never offered. Filed, not papered over: a server fix can currently edit inside a // vfmt: off fence (the fence filter lives in crates/vfmt; a shared helper is the next round's top item -- no corruption possible since only Safe fixes exist, but the hands-off promise has a documented editor-side hole). Also filed: the per-keystroke second parse and a future vfmt.toml lint key. 108 vfmt_server tests (104 unit + 4 e2e). Dev: Opus agent; QA: Sonnet agent (every claim driven live over stdio); review in docs/features/server-lint/README.md. Co-Authored-By: Claude Fable 5 --- Cargo.lock | 1 + crates/vfmt_server/Cargo.toml | 1 + crates/vfmt_server/src/code_action.rs | 361 ++++++++++++++++++++ crates/vfmt_server/src/diagnostics.rs | 44 ++- crates/vfmt_server/src/format.rs | 32 ++ crates/vfmt_server/src/lint.rs | 143 ++++++++ crates/vfmt_server/src/main.rs | 35 +- crates/vfmt_server/src/server.rs | 42 ++- crates/vfmt_server/tests/e2e.rs | 82 +++++ docs/features/server-lint/README.md | 475 ++++++++++++++++++++++++++ docs/features/vfmt-server/README.md | 13 +- 11 files changed, 1210 insertions(+), 19 deletions(-) create mode 100644 crates/vfmt_server/src/code_action.rs create mode 100644 crates/vfmt_server/src/lint.rs create mode 100644 docs/features/server-lint/README.md diff --git a/Cargo.lock b/Cargo.lock index be7ae86..35aaad8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -240,6 +240,7 @@ dependencies = [ "serde_json", "vfmt_core", "vlog_formatter", + "vlog_linter", "vlog_parser", "vlog_semantic", ] diff --git a/crates/vfmt_server/Cargo.toml b/crates/vfmt_server/Cargo.toml index cc033cb..96eaa35 100644 --- a/crates/vfmt_server/Cargo.toml +++ b/crates/vfmt_server/Cargo.toml @@ -13,6 +13,7 @@ vfmt_core = { path = "../vfmt_core" } vlog_parser = { path = "../vlog_parser" } vlog_semantic = { path = "../vlog_semantic" } vlog_formatter = { path = "../vlog_formatter" } +vlog_linter = { path = "../vlog_linter" } lsp-server = { workspace = true } lsp-types = { workspace = true } serde = { workspace = true } diff --git a/crates/vfmt_server/src/code_action.rs b/crates/vfmt_server/src/code_action.rs new file mode 100644 index 0000000..7e60b60 --- /dev/null +++ b/crates/vfmt_server/src/code_action.rs @@ -0,0 +1,361 @@ +//! `textDocument/codeAction` — one quick fix per Safe lint fix, plus one +//! `source.fixAll.vfmt` that applies all of them in a single pass. +//! +//! Only **Safe** fixes are offered. `--unsafe-fixes` is a flag a CLI user types +//! on purpose; a lightbulb in an editor is not that, and a fix that may change +//! what the circuit does must not be one click away. (No rule ships an Unsafe +//! fix today, so this is a rule for the first one that does.) + +use std::collections::HashMap; + +use lsp_types::{ + CodeAction, CodeActionKind, CodeActionOrCommand, Range, TextEdit, Uri, WorkspaceEdit, +}; +use vlog_linter::{apply_fixes, rule_by_name, Applicability, Violation}; + +use crate::convert::Positions; +use crate::state::Document; + +/// The kind of the fix-everything action, namespaced under `source.fixAll` so +/// an editor's fix-on-save can name vfmt without also running another server's +/// fixer. +pub const FIX_ALL: &str = "source.fixAll.vfmt"; + +/// The actions available for `range` in a buffer. +/// +/// `only` is the client's filter; it is honored here rather than left to the +/// client, because a fix-on-save request asks for `source.fixAll.vfmt` alone +/// and computing every quick fix for it would be work nobody reads. +pub fn code_actions( + uri: &Uri, + doc: &Document, + range: Range, + only: Option<&[CodeActionKind]>, + tab_width: usize, +) -> Vec { + let positions = doc.positions(); + let violations = crate::lint::fixable(doc, tab_width); + let mut actions = Vec::new(); + if wanted(only, &CodeActionKind::QUICKFIX) { + let quick = violations.iter().filter_map(|v| quick_fix(uri, &positions, v, range)); + actions.extend(quick.map(CodeActionOrCommand::CodeAction)); + } + if wanted(only, &CodeActionKind::new(FIX_ALL)) { + actions.extend( + fix_all(uri, doc, &positions, &violations).map(CodeActionOrCommand::CodeAction), + ); + } + actions +} + +/// The quick fix for one violation, when it has a Safe fix and the client is +/// asking about a range its diagnostic touches. +fn quick_fix( + uri: &Uri, + positions: &Positions<'_>, + violation: &Violation, + asked: Range, +) -> Option { + let fix = violation.fix.as_ref()?; + if fix.applicability != Applicability::Safe { + return None; + } + let diagnostic = crate::lint::diagnostic(positions, violation); + if !overlaps(diagnostic.range, asked) { + return None; + } + let mut edits: Vec = fix + .edits + .iter() + .map(|(span, text)| TextEdit { range: positions.range(*span), new_text: text.clone() }) + .collect(); + // A fix's edits are a set; ordering them is for readability and for tests, + // not for correctness — LSP requires only that they never overlap. + edits.sort_by_key(|edit| (edit.range.start, edit.range.end)); + Some(CodeAction { + title: title(violation), + kind: Some(CodeActionKind::QUICKFIX), + diagnostics: Some(vec![diagnostic]), + edit: Some(workspace_edit(uri, edits)), + // A Safe fix addresses the finding completely, which is exactly what + // the spec says `isPreferred` means. + is_preferred: Some(true), + ..Default::default() + }) +} + +/// One action applying every Safe fix in the buffer, as a whole-document edit. +/// +/// **One pass, deliberately.** `vfmt check --fix` loops fix → re-lint until +/// nothing changes, because a pass skips a fix overlapping one already applied +/// (a line ending in a tab needs two rounds: `no-tabs` and +/// `no-trailing-whitespace` both want those bytes). An editor does not need +/// that loop: applying this edit changes the buffer, the change re-lints, and +/// the client asks again — the convergence arrives through the edit/re-lint +/// cycle the editor already runs, and one pass per request keeps every action +/// the user sees a description of the buffer in front of them. +/// +/// The edit is the whole document because that is what `apply_fixes` produces +/// and what it guarantees: a set of ranges assembled by hand could interleave +/// two fixes in a way the linter's own skip rule would have refused. +fn fix_all( + uri: &Uri, + doc: &Document, + positions: &Positions<'_>, + violations: &[Violation], +) -> Option { + let fixed = apply_fixes(&doc.text, violations, false); + if fixed.applied == 0 || fixed.output == doc.text { + return None; + } + let edit = TextEdit { range: positions.whole_document(), new_text: fixed.output }; + Some(CodeAction { + title: "vfmt: fix all auto-fixable lint violations".to_string(), + kind: Some(CodeActionKind::new(FIX_ALL)), + // No `diagnostics` list: one pass skips fixes that overlap an applied + // one, so this action cannot honestly name the findings it resolves. + edit: Some(workspace_edit(uri, vec![edit])), + ..Default::default() + }) +} + +/// A one-file workspace edit. +fn workspace_edit(uri: &Uri, edits: Vec) -> WorkspaceEdit { + WorkspaceEdit { changes: Some(HashMap::from([(uri.clone(), edits)])), ..Default::default() } +} + +/// The lightbulb's text: the rule's own one-line summary, and its name, which +/// is what the user would put in a waiver. +fn title(violation: &Violation) -> String { + let what = rule_by_name(violation.rule).map_or(violation.message.as_str(), |r| r.summary()); + format!("vfmt: {what} [{}]", violation.rule) +} + +/// Whether a client asking for `only` wants this kind. A filter is a prefix of +/// the kinds it selects (`source` selects `source.fixAll.vfmt`), and no filter +/// at all selects everything. +fn wanted(only: Option<&[CodeActionKind]>, kind: &CodeActionKind) -> bool { + let Some(only) = only else { return true }; + only.iter().any(|filter| { + let (filter, kind) = (filter.as_str(), kind.as_str()); + kind == filter || kind.strip_prefix(filter).is_some_and(|rest| rest.starts_with('.')) + }) +} + +/// Whether two ranges share a position. Touching counts: a cursor sitting at +/// the first character of a warning is asking about that warning. +fn overlaps(a: Range, b: Range) -> bool { + a.start <= b.end && b.start <= a.end +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::state::Workspace; + use lsp_types::Position; + use std::str::FromStr; + use vlog_linter::{default_rules, run}; + + fn uri() -> Uri { + Uri::from_str("file:///rtl/m.sv").expect("uri") + } + + fn workspace(text: &str) -> Workspace { + let mut ws = Workspace::default(); + ws.set_document(uri(), text.to_string()); + ws + } + + /// Every action offered for the whole buffer. + fn actions_of(ws: &Workspace) -> Vec { + let doc = ws.document(&uri()).expect("open"); + let whole = doc.positions().whole_document(); + code_actions(&uri(), doc, whole, None, 2) + .into_iter() + .map(|a| match a { + CodeActionOrCommand::CodeAction(action) => action, + CodeActionOrCommand::Command(_) => panic!("this server offers no commands"), + }) + .collect() + } + + /// The edits an action carries for this file. + fn edits_of(action: &CodeAction) -> Vec { + action + .edit + .as_ref() + .expect("an edit") + .changes + .as_ref() + .expect("changes") + .get(&uri()) + .expect("this file's edits") + .clone() + } + + /// The buffer an action's edits produce, applied by hand the way a client + /// would: every range refers to the original text, so they are applied + /// from the back. + fn applied(text: &str, action: &CodeAction) -> String { + let index = vlog_parser::LineIndex::new(text); + let positions = Positions::new(text, &index); + let mut edits = edits_of(action); + edits.sort_by_key(|edit| (edit.range.start, edit.range.end)); + let mut out = text.to_string(); + for edit in edits.iter().rev() { + let start = positions.offset(edit.range.start) as usize; + let end = positions.offset(edit.range.end) as usize; + out.replace_range(start..end, &edit.new_text); + } + out + } + + #[test] + fn a_tab_offers_a_quick_fix_that_produces_the_linters_own_output() { + let text = "module m;\n\twire a;\nendmodule\n"; + let ws = workspace(text); + let actions = actions_of(&ws); + let fix = actions.iter().find(|a| a.kind == Some(CodeActionKind::QUICKFIX)).expect("one"); + assert_eq!(fix.title, "vfmt: use spaces, not tabs [no-tabs]"); + assert_eq!(fix.is_preferred, Some(true)); + let diagnostics = fix.diagnostics.as_ref().expect("the finding it resolves"); + assert_eq!(diagnostics.len(), 1); + assert_eq!(diagnostics[0].code, Some(lsp_types::NumberOrString::String("no-tabs".into()))); + // The edit must reproduce what `vfmt check --fix` would have written. + let expected = vlog_linter::apply_fixes( + text, + &run(text, Some("/rtl/m.sv".into()), &default_rules()), + false, + ); + assert_eq!(applied(text, fix), expected.output); + } + + #[test] + fn a_violation_with_no_fix_offers_no_action() { + // `module-filename` deliberately ships no fix — renaming a file is not + // the linter's business, and it is certainly not the editor's. + let text = "module other;\nendmodule\n"; + let ws = workspace(text); + assert!(actions_of(&ws).is_empty(), "nothing to offer"); + } + + #[test] + fn only_the_violation_under_the_cursor_is_offered() { + let text = "module m;\n\twire a;\n\twire b;\nendmodule\n"; + let ws = workspace(text); + let doc = ws.document(&uri()).expect("open"); + let line1 = Range { + start: Position { line: 1, character: 0 }, + end: Position { line: 1, character: 0 }, + }; + let actions = code_actions(&uri(), doc, line1, Some(&[CodeActionKind::QUICKFIX]), 2); + assert_eq!(actions.len(), 1, "the cursor's line only: {actions:#?}"); + } + + #[test] + fn fix_all_applies_every_safe_fix_in_one_pass() { + let text = "module m;\n\twire a;\n wire b; \nendmodule\n"; + let ws = workspace(text); + let actions = actions_of(&ws); + let all = actions + .iter() + .find(|a| a.kind == Some(CodeActionKind::new(FIX_ALL))) + .expect("a fixAll action"); + assert!(all.diagnostics.is_none(), "one pass cannot claim a resolved list"); + let output = applied(text, all); + assert_eq!(output, "module m;\n wire a;\n wire b;\nendmodule\n"); + // And it is the linter's own answer, not a hand-assembled one. + let expected = vlog_linter::apply_fixes( + text, + &run(text, Some("/rtl/m.sv".into()), &default_rules()), + false, + ); + assert_eq!(output, expected.output); + } + + #[test] + fn fix_all_is_one_pass_and_the_next_request_finishes_the_job() { + // A line that is a tab *and* trailing whitespace: both rules want those + // bytes, so one pass applies one of them. The client applies the edit, + // re-lints, and asks again — which is the convergence loop, for free. + let text = "module m;\n\twire a;\t\nendmodule\n"; + let ws = workspace(text); + let first = actions_of(&ws); + let all = first + .iter() + .find(|a| a.kind == Some(CodeActionKind::new(FIX_ALL))) + .expect("a fixAll action"); + let once = applied(text, all); + assert_ne!(once, text, "a pass must make progress"); + + let ws = workspace(&once); + let again = actions_of(&ws); + let settled = match again.iter().find(|a| a.kind == Some(CodeActionKind::new(FIX_ALL))) { + Some(action) => applied(&once, action), + None => once.clone(), + }; + assert_eq!(settled, "module m;\n wire a;\nendmodule\n"); + // Third request: nothing left to offer. + let ws = workspace(&settled); + assert!(actions_of(&ws).is_empty(), "converged"); + } + + #[test] + fn a_clean_buffer_offers_nothing() { + let text = "module m;\n wire a;\nendmodule\n"; + let ws = workspace(text); + assert!(actions_of(&ws).is_empty()); + } + + #[test] + fn a_waived_violation_offers_no_fix() { + let text = "module m;\n\twire a; // vfmt: waive no-tabs\nendmodule\n"; + let ws = workspace(text); + assert!(actions_of(&ws).is_empty(), "a waiver silences the lightbulb too"); + } + + #[test] + fn the_clients_filter_is_honoured() { + let text = "module m;\n\twire a;\nendmodule\n"; + let ws = workspace(text); + let doc = ws.document(&uri()).expect("open"); + let whole = doc.positions().whole_document(); + let fix_all_only = [CodeActionKind::new(FIX_ALL)]; + let actions = code_actions(&uri(), doc, whole, Some(&fix_all_only), 2); + assert_eq!(actions.len(), 1, "no quick fixes when only fixAll was asked for"); + // `source` is a prefix filter for `source.fixAll.vfmt`. + let source = [CodeActionKind::SOURCE]; + assert_eq!(code_actions(&uri(), doc, whole, Some(&source), 2).len(), 1); + // And an unrelated filter selects nothing. + let refactor = [CodeActionKind::REFACTOR]; + assert!(code_actions(&uri(), doc, whole, Some(&refactor), 2).is_empty()); + } + + #[test] + fn the_fix_uses_the_indent_width_it_is_given() { + let text = "module m;\n\twire a;\nendmodule\n"; + let ws = workspace(text); + let doc = ws.document(&uri()).expect("open"); + let whole = doc.positions().whole_document(); + let actions = code_actions(&uri(), doc, whole, Some(&[CodeActionKind::QUICKFIX]), 4); + let CodeActionOrCommand::CodeAction(fix) = &actions[0] else { panic!("an action") }; + assert_eq!(applied(text, fix), "module m;\n wire a;\nendmodule\n"); + } + + #[test] + fn positions_are_utf16_after_multi_byte_content() { + let text = "module m;\n // é 🎉\twire a;\nendmodule\n"; + let ws = workspace(text); + let actions = actions_of(&ws); + let fix = &actions[0]; + let edits = edits_of(fix); + assert_eq!(edits.len(), 1); + assert_eq!(edits[0].range.start.line, 1); + assert_eq!(edits[0].range.start.character, 9, "UTF-16 units, not bytes"); + assert_eq!(edits[0].range.end.character, 10); + // The round trip: applying it must not disturb the multi-byte content. + let out = applied(text, fix); + assert!(out.contains("é 🎉"), "comments are never dropped: {out:?}"); + assert_eq!(out, "module m;\n // é 🎉 wire a;\nendmodule\n"); + } +} diff --git a/crates/vfmt_server/src/diagnostics.rs b/crates/vfmt_server/src/diagnostics.rs index d1d754e..9ab92c6 100644 --- a/crates/vfmt_server/src/diagnostics.rs +++ b/crates/vfmt_server/src/diagnostics.rs @@ -1,4 +1,4 @@ -//! Parse diagnostics, published on every buffer change. +//! Diagnostics, published on every buffer change. use lsp_types::{Diagnostic, DiagnosticSeverity}; @@ -6,7 +6,24 @@ use crate::state::Document; /// The source string every diagnostic this server publishes carries, so a /// user can tell ours from another server's. -const SOURCE: &str = "vfmt"; +pub const SOURCE: &str = "vfmt"; + +/// Everything the server has to say about a buffer: the parse errors first, +/// then the lint warnings. +/// +/// **One list, one publish.** `textDocument/publishDiagnostics` *replaces* a +/// document's diagnostics; it never merges. Publishing the parse pass and the +/// lint pass as two notifications would leave whichever arrived second as the +/// only one on screen, and make the squiggles flicker as each keystroke +/// overwrote the other set. So the two sources are concatenated here and sent +/// once. Each source is already in position order; they are not interleaved, +/// because an error the user must fix reads better above an opinion about +/// style. +pub fn all(doc: &Document) -> Vec { + let mut all = diagnostics(doc); + all.extend(crate::lint::diagnostics(doc)); + all +} /// One LSP diagnostic per diagnostic the tolerant parser recorded. /// @@ -70,6 +87,29 @@ mod tests { assert_eq!(diags[0].range.start.character, 7, "the `;`, in UTF-16 units"); } + #[test] + fn one_list_carries_both_sources() { + // A file that parses cleanly and violates a lint rule: the publish is + // one list, and the lint finding is in it as a warning. + let (ws, uri) = doc_of("module m;\n\twire a;\nendmodule\n"); + let published = all(ws.document(&uri).expect("open")); + assert_eq!(published.len(), 1); + assert_eq!(published[0].severity, Some(DiagnosticSeverity::WARNING)); + assert_eq!(published[0].code, Some(lsp_types::NumberOrString::String("no-tabs".into()))); + } + + #[test] + fn a_parse_error_and_a_lint_warning_arrive_together() { + let (ws, uri) = doc_of("module m;\n\twire ;\nendmodule\n"); + let published = all(ws.document(&uri).expect("open")); + let severities: Vec<_> = published.iter().map(|d| d.severity).collect(); + assert!(severities.contains(&Some(DiagnosticSeverity::ERROR)), "{published:#?}"); + assert!(severities.contains(&Some(DiagnosticSeverity::WARNING)), "{published:#?}"); + assert!(published.iter().all(|d| d.source.as_deref() == Some("vfmt"))); + // Errors first: a parse error is what the user must fix. + assert_eq!(published[0].severity, Some(DiagnosticSeverity::ERROR)); + } + #[test] fn a_lex_error_gets_a_visible_range() { // The lexer gives up at end of file, which a trailing newline makes diff --git a/crates/vfmt_server/src/format.rs b/crates/vfmt_server/src/format.rs index 34ad5bd..c8740c6 100644 --- a/crates/vfmt_server/src/format.rs +++ b/crates/vfmt_server/src/format.rs @@ -58,6 +58,19 @@ pub fn formatting(doc: &Document, config: &Config) -> Result, S Ok(Some(TextEdit { range: doc.positions().whole_document(), new_text: formatted })) } +/// The indent width governing a buffer, for a lint fix that has to write +/// spaces where a tab was. +/// +/// A `textDocument/codeAction` request carries no `FormattingOptions`, so there +/// is no client `tabSize` to consider here — the precedence is just +/// `vfmt.toml` > the built-in default. A broken config is silent on this path: +/// the formatting path is where the user is told about it, and warning from a +/// lightbulb the editor requests on every cursor move would be noise. +pub fn indent_width(path: Option<&Path>) -> usize { + let (file, _problem) = discover(path); + file.indent.unwrap_or(Config::default().indent_width) +} + /// The config file governing `path`, by the CLI's own discovery rule, or the /// error that stopped it from being read. A buffer with no path (`untitled:`) /// has no directory to search from, so it gets no config. @@ -247,6 +260,25 @@ mod tests { assert_eq!(edit.new_text, "module m;\n wire a;\nendmodule\n"); } + #[test] + fn a_lint_fixs_indent_comes_from_the_config_or_the_built_in_default() { + // A code action has no `tabSize` to consider, so a quick fix that + // writes spaces where a tab was gets the buffer's own `vfmt.toml`. + let tree = Tree::new("indent = 4\n"); + let (ws, uri) = tree.document("module m;\n\twire a;\nendmodule\n"); + let doc = ws.document(&uri).expect("open"); + assert_eq!(indent_width(doc.path.as_deref()), 4); + assert_eq!(indent_width(None), Config::default().indent_width, "an untitled buffer"); + } + + #[test] + fn a_broken_config_leaves_the_lint_fix_on_the_default_indent_and_says_nothing() { + let tree = Tree::new("indent = 4\nbogus = 1\n"); + let (ws, uri) = tree.document("module m;\n\twire a;\nendmodule\n"); + let doc = ws.document(&uri).expect("open"); + assert_eq!(indent_width(doc.path.as_deref()), Config::default().indent_width); + } + #[test] fn an_untitled_buffer_has_no_directory_to_discover_from() { let uri = Uri::from_str("untitled:Untitled-1").expect("uri"); diff --git a/crates/vfmt_server/src/lint.rs b/crates/vfmt_server/src/lint.rs new file mode 100644 index 0000000..b9d5a32 --- /dev/null +++ b/crates/vfmt_server/src/lint.rs @@ -0,0 +1,143 @@ +//! Lint findings, and the diagnostics they become. +//! +//! `vlog_linter` is the same engine `vfmt check` runs, with the same default +//! rule set — an editor that disagreed with CI about what a violation is would +//! be worse than one that showed none. Selection (`--select`/`--ignore`) has no +//! `vfmt.toml` key yet, so there is nothing here to configure; see +//! `docs/features/server-lint/README.md`. + +use lsp_types::{Diagnostic, DiagnosticSeverity, NumberOrString}; +use vlog_linter::{default_rules, lint, run, LintContext, Violation}; + +use crate::convert::Positions; +use crate::diagnostics::SOURCE; +use crate::state::Document; + +/// Every violation the default rules find in a buffer. +/// +/// This is the diagnostics path, which never looks at a fix, so the width a +/// `no-tabs` fix would expand a tab to is left at the linter's own default. +/// The linter re-parses the text the document already parsed — the duplicated +/// parse is `linter-core`'s own "one parse, two tools" TODO, not something to +/// work around here. +pub fn violations(doc: &Document) -> Vec { + run(&doc.text, doc.path.clone(), &default_rules()) +} + +/// The same findings, with their fixes built for `tab_width`. +/// +/// The code-action path passes the indent width of the `vfmt.toml` governing +/// the buffer, so a quick fix that replaces a tab writes exactly what `vfmt` +/// would have written there. +pub fn fixable(doc: &Document, tab_width: usize) -> Vec { + let ctx = LintContext::new(&doc.text, doc.path.clone()).with_tab_width(tab_width); + lint(&ctx, &default_rules()) +} + +/// One LSP diagnostic per lint violation. +pub fn diagnostics(doc: &Document) -> Vec { + let positions = doc.positions(); + violations(doc).iter().map(|v| diagnostic(&positions, v)).collect() +} + +/// The diagnostic a violation becomes. +/// +/// **Warning**, never Error: a lint finding is an opinion about style, and a +/// parse error is the compiler refusing. The `code` is the rule's stable name, +/// which is what a user needs to write a waiver or an `--ignore`, and what a +/// code action matches on. +pub fn diagnostic(positions: &Positions<'_>, violation: &Violation) -> Diagnostic { + Diagnostic { + range: positions.diagnostic_range(violation.span), + severity: Some(DiagnosticSeverity::WARNING), + code: Some(NumberOrString::String(violation.rule.to_string())), + source: Some(SOURCE.to_string()), + message: violation.message.clone(), + ..Default::default() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::state::Workspace; + use lsp_types::Uri; + use std::str::FromStr; + + fn doc_of(text: &str) -> (Workspace, Uri) { + let uri = Uri::from_str("file:///rtl/m.sv").expect("uri"); + let mut ws = Workspace::default(); + ws.set_document(uri.clone(), text.to_string()); + (ws, uri) + } + + #[test] + fn a_tab_becomes_one_warning_carrying_its_rule_name() { + let (ws, uri) = doc_of("module m;\n\twire a;\nendmodule\n"); + let diags = diagnostics(ws.document(&uri).expect("open")); + assert_eq!(diags.len(), 1); + assert_eq!(diags[0].severity, Some(DiagnosticSeverity::WARNING)); + assert_eq!(diags[0].code, Some(NumberOrString::String("no-tabs".into()))); + assert_eq!(diags[0].source.as_deref(), Some("vfmt")); + assert_eq!(diags[0].range.start.line, 1); + assert!(diags[0].range.start < diags[0].range.end, "never zero-width"); + } + + #[test] + fn a_waived_violation_is_never_published() { + let (ws, uri) = doc_of("module m;\n\twire a; // vfmt: waive no-tabs\nendmodule\n"); + assert!(diagnostics(ws.document(&uri).expect("open")).is_empty()); + } + + #[test] + fn the_module_filename_rule_sees_the_uris_own_path() { + // The rule is silent without a file name, so this also proves the path + // reached the linter rather than the buffer being linted anonymously. + let (ws, uri) = doc_of("module other;\nendmodule\n"); + let diags = diagnostics(ws.document(&uri).expect("open")); + assert_eq!(diags.len(), 1); + assert_eq!(diags[0].code, Some(NumberOrString::String("module-filename".into()))); + assert!(diags[0].message.contains("m.sv"), "{}", diags[0].message); + } + + #[test] + fn an_untitled_buffer_is_linted_without_a_name() { + let uri = Uri::from_str("untitled:Untitled-1").expect("uri"); + let mut ws = Workspace::default(); + ws.set_document(uri.clone(), "module other;\n\twire a;\nendmodule\n".to_string()); + let diags = diagnostics(ws.document(&uri).expect("open")); + assert_eq!(diags.len(), 1, "the tab, and no module-filename: {diags:#?}"); + assert_eq!(diags[0].code, Some(NumberOrString::String("no-tabs".into()))); + } + + #[test] + fn multi_byte_content_shifts_a_violations_character() { + // The `é` is 2 bytes but 1 UTF-16 unit, and `🎉` is 4 bytes but 2: a + // byte-based server puts this warning four columns to the right. + let (ws, uri) = doc_of("module m;\n // é 🎉\twire a;\nendmodule\n"); + let diags = diagnostics(ws.document(&uri).expect("open")); + assert_eq!(diags.len(), 1); + assert_eq!(diags[0].code, Some(NumberOrString::String("no-tabs".into()))); + assert_eq!(diags[0].range.start.line, 1); + assert_eq!(diags[0].range.start.character, 9, "in UTF-16 units, not bytes"); + } + + #[test] + fn a_file_that_does_not_parse_is_still_linted() { + // The tolerant parse is what makes a text rule work in a broken file. + let (ws, uri) = doc_of("module m;\n\twire ;\nendmodule\n"); + let diags = diagnostics(ws.document(&uri).expect("open")); + assert!(diags.iter().any(|d| d.code == Some(NumberOrString::String("no-tabs".into())))); + } + + #[test] + fn a_fix_expands_a_tab_to_the_width_it_is_given() { + let (ws, uri) = doc_of("module m;\n\twire a;\nendmodule\n"); + let doc = ws.document(&uri).expect("open"); + for width in [2usize, 4] { + let found = fixable(doc, width); + let fix = found[0].fix.as_ref().expect("no-tabs offers a fix"); + assert_eq!(fix.edits[0].1, " ".repeat(width)); + } + } +} diff --git a/crates/vfmt_server/src/main.rs b/crates/vfmt_server/src/main.rs index bce6cb2..70b4151 100644 --- a/crates/vfmt_server/src/main.rs +++ b/crates/vfmt_server/src/main.rs @@ -6,10 +6,12 @@ //! `vlog_parser`, `vlog_semantic` or `vlog_formatter`. See //! `docs/features/vfmt-server/README.md`. +mod code_action; mod convert; mod diagnostics; mod format; mod hover; +mod lint; mod locate; mod nav; mod server; @@ -23,9 +25,10 @@ use std::path::PathBuf; use lsp_server::Connection; use lsp_types::{ - InitializeParams, OneOf, PositionEncodingKind, SemanticTokensFullOptions, SemanticTokensLegend, - SemanticTokensOptions, SemanticTokensServerCapabilities, ServerCapabilities, - TextDocumentSyncCapability, TextDocumentSyncKind, WorkDoneProgressOptions, + CodeActionKind, CodeActionOptions, CodeActionProviderCapability, InitializeParams, OneOf, + PositionEncodingKind, SemanticTokensFullOptions, SemanticTokensLegend, SemanticTokensOptions, + SemanticTokensServerCapabilities, ServerCapabilities, TextDocumentSyncCapability, + TextDocumentSyncKind, WorkDoneProgressOptions, }; use crate::server::Server; @@ -61,6 +64,17 @@ fn capabilities() -> ServerCapabilities { hover_provider: Some(lsp_types::HoverProviderCapability::Simple(true)), document_symbol_provider: Some(OneOf::Left(true)), workspace_symbol_provider: Some(OneOf::Left(true)), + // The kinds are listed rather than `Simple(true)` so a client can ask + // for one of them alone — which is how fix-on-save is configured. + code_action_provider: Some(CodeActionProviderCapability::Options(CodeActionOptions { + code_action_kinds: Some(vec![ + CodeActionKind::QUICKFIX, + CodeActionKind::new(code_action::FIX_ALL), + ]), + work_done_progress_options: WorkDoneProgressOptions::default(), + // Every action is returned complete; there is nothing to resolve. + resolve_provider: None, + })), semantic_tokens_provider: Some(SemanticTokensServerCapabilities::SemanticTokensOptions( SemanticTokensOptions { work_done_progress_options: WorkDoneProgressOptions::default(), @@ -113,6 +127,7 @@ mod tests { assert!(caps.document_symbol_provider.is_some()); assert!(caps.workspace_symbol_provider.is_some()); assert!(caps.semantic_tokens_provider.is_some()); + assert!(caps.code_action_provider.is_some()); // Deliberately absent until the engines exist — see the README. assert!(caps.document_range_formatting_provider.is_none(), "no --lines yet"); assert!(caps.completion_provider.is_none()); @@ -127,6 +142,20 @@ mod tests { assert_eq!(tokens::token_modifiers().len(), 1); } + #[test] + fn the_two_code_action_kinds_are_named_in_the_capability() { + // A client filtering by kind (fix-on-save does) sees nothing unless the + // kinds it may ask for are advertised. + let Some(CodeActionProviderCapability::Options(options)) = + capabilities().code_action_provider + else { + panic!("the kinds must be listed, not just `true`"); + }; + let kinds = options.code_action_kinds.expect("kinds"); + assert!(kinds.contains(&CodeActionKind::QUICKFIX)); + assert!(kinds.contains(&CodeActionKind::new(code_action::FIX_ALL))); + } + #[test] fn utf16_is_advertised_because_that_is_what_convert_implements() { assert_eq!(capabilities().position_encoding, Some(PositionEncodingKind::UTF16)); diff --git a/crates/vfmt_server/src/server.rs b/crates/vfmt_server/src/server.rs index 6878d5b..29757b5 100644 --- a/crates/vfmt_server/src/server.rs +++ b/crates/vfmt_server/src/server.rs @@ -14,22 +14,22 @@ use lsp_types::notification::{ LogMessage, Notification as _, PublishDiagnostics, ShowMessage, }; use lsp_types::request::{ - DocumentSymbolRequest, Formatting, GotoDefinition, HoverRequest, References, Request as _, - SemanticTokensFullRequest, WorkspaceSymbolRequest, + CodeActionRequest, DocumentSymbolRequest, Formatting, GotoDefinition, HoverRequest, References, + Request as _, SemanticTokensFullRequest, WorkspaceSymbolRequest, }; use lsp_types::{ - DidChangeTextDocumentParams, DidCloseTextDocumentParams, DidOpenTextDocumentParams, - DidSaveTextDocumentParams, DocumentFormattingParams, DocumentSymbolParams, - DocumentSymbolResponse, GotoDefinitionParams, GotoDefinitionResponse, HoverParams, - LogMessageParams, MessageType, Position, PublishDiagnosticsParams, ReferenceParams, - SemanticTokensParams, SemanticTokensResult, ShowMessageParams, Uri, WorkspaceSymbolParams, - WorkspaceSymbolResponse, + CodeActionParams, DidChangeTextDocumentParams, DidCloseTextDocumentParams, + DidOpenTextDocumentParams, DidSaveTextDocumentParams, DocumentFormattingParams, + DocumentSymbolParams, DocumentSymbolResponse, GotoDefinitionParams, GotoDefinitionResponse, + HoverParams, LogMessageParams, MessageType, Position, PublishDiagnosticsParams, + ReferenceParams, SemanticTokensParams, SemanticTokensResult, ShowMessageParams, Uri, + WorkspaceSymbolParams, WorkspaceSymbolResponse, }; use serde::de::DeserializeOwned; use serde_json::Value; use crate::state::Workspace; -use crate::{diagnostics, format, hover, nav, symbols, tokens}; +use crate::{code_action, diagnostics, format, hover, nav, symbols, tokens}; /// Everything the server owns. pub struct Server { @@ -121,6 +121,25 @@ impl Server { None => Ok(Value::Null), } }), + CodeActionRequest::METHOD => decode(request).and_then(|p: CodeActionParams| { + let uri = p.text_document.uri; + match self.workspace.document(&uri) { + Some(doc) => { + // A code-action request carries no `tabSize`, so the + // width a `no-tabs` fix writes comes from the buffer's + // own `vfmt.toml` or from the built-in default. + let tab_width = format::indent_width(doc.path.as_deref()); + to_value(code_action::code_actions( + &uri, + doc, + p.range, + p.context.only.as_deref(), + tab_width, + )) + } + None => Ok(Value::Null), + } + }), WorkspaceSymbolRequest::METHOD => { decode(request).and_then(|p: WorkspaceSymbolParams| { to_value(WorkspaceSymbolResponse::Flat(symbols::workspace_symbols( @@ -232,9 +251,12 @@ impl Server { self.workspace.set_document(uri, text); } + /// Publish everything known about a buffer — parse errors and lint + /// warnings — in one notification. Two publishes for one version would + /// leave only the second on screen, since LSP replaces rather than merges. fn publish(&self, uri: &Uri) { let Some(doc) = self.workspace.document(uri) else { return }; - self.send_diagnostics(uri.clone(), diagnostics::diagnostics(doc)); + self.send_diagnostics(uri.clone(), diagnostics::all(doc)); } fn send_diagnostics(&self, uri: Uri, diagnostics: Vec) { diff --git a/crates/vfmt_server/tests/e2e.rs b/crates/vfmt_server/tests/e2e.rs index 2bf2d08..69f23e4 100644 --- a/crates/vfmt_server/tests/e2e.rs +++ b/crates/vfmt_server/tests/e2e.rs @@ -168,6 +168,88 @@ fn a_broken_vfmt_toml_warns_once_and_still_formats() { let _ = std::fs::remove_dir_all(&dir); } +/// A file with a tab (`no-tabs`, Safe fix) and a trailing space +/// (`no-trailing-whitespace`, Safe fix) — and a name matching its module, so +/// `module-filename` stays quiet and every finding here is fixable. +const VIOLATING: &str = "module lint_me;\n\twire a;\n wire b; \nendmodule\n"; + +#[test] +fn lint_diagnostics_and_a_code_action_round_trip_over_the_wire() { + let dir = temp_dir("lint"); + let file = dir.join("lint_me.sv"); + std::fs::write(&file, VIOLATING).expect("write"); + let root = format!("file://{}", dir.display()); + let uri = format!("file://{}", file.display()); + + let session = [ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(VIOLATING).expect("json") + )), + // Every action for the whole file. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/codeAction","params":{{"textDocument":{{"uri":"{uri}"}},"range":{{"start":{{"line":0,"character":0}},"end":{{"line":3,"character":0}}}},"context":{{"diagnostics":[]}}}}}}"# + )), + // And the fix-on-save request an editor sends: one kind only. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/codeAction","params":{{"textDocument":{{"uri":"{uri}"}},"range":{{"start":{{"line":0,"character":0}},"end":{{"line":3,"character":0}}}},"context":{{"diagnostics":[],"only":["source.fixAll.vfmt"]}}}}}}"# + )), + 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); + + // 1. The capability was advertised with both kinds. + let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response"); + let kinds = &initialize["result"]["capabilities"]["codeActionProvider"]["codeActionKinds"]; + let kinds = kinds.as_array().expect("the kinds are listed, not just `true`"); + assert!(kinds.iter().any(|k| k == "quickfix"), "{kinds:#?}"); + assert!(kinds.iter().any(|k| k == "source.fixAll.vfmt"), "{kinds:#?}"); + + // 2. Exactly one publish for this version, carrying both lint findings. + let published: Vec<_> = + messages.iter().filter(|m| m["method"] == "textDocument/publishDiagnostics").collect(); + assert_eq!(published.len(), 1, "one publish replaces, two would flicker: {published:#?}"); + let diagnostics = published[0]["params"]["diagnostics"].as_array().expect("an array"); + assert_eq!(diagnostics.len(), 2, "{diagnostics:#?}"); + let codes: Vec<&str> = diagnostics.iter().filter_map(|d| d["code"].as_str()).collect(); + assert!(codes.contains(&"no-tabs"), "{codes:?}"); + assert!(codes.contains(&"no-trailing-whitespace"), "{codes:?}"); + for diagnostic in diagnostics { + assert_eq!(diagnostic["severity"], 2, "a lint finding is a warning"); + assert_eq!(diagnostic["source"], "vfmt"); + } + + // 3. Two quick fixes and one fixAll, and the quick fixes name the finding. + let actions = messages.iter().find(|m| m["id"] == 2).expect("code action response"); + let actions = actions["result"].as_array().expect("an array of actions"); + let quick: Vec<_> = actions.iter().filter(|a| a["kind"] == "quickfix").collect(); + assert_eq!(quick.len(), 2, "{actions:#?}"); + assert_eq!(quick[0]["diagnostics"].as_array().expect("its diagnostic").len(), 1); + let all: Vec<_> = actions.iter().filter(|a| a["kind"] == "source.fixAll.vfmt").collect(); + assert_eq!(all.len(), 1, "{actions:#?}"); + + // 4. The filtered request returns the fixAll action and nothing else, and + // its edit is the whole document with every Safe fix applied. + let filtered = messages.iter().find(|m| m["id"] == 3).expect("filtered response"); + let filtered = filtered["result"].as_array().expect("an array"); + assert_eq!(filtered.len(), 1, "only what was asked for: {filtered:#?}"); + let edits = filtered[0]["edit"]["changes"][uri.as_str()].as_array().expect("edits"); + assert_eq!(edits.len(), 1, "one whole-document edit"); + assert_eq!( + edits[0]["newText"], "module lint_me;\n wire a;\n wire b;\nendmodule\n", + "the linter's own fixed output" + ); + + let _ = std::fs::remove_dir_all(&dir); +} + /// A buffer that is broken *and* still has a resolvable reference: error /// recovery is what makes both true at once, and the LSP depends on it. const SOURCE: &str = "module top;\n wire a;\n assign a = 1;\n wire ;\nendmodule\n"; diff --git a/docs/features/server-lint/README.md b/docs/features/server-lint/README.md new file mode 100644 index 0000000..fa43cd4 --- /dev/null +++ b/docs/features/server-lint/README.md @@ -0,0 +1,475 @@ +# server-lint + +## Goal + +`vfmt check` has existed since round 11 and the language server has published +parse errors since the same round, but the two never met: an editor running +`vfmt-server` saw syntax errors and nothing else, while CI running `vfmt check` +saw seven rules' worth of findings. This round wires `vlog_linter` into +`vfmt_server` so the editor shows what CI will say — lint findings as +**warnings** alongside the parse **errors**, in **one** `publishDiagnostics` per +change — and adds `textDocument/codeAction`: a quick fix per Safe fix, and a +`source.fixAll.vfmt` action for fix-on-save. Nothing about the linter changed; +this is protocol-layer wiring, which is all `vfmt_server` is allowed to be. + +## Assumptions + +- **One publish per version, always.** `textDocument/publishDiagnostics` + *replaces* a document's diagnostics; it never merges them. Publishing the + parse pass and the lint pass as two notifications for one version is the + classic flicker bug — whichever arrives second is the only one the user sees, + and which that is depends on ordering nobody controls. `diagnostics::all` + therefore concatenates both sources and the server sends the result once, from + the single `publish()` path every notification already goes through. +- **Errors first, then warnings, each in position order.** The two lists are + concatenated, not interleaved: a parse error is the thing the user must fix + and reads better above an opinion about style. Every editor sorts the list its + own way anyway; what matters is that the order is deterministic, and it is. +- **A lint finding is a `Warning`, a parse error stays an `Error`.** The linter + has opinions; the parser reports the file not being Verilog. `code` is the + rule's stable kebab-case name — the string the user needs to write a waiver or + an `--ignore`, and the string a code action matches on. `source` is `"vfmt"` + for both, as before. +- **The linter is handed the URI's own path**, so `module-filename` can speak. + It is the one default rule that needs a file name; without the path it goes + quiet, which would have made the editor disagree with CI on exactly the rule + whose whole subject is the file name. An `untitled:` buffer genuinely has no + path and genuinely gets no `module-filename` finding — the same behavior as + `vfmt check` on stdin without `--stdin-filename`. +- **The document is parsed twice per change, and that is a known cost, not an + oversight.** `Document::new` parses for the server, and `LintContext::new` + parses again inside the linter. `linter-core`'s own Handshakes file this as + "one parse, two tools" (TODO §4) and say what the fix is: `LintContext` would + have to accept a pre-built tree. Refactoring `vlog_linter` from this round was + out of scope and would have been the wrong place to decide it — the CLI pays + the same cost. Measured shape of the cost: it is one extra tolerant parse per + keystroke of a single file, which is the same order as the analysis the server + already redoes per keystroke by design (TODO §6, "per-file recompute is fine + at Verilog file sizes"). When the shared-parse work lands, exactly one call + site here changes. +- **Only Safe fixes are ever offered.** `--unsafe-fixes` is a flag a CLI user + types on purpose; a lightbulb is not that, and a fix that can change what the + circuit does must not be one click away. No rule ships an Unsafe fix today, so + this is a rule written for the first one that does — and it is enforced in + code (`quick_fix` returns `None` for anything not `Applicability::Safe`) and + in `apply_fixes(.., include_unsafe = false)` for the fix-all path, not just + stated here. +- **`source.fixAll.vfmt` is one pass, deliberately.** `vfmt check --fix` loops + fix → re-lint until nothing changes, because a single pass skips any fix + overlapping one already applied (the everyday case is a line ending in a tab, + which `no-tabs` and `no-trailing-whitespace` both want to rewrite). The server + does **not** reproduce that loop: applying the action changes the buffer, the + change re-lints, the client asks again, and convergence arrives for free + through the edit/re-lint cycle the editor already runs. One pass per request + also keeps every action the user is shown a description of the buffer actually + in front of them, rather than of a hypothetical buffer three rounds ahead. + Pinned by `fix_all_is_one_pass_and_the_next_request_finishes_the_job`. +- **The fix-all edit is the whole document.** That is what `apply_fixes` + produces and what it guarantees — a set of ranges assembled by hand here could + interleave two fixes in a way the linter's own skip rule would have refused. + It matches what `textDocument/formatting` already sends, so no client is + surprised by the shape. +- **A quick fix's tab-expansion width comes from `vfmt.toml`.** A code-action + request carries no `FormattingOptions`, so unlike formatting there is no + client `tabSize` in play: the precedence is `vfmt.toml` > the built-in + default, via `format::indent_width`. Without this, a project with `indent = 4` + would get a quick fix inserting two spaces that format-on-save then rewrites — + precisely the CLI/editor divergence `vfmt-core-lift` exists to prevent. The + diagnostics path does not do this lookup: it never reads a fix, so it would be + a config file read per keystroke bought for nothing. +- **A broken `vfmt.toml` is silent on the code-action path.** The formatting + path already warns once per file change (`vfmt-core-lift`); warning again from + a lightbulb an editor requests on every cursor move would train the user to + ignore vfmt's messages. The fix falls back to the built-in indent width. +- **The client's `context.only` filter is honored here rather than left to the + client.** The spec permits a server to return everything and let the client + filter, but fix-on-save asks for `source.fixAll.vfmt` alone, and computing + every quick fix for a request that discards them is work nobody reads. + Filtering is hierarchical, as the spec says: `source` selects + `source.fixAll.vfmt`. +- **A quick fix is offered when its diagnostic range *touches* the requested + range.** A cursor sitting on the first character of a warning is asking about + that warning; an empty requested range (a bare cursor) is the normal case. +- **Waivers, fences and rule selection are the linter's business, not this + crate's.** A `// vfmt: waive no-tabs` suppresses the diagnostic and therefore + the lightbulb, because the finding never reaches this crate. **Note the one + asymmetry with the CLI:** `vfmt check --fix` additionally refuses to fix + inside a `// verilog_format: off` fence, and that refusal lives in + `crates/vfmt/src/lint.rs`, not in `vlog_linter` — so it is **not** inherited + here. See Status/TODO; it is the one honest gap this round leaves. + +## Handshakes + +**Consumed from `vlog_linter`** (all already `pub`; nothing in that crate was +modified, and nothing needed to be): + +- `run(source, Option, &[&dyn Rule]) -> Vec` — the + diagnostics path. +- `lint(&LintContext, &[&dyn Rule])` with + `LintContext::new(source, path).with_tab_width(w)` — the code-action path, + which needs the fix text built for the buffer's indent width. +- `default_rules()`, `rule_by_name(name)` (for the lightbulb's title, from + `Rule::summary`), `Violation { rule, message, span, fix }`, + `Fix { edits: Vec<(TextRange, String)>, applicability }`, + `Applicability::{Safe, Unsafe}`, `apply_fixes(source, &[Violation], + include_unsafe) -> Fixed { output, applied }`. + +Relied on, and stated so it breaks loudly if it stops being true: rule **names +are stable** (they are this feature's `Diagnostic::code` and appear in users' +waivers), `run` **never panics and never writes**, and findings come back +**sorted by `(span.start, span.end, rule)`** — all three are promises in +`docs/features/linter-core/README.md`'s Handshakes. + +**Consumed from `vfmt_core`** — nothing new: `format::indent_width` reuses the +existing private `discover`, which is `Discovery::for_file`. + +**Promised to nobody.** `vfmt_server` is still a leaf binary with no library +target. `editors/**` was not touched: a client needs no change to receive lint +diagnostics, and `editor.codeActionsOnSave` naming `source.fixAll.vfmt` is a +user setting, not an extension one. + +**Requested of others — not done here:** + +1. *linter-core / whoever unifies the pipelines*: **one parse, two tools.** This + crate now pays the duplicated parse per keystroke, which makes it the second + caller with a reason to want `LintContext` to accept a pre-built + `SourceFile`. Nothing here blocks on it; when it lands, `lint.rs` is the one + file that changes. +2. *linter-core / config-discovery*: **a `lint` key in `vfmt.toml`.** The server + runs `default_rules()` and nothing else, because there is no configured rule + set to read — `--select`/`--ignore` are CLI-only. When `lint = [...]` lands, + `lint.rs` should resolve it through the same `Discovery` the formatter uses, + with the same anchored-at-the-document rule. +3. *lead*: **the fence gap.** `vfmt check --fix` will not rewrite bytes inside a + `// verilog_format: off` region, but that filter lives in + `crates/vfmt/src/lint.rs` (it needs `vlog_formatter::fence`, which the linter + crate deliberately does not depend on). This round did not duplicate it — a + third copy of "what is fenced" is exactly how the three answers drift — so a + quick fix in this server *can* edit inside a fence. Reported honestly rather + than half-fixed: the right home is a shared helper both front ends call. It + cannot corrupt code (every offered fix is Safe), but it does violate the + fence's "hands off" promise the same way the CLI did before its QA round. +4. *lead*: **`TODO.md:353` is now stale.** §6's `vfmt_server` entry still lists + "lint diagnostics (waits on `vlog_linter`)" under **Not shipped**. TODO.md is + outside this round's stated scope, so it was left alone rather than edited; + the checkbox itself is already `[x]` and needs no flip. + +## Capabilities, as this round leaves them + +| LSP request | Engine it consumes | Notes | +|---|---|---| +| `textDocument/publishDiagnostics` | `vlog_parser::parse_source_tolerant` **+ `vlog_linter::run`** | One publish per change carrying both: parse errors as `Error`, lint findings as `Warning` with `code` = rule name | +| `textDocument/codeAction` | `vlog_linter` fixes | `quickfix` per Safe fix (`isPreferred`, `diagnostics` populated); one `source.fixAll.vfmt` whole-document edit | + +The `initialize` diff is exactly one field: + +```rust +code_action_provider: Some(CodeActionProviderCapability::Options(CodeActionOptions { + code_action_kinds: Some(vec![ + CodeActionKind::QUICKFIX, + CodeActionKind::new("source.fixAll.vfmt"), + ]), + work_done_progress_options: WorkDoneProgressOptions::default(), + resolve_provider: None, +})), +``` + +`Options` rather than `Simple(true)` on purpose: a client that filters by kind +(which is how fix-on-save is configured) has to be told which kinds exist. +`resolve_provider` is `None` because every action is returned complete. + +**Still deliberately not advertised**, unchanged by this round and absent from +the initialize result rather than present-and-false: `rangeFormatting` (waits on +TODO §2 `--lines`), `completion`, `rename`, `signatureHelp`, and cross-file +`references`. + +## Status / TODO + +- [x] `vlog_linter` added to `crates/vfmt_server/Cargo.toml` (path dependency; + the crate was already a workspace member, so the root `Cargo.toml` needed + **no** edit). +- [x] `src/lint.rs`: violations for the diagnostics path, violations-with-fixes + for the code-action path, and the `Violation` → `Diagnostic` conversion. +- [x] `src/diagnostics.rs`: `all()` — parse errors then lint warnings, one list. +- [x] `server.rs`: `publish()` sends that one list; every path that published + before (`didOpen`, `didChange`, `didSave`, and the post-save republish of + every open buffer) now publishes both sources, unchanged otherwise. +- [x] `src/code_action.rs`: quick fixes, `source.fixAll.vfmt`, `context.only` + filtering, range-overlap matching. +- [x] `format::indent_width` — the config-governed tab width a fix writes. +- [x] `textDocument/codeAction` wired into the request dispatcher. +- [x] `codeActionProvider` advertised with both kinds. +- [x] Handler tests: publish merge, waived violation, `module-filename` from the + URI, untitled buffer, UTF-16 positions after multi-byte content, quick fix + reproducing `apply_fixes`' own output, fix-all over multiple fixes, + one-pass convergence, client filter, indent width. +- [x] e2e through the real binary: one publish carrying two rule codes, the + capability's kinds on the wire, quick fixes + fixAll, and a filtered + fix-on-save request. +- [x] `docs/features/vfmt-server/README.md` deferred list annotated. +- [ ] **Not done, deliberately:** rule selection. No `vfmt.toml` `lint` key + exists (Handshake 2); the server runs `default_rules()`. +- [ ] **Not done, deliberately:** offering Unsafe fixes. No rule ships one, and + when one does it wants a decision (a separate `source.fixAll` kind? a + client setting?), not a silent inclusion. +- [ ] **Not done:** fence-aware fixes (Handshake 3) — a quick fix can edit + inside a `// verilog_format: off` region, where `vfmt check --fix` would + not. +- [ ] **Not done:** `codeAction/resolve`. Every action is cheap to build in + full; lazy resolution is a payload optimization for actions that are not. +- [ ] **Not done:** sharing one parse with the linter (Handshake 1). + +## Work log + +### 2026-08-19 — dev agent + +- Read `CLAUDE.md`, `docs/features/vfmt-server/README.md`, + `docs/features/linter-core/README.md` and + `docs/features/vfmt-core-lift/README.md` in full (QA logs and Reviews + included) before writing anything, plus `vlog_linter`'s public surface + (`lib.rs`, `violation.rs`, `context.rs`, `registry.rs`). No engine crate + needed a change, again: every entry point this round wanted was already + public and already documented. +- **The publish merge was the one decision with a wrong answer available.** + Adding a second `send_diagnostics` call for lint findings would have looked + right in every unit test and flickered in every editor, because LSP replaces + rather than merges. The merge is therefore in `diagnostics::all` — one + function, called from the one `publish()` path every notification already used + — rather than at the four notification sites. The e2e test asserts on the + **count of publish notifications** (`== 1`), which is the assertion that would + catch a regression here; asserting only on the contents would not. +- **Two lint entry points, for one honest reason.** `lint::violations` (the + diagnostics path) calls `vlog_linter::run` and never looks at a fix, so it + does no config work per keystroke. `lint::fixable` (the code-action path) + builds a `LintContext` with the tab width of the governing `vfmt.toml`, since + a fix that writes two spaces into an `indent = 4` project is a fix + format-on-save immediately overwrites. The split costs three lines and buys + the CLI/editor parity `vfmt-core-lift` was about. +- **`fixAll` is one pass and says so in a doc comment at the function**, with + the reasoning (the client's own edit/re-lint cycle *is* the convergence loop). + The tab-and-trailing-whitespace case — the everyday two-round example from + `linter-core` — is the test that pins it: pass one changes the buffer, a + second request finishes it, a third offers nothing. +- **`fixAll` carries no `diagnostics` list.** A pass skips fixes overlapping an + applied one, so the action cannot honestly claim which findings it resolves. + Quick fixes, which resolve exactly one, do carry theirs — built by the same + `lint::diagnostic` the publisher uses, so the diagnostic in the action is + equal to the one on screen rather than a lookalike reconstructed by hand. +- **`context.only` is honored** with hierarchical prefix matching, because + fix-on-save requests `source.fixAll.vfmt` alone and would otherwise be handed + every quick fix in the file to throw away. +- **Two clippy warnings fixed by restructuring, not by `#[allow]`**: both were + `clippy::mutable_key_type` on a `let`-bound `&HashMap>` in + the tests (`lsp_types::Uri` has interior mutability, and the map type is the + protocol's, not ours). Replaced with an `edits_of(action)` helper that returns + the `Vec` directly, so no map is ever bound. No `#[allow]` was added + anywhere in this round. +- No `unwrap`/`expect`/`panic!`/`unsafe` outside `#[cfg(test)]` in any file + added or touched. +- Did not touch `vlog_linter`, `vlog_parser`, `vlog_formatter`, `vlog_semantic`, + `vfmt`, `vfmt_core` or `editors/**`. Root `Cargo.toml` needed no edit — + `vlog_linter` is already a workspace member, so the dependency is one path + line in this crate's own manifest (`Cargo.lock` gained the corresponding + one-line edge). `TODO.md` left alone per the round's stated scope, with the + one stale sentence filed as Handshake 4. Did not run `git commit`/`git push`. + +**Results.** + +- `cargo test -p vfmt_server`: **108 passed, 0 failed** (104 unit + 4 e2e), + up from 85 (82 + 3). New: 7 in `lint.rs`, 10 in `code_action.rs`, 2 in + `diagnostics.rs`, 2 in `format.rs`, 2 in `main.rs`, 1 e2e. +- `cargo clippy -p vfmt_server --all-targets`: **0 warnings from this crate**. + One warning reaches the output from a dependency — `vlog_formatter`'s + `with_comma is never used` — which belongs to the concurrent round live in + `vlog_parser`/`vlog_formatter`, not to anything here. +- `cargo fmt --all -- --check`: clean. +- `cargo test --workspace`: **547 passed, 0 failed**, measured after the + concurrent round's tree settled. +- **Concurrency note.** Mid-round the other agent landed new `ast::Module` / + `ast::AnsiPort` fields, and for ~20 minutes nothing in the workspace compiled, + this crate included. Nothing was touched in response; the gates were re-run + once `vlog_parser` built again and are the numbers above. `-p vfmt_server`'s + own 104 + 4 is the count that belongs to this feature and did not move across + the break. +- Files added: `crates/vfmt_server/src/{lint,code_action}.rs`, this README. + Files edited: `crates/vfmt_server/Cargo.toml` (one line), + `crates/vfmt_server/src/{main,server,diagnostics,format}.rs`, + `crates/vfmt_server/tests/e2e.rs`, one annotation line in + `docs/features/vfmt-server/README.md`. + +## QA log + +### 2026-08-19 — QA agent + +Scoped to `-p vfmt_server` per the concurrency note (a second agent was live +in `vlog_parser`/`vlog_formatter` for the directives-in-lists round; the tree +briefly failed to build mid-session and recovered on its own — retested after +and the numbers below are post-recovery). No files touched outside this QA +log entry. + +**Gates.** + +- `cargo test -p vfmt_server`: **104 unit + 4 e2e, 0 failed** — matches the + claimed count exactly. +- `cargo clippy -p vfmt_server --all-targets`: **0 warnings from this crate.** +- `cargo fmt --all -- --check`: clean. +- `grep -rn "#\[allow" crates/vfmt_server/src/{lint,code_action,diagnostics,format,main,server}.rs crates/vfmt_server/tests/e2e.rs` + finds exactly one hit, `main.rs:112` (`#[allow(deprecated)]` on + `root_uri`) — confirmed via `git diff crates/vfmt_server/src/main.rs` to + predate this round (it sits outside every hunk this diff touches). **No + new `#[allow]` was added.** + +**Claim 1 — single-publish merge: PASS.** +`grep -rn "send_diagnostics\|PublishDiagnostics" crates/vfmt_server/src/` +shows exactly one call site that ever sends a non-empty diagnostics list — +`server.rs:259`, `self.send_diagnostics(uri.clone(), diagnostics::all(doc))` +inside `publish()` — plus the `didClose` clear-with-`Vec::new()` at line 236, +which is not a second source, it is the documented "clear what we drew" +case. No other path calls `send_diagnostics` or constructs a +`PublishDiagnosticsParams`. Drove the real binary (hand-rolled Python LSP +client, framed JSON-RPC over stdio, script kept at +`/private/tmp/claude-501/.../scratchpad/test1_publish_merge.py`): +`didOpen` on `"module m;\n\twire ;\nendmodule\n"` (a tab **and** a parse +error) produced **exactly one** `publishDiagnostics`, carrying one `Error` +(unnamed `wire`) and one `Warning` `code: "no-tabs"`. `didChange` fixing the +parse error but keeping the tab: still one publish, error gone, `no-tabs` +warning persists. `didChange` adding `// vfmt: waive no-tabs`: still one +publish, diagnostics array empty. All three steps matched the claim exactly. + +**Claim 2 — codeAction: PASS**, verified against the real binary +(`test2_codeaction.py`, `test3_convergence.py`): +- A `codeAction` request at the tab returned one `quickfix` + (`isPreferred: true`, `diagnostics` = one entry, built from the same + `lint::diagnostic` the publisher uses — confirmed both by source + (`code_action.rs:63`) and by the wire payload being byte-identical to the + publish's own diagnostic) and one `source.fixAll.vfmt`. The quickfix's + edit, applied by hand from UTF-16 positions, was byte-identical to + `vfmt check --fix`'s output on the same file. +- `fixAll` carried no `diagnostics` key (absent from the JSON entirely, i.e. + `None`, matching the one-pass argument in the README) and its one + whole-document edit also matched `vfmt check --fix`. +- Convergence: a line with both a leading tab and a trailing tab + (`no-tabs` + `no-trailing-whitespace` both wanting those bytes) took + **3 rounds** to reach a clean buffer via repeated `fixAll` → `didChange` → + `fixAll` — within the documented "2-3 rounds" window. Round 3 returned no + `fixAll` action at all (nothing left to fix), which is the correct + "converged" signal. +- `context.only=["source"]` returned only the `fixAll` action (1 action); + `context.only=["quickfix"]` returned only the quickfix (1 action) — both + confirmed live, not just via the existing unit test. +- Tab width from `vfmt.toml`: a scratch tree with `indent = 4` produced a + quickfix expanding the tab to 4 spaces; a tree with no config produced 2 + spaces (the built-in default) — both driven through the real binary + (`test6_config_and_filename.py`). +- Diagnostics path skips config reads: `grep -rn "indent_width" crates/vfmt_server/src/*.rs` + shows `format::indent_width` called from exactly one site, + `server.rs:131`, inside the `CodeActionRequest` handler. Neither + `lint::violations` nor `lint::diagnostics` (the path every `didOpen`/ + `didChange`/`didSave` publish goes through) calls it or `Discovery` + anywhere. Confirmed by static read since a per-keystroke file read isn't + directly observable from outside; the absence of the call is the proof. +- Unsafe fixes excluded: confirmed in code (`code_action.rs:60-62` returns + `None` for non-`Safe`; `fix_all` calls `apply_fixes(.., false)`) and by + `grep -rn "Applicability::Unsafe" crates/vlog_linter/src/rules/` finding + no rule that constructs one — there is nothing to accidentally offer today. + +**Claim 3 — capabilities: PASS.** `main.rs`'s `capabilities()` diff is +exactly the one field the README documents (`code_action_provider: Options` +with `[QUICKFIX, "source.fixAll.vfmt"]`, `resolve_provider: None`); nothing +else in `capabilities()` changed per `git diff`. `caps.code_action_provider` +is `Options`, not `Simple(true)` — asserted by +`the_two_code_action_kinds_are_named_in_the_capability` and by the e2e test +reading the actual wire payload. `rangeFormatting`/`completion`/`rename` +remain `None`, asserted by the pre-existing +`every_advertised_capability_is_implemented` test (still passing, unmodified +in spirit — only gained one new assertion for `code_action_provider`). + +**Claim 4 — tests: PASS**, numbers above. + +**Claim 5 — handshakes: PASS**, and the fence gap was reproduced live rather +than taken on faith. `test4_fence_gap.py`: a file with +`// verilog_format: off` / a tabbed line / `// verilog_format: on` — +`vfmt check --fix` left the tab untouched (confirmed: output still contains +the literal tab byte); the server's `fixAll` action **did** rewrite it to +spaces (confirmed: applied output has the tab replaced). This is exactly +what Handshake 3 claims, stated as a known gap rather than silently — the +handshake text is accurate, not aspirational. The other three handshakes +(second-parse-per-keystroke in `lint.rs`'s own doc comments, no `lint` key +in `vfmt.toml` yet, `TODO.md:353` being stale) were spot-checked against the +actual files and are accurate: `TODO.md`'s "Not shipped, deliberately: ... +lint diagnostics (waits on `vlog_linter`)" line is indeed still present and +now stale, and its checkbox is already `[x]`, exactly as claimed. + +**UTF-16 under fixes: PASS.** `test5_utf16.py`: a violation on a line after +`🎉🎉 café` (multi-byte, multi-UTF-16-unit content) — the server's `fixAll` +edit, applied from its UTF-16 positions, produced output **byte-identical** +to `vfmt check --fix` on the same file, and the emoji/accented content was +untouched. + +**module-filename via URI: PASS.** A `file://` URI whose module name +mismatches its filename produced the `module-filename` warning (message +correctly named both names); the same content opened under an `untitled:` +URI produced zero diagnostics for that rule and the server did not error or +hang on a subsequent `codeAction` request against the same untitled buffer +(returned `[]`, no `error` field). + +**Documentation.** README has all seven CLAUDE.md-required sections, all +populated except Review (correctly reserved for the lead). The two +`docs/features/vfmt-server/README.md` annotation locations (the "Deferred" +paragraph's `lint diagnostics (waits on \`vlog_linter\`)` clause, and the +Status/TODO `lint diagnostics` checklist item) are each a single +struck-through-and-replaced item, word-wrapped across several physical lines +in the file's existing 80-column convention — consistent with "one +annotation" per location, not a rewrite of surrounding content. Minor, +non-blocking nit: the dev's own work-log sentence says "one annotation line +in `docs/features/vfmt-server/README.md`" (singular), but two separate +locations in that file were actually touched (the Deferred-paragraph clause +and the Status/TODO item) — the substance of both edits is correct and +scoped, this is purely a miscount in the work-log's own wording. + +**No BLOCKING findings.** No double-publish observed in any of five live +sessions across the scenarios above (always exactly one +`publishDiagnostics` per change). No fix landed on wrong bytes under UTF-16 +(byte-identical to the CLI in the emoji test). No Unsafe fix was ever +offered (none exists to offer, and the two guard sites hold). + +Nothing in this feature required touching `verify.rs`, so CLAUDE.md's rule 4 +(masked-corruption attack tests for widened forgiveness) does not apply to +this round. + +## Review + +**2026-08-19 — lead. Verdict: accepted and committed. Linting in the +editor — the last line of the owner's original feature list — is live.** + +Points reviewed and accepted: + +1. **The flicker bug made structurally impossible** rather than avoided + by discipline: one merged list through the one publish path, with + the e2e asserting on notification *count*. That's the design habit + this project has been building all day, applied to the protocol + layer. +2. **fixAll as one honest pass**: no converge loop (the client's + edit/re-lint cycle provides it, verified live at 3 rounds), and no + `diagnostics` list on the action because a pass that skips + overlapping fixes can't honestly name what it resolved. Declining + to claim what you can't prove is the house style. +3. **Quick fixes byte-identical to `vfmt check --fix`** — the two + front ends provably agree, which is the property users will + actually rely on. +4. **The fence gap filed, not papered over**: a server fix can edit + inside `// vfmt: off` because the fence filter lives in + `crates/vfmt`, and a third copy of "what is fenced" is how answers + drift. QA reproduced both sides live. This is the top item for the + next round — a shared fence-region helper (likely in + `vlog_formatter` next to `fence.rs`, or `vfmt_core`) that the CLI + and the server both call. Until then: no corruption is possible + (only Safe fixes exist), but the hands-off promise has a documented + editor-side hole. +5. The second-parse-per-keystroke cost and the `vfmt.toml` `lint` key + stay filed where they belong (vlog_linter's one-parse-two-tools + TODO and config-discovery's key list respectively). + +Lead note on QA's nit: the work-log's "one annotation line" was two +locations — both correct; miscount acknowledged here rather than +rewriting the dev's log. diff --git a/docs/features/vfmt-server/README.md b/docs/features/vfmt-server/README.md index 151c763..26b0169 100644 --- a/docs/features/vfmt-server/README.md +++ b/docs/features/vfmt-server/README.md @@ -26,7 +26,10 @@ looks like language knowledge in here is a bug or a `Handshake` request. | `workspace/symbol` | `WorkspaceIndex::workspace_symbols` | Capped at 256 hits | Deferred, deliberately, and named in Status/TODO below: range formatting -(waits on TODO.md §2 `--lines`), lint diagnostics (waits on `vlog_linter`), +(waits on TODO.md §2 `--lines`), ~~lint diagnostics (waits on `vlog_linter`)~~ +**delivered by server-lint (round 13): lint findings publish as warnings in the +same notification as the parse errors, and `textDocument/codeAction` offers +their Safe fixes — see `docs/features/server-lint/README.md`**, completion / rename / signature help, and cross-file references. (`vfmt.toml` discovery and `.gitignore`-aware indexing, deferred when this was written, were delivered by vfmt-core-lift the same day — lead note.) @@ -368,9 +371,11 @@ it was written rather than starting mid-line. - [ ] **Not done, deliberately:** `rangeFormatting`. It reuses TODO.md §2's `--lines`, which does not exist yet; advertising the capability before the engine does is how an editor learns to distrust a server. -- [ ] **Not done:** lint diagnostics. `vlog_linter` is a concurrent round; - when it lands, the diagnostic publisher gains a second source and - nothing else changes. +- [x] ~~**Not done:** lint diagnostics.~~ Delivered by **server-lint** + (round 13): the publisher gained the second source — in + the *same* notification, since LSP replaces rather than merges — plus + `textDocument/codeAction` for the Safe fixes. + `docs/features/server-lint/README.md`. - [ ] **Not done:** completion, rename, signature help (TODO.md §6's "then" list). - [ ] **Not done:** cross-file references. `references_of` is per-file, and