Skip to main content

lang_check/
lsp.rs

1//! LSP JSON-RPC backend for language-check-server.
2//!
3//! Reuses the existing orchestrator, prose extraction, config, dictionary, and
4//! ignore-store logic.  Activated with `language-check-server --lsp`.
5
6#![allow(clippy::cast_possible_truncation)]
7
8use std::collections::HashMap;
9use std::path::{Path, PathBuf};
10use std::sync::Arc;
11
12use dashmap::DashMap;
13use tokio::sync::Mutex;
14use tower_lsp::jsonrpc::Result;
15use tower_lsp::lsp_types::{
16    CodeAction, CodeActionKind, CodeActionOrCommand, CodeActionParams,
17    CodeActionProviderCapability, CodeActionResponse, Command, Diagnostic, DiagnosticSeverity,
18    DidChangeConfigurationParams, DidChangeTextDocumentParams, DidCloseTextDocumentParams,
19    DidOpenTextDocumentParams, DidSaveTextDocumentParams, ExecuteCommandOptions,
20    ExecuteCommandParams, InitializeParams, InitializeResult, InitializedParams, NumberOrString,
21    Position, Range, ServerCapabilities, ServerInfo, TextDocumentSyncCapability,
22    TextDocumentSyncKind, TextEdit, Url, WorkspaceEdit,
23};
24use tower_lsp::{Client, LanguageServer, LspService, Server};
25use tracing::{debug, info, warn};
26
27use crate::checker;
28use crate::config::Config;
29use crate::dictionary::Dictionary;
30use crate::hashing::{DiagnosticFingerprint, IgnoreStore};
31use crate::morphology::AffixAnalyzer;
32use crate::names::NameFilter;
33use crate::orchestrator::Orchestrator;
34use crate::prose;
35use crate::sls::SchemaRegistry;
36use crate::suppression::{SuppressionContext, retain_visible};
37use crate::text_util::safe_slice;
38
39// ── LSP settings ────────────────────────────────────────────────────────────
40
41/// Settings received via `workspace/didChangeConfiguration`.
42#[derive(Debug, Default, serde::Deserialize)]
43#[serde(default)]
44struct LspSettings {
45    #[serde(alias = "langCheck")]
46    lang_check: LangCheckSettings,
47}
48
49#[derive(Debug, Default, serde::Deserialize)]
50#[serde(default)]
51struct LangCheckSettings {
52    engines: Option<EngineSettings>,
53    performance: Option<PerformanceSettings>,
54    names: Option<NameSettings>,
55    dictionaries: Option<DictionarySettings>,
56}
57
58#[derive(Debug, Default, serde::Deserialize)]
59#[serde(default)]
60struct DictionarySettings {
61    bundled: Option<bool>,
62    disabled: Option<Vec<String>>,
63    paths: Option<Vec<String>>,
64}
65
66#[derive(Debug, Default, serde::Deserialize)]
67#[serde(default)]
68struct NameSettings {
69    enabled: Option<bool>,
70    aggressiveness: Option<crate::names::Aggressiveness>,
71}
72
73#[derive(Debug, Default, serde::Deserialize)]
74#[serde(default)]
75struct EngineSettings {
76    harper: Option<bool>,
77    languagetool: Option<bool>,
78    languagetool_url: Option<String>,
79    vale: Option<bool>,
80    proselint: Option<bool>,
81    spell_language: Option<String>,
82}
83
84#[derive(Debug, Default, serde::Deserialize)]
85#[serde(default)]
86struct PerformanceSettings {
87    high_performance_mode: Option<bool>,
88    debounce_ms: Option<u64>,
89    max_file_size: Option<usize>,
90}
91
92// ── Document store ──────────────────────────────────────────────────────────
93
94/// In-memory text of open documents (keyed by URI string).
95/// Value is `(text, language_id)`.
96type DocumentStore = DashMap<String, (String, String)>;
97
98// ── Backend ─────────────────────────────────────────────────────────────────
99
100pub struct Backend {
101    client: Client,
102    orchestrator: Arc<Mutex<Orchestrator>>,
103    config: Arc<Mutex<Config>>,
104    dictionary: Arc<Mutex<Dictionary>>,
105    morphology: Arc<Mutex<Option<AffixAnalyzer>>>,
106    name_filter: Arc<Mutex<Option<NameFilter>>>,
107    ignore_store: Arc<Mutex<IgnoreStore>>,
108    schema_registry: Arc<Mutex<SchemaRegistry>>,
109    documents: DocumentStore,
110    workspace_root: Mutex<Option<PathBuf>>,
111}
112
113impl Backend {
114    fn new(client: Client) -> Self {
115        Self {
116            client,
117            orchestrator: Arc::new(Mutex::new(Orchestrator::new(Config::default()))),
118            config: Arc::new(Mutex::new(Config::default())),
119            dictionary: Arc::new(Mutex::new(Dictionary::new())),
120            morphology: Arc::new(Mutex::new(None)),
121            name_filter: Arc::new(Mutex::new(None)),
122            ignore_store: Arc::new(Mutex::new(IgnoreStore::new())),
123            schema_registry: Arc::new(Mutex::new(SchemaRegistry::new())),
124            documents: DashMap::new(),
125            workspace_root: Mutex::new(None),
126        }
127    }
128
129    /// Initialise all state from the workspace root (config, dictionary, …).
130    async fn init_workspace(&self, root: &Path) {
131        let config = Config::load_or_warn(root);
132        info!(
133            harper = config.engines.harper.enabled,
134            languagetool = config.engines.languagetool.enabled,
135            vale = config.engines.vale.enabled,
136            proselint = config.engines.proselint.enabled,
137            "LSP: engines configured"
138        );
139
140        self.orchestrator.lock().await.update_config(config.clone());
141        *self.config.lock().await = config.clone();
142
143        self.reload_dictionary(root, &config).await;
144
145        *self.morphology.lock().await = config
146            .morphology
147            .enabled
148            .then(|| AffixAnalyzer::new(&config.engines.spell_language));
149
150        *self.name_filter.lock().await = config.names.enabled.then(|| {
151            info!(
152                aggressiveness = ?config.names.aggressiveness,
153                "LSP: name detection enabled"
154            );
155            NameFilter::new(config.names.aggressiveness, &config.engines.spell_language)
156        });
157
158        if let Ok(store) = IgnoreStore::load(root) {
159            *self.ignore_store.lock().await = store;
160        }
161        if let Ok(reg) = SchemaRegistry::from_workspace(root) {
162            *self.schema_registry.lock().await = reg;
163        }
164
165        *self.workspace_root.lock().await = Some(root.to_path_buf());
166    }
167
168    /// Apply LSP settings on top of the workspace config.
169    /// Rebuild the dictionary from `config`, replacing whatever was loaded before.
170    ///
171    /// Shared by workspace init and `didChangeConfiguration` so a toggled set
172    /// takes effect without an editor restart, and so the two paths cannot drift.
173    async fn reload_dictionary(&self, root: &Path, config: &Config) {
174        match Dictionary::load(root) {
175            Ok(mut dict) => {
176                if config.dictionaries.bundled {
177                    dict.load_bundled_except(&config.dictionaries.disabled);
178                }
179                for p in &config.dictionaries.paths {
180                    if let Err(e) = dict.load_wordlist_file(Path::new(p), root) {
181                        warn!(path = p, "Could not load wordlist: {e}");
182                    }
183                }
184                if config.morphology.inflections {
185                    dict.derive_inflections();
186                }
187                *self.dictionary.lock().await = dict;
188            }
189            Err(e) => warn!("Could not load dictionary: {e}"),
190        }
191    }
192
193    async fn apply_settings(&self, settings: &LangCheckSettings) {
194        let mut config = self.config.lock().await;
195        if let Some(ref eng) = settings.engines {
196            if let Some(v) = eng.harper {
197                config.engines.harper.enabled = v;
198            }
199            if let Some(v) = eng.languagetool {
200                config.engines.languagetool.enabled = v;
201            }
202            if let Some(ref v) = eng.languagetool_url {
203                config.engines.languagetool.url.clone_from(v);
204            }
205            if let Some(v) = eng.vale {
206                config.engines.vale.enabled = v;
207            }
208            if let Some(v) = eng.proselint {
209                config.engines.proselint.enabled = v;
210            }
211            if let Some(ref v) = eng.spell_language {
212                config.engines.spell_language.clone_from(v);
213            }
214        }
215        if let Some(ref names) = settings.names {
216            if let Some(v) = names.enabled {
217                config.names.enabled = v;
218            }
219            if let Some(v) = names.aggressiveness {
220                config.names.aggressiveness = v;
221            }
222        }
223        if let Some(ref dicts) = settings.dictionaries {
224            if let Some(v) = dicts.bundled {
225                config.dictionaries.bundled = v;
226            }
227            if let Some(ref v) = dicts.disabled {
228                config.dictionaries.disabled.clone_from(v);
229            }
230            if let Some(ref v) = dicts.paths {
231                config.dictionaries.paths.clone_from(v);
232            }
233        }
234        if let Some(ref perf) = settings.performance {
235            if let Some(v) = perf.high_performance_mode {
236                config.performance.high_performance_mode = v;
237            }
238            if let Some(v) = perf.debounce_ms {
239                config.performance.debounce_ms = v;
240            }
241            if let Some(v) = perf.max_file_size {
242                config.performance.max_file_size = v;
243            }
244        }
245        let updated = config.clone();
246        drop(config);
247        *self.morphology.lock().await = updated
248            .morphology
249            .enabled
250            .then(|| AffixAnalyzer::new(&updated.engines.spell_language));
251        *self.name_filter.lock().await = updated.names.enabled.then(|| {
252            NameFilter::new(
253                updated.names.aggressiveness,
254                &updated.engines.spell_language,
255            )
256        });
257        if settings.dictionaries.is_some()
258            && let Some(root) = self.workspace_root.lock().await.clone()
259        {
260            self.reload_dictionary(&root, &updated).await;
261        }
262        self.orchestrator.lock().await.update_config(updated);
263        info!("LSP: config updated via didChangeConfiguration");
264    }
265
266    /// Re-diagnose all currently open documents.
267    async fn rediagnose_all(&self) {
268        let entries: Vec<(String, String, String)> = self
269            .documents
270            .iter()
271            .map(|r| {
272                let (text, lang_id) = r.value();
273                (r.key().clone(), text.clone(), lang_id.clone())
274            })
275            .collect();
276        for (uri_str, text, lang_id) in entries {
277            if let Ok(uri) = Url::parse(&uri_str) {
278                self.diagnose(&uri, &text, &lang_id).await;
279            }
280        }
281    }
282
283    /// Run diagnostics on a document and publish them.
284    // The three suppression-source guards are borrowed by `SuppressionContext`, so they
285    // genuinely have to outlive the `retain_visible` call; clippy's nursery lint reads
286    // the last direct mention of each guard as its last use and asks for an earlier drop
287    // that would not compile. The server binary allows this lint file-wide for the same
288    // pattern.
289    #[allow(clippy::significant_drop_tightening)]
290    async fn diagnose(&self, uri: &Url, text: &str, lang_id: &str) {
291        let canonical = crate::languages::resolve_language_id(lang_id);
292
293        let extraction = {
294            let schema_reg = self.schema_registry.lock().await;
295            let cfg = self.config.lock().await;
296            let latex_extras = prose::latex::LatexExtras {
297                skip_envs: &cfg.languages.latex.skip_environments,
298                skip_commands: &cfg.languages.latex.skip_commands,
299            };
300            let result = prose::extract_with_fallback(
301                text,
302                canonical,
303                None,
304                Some(&schema_reg),
305                &latex_extras,
306            );
307            drop(cfg);
308            drop(schema_reg);
309            result
310        };
311
312        let ranges = match extraction {
313            Ok(r) => r,
314            Err(e) => {
315                warn!(uri = %uri, "Extraction error: {e}");
316                return;
317            }
318        };
319
320        let mut all_diagnostics: Vec<Diagnostic> = Vec::new();
321
322        let prose_texts = crate::prose::range_texts(&ranges, text);
323        let batch = {
324            let mut orch = self.orchestrator.lock().await;
325            orch.check_batch(&prose_texts, lang_id).await
326        };
327
328        let batch = batch.unwrap_or_else(|e| {
329            warn!(uri = %uri, "Check error: {e}");
330            Vec::new()
331        });
332        for (range, mut diags) in ranges.iter().zip(batch) {
333            range.adopt_diagnostics(text, &mut diags);
334
335            {
336                let ignore = self.ignore_store.lock().await;
337                let dict = self.dictionary.lock().await;
338                let morphology = self.morphology.lock().await;
339                let names = self.name_filter.lock().await;
340                let mut ctx = SuppressionContext::new()
341                    .with_ignore(&ignore)
342                    .with_dictionary(&dict);
343                if let Some(analyzer) = morphology.as_ref() {
344                    ctx = ctx.with_morphology(analyzer);
345                }
346                if let Some(filter) = names.as_ref() {
347                    ctx = ctx.with_names(filter);
348                }
349                retain_visible(&mut diags, text, &ctx);
350            }
351
352            all_diagnostics.extend(diags.iter().map(|d| to_lsp_diagnostic(text, d)));
353        }
354
355        self.client
356            .publish_diagnostics(uri.clone(), all_diagnostics, None)
357            .await;
358    }
359}
360
361// ── LanguageServer impl ─────────────────────────────────────────────────────
362
363#[tower_lsp::async_trait]
364impl LanguageServer for Backend {
365    async fn initialize(&self, params: InitializeParams) -> Result<InitializeResult> {
366        if let Some(root_uri) = params.root_uri
367            && let Ok(path) = root_uri.to_file_path()
368        {
369            self.init_workspace(&path).await;
370        }
371
372        Ok(InitializeResult {
373            capabilities: ServerCapabilities {
374                text_document_sync: Some(TextDocumentSyncCapability::Kind(
375                    TextDocumentSyncKind::FULL,
376                )),
377                code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
378                execute_command_provider: Some(ExecuteCommandOptions {
379                    commands: vec![
380                        "langCheck.addDictionaryWord".into(),
381                        "langCheck.ignoreDiagnostic".into(),
382                    ],
383                    ..Default::default()
384                }),
385                ..Default::default()
386            },
387            server_info: Some(ServerInfo {
388                name: "language-check-server".into(),
389                version: Some(env!("CARGO_PKG_VERSION").into()),
390            }),
391        })
392    }
393
394    async fn initialized(&self, _: InitializedParams) {
395        info!("LSP client initialized");
396    }
397
398    async fn shutdown(&self) -> Result<()> {
399        Ok(())
400    }
401
402    async fn did_open(&self, params: DidOpenTextDocumentParams) {
403        let uri = params.text_document.uri;
404        let text = params.text_document.text;
405        let lang_id = params.text_document.language_id.clone();
406        self.documents
407            .insert(uri.to_string(), (text.clone(), lang_id.clone()));
408        self.diagnose(&uri, &text, &lang_id).await;
409    }
410
411    async fn did_change(&self, params: DidChangeTextDocumentParams) {
412        let uri = params.text_document.uri;
413        if let Some(change) = params.content_changes.into_iter().last() {
414            let lang_id = guess_lang_id(&uri);
415            self.documents
416                .insert(uri.to_string(), (change.text.clone(), lang_id.clone()));
417            self.diagnose(&uri, &change.text, &lang_id).await;
418        }
419    }
420
421    async fn did_save(&self, params: DidSaveTextDocumentParams) {
422        let uri = params.text_document.uri;
423        let key = uri.to_string();
424        let entry = self.documents.get(&key).map(|r| r.value().clone());
425        if let Some((text, lang_id)) = entry {
426            self.diagnose(&uri, &text, &lang_id).await;
427        }
428    }
429
430    async fn did_close(&self, params: DidCloseTextDocumentParams) {
431        self.documents.remove(&params.text_document.uri.to_string());
432    }
433
434    async fn did_change_configuration(&self, params: DidChangeConfigurationParams) {
435        let settings: LspSettings = serde_json::from_value(params.settings).unwrap_or_default();
436        self.apply_settings(&settings.lang_check).await;
437        self.rediagnose_all().await;
438    }
439
440    async fn code_action(&self, params: CodeActionParams) -> Result<Option<CodeActionResponse>> {
441        let uri = &params.text_document.uri;
442        let mut actions: Vec<CodeActionOrCommand> = Vec::new();
443
444        for diag in &params.context.diagnostics {
445            if diag.source.as_deref() != Some("language-check") {
446                continue;
447            }
448
449            let Some(data) = &diag.data else { continue };
450            let Some(obj) = data.as_object() else {
451                continue;
452            };
453
454            // Apply suggestion actions
455            if let Some(suggestions) = obj.get("suggestions").and_then(|v| v.as_array()) {
456                for s in suggestions {
457                    if let Some(text) = s.as_str() {
458                        let edit = TextEdit {
459                            range: diag.range,
460                            new_text: text.to_string(),
461                        };
462                        let mut changes = HashMap::new();
463                        changes.insert(uri.clone(), vec![edit]);
464                        actions.push(CodeActionOrCommand::CodeAction(CodeAction {
465                            title: format!("Replace with \"{text}\""),
466                            kind: Some(CodeActionKind::QUICKFIX),
467                            diagnostics: Some(vec![diag.clone()]),
468                            edit: Some(WorkspaceEdit {
469                                changes: Some(changes),
470                                ..Default::default()
471                            }),
472                            ..Default::default()
473                        }));
474                    }
475                }
476            }
477
478            // Add to dictionary (spelling rules)
479            if let Some(rule_id) = obj.get("rule_id").and_then(|v| v.as_str())
480                && (rule_id.contains("TYPO")
481                    || rule_id.contains("MORFOLOGIK")
482                    || rule_id.contains("spelling"))
483                && let Some(doc) = self.documents.get(&uri.to_string())
484            {
485                let word = extract_word_at_range(&doc.value().0, diag.range).unwrap_or_default();
486                if !word.is_empty() {
487                    actions.push(CodeActionOrCommand::CodeAction(CodeAction {
488                        title: format!("Add \"{word}\" to dictionary"),
489                        kind: Some(CodeActionKind::QUICKFIX),
490                        diagnostics: Some(vec![diag.clone()]),
491                        command: Some(Command {
492                            title: "Add to dictionary".into(),
493                            command: "langCheck.addDictionaryWord".into(),
494                            arguments: Some(vec![serde_json::json!(word)]),
495                        }),
496                        ..Default::default()
497                    }));
498                }
499            }
500        }
501
502        if actions.is_empty() {
503            Ok(None)
504        } else {
505            Ok(Some(actions))
506        }
507    }
508
509    async fn execute_command(
510        &self,
511        params: ExecuteCommandParams,
512    ) -> Result<Option<serde_json::Value>> {
513        match params.command.as_str() {
514            "langCheck.addDictionaryWord" => {
515                if let Some(word_val) = params.arguments.first()
516                    && let Some(word) = word_val.as_str()
517                {
518                    debug!(word, "Adding to dictionary");
519                    let mut dict = self.dictionary.lock().await;
520                    if let Err(e) = dict.add_word(word) {
521                        warn!(word, "Failed to add word: {e}");
522                    }
523                }
524            }
525            "langCheck.ignoreDiagnostic" => {
526                if let Some(args) = params.arguments.first()
527                    && let Some(obj) = args.as_object()
528                {
529                    let message = obj
530                        .get("message")
531                        .and_then(|v| v.as_str())
532                        .unwrap_or_default();
533                    let context = obj
534                        .get("context")
535                        .and_then(|v| v.as_str())
536                        .unwrap_or_default();
537                    let start = obj
538                        .get("start_byte")
539                        .and_then(serde_json::Value::as_u64)
540                        .map_or(0, |v| v as usize);
541                    let end = obj
542                        .get("end_byte")
543                        .and_then(serde_json::Value::as_u64)
544                        .map_or(0, |v| v as usize);
545                    let fp = DiagnosticFingerprint::new(message, context, start, end);
546                    self.ignore_store.lock().await.ignore(&fp);
547                }
548            }
549            _ => {}
550        }
551        Ok(None)
552    }
553}
554
555// ── Helpers ─────────────────────────────────────────────────────────────────
556
557/// Convert an internal Diagnostic to an LSP Diagnostic.
558fn to_lsp_diagnostic(text: &str, d: &checker::Diagnostic) -> Diagnostic {
559    let range = byte_range_to_lsp(text, d.start_byte as usize, d.end_byte as usize);
560    let severity = match d.severity {
561        3 => Some(DiagnosticSeverity::ERROR),
562        2 => Some(DiagnosticSeverity::WARNING),
563        4 => Some(DiagnosticSeverity::HINT),
564        // SEVERITY_UNSPECIFIED (0) and SEVERITY_INFORMATION (1)
565        _ => Some(DiagnosticSeverity::INFORMATION),
566    };
567
568    let data = serde_json::json!({
569        "suggestions": d.suggestions,
570        "rule_id": d.rule_id,
571        "unified_id": d.unified_id,
572    });
573
574    Diagnostic {
575        range,
576        severity,
577        source: Some("language-check".into()),
578        code: Some(NumberOrString::String(d.unified_id.clone())),
579        message: d.message.clone(),
580        data: Some(data),
581        ..Default::default()
582    }
583}
584
585/// Convert byte offsets to an LSP Range (line/character).
586fn byte_range_to_lsp(text: &str, start: usize, end: usize) -> Range {
587    Range {
588        start: byte_to_position(text, start),
589        end: byte_to_position(text, end),
590    }
591}
592
593fn byte_to_position(text: &str, byte_offset: usize) -> Position {
594    let offset = byte_offset.min(text.len());
595    let prefix = &text[..offset];
596    let line = prefix.matches('\n').count() as u32;
597    let last_newline = prefix.rfind('\n').map_or(0, |i| i + 1);
598    let character = prefix[last_newline..].chars().count() as u32;
599    Position { line, character }
600}
601
602/// Guess a language ID from a file URI extension.
603fn guess_lang_id(uri: &Url) -> String {
604    let path = uri.path();
605    let ext = path.rsplit('.').next().unwrap_or("");
606    match ext {
607        "html" | "htm" | "xhtml" => "html",
608        "tex" | "latex" | "ltx" => "latex",
609        "typ" => "typst",
610        "rst" => "rst",
611        "org" => "org",
612        "bib" => "bibtex",
613        "Rnw" | "rnw" | "Snw" | "snw" => "sweave",
614        "tree" => "forester",
615        // md, mdx, markdown, and everything else defaults to markdown
616        _ => "markdown",
617    }
618    .to_string()
619}
620
621/// Extract the word at a given LSP range from a document.
622fn extract_word_at_range(text: &str, range: Range) -> Option<String> {
623    let start = position_to_byte(text, range.start)?;
624    let end = position_to_byte(text, range.end)?;
625    Some(safe_slice(text, start, end).to_string())
626}
627
628fn position_to_byte(text: &str, pos: Position) -> Option<usize> {
629    let mut line = 0u32;
630    let mut byte = 0usize;
631    for (i, ch) in text.char_indices() {
632        if line == pos.line {
633            let col_offset = text[byte..].char_indices().nth(pos.character as usize);
634            return Some(col_offset.map_or(text.len(), |(off, _)| byte + off));
635        }
636        if ch == '\n' {
637            line += 1;
638            byte = i + 1;
639        }
640    }
641    if line == pos.line {
642        let col_offset = text[byte..].char_indices().nth(pos.character as usize);
643        return Some(col_offset.map_or(text.len(), |(off, _)| byte + off));
644    }
645    None
646}
647
648// ── Entry point ─────────────────────────────────────────────────────────────
649
650/// Run the LSP server on stdin/stdout.
651pub async fn run_lsp() {
652    let stdin = tokio::io::stdin();
653    let stdout = tokio::io::stdout();
654
655    let (service, socket) = LspService::new(Backend::new);
656    Server::new(stdin, stdout, socket).serve(service).await;
657}