Skip to main content

logicaffeine_lsp/
server.rs

1use std::sync::Arc;
2
3use lsp_types::*;
4use tower_lsp::jsonrpc::Result;
5use tower_lsp::{Client, LanguageServer};
6
7use crate::document::DocumentState;
8use crate::flycheck::{CargoFlycheck, Flycheck, FlycheckRunner};
9use crate::scheduler::{Scheduler, DEBOUNCE};
10use crate::semantic_tokens;
11use crate::state::ServerState;
12use crate::workspace::WorkspaceIndex;
13
14pub struct LogicAffeineServer {
15    client: Client,
16    state: Arc<ServerState>,
17    scheduler: Arc<Scheduler>,
18    workspace_index: Arc<WorkspaceIndex>,
19    workspace_roots: std::sync::Mutex<Vec<std::path::PathBuf>>,
20    flycheck: Arc<Flycheck>,
21    /// `logicaffeine.flycheck.enable` — on-save rustc analysis (default on).
22    flycheck_enabled: std::sync::atomic::AtomicBool,
23}
24
25impl LogicAffeineServer {
26    pub fn new(client: Client) -> Self {
27        Self::with_flycheck(client, Box::new(CargoFlycheck::new()))
28    }
29
30    /// Construct with an injected check engine — the seam mock-runner tests
31    /// use to prove merge/staleness/dedup behavior without a toolchain.
32    pub fn with_flycheck(client: Client, runner: Box<dyn FlycheckRunner>) -> Self {
33        LogicAffeineServer {
34            client,
35            state: Arc::new(ServerState::new()),
36            scheduler: Arc::new(Scheduler::new()),
37            workspace_index: Arc::new(WorkspaceIndex::new()),
38            workspace_roots: std::sync::Mutex::new(Vec::new()),
39            flycheck: Arc::new(Flycheck::new(runner)),
40            flycheck_enabled: std::sync::atomic::AtomicBool::new(true),
41        }
42    }
43
44    /// The cache key for this document's flycheck runs: the workspace root
45    /// when one is open, else the file's own directory.
46    fn workspace_key(&self, uri: &Url) -> String {
47        if let Some(root) = self.workspace_roots.lock().unwrap().first() {
48            return root.display().to_string();
49        }
50        uri.to_file_path()
51            .ok()
52            .and_then(|p| p.parent().map(|d| d.display().to_string()))
53            .unwrap_or_else(|| uri.to_string())
54    }
55
56    /// Analyze `text` off the async runtime, and — if `generation` is still
57    /// current when done — install the snapshot and publish its diagnostics.
58    async fn analyze_and_publish(
59        client: Client,
60        state: Arc<ServerState>,
61        scheduler: Arc<Scheduler>,
62        flycheck: Arc<Flycheck>,
63        uri: Url,
64        text: String,
65        version: i32,
66        generation: u64,
67    ) {
68        let analysis_uri = uri.clone();
69        let document = match tokio::task::spawn_blocking(move || {
70            DocumentState::with_uri(text, version, Some(&analysis_uri))
71        })
72        .await
73        {
74            Ok(document) => document,
75            Err(join_error) => {
76                // Defense in depth: the parser is total by construction, but
77                // an analysis panic must degrade to "stale snapshot", never
78                // take the document (or the server) down.
79                log::error!("analysis panicked for {uri}: {join_error}");
80                return;
81            }
82        };
83
84        if !scheduler.is_current(&uri, generation) {
85            return;
86        }
87        let snapshot = state.install_snapshot(uri.clone(), document);
88        let mut diagnostics = snapshot.diagnostics.clone();
89        diagnostics.extend(flycheck.diagnostics_for(&uri));
90        client
91            .publish_diagnostics(uri, diagnostics, Some(snapshot.version))
92            .await;
93    }
94}
95
96#[tower_lsp::async_trait]
97impl LanguageServer for LogicAffeineServer {
98    async fn initialize(&self, params: InitializeParams) -> Result<InitializeResult> {
99        let mut roots = Vec::new();
100        if let Some(folders) = params.workspace_folders {
101            roots.extend(folders.iter().filter_map(|f| f.uri.to_file_path().ok()));
102        }
103        #[allow(deprecated)]
104        if roots.is_empty() {
105            if let Some(root) = params.root_uri.and_then(|u| u.to_file_path().ok()) {
106                roots.push(root);
107            }
108        }
109        *self.workspace_roots.lock().unwrap() = roots;
110
111        Ok(InitializeResult {
112            capabilities: ServerCapabilities {
113                text_document_sync: Some(TextDocumentSyncCapability::Options(
114                    TextDocumentSyncOptions {
115                        open_close: Some(true),
116                        change: Some(TextDocumentSyncKind::INCREMENTAL),
117                        save: Some(TextDocumentSyncSaveOptions::SaveOptions(SaveOptions {
118                            include_text: Some(false),
119                        })),
120                        ..Default::default()
121                    },
122                )),
123                semantic_tokens_provider: Some(
124                    SemanticTokensServerCapabilities::SemanticTokensOptions(
125                        SemanticTokensOptions {
126                            legend: semantic_tokens::legend(),
127                            full: Some(SemanticTokensFullOptions::Delta { delta: Some(true) }),
128                            range: Some(true),
129                            ..Default::default()
130                        },
131                    ),
132                ),
133                document_symbol_provider: Some(OneOf::Left(true)),
134                definition_provider: Some(OneOf::Left(true)),
135                hover_provider: Some(HoverProviderCapability::Simple(true)),
136                completion_provider: Some(CompletionOptions {
137                    trigger_characters: Some(vec![
138                        ".".to_string(),
139                        ":".to_string(),
140                        "'".to_string(),
141                    ]),
142                    ..Default::default()
143                }),
144                references_provider: Some(OneOf::Left(true)),
145                signature_help_provider: Some(SignatureHelpOptions {
146                    trigger_characters: Some(vec![" ".to_string(), ",".to_string()]),
147                    ..Default::default()
148                }),
149                code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
150                rename_provider: Some(OneOf::Right(RenameOptions {
151                    prepare_provider: Some(true),
152                    work_done_progress_options: Default::default(),
153                })),
154                folding_range_provider: Some(FoldingRangeProviderCapability::Simple(true)),
155                inlay_hint_provider: Some(OneOf::Left(true)),
156                code_lens_provider: Some(CodeLensOptions {
157                    resolve_provider: Some(false),
158                }),
159                document_formatting_provider: Some(OneOf::Left(true)),
160                document_range_formatting_provider: Some(OneOf::Left(true)),
161                document_on_type_formatting_provider: Some(DocumentOnTypeFormattingOptions {
162                    first_trigger_character: ".".to_string(),
163                    more_trigger_character: None,
164                }),
165                document_highlight_provider: Some(OneOf::Left(true)),
166                selection_range_provider: Some(SelectionRangeProviderCapability::Simple(true)),
167                call_hierarchy_provider: Some(CallHierarchyServerCapability::Simple(true)),
168                diagnostic_provider: Some(DiagnosticServerCapabilities::Options(
169                    DiagnosticOptions {
170                        identifier: None,
171                        inter_file_dependencies: false,
172                        workspace_diagnostics: false,
173                        work_done_progress_options: Default::default(),
174                    },
175                )),
176                workspace_symbol_provider: Some(OneOf::Left(true)),
177                ..Default::default()
178            },
179            server_info: Some(ServerInfo {
180                name: "logicaffeine-lsp".to_string(),
181                version: Some(env!("CARGO_PKG_VERSION").to_string()),
182            }),
183        })
184    }
185
186    async fn initialized(&self, _: InitializedParams) {
187        log::info!("LogicAffeine LSP initialized");
188        // Index the workspace in the background; requests answer from
189        // whatever has landed so far.
190        let roots = self.workspace_roots.lock().unwrap().clone();
191        let index = Arc::clone(&self.workspace_index);
192        tokio::task::spawn_blocking(move || {
193            for root in roots {
194                index.scan_folder(&root);
195            }
196        });
197    }
198
199    async fn did_change_configuration(&self, params: DidChangeConfigurationParams) {
200        // `logicaffeine.flycheck.enable` — the only server-side setting today.
201        let enabled = params
202            .settings
203            .pointer("/logicaffeine/flycheck/enable")
204            .and_then(|v| v.as_bool())
205            .unwrap_or(true);
206        let was = self
207            .flycheck_enabled
208            .swap(enabled, std::sync::atomic::Ordering::SeqCst);
209        if was && !enabled {
210            // Turning it off retracts published findings: republish every
211            // open document's interactive-only set.
212            let uris = self.scheduler.open_uris();
213            for uri in uris {
214                self.flycheck.forget(&uri);
215                if let Some(doc) = self.state.snapshot(&uri) {
216                    self.client
217                        .publish_diagnostics(uri, doc.diagnostics.clone(), Some(doc.version))
218                        .await;
219                }
220            }
221        }
222    }
223
224    async fn did_save(&self, params: DidSaveTextDocumentParams) {
225        if !self
226            .flycheck_enabled
227            .load(std::sync::atomic::Ordering::SeqCst)
228        {
229            // Workspace re-index still happens; only the rustc pass is off.
230            if let Ok(path) = params.text_document.uri.to_file_path() {
231                let index = Arc::clone(&self.workspace_index);
232                tokio::task::spawn_blocking(move || index.index_file(&path));
233            }
234            return;
235        }
236        let uri = params.text_document.uri;
237        if let Ok(path) = uri.to_file_path() {
238            let index = Arc::clone(&self.workspace_index);
239            tokio::task::spawn_blocking(move || index.index_file(&path));
240        }
241
242        // Flycheck: run rustc's analysis over the saved text in the
243        // background; the generation guard means a newer save always wins.
244        let Some((text, version)) = self.scheduler.current_text(&uri) else {
245            return;
246        };
247        let generation = self.flycheck.begin_save(&uri);
248        let workspace_key = self.workspace_key(&uri);
249        let client = self.client.clone();
250        let state = Arc::clone(&self.state);
251        let flycheck = Arc::clone(&self.flycheck);
252        tokio::spawn(async move {
253            let run_text = text.clone();
254            let run_flycheck = Arc::clone(&flycheck);
255            let findings =
256                tokio::task::spawn_blocking(move || run_flycheck.run(&run_text, &workspace_key))
257                    .await
258                    .expect("flycheck task panicked");
259
260            // Unavailable toolchain: interactive-only diagnostics, silently.
261            let Some(findings) = findings else { return };
262
263            let interactive = state
264                .snapshot(&uri)
265                .map(|doc| doc.diagnostics.clone())
266                .unwrap_or_default();
267            let Some(rustc_diagnostics) =
268                flycheck.complete(&uri, generation, findings, &text, &interactive)
269            else {
270                return; // a newer save or an edit superseded this run
271            };
272
273            let mut diagnostics = interactive;
274            diagnostics.extend(rustc_diagnostics);
275            client
276                .publish_diagnostics(uri, diagnostics, Some(version))
277                .await;
278        });
279    }
280
281    async fn did_change_watched_files(&self, params: DidChangeWatchedFilesParams) {
282        let index = Arc::clone(&self.workspace_index);
283        tokio::task::spawn_blocking(move || {
284            for change in params.changes {
285                match change.typ {
286                    FileChangeType::DELETED => index.remove(&change.uri),
287                    _ => {
288                        if let Ok(path) = change.uri.to_file_path() {
289                            index.index_file(&path);
290                        }
291                    }
292                }
293            }
294        });
295    }
296
297    async fn symbol(
298        &self,
299        params: WorkspaceSymbolParams,
300    ) -> Result<Option<Vec<SymbolInformation>>> {
301        let hits = self.workspace_index.query(&params.query, 256);
302        if hits.is_empty() {
303            return Ok(None);
304        }
305        #[allow(deprecated)]
306        Ok(Some(
307            hits.into_iter()
308                .map(|s| SymbolInformation {
309                    name: s.name,
310                    kind: s.kind,
311                    tags: None,
312                    deprecated: None,
313                    location: s.location,
314                    container_name: s.container,
315                })
316                .collect(),
317        ))
318    }
319
320    async fn shutdown(&self) -> Result<()> {
321        Ok(())
322    }
323
324    async fn did_open(&self, params: DidOpenTextDocumentParams) {
325        let uri = params.text_document.uri;
326        let text = params.text_document.text;
327        let version = params.text_document.version;
328
329        let generation = self.scheduler.open(uri.clone(), text.clone(), version);
330        // First analysis runs immediately — no debounce on open.
331        Self::analyze_and_publish(
332            self.client.clone(),
333            Arc::clone(&self.state),
334            Arc::clone(&self.scheduler),
335            Arc::clone(&self.flycheck),
336            uri,
337            text,
338            version,
339            generation,
340        )
341        .await;
342    }
343
344    async fn did_change(&self, params: DidChangeTextDocumentParams) {
345        let uri = params.text_document.uri;
346        let version = params.text_document.version;
347
348        let Some(generation) = self
349            .scheduler
350            .apply_changes(&uri, params.content_changes, version)
351        else {
352            return;
353        };
354
355        // Edits invalidate flycheck findings — their positions would lie. If any
356        // were on screen, retract them NOW (republish the interactive-only
357        // snapshot) so they don't linger at pre-edit positions until the debounce.
358        if self.flycheck.clear(&uri) {
359            if let Some(doc) = self.state.snapshot(&uri) {
360                self.client
361                    .publish_diagnostics(uri.clone(), doc.diagnostics.clone(), Some(doc.version))
362                    .await;
363            }
364        }
365
366        // Debounce: analysis fires only if no newer edit arrives in the
367        // window; the generation guard drops stale results after it.
368        let client = self.client.clone();
369        let state = Arc::clone(&self.state);
370        let scheduler = Arc::clone(&self.scheduler);
371        let flycheck = Arc::clone(&self.flycheck);
372        tokio::spawn(async move {
373            tokio::time::sleep(DEBOUNCE).await;
374            let Some((text, version)) = scheduler.current_if(&uri, generation) else {
375                return;
376            };
377            Self::analyze_and_publish(
378                client, state, scheduler, flycheck, uri, text, version, generation,
379            )
380            .await;
381        });
382    }
383
384    async fn did_close(&self, params: DidCloseTextDocumentParams) {
385        self.scheduler.close(&params.text_document.uri);
386        self.state.close_document(&params.text_document.uri);
387        self.flycheck.forget(&params.text_document.uri);
388        // Clear diagnostics on close
389        self.client
390            .publish_diagnostics(params.text_document.uri, vec![], None)
391            .await;
392    }
393
394    async fn semantic_tokens_full(
395        &self,
396        params: SemanticTokensParams,
397    ) -> Result<Option<SemanticTokensResult>> {
398        let uri = &params.text_document.uri;
399        let doc = match self.state.snapshot(uri) {
400            Some(doc) => doc,
401            None => return Ok(None),
402        };
403
404        let data = semantic_tokens::encode_document_tokens(&doc);
405        let result_id = self.state.cache_semantic_tokens(uri.clone(), data.clone());
406
407        Ok(Some(SemanticTokensResult::Tokens(SemanticTokens {
408            result_id: Some(result_id),
409            data,
410        })))
411    }
412
413    async fn semantic_tokens_full_delta(
414        &self,
415        params: SemanticTokensDeltaParams,
416    ) -> Result<Option<SemanticTokensFullDeltaResult>> {
417        let uri = &params.text_document.uri;
418        let doc = match self.state.snapshot(uri) {
419            Some(doc) => doc,
420            None => return Ok(None),
421        };
422
423        let data = semantic_tokens::encode_document_tokens(&doc);
424        let previous = self.state.cached_semantic_tokens(uri);
425        let result_id = self.state.cache_semantic_tokens(uri.clone(), data.clone());
426
427        match previous {
428            Some((prev_id, prev_data)) if prev_id == params.previous_result_id => {
429                let edits = semantic_tokens::semantic_token_edits(&prev_data, &data);
430                Ok(Some(SemanticTokensFullDeltaResult::TokensDelta(
431                    SemanticTokensDelta {
432                        result_id: Some(result_id),
433                        edits,
434                    },
435                )))
436            }
437            // Unknown or stale id: answer with the full set.
438            _ => Ok(Some(SemanticTokensFullDeltaResult::Tokens(
439                SemanticTokens {
440                    result_id: Some(result_id),
441                    data,
442                },
443            ))),
444        }
445    }
446
447    async fn semantic_tokens_range(
448        &self,
449        params: SemanticTokensRangeParams,
450    ) -> Result<Option<SemanticTokensRangeResult>> {
451        let uri = &params.text_document.uri;
452        let doc = match self.state.snapshot(uri) {
453            Some(doc) => doc,
454            None => return Ok(None),
455        };
456
457        let start = doc.line_index.offset(params.range.start);
458        let end = doc.line_index.offset(params.range.end);
459        let data = semantic_tokens::encode_document_tokens_in_range(&doc, start, end);
460
461        Ok(Some(SemanticTokensRangeResult::Tokens(SemanticTokens {
462            result_id: None,
463            data,
464        })))
465    }
466
467    async fn document_symbol(
468        &self,
469        params: DocumentSymbolParams,
470    ) -> Result<Option<DocumentSymbolResponse>> {
471        let uri = &params.text_document.uri;
472        let doc = match self.state.snapshot(uri) {
473            Some(doc) => doc,
474            None => return Ok(None),
475        };
476
477        let symbols = crate::document_symbols::document_symbols(&doc);
478        Ok(Some(DocumentSymbolResponse::Nested(symbols)))
479    }
480
481    async fn goto_definition(
482        &self,
483        params: GotoDefinitionParams,
484    ) -> Result<Option<GotoDefinitionResponse>> {
485        let uri = &params.text_document_position_params.text_document.uri;
486        let position = params.text_document_position_params.position;
487
488        let doc = match self.state.snapshot(uri) {
489            Some(doc) => doc,
490            None => return Ok(None),
491        };
492
493        if let Some(local) = crate::definition::goto_definition(&doc, position, uri) {
494            return Ok(Some(local));
495        }
496
497        // Cross-file: resolve the name under the cursor against the
498        // workspace index when this document doesn't define it.
499        let offset = doc.line_index.offset(position);
500        let name = doc
501            .tokens
502            .iter()
503            .find(|t| t.span.start <= offset && offset < t.span.end)
504            .and_then(|t| crate::index::resolve_token_name(t, &doc.interner))
505            .map(|n| n.to_string());
506        Ok(name
507            .and_then(|n| self.workspace_index.definition_of(&n))
508            .map(GotoDefinitionResponse::Scalar))
509    }
510
511    async fn hover(&self, params: HoverParams) -> Result<Option<Hover>> {
512        let uri = &params.text_document_position_params.text_document.uri;
513        let position = params.text_document_position_params.position;
514
515        let doc = match self.state.snapshot(uri) {
516            Some(doc) => doc,
517            None => return Ok(None),
518        };
519
520        Ok(crate::hover::hover_with_workspace(
521            &doc,
522            position,
523            &*self.workspace_index,
524        ))
525    }
526
527    async fn completion(&self, params: CompletionParams) -> Result<Option<CompletionResponse>> {
528        let uri = &params.text_document_position.text_document.uri;
529        let position = params.text_document_position.position;
530
531        let doc = match self.state.snapshot(uri) {
532            Some(doc) => doc,
533            None => return Ok(None),
534        };
535
536        Ok(crate::completion::completions_with_workspace(
537            &doc,
538            position,
539            &*self.workspace_index,
540            uri,
541        ))
542    }
543
544    async fn references(&self, params: ReferenceParams) -> Result<Option<Vec<Location>>> {
545        let uri = &params.text_document_position.text_document.uri;
546        let position = params.text_document_position.position;
547
548        let doc = match self.state.snapshot(uri) {
549            Some(doc) => doc,
550            None => return Ok(None),
551        };
552
553        let include_declaration = params.context.include_declaration;
554        let mut locations =
555            crate::references::find_references(&doc, position, uri, include_declaration);
556
557        // Cross-file: LIVE buffers answer for themselves; the workspace
558        // index answers for everything on disk that isn't open.
559        if let Some(name) = crate::references::name_at(&doc, position) {
560            if crate::references::is_cross_file_symbol(&doc, &name) {
561                let open_docs = self.state.open_documents();
562                for (other_uri, other_doc) in &open_docs {
563                    if other_uri == uri {
564                        continue;
565                    }
566                    for range in crate::references::cross_file_candidates(
567                        other_doc,
568                        &name,
569                        include_declaration,
570                    ) {
571                        locations.push(Location {
572                            uri: other_uri.clone(),
573                            range,
574                        });
575                    }
576                }
577                let skip: Vec<&Url> = open_docs.iter().map(|(u, _)| u).collect();
578                locations.extend(self.workspace_index.references_of(&name, &skip));
579            }
580        }
581
582        if locations.is_empty() {
583            Ok(None)
584        } else {
585            Ok(Some(locations))
586        }
587    }
588
589    async fn signature_help(&self, params: SignatureHelpParams) -> Result<Option<SignatureHelp>> {
590        let uri = &params.text_document_position_params.text_document.uri;
591        let position = params.text_document_position_params.position;
592
593        let doc = match self.state.snapshot(uri) {
594            Some(doc) => doc,
595            None => return Ok(None),
596        };
597
598        Ok(crate::signature_help::signature_help(&doc, position))
599    }
600
601    async fn code_action(&self, params: CodeActionParams) -> Result<Option<CodeActionResponse>> {
602        let uri = &params.text_document.uri;
603        let range = params.range;
604
605        let doc = match self.state.snapshot(uri) {
606            Some(doc) => doc,
607            None => return Ok(None),
608        };
609
610        let mut actions = crate::code_actions::code_actions(&doc, range, uri);
611        // Auto-import quickfixes need the workspace index (which module exports the
612        // unresolved name) — computed from the LIVE buffer's references.
613        actions.extend(crate::code_actions::import_code_actions(
614            &doc,
615            range,
616            uri,
617            &*self.workspace_index,
618        ));
619        actions.extend(crate::code_actions::unused_import_actions(
620            &doc,
621            range,
622            uri,
623            &*self.workspace_index,
624        ));
625        if actions.is_empty() {
626            Ok(None)
627        } else {
628            Ok(Some(actions))
629        }
630    }
631
632    async fn rename(&self, params: RenameParams) -> Result<Option<WorkspaceEdit>> {
633        let uri = &params.text_document_position.text_document.uri;
634        let position = params.text_document_position.position;
635
636        let doc = match self.state.snapshot(uri) {
637            Some(doc) => doc,
638            None => return Ok(None),
639        };
640
641        let new_name = params.new_name;
642        let mut edit = match crate::rename::rename(&doc, position, new_name.clone(), uri) {
643            Some(edit) => edit,
644            None => return Ok(None),
645        };
646
647        // Cross-file: LIVE buffers answer for themselves; the workspace
648        // index answers for everything on disk that isn't open.
649        if let Some(name) = crate::references::name_at(&doc, position) {
650            if crate::references::is_cross_file_symbol(&doc, &name) {
651                let changes = edit.changes.get_or_insert_with(Default::default);
652                let open_docs = self.state.open_documents();
653                for (other_uri, other_doc) in &open_docs {
654                    if other_uri == uri {
655                        continue;
656                    }
657                    let ranges = crate::references::cross_file_candidates(other_doc, &name, true);
658                    if !ranges.is_empty() {
659                        changes.entry(other_uri.clone()).or_default().extend(
660                            ranges.into_iter().map(|range| TextEdit {
661                                range,
662                                new_text: new_name.clone(),
663                            }),
664                        );
665                    }
666                }
667                let skip: Vec<&Url> = open_docs.iter().map(|(u, _)| u).collect();
668                for location in self.workspace_index.references_of(&name, &skip) {
669                    changes.entry(location.uri).or_default().push(TextEdit {
670                        range: location.range,
671                        new_text: new_name.clone(),
672                    });
673                }
674            }
675        }
676
677        Ok(Some(edit))
678    }
679
680    async fn prepare_rename(
681        &self,
682        params: TextDocumentPositionParams,
683    ) -> Result<Option<PrepareRenameResponse>> {
684        let uri = &params.text_document.uri;
685        let position = params.position;
686
687        let doc = match self.state.snapshot(uri) {
688            Some(doc) => doc,
689            None => return Ok(None),
690        };
691
692        Ok(
693            crate::rename::prepare_rename(&doc, position).map(|(range, text)| {
694                PrepareRenameResponse::RangeWithPlaceholder {
695                    range,
696                    placeholder: text,
697                }
698            }),
699        )
700    }
701
702    async fn folding_range(&self, params: FoldingRangeParams) -> Result<Option<Vec<FoldingRange>>> {
703        let uri = &params.text_document.uri;
704
705        let doc = match self.state.snapshot(uri) {
706            Some(doc) => doc,
707            None => return Ok(None),
708        };
709
710        let ranges = crate::folding::folding_ranges(&doc);
711        if ranges.is_empty() {
712            Ok(None)
713        } else {
714            Ok(Some(ranges))
715        }
716    }
717
718    async fn inlay_hint(&self, params: InlayHintParams) -> Result<Option<Vec<InlayHint>>> {
719        let uri = &params.text_document.uri;
720
721        let doc = match self.state.snapshot(uri) {
722            Some(doc) => doc,
723            None => return Ok(None),
724        };
725
726        let hints = crate::inlay_hints::inlay_hints(&doc, params.range);
727        if hints.is_empty() {
728            Ok(None)
729        } else {
730            Ok(Some(hints))
731        }
732    }
733
734    async fn code_lens(&self, params: CodeLensParams) -> Result<Option<Vec<CodeLens>>> {
735        let uri = &params.text_document.uri;
736
737        let doc = match self.state.snapshot(uri) {
738            Some(doc) => doc,
739            None => return Ok(None),
740        };
741
742        let lenses = crate::code_lens::code_lenses(&doc, uri);
743        if lenses.is_empty() {
744            Ok(None)
745        } else {
746            Ok(Some(lenses))
747        }
748    }
749
750    async fn document_highlight(
751        &self,
752        params: DocumentHighlightParams,
753    ) -> Result<Option<Vec<DocumentHighlight>>> {
754        let uri = &params.text_document_position_params.text_document.uri;
755        let doc = match self.state.snapshot(uri) {
756            Some(doc) => doc,
757            None => return Ok(None),
758        };
759        Ok(crate::document_highlights::document_highlights(
760            &doc,
761            params.text_document_position_params.position,
762        ))
763    }
764
765    async fn selection_range(
766        &self,
767        params: SelectionRangeParams,
768    ) -> Result<Option<Vec<SelectionRange>>> {
769        let doc = match self.state.snapshot(&params.text_document.uri) {
770            Some(doc) => doc,
771            None => return Ok(None),
772        };
773        Ok(Some(crate::selection_ranges::selection_ranges(
774            &doc,
775            &params.positions,
776        )))
777    }
778
779    async fn on_type_formatting(
780        &self,
781        params: DocumentOnTypeFormattingParams,
782    ) -> Result<Option<Vec<TextEdit>>> {
783        let uri = &params.text_document_position.text_document.uri;
784        let doc = match self.state.snapshot(uri) {
785            Some(doc) => doc,
786            None => return Ok(None),
787        };
788
789        // Normalize the line the sentence just closed on — the same rule set
790        // `largo fmt` applies, one sentence at a time.
791        let line_number = params.text_document_position.position.line as usize;
792        let Some(line) = doc.source.split('\n').nth(line_number) else {
793            return Ok(None);
794        };
795        // Inside a multiline string every byte is content: an odd number of
796        // """ delimiters before this line means the sentence-closing `.`
797        // was typed inside one — never touch it. The LIVE text decides (the
798        // snapshot can lag a keystroke behind).
799        let live = self
800            .scheduler
801            .current_text(uri)
802            .map(|(text, _)| text)
803            .unwrap_or_else(|| doc.source.clone());
804        let line_start_offset: usize = live
805            .split('\n')
806            .take(line_number)
807            .map(|l| l.len() + 1)
808            .sum();
809        let delimiters_before = live[..line_start_offset.min(live.len())]
810            .matches("\"\"\"")
811            .count();
812        if delimiters_before % 2 == 1 {
813            return Ok(None);
814        }
815        let formatted = logicaffeine_language::source_format::format_line(line);
816        if formatted == line {
817            return Ok(None);
818        }
819        let end_character = line.encode_utf16().count() as u32;
820        Ok(Some(vec![TextEdit {
821            range: Range {
822                start: Position {
823                    line: line_number as u32,
824                    character: 0,
825                },
826                end: Position {
827                    line: line_number as u32,
828                    character: end_character,
829                },
830            },
831            new_text: formatted,
832        }]))
833    }
834
835    async fn prepare_call_hierarchy(
836        &self,
837        params: CallHierarchyPrepareParams,
838    ) -> Result<Option<Vec<CallHierarchyItem>>> {
839        let uri = &params.text_document_position_params.text_document.uri;
840        let doc = match self.state.snapshot(uri) {
841            Some(doc) => doc,
842            None => return Ok(None),
843        };
844        Ok(crate::call_hierarchy::prepare(
845            &doc,
846            params.text_document_position_params.position,
847            uri,
848        ))
849    }
850
851    async fn incoming_calls(
852        &self,
853        params: CallHierarchyIncomingCallsParams,
854    ) -> Result<Option<Vec<CallHierarchyIncomingCall>>> {
855        let uri = &params.item.uri;
856        let doc = match self.state.snapshot(uri) {
857            Some(doc) => doc,
858            None => return Ok(None),
859        };
860        Ok(Some(crate::call_hierarchy::incoming_calls(
861            &doc,
862            &params.item,
863            uri,
864        )))
865    }
866
867    async fn outgoing_calls(
868        &self,
869        params: CallHierarchyOutgoingCallsParams,
870    ) -> Result<Option<Vec<CallHierarchyOutgoingCall>>> {
871        let uri = &params.item.uri;
872        let doc = match self.state.snapshot(uri) {
873            Some(doc) => doc,
874            None => return Ok(None),
875        };
876        Ok(Some(crate::call_hierarchy::outgoing_calls(
877            &doc,
878            &params.item,
879            uri,
880        )))
881    }
882
883    async fn diagnostic(
884        &self,
885        params: DocumentDiagnosticParams,
886    ) -> Result<DocumentDiagnosticReportResult> {
887        let uri = &params.text_document.uri;
888        let (items, result_id) = match self.state.snapshot(uri) {
889            Some(doc) => {
890                let mut items = doc.diagnostics.clone();
891                let rustc = self.flycheck.diagnostics_for(uri);
892                // The id covers BOTH engines: a flycheck completion changes
893                // the report without a version bump.
894                let result_id = format!("{}:{}", doc.version, rustc.len());
895                items.extend(rustc);
896                (items, result_id)
897            }
898            None => (Vec::new(), "closed".to_string()),
899        };
900
901        if params.previous_result_id.as_deref() == Some(result_id.as_str()) {
902            return Ok(DocumentDiagnosticReportResult::Report(
903                DocumentDiagnosticReport::Unchanged(RelatedUnchangedDocumentDiagnosticReport {
904                    related_documents: None,
905                    unchanged_document_diagnostic_report: UnchangedDocumentDiagnosticReport {
906                        result_id,
907                    },
908                }),
909            ));
910        }
911
912        Ok(DocumentDiagnosticReportResult::Report(
913            DocumentDiagnosticReport::Full(RelatedFullDocumentDiagnosticReport {
914                related_documents: None,
915                full_document_diagnostic_report: FullDocumentDiagnosticReport {
916                    result_id: Some(result_id),
917                    items,
918                },
919            }),
920        ))
921    }
922
923    async fn range_formatting(
924        &self,
925        params: DocumentRangeFormattingParams,
926    ) -> Result<Option<Vec<TextEdit>>> {
927        let uri = &params.text_document.uri;
928        let doc = match self.state.snapshot(uri) {
929            Some(doc) => doc,
930            None => return Ok(None),
931        };
932        let edits = crate::formatting::format_range(&doc, params.range);
933        if edits.is_empty() {
934            Ok(None)
935        } else {
936            Ok(Some(edits))
937        }
938    }
939
940    async fn formatting(&self, params: DocumentFormattingParams) -> Result<Option<Vec<TextEdit>>> {
941        let uri = &params.text_document.uri;
942
943        let doc = match self.state.snapshot(uri) {
944            Some(doc) => doc,
945            None => return Ok(None),
946        };
947
948        let edits = crate::formatting::format_document(&doc);
949        if edits.is_empty() {
950            Ok(None)
951        } else {
952            Ok(Some(edits))
953        }
954    }
955}