411 lines
17 KiB
Rust
411 lines
17 KiB
Rust
//! `textDocument/codeAction` — one quick fix per Safe lint fix, plus one
|
|
//! `source.fixAll.lucisv` 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 lucisv without also running another server's
|
|
/// fixer.
|
|
pub const FIX_ALL: &str = "source.fixAll.lucisv";
|
|
|
|
/// 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.lucisv` 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<CodeActionOrCommand> {
|
|
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<CodeAction> {
|
|
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<TextEdit> = 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.** `lucisv 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<CodeAction> {
|
|
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: "lucisv: 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<TextEdit>) -> 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!("lucisv: {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.lucisv`), and no filter
|
|
/// at all selects everything.
|
|
pub 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<CodeAction> {
|
|
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<TextEdit> {
|
|
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, "lucisv: 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 `lucisv 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");
|
|
}
|
|
|
|
/// A tab inside a fence and a tab outside one, both `no-tabs` findings.
|
|
const FENCED: &str =
|
|
"module m;\n// lucisv: off\n\twire a;\n// lucisv: on\n\twire b;\nendmodule\n";
|
|
|
|
#[test]
|
|
fn a_violation_inside_a_fence_gets_a_diagnostic_but_no_quick_fix() {
|
|
let ws = workspace(FENCED);
|
|
let doc = ws.document(&uri()).expect("open");
|
|
// The finding is published — `off` silences the fix, not the report.
|
|
let fenced_line = 2;
|
|
let published = crate::lint::diagnostics(doc);
|
|
assert!(
|
|
published.iter().any(|d| d.range.start.line == fenced_line),
|
|
"the fenced tab is still reported: {published:#?}"
|
|
);
|
|
// ...but the cursor on it offers no lightbulb.
|
|
let at = Range {
|
|
start: Position { line: fenced_line, character: 0 },
|
|
end: Position { line: fenced_line, character: 0 },
|
|
};
|
|
let actions = code_actions(&uri(), doc, at, Some(&[CodeActionKind::QUICKFIX]), 2);
|
|
assert!(actions.is_empty(), "no quick fix inside a fence: {actions:#?}");
|
|
// The unfenced tab one line further down still has one.
|
|
let at = Range {
|
|
start: Position { line: 4, character: 0 },
|
|
end: Position { line: 4, character: 0 },
|
|
};
|
|
assert_eq!(code_actions(&uri(), doc, at, Some(&[CodeActionKind::QUICKFIX]), 2).len(), 1);
|
|
}
|
|
|
|
#[test]
|
|
fn fix_all_edits_the_unfenced_violations_only() {
|
|
let ws = workspace(FENCED);
|
|
let actions = actions_of(&ws);
|
|
let all = actions
|
|
.iter()
|
|
.find(|a| a.kind == Some(CodeActionKind::new(FIX_ALL)))
|
|
.expect("a fixAll action");
|
|
let output = applied(FENCED, all);
|
|
assert_eq!(
|
|
output, "module m;\n// lucisv: off\n\twire a;\n// lucisv: on\n wire b;\nendmodule\n",
|
|
"the fenced line is byte-identical, the free one is fixed"
|
|
);
|
|
// And the fenced bytes really are the input's own, tab included.
|
|
let fenced = FENCED.find("\twire a;").expect("fenced line");
|
|
assert!(output.contains("\twire a;"), "{output:?}");
|
|
assert_eq!(&output[..fenced], &FENCED[..fenced]);
|
|
}
|
|
|
|
#[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; // lucisv: 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.lucisv`.
|
|
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");
|
|
}
|
|
}
|