feat: publish LSP replacement diagnostics
Rust CI JohnSlop passed all CI checks.
Gitea/john_slop/pipeline/head This commit looks good Details

This commit is contained in:
Dandaedre 2026-09-29 17:03:04 +02:00
parent 01be964765
commit a112b4bcb0
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
2 changed files with 88 additions and 10 deletions

View File

@ -7,13 +7,14 @@ use tower_lsp_server::{
Client, LanguageServer,
jsonrpc::Result as JsonResult,
ls_types::{
DidChangeTextDocumentParams, DidCloseTextDocumentParams, DidOpenTextDocumentParams,
InitializeParams, InitializeResult, InitializedParams, Position, Range, ServerCapabilities,
ServerInfo, TextDocumentSyncCapability, TextDocumentSyncKind, Uri,
Diagnostic, DiagnosticSeverity, DidChangeTextDocumentParams, DidCloseTextDocumentParams,
DidOpenTextDocumentParams, InitializeParams, InitializeResult, InitializedParams,
NumberOrString, Position, Range, ServerCapabilities, ServerInfo,
TextDocumentSyncCapability, TextDocumentSyncKind, Uri,
},
};
use crate::{Config, ConfigLoader};
use crate::{Config, ConfigLoader, plan_replacements};
/// Failure to convert a canonical UTF-8 byte offset into an LSP position.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
@ -101,6 +102,38 @@ impl<'source> LineIndex<'source> {
}
}
/// Convert configured replacement edits into stable LSP diagnostics.
pub fn replacement_diagnostics(
config: &Config,
source: &str,
) -> Result<Vec<Diagnostic>, PositionError> {
let index = LineIndex::new(source);
plan_replacements(config, source)
.into_iter()
.map(|edit| {
let matched = &source[edit.byte_span.clone()];
let rule = config
.replacements
.iter()
.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(
index.range(edit.byte_span)?,
Some(DiagnosticSeverity::WARNING),
code,
Some("john-slop".to_owned()),
format!(
"Replace {matched:?} with ASCII {:?}: {rationale}",
edit.replacement
),
None,
None,
))
})
.collect()
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct OpenDocument {
version: i32,
@ -148,6 +181,10 @@ impl DocumentStore {
fn close(&mut self, uri: &Uri) -> bool {
self.documents.remove(uri).is_some()
}
fn get(&self, uri: &Uri) -> Option<OpenDocument> {
self.documents.get(uri).cloned()
}
}
/// Stdio LSP backend backed by authoritative snapshots of open documents.
@ -155,7 +192,7 @@ impl DocumentStore {
pub struct LspBackend {
client: Client,
_config_loader: ConfigLoader,
_config: RwLock<Config>,
config: RwLock<Config>,
documents: RwLock<DocumentStore>,
}
@ -165,10 +202,30 @@ impl LspBackend {
Self {
client,
_config_loader: config_loader,
_config: RwLock::new(config),
config: RwLock::new(config),
documents: RwLock::new(DocumentStore::default()),
}
}
async fn publish_replacements(&self, uri: Uri) {
let Some(snapshot) = self.documents.read().await.get(&uri) else {
return;
};
let config = self.config.read().await.clone();
let diagnostics = replacement_diagnostics(&config, &snapshot.text).unwrap_or_default();
let is_current = self
.documents
.read()
.await
.get(&uri)
.is_some_and(|document| document.version == snapshot.version);
if is_current {
self.client
.publish_diagnostics(uri, diagnostics, Some(snapshot.version))
.await;
}
}
}
impl LanguageServer for LspBackend {
@ -195,11 +252,16 @@ impl LanguageServer for LspBackend {
}
async fn did_open(&self, params: DidOpenTextDocumentParams) {
let uri = params.text_document.uri.clone();
self.documents.write().await.open(params);
self.publish_replacements(uri).await;
}
async fn did_change(&self, params: DidChangeTextDocumentParams) {
self.documents.write().await.change(params);
let uri = params.text_document.uri.clone();
if self.documents.write().await.change(params) {
self.publish_replacements(uri).await;
}
}
async fn did_close(&self, params: DidCloseTextDocumentParams) {
@ -214,11 +276,11 @@ mod tests {
use std::str::FromStr;
use tower_lsp_server::ls_types::{
DidChangeTextDocumentParams, DidOpenTextDocumentParams, Position,
DidChangeTextDocumentParams, DidOpenTextDocumentParams, NumberOrString, Position,
TextDocumentContentChangeEvent, TextDocumentItem, Uri, VersionedTextDocumentIdentifier,
};
use super::{DocumentStore, LineIndex, PositionError};
use super::{DocumentStore, LineIndex, PositionError, replacement_diagnostics};
fn uri() -> Uri {
Uri::from_str("file:///tmp/example.txt").unwrap()
@ -339,4 +401,20 @@ mod tests {
})
);
}
#[test]
fn replacement_diagnostics_have_utf16_ranges_stable_codes_and_source() {
let diagnostics =
replacement_diagnostics(&crate::Config::embedded(), "😀— ordinary prose").unwrap();
assert_eq!(diagnostics.len(), 1);
assert_eq!(diagnostics[0].range.start, Position::new(0, 2));
assert_eq!(diagnostics[0].range.end, Position::new(0, 3));
assert_eq!(
diagnostics[0].code,
Some(NumberOrString::String("em-dash".to_owned()))
);
assert_eq!(diagnostics[0].source.as_deref(), Some("john-slop"));
assert!(diagnostics[0].message.contains("ASCII \"-\""));
}
}

View File

@ -195,7 +195,7 @@ first formatter milestone tag.
open document.
- [x] Build and thoroughly test byte-offset to LSP UTF-16 line/character mapping,
including CRLF, emoji, combining marks, astral characters, and EOF positions.
- [ ] Publish diagnostics only for configured ASCII-replacement findings in the
- [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
replacement engine; reject stale-version requests.