feat: add versioned LSP quick fixes
This commit is contained in:
parent
a112b4bcb0
commit
90c2848d63
167
src/lsp.rs
167
src/lsp.rs
|
|
@ -5,12 +5,15 @@ use std::{collections::HashMap, ops::Range as ByteRange};
|
|||
use tokio::sync::RwLock;
|
||||
use tower_lsp_server::{
|
||||
Client, LanguageServer,
|
||||
jsonrpc::Result as JsonResult,
|
||||
jsonrpc::{Error as JsonError, Result as JsonResult},
|
||||
ls_types::{
|
||||
Diagnostic, DiagnosticSeverity, DidChangeTextDocumentParams, DidCloseTextDocumentParams,
|
||||
DidOpenTextDocumentParams, InitializeParams, InitializeResult, InitializedParams,
|
||||
NumberOrString, Position, Range, ServerCapabilities, ServerInfo,
|
||||
TextDocumentSyncCapability, TextDocumentSyncKind, Uri,
|
||||
CodeAction, CodeActionKind, CodeActionOptions, CodeActionOrCommand, CodeActionParams,
|
||||
CodeActionProviderCapability, CodeActionResponse, Diagnostic, DiagnosticSeverity,
|
||||
DidChangeTextDocumentParams, DidCloseTextDocumentParams, DidOpenTextDocumentParams,
|
||||
DocumentChanges, InitializeParams, InitializeResult, InitializedParams, NumberOrString,
|
||||
OneOf, OptionalVersionedTextDocumentIdentifier, Position, Range, ServerCapabilities,
|
||||
ServerInfo, TextDocumentEdit, TextDocumentSyncCapability, TextDocumentSyncKind,
|
||||
TextEdit as LspTextEdit, Uri, WorkspaceEdit,
|
||||
},
|
||||
};
|
||||
|
||||
|
|
@ -106,6 +109,7 @@ impl<'source> LineIndex<'source> {
|
|||
pub fn replacement_diagnostics(
|
||||
config: &Config,
|
||||
source: &str,
|
||||
version: i32,
|
||||
) -> Result<Vec<Diagnostic>, PositionError> {
|
||||
let index = LineIndex::new(source);
|
||||
plan_replacements(config, source)
|
||||
|
|
@ -118,7 +122,7 @@ pub fn replacement_diagnostics(
|
|||
.find(|rule| rule.enabled && rule.source == matched);
|
||||
let code = rule.map(|rule| NumberOrString::String(rule.id.clone()));
|
||||
let rationale = rule.map_or("configured non-ASCII text", |rule| &rule.rationale);
|
||||
Ok(Diagnostic::new(
|
||||
let mut diagnostic = Diagnostic::new(
|
||||
index.range(edit.byte_span)?,
|
||||
Some(DiagnosticSeverity::WARNING),
|
||||
code,
|
||||
|
|
@ -129,11 +133,76 @@ pub fn replacement_diagnostics(
|
|||
),
|
||||
None,
|
||||
None,
|
||||
))
|
||||
);
|
||||
diagnostic.data = Some(serde_json::json!({ "version": version }));
|
||||
Ok(diagnostic)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn replacement_code_actions(
|
||||
config: &Config,
|
||||
uri: &Uri,
|
||||
snapshot: &OpenDocument,
|
||||
requested_range: &Range,
|
||||
diagnostics: &[Diagnostic],
|
||||
) -> Result<Vec<CodeActionOrCommand>, PositionError> {
|
||||
let index = LineIndex::new(&snapshot.text);
|
||||
plan_replacements(config, &snapshot.text)
|
||||
.into_iter()
|
||||
.filter_map(|edit| {
|
||||
let range = match index.range(edit.byte_span) {
|
||||
Ok(range) => range,
|
||||
Err(error) => return Some(Err(error)),
|
||||
};
|
||||
if !ranges_overlap(&range, requested_range) {
|
||||
return None;
|
||||
}
|
||||
let related = diagnostics
|
||||
.iter()
|
||||
.find(|diagnostic| {
|
||||
diagnostic.source.as_deref() == Some("john-slop") && diagnostic.range == range
|
||||
})
|
||||
.cloned();
|
||||
let text_edit = LspTextEdit::new(range, edit.replacement.clone());
|
||||
let workspace_edit = WorkspaceEdit {
|
||||
changes: None,
|
||||
document_changes: Some(DocumentChanges::Edits(vec![TextDocumentEdit {
|
||||
text_document: OptionalVersionedTextDocumentIdentifier::new(
|
||||
uri.clone(),
|
||||
snapshot.version,
|
||||
),
|
||||
edits: vec![OneOf::Left(text_edit)],
|
||||
}])),
|
||||
change_annotations: None,
|
||||
};
|
||||
Some(Ok(CodeActionOrCommand::CodeAction(CodeAction {
|
||||
title: format!("Replace with ASCII {:?}", edit.replacement),
|
||||
kind: Some(CodeActionKind::QUICKFIX),
|
||||
diagnostics: related.map(|diagnostic| vec![diagnostic]),
|
||||
edit: Some(workspace_edit),
|
||||
is_preferred: Some(true),
|
||||
data: Some(serde_json::json!({ "version": snapshot.version })),
|
||||
..CodeAction::default()
|
||||
})))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn ranges_overlap(left: &Range, right: &Range) -> bool {
|
||||
left.start <= right.end && right.start <= left.end
|
||||
}
|
||||
|
||||
fn requested_version_is_current(diagnostics: &[Diagnostic], version: i32) -> bool {
|
||||
diagnostics
|
||||
.iter()
|
||||
.filter(|diagnostic| diagnostic.source.as_deref() == Some("john-slop"))
|
||||
.filter_map(|diagnostic| diagnostic.data.as_ref())
|
||||
.filter_map(|data| data.get("version"))
|
||||
.filter_map(serde_json::Value::as_i64)
|
||||
.all(|requested| requested == i64::from(version))
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
struct OpenDocument {
|
||||
version: i32,
|
||||
|
|
@ -212,7 +281,8 @@ impl LspBackend {
|
|||
return;
|
||||
};
|
||||
let config = self.config.read().await.clone();
|
||||
let diagnostics = replacement_diagnostics(&config, &snapshot.text).unwrap_or_default();
|
||||
let diagnostics =
|
||||
replacement_diagnostics(&config, &snapshot.text, snapshot.version).unwrap_or_default();
|
||||
let is_current = self
|
||||
.documents
|
||||
.read()
|
||||
|
|
@ -239,6 +309,13 @@ impl LanguageServer for LspBackend {
|
|||
text_document_sync: Some(TextDocumentSyncCapability::Kind(
|
||||
TextDocumentSyncKind::FULL,
|
||||
)),
|
||||
code_action_provider: Some(CodeActionProviderCapability::Options(
|
||||
CodeActionOptions {
|
||||
code_action_kinds: Some(vec![CodeActionKind::QUICKFIX]),
|
||||
resolve_provider: Some(false),
|
||||
..CodeActionOptions::default()
|
||||
},
|
||||
)),
|
||||
..ServerCapabilities::default()
|
||||
},
|
||||
offset_encoding: None,
|
||||
|
|
@ -269,6 +346,31 @@ impl LanguageServer for LspBackend {
|
|||
self.documents.write().await.close(&uri);
|
||||
self.client.publish_diagnostics(uri, Vec::new(), None).await;
|
||||
}
|
||||
|
||||
async fn code_action(
|
||||
&self,
|
||||
params: CodeActionParams,
|
||||
) -> JsonResult<Option<CodeActionResponse>> {
|
||||
let uri = params.text_document.uri;
|
||||
let Some(snapshot) = self.documents.read().await.get(&uri) else {
|
||||
return Ok(None);
|
||||
};
|
||||
if !requested_version_is_current(¶ms.context.diagnostics, snapshot.version) {
|
||||
return Err(JsonError::invalid_params(
|
||||
"code action diagnostics refer to a stale document version",
|
||||
));
|
||||
}
|
||||
let config = self.config.read().await.clone();
|
||||
let actions = replacement_code_actions(
|
||||
&config,
|
||||
&uri,
|
||||
&snapshot,
|
||||
¶ms.range,
|
||||
¶ms.context.diagnostics,
|
||||
)
|
||||
.map_err(|error| JsonError::invalid_params(error.to_string()))?;
|
||||
Ok(Some(actions))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
@ -280,7 +382,10 @@ mod tests {
|
|||
TextDocumentContentChangeEvent, TextDocumentItem, Uri, VersionedTextDocumentIdentifier,
|
||||
};
|
||||
|
||||
use super::{DocumentStore, LineIndex, PositionError, replacement_diagnostics};
|
||||
use super::{
|
||||
DocumentStore, LineIndex, OpenDocument, PositionError, replacement_code_actions,
|
||||
replacement_diagnostics, requested_version_is_current,
|
||||
};
|
||||
|
||||
fn uri() -> Uri {
|
||||
Uri::from_str("file:///tmp/example.txt").unwrap()
|
||||
|
|
@ -405,7 +510,7 @@ mod tests {
|
|||
#[test]
|
||||
fn replacement_diagnostics_have_utf16_ranges_stable_codes_and_source() {
|
||||
let diagnostics =
|
||||
replacement_diagnostics(&crate::Config::embedded(), "😀— ordinary prose").unwrap();
|
||||
replacement_diagnostics(&crate::Config::embedded(), "😀— ordinary prose", 7).unwrap();
|
||||
|
||||
assert_eq!(diagnostics.len(), 1);
|
||||
assert_eq!(diagnostics[0].range.start, Position::new(0, 2));
|
||||
|
|
@ -416,5 +521,47 @@ mod tests {
|
|||
);
|
||||
assert_eq!(diagnostics[0].source.as_deref(), Some("john-slop"));
|
||||
assert!(diagnostics[0].message.contains("ASCII \"-\""));
|
||||
assert_eq!(
|
||||
diagnostics[0].data,
|
||||
Some(serde_json::json!({ "version": 7 }))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quick_fix_uses_exact_versioned_replacement_edit() {
|
||||
let config = crate::Config::embedded();
|
||||
let source = "😀—text";
|
||||
let document = OpenDocument {
|
||||
version: 9,
|
||||
language_id: "plaintext".to_owned(),
|
||||
text: source.to_owned(),
|
||||
};
|
||||
let diagnostics = replacement_diagnostics(&config, source, 9).unwrap();
|
||||
let actions = replacement_code_actions(
|
||||
&config,
|
||||
&uri(),
|
||||
&document,
|
||||
&diagnostics[0].range,
|
||||
&diagnostics,
|
||||
)
|
||||
.unwrap();
|
||||
let value = serde_json::to_value(&actions).unwrap();
|
||||
|
||||
assert_eq!(actions.len(), 1);
|
||||
assert_eq!(value[0]["kind"], "quickfix");
|
||||
assert_eq!(
|
||||
value[0]["edit"]["documentChanges"][0]["textDocument"]["version"],
|
||||
9
|
||||
);
|
||||
assert_eq!(
|
||||
value[0]["edit"]["documentChanges"][0]["edits"][0]["newText"],
|
||||
"-"
|
||||
);
|
||||
assert_eq!(
|
||||
value[0]["edit"]["documentChanges"][0]["edits"][0]["range"]["start"]["character"],
|
||||
2
|
||||
);
|
||||
assert!(requested_version_is_current(&diagnostics, 9));
|
||||
assert!(!requested_version_is_current(&diagnostics, 10));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
2
tasks.md
2
tasks.md
|
|
@ -197,7 +197,7 @@ first formatter milestone tag.
|
|||
including CRLF, emoji, combining marks, astral characters, and EOF positions.
|
||||
- [x] Publish diagnostics only for configured ASCII-replacement findings in the
|
||||
initial release. Include stable codes and source `john-slop`.
|
||||
- [ ] Expose quick fixes/code actions using the exact edits from the shared
|
||||
- [x] Expose quick fixes/code actions using the exact edits from the shared
|
||||
replacement engine; reject stale-version requests.
|
||||
- [ ] Recompute after open/change/configuration updates, clear on close, and avoid
|
||||
publishing obsolete results when analysis overlaps newer edits.
|
||||
|
|
|
|||
Loading…
Reference in New Issue