Skip to main content

swls_core/
backend.rs

1use std::collections::HashMap;
2
3use crate::text::LineIndex;
4use bevy_ecs::{
5    bundle::Bundle,
6    component::Component,
7    entity::Entity,
8    query::With,
9    schedule::ScheduleLabel,
10    world::{CommandQueue, World},
11};
12use completion::CompletionRequest;
13use goto_type::GotoTypeRequest;
14use references::ReferencesRequest;
15use request::{GotoTypeDefinitionParams, GotoTypeDefinitionResponse};
16use tracing::{debug, error, info, instrument, warn};
17
18use crate::{
19    client::Client,
20    feature::{
21        code_action::{CodeActionRequest, Label as CodeActionLabel},
22        goto_definition::GotoDefinitionRequest,
23    },
24    lsp_types::{request::SemanticTokensRefresh, *},
25    prelude::*,
26    Started, Startup,
27};
28
29/// Error returned by [`Backend`] request handlers.
30///
31/// No handler currently fails at the protocol level, so this type is uninhabited.
32/// It exists so handlers can return a transport-agnostic [`Result`] that front-ends
33/// map onto their own error type (e.g. `tower_lsp::jsonrpc::Error`) without `swls-core`
34/// depending on any transport crate.
35#[derive(Debug)]
36pub enum ServerError {}
37
38/// Transport-agnostic result type for [`Backend`] request handlers.
39pub type Result<T> = std::result::Result<T, ServerError>;
40
41/// Transport-agnostic LSP request handler.
42///
43/// `Backend` exposes inherent `async` methods mirroring the LSP requests. Front-ends
44/// (the `swls` binary's `tower_lsp` adapter, or a future wasm dispatcher) call these
45/// directly. It is generic over the [`Client`] used to send server-to-client messages.
46pub struct Backend<C> {
47    sender: CommandSender,
48    client: C,
49    semantic_tokens: Vec<SemanticTokenType>,
50    /// Whether the client lets the server register file watchers.
51    watch_files: std::sync::atomic::AtomicBool,
52}
53
54/// Files the server asks the client to watch: the RDF files it may have
55/// loaded in the background (workspace index, `owl:imports`, configuration).
56const WATCHED_FILES: &str = "**/*.{ttl,nt,owl,trig,n3}";
57
58impl<C> std::fmt::Debug for Backend<C> {
59    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60        f.debug_struct("Backend")
61            .field("semantic_tokens", &self.semantic_tokens)
62            .finish_non_exhaustive()
63    }
64}
65
66impl<C: Client> Backend<C> {
67    pub fn new(sender: CommandSender, client: C, tokens: Vec<SemanticTokenType>) -> Self {
68        Self {
69            sender,
70            client,
71            semantic_tokens: tokens,
72            watch_files: std::sync::atomic::AtomicBool::new(false),
73        }
74    }
75
76    /// `config` combined with the global and the workspace config files.
77    async fn with_config_files(&self, mut config: Config, root: Option<&Url>) -> Config {
78        // Without a file system (the world is gone) there are no config files
79        // to read; keep the options the client sent.
80        if let Some(fs) = self.run(|w| w.resource::<Fs>().clone()).await {
81            if let Some(global) = LocalConfig::global(&fs).await {
82                config.local.combine(global);
83            }
84            if let Some(root) = root {
85                if let Some(local) = LocalConfig::local(&fs, root).await {
86                    config.local.combine(local);
87                }
88            }
89        }
90        config
91    }
92
93    async fn run<T: Send + Sync + 'static>(
94        &self,
95        f: impl FnOnce(&mut World) -> T + Send + Sync + 'static,
96    ) -> Option<T> {
97        let (tx, rx) = futures::channel::oneshot::channel();
98        let mut commands = CommandQueue::default();
99        commands.push(move |world: &mut World| {
100            let o = f(world);
101            if tx.send(o).is_err() {
102                error!("Failed to run schedule for {}", stringify!(T));
103            };
104        });
105
106        if let Err(e) = self.sender.0.unbounded_send(commands) {
107            error!("Failed to send commands {}", e);
108            return None;
109        }
110
111        rx.await.ok()
112    }
113
114    /// Run `schedule` for the document at `url` with the request component(s)
115    /// `param`, and take the response component `T`.
116    ///
117    /// The document is looked up inside the world, in the same step that runs
118    /// the schedule, so a document closed in between cannot be used after it
119    /// is gone. `None` when there is no such document.
120    async fn run_schedule<T: Component>(
121        &self,
122        url: Url,
123        schedule: impl ScheduleLabel + Clone,
124        param: impl Bundle,
125    ) -> Option<T> {
126        let (tx, rx) = futures::channel::oneshot::channel();
127
128        let mut commands = CommandQueue::default();
129        commands.push(move |world: &mut World| {
130            let Some(entity) = find_document(world, &url) else {
131                debug!("No document {}", url);
132                let _ = tx.send(None);
133                return;
134            };
135            world.entity_mut(entity).insert(param);
136            world.run_schedule(schedule.clone());
137            if tx.send(world.entity_mut(entity).take::<T>()).is_err() {
138                error!(name: "Failed to run schedule", "Failed to run schedule {:?}", schedule);
139            };
140        });
141
142        if let Err(e) = self.sender.0.unbounded_send(commands) {
143            error!("Failed to send commands {}", e);
144            return None;
145        }
146
147        rx.await.unwrap_or_default()
148    }
149
150    /// The document a request is about. Requests refer to documents by URL;
151    /// the entity is looked up when the request runs (see [`Self::run_schedule`]).
152    async fn document(&self, uri: &str) -> Option<Url> {
153        Url::parse(uri).ok()
154    }
155
156    /// Whether the given LSP feature has been disabled via [`ServerConfig`].
157    async fn is_disabled(&self, feature: Disabled) -> bool {
158        self.run(move |world| {
159            world
160                .resource::<ServerConfig>()
161                .config
162                .local
163                .is_disabled(feature)
164        })
165        .await
166        .unwrap_or(false)
167    }
168}
169
170impl<C: Client> Backend<C> {
171    #[instrument(skip(self, init))]
172    pub async fn initialize(&self, init: InitializeParams) -> Result<InitializeResult> {
173        info!("Initialize");
174
175        // Clients that only send a root get that root as their workspace.
176        let workspaces = init
177            .workspace_folders
178            .clone()
179            .filter(|w| !w.is_empty())
180            .or_else(|| {
181                init.root_uri.clone().map(|uri| {
182                    vec![WorkspaceFolder {
183                        name: uri.path().to_string(),
184                        uri,
185                    }]
186                })
187            })
188            .unwrap_or_default();
189        let config: Config = match init.initialization_options.clone() {
190            None | Some(serde_json::Value::Null) => Config::default(),
191            Some(options) => match serde_json::from_value(options) {
192                Ok(config) => config,
193                Err(e) => {
194                    // A single wrong value would otherwise reset every setting
195                    // without a trace.
196                    let msg = format!("Invalid swls initializationOptions, using defaults: {e}");
197                    warn!("{msg}");
198                    self.client.log_message(MessageType::WARNING, msg).await;
199                    Config::default()
200                }
201            },
202        };
203
204        let config = self.with_config_files(config, init.root_uri.as_ref()).await;
205        let server_config = ServerConfig { config, workspaces };
206
207        let watch_files = init
208            .capabilities
209            .workspace
210            .as_ref()
211            .and_then(|w| w.did_change_watched_files.as_ref())
212            .and_then(|w| w.dynamic_registration)
213            .unwrap_or(false);
214        self.watch_files
215            .store(watch_files, std::sync::atomic::Ordering::Relaxed);
216
217        info!("Initialize {:?}", server_config);
218        let document_selectors: Vec<_> = [
219            ("sparql", server_config.config.sparql.unwrap_or(true)),
220            ("turtle", server_config.config.turtle.unwrap_or(true)),
221            ("trig", server_config.config.trig.unwrap_or(true)),
222            ("n3", server_config.config.n3.unwrap_or(false)),
223            ("jsonld", server_config.config.jsonld.unwrap_or(true)),
224        ]
225        .into_iter()
226        .filter(|(_, x)| *x)
227        .map(|(x, _)| DocumentFilter {
228            language: Some(String::from(x)),
229            scheme: None,
230            pattern: None,
231        })
232        .collect();
233
234        let disabled = server_config.config.local.disabled.clone();
235        let is_enabled = |d: Disabled| !disabled.contains(&d);
236
237        self.run(|world| {
238            world.insert_resource(server_config);
239            world.run_schedule(Startup);
240        })
241        .await;
242
243        // let triggers = L::TRIGGERS.iter().copied().map(String::from).collect();
244        Ok(InitializeResult {
245            server_info: None,
246            capabilities: ServerCapabilities {
247                inlay_hint_provider: is_enabled(Disabled::InlayHint).then_some(OneOf::Left(true)),
248                text_document_sync: Some(TextDocumentSyncCapability::Kind(
249                    TextDocumentSyncKind::FULL,
250                )),
251                code_action_provider: is_enabled(Disabled::CodeAction)
252                    .then_some(CodeActionProviderCapability::Simple(true)),
253                completion_provider: is_enabled(Disabled::Completion).then_some(
254                    CompletionOptions {
255                        resolve_provider: Some(false),
256                        trigger_characters: Some(vec![String::from(":")]),
257                        work_done_progress_options: Default::default(),
258                        all_commit_characters: None,
259                        completion_item: None,
260                    },
261                ),
262                // implementation_provider: Some(ImplementationProviderCapability::Simple(true)),
263                type_definition_provider: is_enabled(Disabled::GotoTypeDefinition)
264                    .then_some(TypeDefinitionProviderCapability::Simple(true)),
265                references_provider: is_enabled(Disabled::References).then_some(OneOf::Left(true)),
266                hover_provider: is_enabled(Disabled::Hover)
267                    .then_some(HoverProviderCapability::Simple(true)),
268                definition_provider: is_enabled(Disabled::GotoDefinition)
269                    .then_some(OneOf::Left(true)),
270                document_formatting_provider: is_enabled(Disabled::Format)
271                    .then_some(OneOf::Left(true)),
272                document_on_type_formatting_provider: is_enabled(Disabled::PrefixAutoInsert)
273                    .then_some(DocumentOnTypeFormattingOptions {
274                        first_trigger_character: ":".to_string(),
275                        more_trigger_character: None,
276                    }),
277                semantic_tokens_provider: is_enabled(Disabled::SemanticTokens).then_some(
278                    SemanticTokensServerCapabilities::SemanticTokensRegistrationOptions(
279                        SemanticTokensRegistrationOptions {
280                            text_document_registration_options: {
281                                TextDocumentRegistrationOptions {
282                                    document_selector: Some(document_selectors),
283                                }
284                            },
285                            semantic_tokens_options: SemanticTokensOptions {
286                                work_done_progress_options: WorkDoneProgressOptions::default(),
287                                legend: SemanticTokensLegend {
288                                    token_types: self.semantic_tokens.clone(),
289                                    token_modifiers: vec![],
290                                },
291                                range: Some(false),
292                                full: Some(SemanticTokensFullOptions::Bool(true)),
293                            },
294                            static_registration_options: StaticRegistrationOptions::default(),
295                        },
296                    ),
297                ),
298                rename_provider: is_enabled(Disabled::Rename).then_some(OneOf::Right(
299                    RenameOptions {
300                        prepare_provider: Some(true),
301                        work_done_progress_options: Default::default(),
302                    },
303                )),
304                document_link_provider: is_enabled(Disabled::DocumentLink).then_some(
305                    DocumentLinkOptions {
306                        resolve_provider: Some(false),
307                        work_done_progress_options: Default::default(),
308                    },
309                ),
310                document_symbol_provider: is_enabled(Disabled::DocumentSymbol)
311                    .then_some(OneOf::Left(true)),
312                folding_range_provider: is_enabled(Disabled::FoldingRange)
313                    .then_some(FoldingRangeProviderCapability::Simple(true)),
314                workspace_symbol_provider: is_enabled(Disabled::WorkspaceSymbol)
315                    .then_some(OneOf::Left(true)),
316                execute_command_provider: Some(ExecuteCommandOptions {
317                    commands: vec![crate::systems::ALLOW_PROPERTY_COMMAND.to_string()],
318                    work_done_progress_options: Default::default(),
319                }),
320                ..ServerCapabilities::default()
321            },
322        })
323    }
324
325    pub async fn initialized(&self, _params: InitializedParams) {
326        self.run(|world| {
327            tracing::info!("initialized");
328            world.run_schedule(Started);
329        })
330        .await;
331
332        // Ask the client to report changes to RDF files on disk, so background
333        // documents (workspace files, imports) stay current.
334        if self.watch_files.load(std::sync::atomic::Ordering::Relaxed) {
335            let options = DidChangeWatchedFilesRegistrationOptions {
336                watchers: vec![FileSystemWatcher {
337                    glob_pattern: GlobPattern::String(WATCHED_FILES.to_string()),
338                    kind: None,
339                }],
340            };
341            let registration = Registration {
342                id: String::from("swls-watched-files"),
343                method: String::from("workspace/didChangeWatchedFiles"),
344                register_options: serde_json::to_value(options).ok(),
345            };
346            let _ = self
347                .client
348                .send_request::<request::RegisterCapability>(RegistrationParams {
349                    registrations: vec![registration],
350                })
351                .await;
352        }
353    }
354
355    /// Files changed on disk. Background documents are reloaded (or dropped
356    /// when deleted), and new RDF files in the workspace are indexed. A file
357    /// open in the editor keeps the editor's text.
358    #[instrument(skip(self, params))]
359    pub async fn did_change_watched_files(&self, params: DidChangeWatchedFilesParams) {
360        enum Action {
361            Reload(Entity),
362            /// Index a new file of the workspace folder (its root).
363            Load(Url),
364            Nothing,
365        }
366        let Some(fs) = self.run(|w| w.resource::<Fs>().clone()).await else {
367            return;
368        };
369        for change in params.changes {
370            let url = change.uri;
371            if change.typ == FileChangeType::DELETED {
372                let url = url.clone();
373                self.run(move |world| crate::document::remove_background(world, &url))
374                    .await;
375                continue;
376            }
377            let action = {
378                let url = url.clone();
379                self.run(move |world| match find_document(world, &url) {
380                    Some(e) if world.entity(e).contains::<Open>() => Action::Nothing,
381                    Some(e) => Action::Reload(e),
382                    None => {
383                        let config = world.resource::<ServerConfig>();
384                        let root = (!config.config.local.is_disabled(Disabled::WorkspaceIndex)
385                            && crate::workspace::is_workspace_file(&url))
386                        .then(|| crate::workspace::workspace_root(config, &url))
387                        .flatten();
388                        match root {
389                            Some(root) => Action::Load(root),
390                            None => Action::Nothing,
391                        }
392                    }
393                })
394                .await
395                .unwrap_or(Action::Nothing)
396            };
397            match action {
398                Action::Reload(entity) => {
399                    if let Some(content) = fs.0.read_file(&url).await {
400                        self.run(move |world| {
401                            crate::document::restore_background(world, entity, content)
402                        })
403                        .await;
404                    }
405                }
406                Action::Load(root) => {
407                    // The same files the startup walk skips (git-ignored, …).
408                    if !fs.0.is_ignored(&root, &url).await {
409                        crate::workspace::load_workspace_file(&fs, url, &self.sender).await;
410                    }
411                }
412                Action::Nothing => {}
413            }
414        }
415    }
416
417    /// The client's settings changed: apply them like `initializationOptions`
418    /// (combined with the config files), load newly configured ontologies and
419    /// shapes, and re-check open documents. Capabilities announced at
420    /// `initialize` cannot change.
421    #[instrument(skip(self, params))]
422    pub async fn did_change_configuration(&self, params: DidChangeConfigurationParams) {
423        // Clients send either the settings themselves or `{ "swls": … }`.
424        let settings = match params.settings {
425            serde_json::Value::Object(mut map) if map.contains_key("swls") => {
426                map.remove("swls").unwrap_or_default()
427            }
428            other => other,
429        };
430        if settings.is_null() {
431            return;
432        }
433        let config: Config = match serde_json::from_value(settings) {
434            Ok(config) => config,
435            Err(e) => {
436                let msg = format!("Invalid swls settings, keeping the current ones: {e}");
437                warn!("{msg}");
438                self.client.log_message(MessageType::WARNING, msg).await;
439                return;
440            }
441        };
442        let root = self
443            .run(|w| {
444                w.resource::<ServerConfig>()
445                    .workspaces
446                    .first()
447                    .map(|w| w.uri.clone())
448            })
449            .await
450            .flatten();
451        let config = self.with_config_files(config, root.as_ref()).await;
452
453        self.run(move |world| {
454            world.resource_mut::<ServerConfig>().config = config;
455            world.run_schedule(crate::ConfigChanged);
456            // Re-check every open document with the new settings.
457            let open: Vec<Entity> = world
458                .query_filtered::<Entity, With<Open>>()
459                .iter(world)
460                .collect();
461            for e in open {
462                if let Some(mut source) = world.get_mut::<Source>(e) {
463                    bevy_ecs::change_detection::DetectChangesMut::set_changed(&mut source);
464                }
465            }
466            world.run_schedule(ParseLabel);
467            world.flush();
468        })
469        .await;
470    }
471
472    pub async fn did_change_workspace_folders(
473        &self,
474        params: DidChangeWorkspaceFoldersParams,
475    ) -> () {
476        self.run(move |world| {
477            let mut config = world.resource_mut::<ServerConfig>();
478            let WorkspaceFoldersChangeEvent { added, removed } = params.event;
479
480            for r in removed {
481                if let Some(idx) = config.workspaces.iter().position(|x| x == &r) {
482                    config.workspaces.remove(idx);
483                }
484            }
485
486            // This is nice and all, but we don't bubble this event up in the world
487            config.workspaces.extend(added);
488        })
489        .await;
490    }
491
492    #[instrument(skip(self, params), fields(uri = %params.text_document.uri.as_str()))]
493    pub async fn semantic_tokens_full(
494        &self,
495        params: SemanticTokensParams,
496    ) -> Result<Option<SemanticTokensResult>> {
497        debug!("semantic tokens full");
498        if self.is_disabled(Disabled::SemanticTokens).await {
499            return Ok(None);
500        }
501        let uri = params.text_document.uri.as_str();
502        let Some(doc) = self.document(uri).await else {
503            debug!("No document {}", uri);
504            return Ok(None);
505        };
506
507        if let Some(res) = self
508            .run_schedule::<HighlightRequest>(doc, SemanticLabel, HighlightRequest(vec![]))
509            .await
510        {
511            Ok(Some(SemanticTokensResult::Tokens(
512                crate::lsp_types::SemanticTokens {
513                    result_id: None,
514                    data: res.0,
515                },
516            )))
517        } else {
518            debug!("resulting in no tokens");
519            Ok(None)
520        }
521    }
522
523    #[instrument(skip(self))]
524    pub async fn shutdown(&self) -> Result<()> {
525        info!("Shutting down!");
526
527        Ok(())
528    }
529
530    #[instrument(skip(self, params), fields(uri = %params.text_document_position.text_document.uri.as_str()))]
531    pub async fn references(&self, params: ReferenceParams) -> Result<Option<Vec<Location>>> {
532        if self.is_disabled(Disabled::References).await {
533            return Ok(None);
534        }
535        let Some(doc) = self
536            .document(params.text_document_position.text_document.uri.as_str())
537            .await
538        else {
539            return Ok(None);
540        };
541
542        let pos = params.text_document_position.position;
543
544        let arr = self
545            .run_schedule::<ReferencesRequest>(
546                doc,
547                ReferencesLabel,
548                (PositionComponent(pos), ReferencesRequest(Vec::new())),
549            )
550            .await
551            .map(|x| x.0);
552
553        Ok(arr)
554    }
555
556    #[instrument(skip(self, params), fields(uri = %params.text_document.uri.as_str()))]
557    pub async fn prepare_rename(
558        &self,
559        params: TextDocumentPositionParams,
560    ) -> Result<Option<PrepareRenameResponse>> {
561        if self.is_disabled(Disabled::Rename).await {
562            return Ok(None);
563        }
564        let Some(doc) = self.document(params.text_document.uri.as_str()).await else {
565            return Ok(None);
566        };
567
568        let pos = params.position;
569
570        let resp = self
571            .run_schedule::<PrepareRenameRequest>(doc, PrepareRenameLabel, PositionComponent(pos))
572            .await
573            .map(|x| PrepareRenameResponse::RangeWithPlaceholder {
574                range: x.range,
575                placeholder: x.placeholder,
576            });
577
578        Ok(resp)
579    }
580
581    #[instrument(skip(self, params), fields(uri = %params.text_document_position.text_document.uri.as_str()))]
582    pub async fn rename(&self, params: RenameParams) -> Result<Option<WorkspaceEdit>> {
583        if self.is_disabled(Disabled::Rename).await {
584            return Ok(Some(WorkspaceEdit::new(HashMap::new())));
585        }
586        let Some(doc) = self
587            .document(params.text_document_position.text_document.uri.as_str())
588            .await
589        else {
590            return Ok(None);
591        };
592
593        let pos = params.text_document_position.position;
594
595        let mut change_map: HashMap<crate::lsp_types::Url, Vec<TextEdit>> = HashMap::new();
596        if let Some(changes) = self
597            .run_schedule::<RenameEdits>(
598                doc,
599                RenameLabel,
600                (
601                    PositionComponent(pos),
602                    RenameEdits(Vec::new(), params.new_name),
603                ),
604            )
605            .await
606        {
607            for (url, change) in changes.0 {
608                let entry = change_map.entry(url);
609                entry.or_default().push(change);
610            }
611        }
612        Ok(Some(WorkspaceEdit::new(change_map)))
613    }
614
615    pub async fn hover(&self, params: HoverParams) -> Result<Option<crate::lsp_types::Hover>> {
616        if self.is_disabled(Disabled::Hover).await {
617            return Ok(None);
618        }
619        let request: HoverRequest = HoverRequest::default();
620
621        let Some(doc) = self
622            .document(
623                params
624                    .text_document_position_params
625                    .text_document
626                    .uri
627                    .as_str(),
628            )
629            .await
630        else {
631            return Ok(None);
632        };
633
634        let pos = params.text_document_position_params.position;
635
636        if let Some(hover) = self
637            .run_schedule::<HoverRequest>(doc, HoverLabel, (request, PositionComponent(pos)))
638            .await
639        {
640            tracing::debug!("hover returned {} items", hover.0.len());
641            if !hover.0.is_empty() {
642                return Ok(Some(crate::lsp_types::Hover {
643                    contents: crate::lsp_types::HoverContents::Markup(MarkupContent {
644                        kind: MarkupKind::Markdown,
645                        value: hover.0.join("\n\n---\n\n"),
646                    }),
647                    range: hover.1,
648                }));
649            }
650        }
651
652        Ok(None)
653    }
654
655    pub async fn inlay_hint(&self, params: InlayHintParams) -> Result<Option<Vec<InlayHint>>> {
656        debug!("Inlay hints called");
657        if self.is_disabled(Disabled::InlayHint).await {
658            return Ok(None);
659        }
660        let uri = params.text_document.uri.as_str();
661        let Some(doc) = self.document(uri).await else {
662            debug!("No document {}", uri);
663            return Ok(None);
664        };
665
666        let request = self
667            .run_schedule::<InlayRequest>(doc, InlayLabel, InlayRequest::default())
668            .await;
669
670        debug!(
671            "Inlay hints resolved {} hints",
672            request.as_ref().map(|x| x.0.len()).unwrap_or(0)
673        );
674
675        Ok(request.map(|x| x.0))
676    }
677
678    #[instrument(skip(self))]
679    pub async fn formatting(
680        &self,
681        params: DocumentFormattingParams,
682    ) -> Result<Option<Vec<TextEdit>>> {
683        if self.is_disabled(Disabled::Format).await {
684            return Ok(None);
685        }
686        let uri = params.text_document.uri.as_str();
687        let Some(doc) = self.document(uri).await else {
688            debug!("No document {}", uri);
689            return Ok(None);
690        };
691
692        let request = self
693            .run_schedule::<FormatRequest>(doc, FormatLabel, FormatRequest(None))
694            .await;
695        Ok(request.and_then(|x| x.0))
696    }
697
698    #[instrument(skip(self, params), fields(uri = %params.text_document_position.text_document.uri.as_str()))]
699    pub async fn on_type_formatting(
700        &self,
701        params: DocumentOnTypeFormattingParams,
702    ) -> Result<Option<Vec<TextEdit>>> {
703        if self.is_disabled(Disabled::PrefixAutoInsert).await {
704            return Ok(None);
705        }
706        let uri = params.text_document_position.text_document.uri.as_str();
707        let Some(doc) = self.document(uri).await else {
708            return Ok(None);
709        };
710
711        // The exact position after the typed character: the scan expects the
712        // cursor right after `:`.
713        let pos = params.text_document_position.position;
714        let request = self
715            .run_schedule::<on_type_format::OnTypeFormatRequest>(
716                doc,
717                OnTypeFormatLabel,
718                (
719                    PositionComponent(pos),
720                    on_type_format::OnTypeFormatRequest(None),
721                ),
722            )
723            .await;
724        Ok(request.and_then(|x| x.0))
725    }
726
727    #[instrument(skip(self, params), fields(uri = %params.text_document.uri.as_str()))]
728    pub async fn did_open(&self, params: DidOpenTextDocumentParams) {
729        let item = params.text_document;
730        let url = item.uri.as_str().to_string();
731
732        self.run(|world| {
733            crate::document::open_document(world, item);
734        })
735        .await;
736        debug!("Opened {}", url);
737
738        debug!("Requesting tokens refresh");
739        let _ = self.client.send_request::<SemanticTokensRefresh>(()).await;
740        debug!("Semantic tokens refresh");
741    }
742
743    /// The editor closed a document.
744    ///
745    /// A document the server also loads by itself (e.g. a cached ontology the
746    /// user opened through goto-definition) gets the server's copy back, so
747    /// unsaved edits never stick. See [`crate::document`].
748    #[instrument(skip(self, params), fields(uri = %params.text_document.uri.as_str()))]
749    pub async fn did_close(&self, params: DidCloseTextDocumentParams) {
750        let url = params.text_document.uri;
751
752        let closed = {
753            let url = url.clone();
754            self.run(move |world| crate::document::close_document(world, &url))
755                .await
756        };
757
758        if let Some(crate::document::Closed::Background { entity, snapshot }) = closed {
759            let fs = self.run(|w| w.resource::<Fs>().clone()).await;
760            let on_disk = match fs {
761                Some(fs) => fs.0.read_file(&url).await,
762                None => None,
763            };
764            if let Some(content) = on_disk.or(snapshot) {
765                self.run(move |world| crate::document::restore_background(world, entity, content))
766                    .await;
767            }
768        }
769    }
770
771    #[instrument(skip(self, params), fields(uri = %params.text_document.uri.as_str()))]
772    pub async fn did_change(&self, params: DidChangeTextDocumentParams) {
773        let Some(doc) = self.document(params.text_document.uri.as_str()).await else {
774            debug!("No document {}", params.text_document.uri.as_str());
775            return;
776        };
777
778        let change = {
779            if let Some(c) = params.content_changes.into_iter().next() {
780                c
781            } else {
782                return;
783            }
784        };
785
786        self.run(move |world| {
787            let Some(entity) = find_document(world, &doc) else {
788                debug!("No document {}", doc);
789                return;
790            };
791            let rope_c = RopeC(LineIndex::new(&change.text));
792            world
793                .entity_mut(entity)
794                .insert((Source(change.text), rope_c));
795            world.run_schedule(ParseLabel);
796            world.flush();
797        })
798        .await;
799    }
800
801    #[instrument(skip(self, params), fields(uri = %params.text_document.uri.as_str()))]
802    pub async fn did_save(&self, params: DidSaveTextDocumentParams) {
803        let url = params.text_document.uri;
804
805        self.run(move |world| {
806            // A saved workspace file now feeds the other documents.
807            crate::document::save_document(world, &url);
808            world.run_schedule(SaveLabel);
809
810            debug!("Ran OnSave Schedule");
811        })
812        .await;
813    }
814
815    #[instrument(skip(self, params), fields(uri = %params.text_document_position_params.text_document.uri.as_str()))]
816    pub async fn goto_definition(
817        &self,
818        params: GotoDefinitionParams,
819    ) -> Result<Option<GotoDefinitionResponse>> {
820        if self.is_disabled(Disabled::GotoDefinition).await {
821            return Ok(None);
822        }
823        let Some(doc) = self
824            .document(
825                params
826                    .text_document_position_params
827                    .text_document
828                    .uri
829                    .as_str(),
830            )
831            .await
832        else {
833            return Ok(None);
834        };
835
836        let pos = params.text_document_position_params.position;
837
838        let arr = self
839            .run_schedule::<GotoDefinitionRequest>(
840                doc,
841                GotoDefinitionLabel,
842                (PositionComponent(pos), GotoDefinitionRequest(Vec::new())),
843            )
844            .await
845            .map(|x| {
846                tracing::debug!("goto definition: {} locations", x.0.len());
847                GotoDefinitionResponse::Array(x.0)
848            });
849
850        Ok(arr)
851    }
852
853    #[instrument(skip(self, params), fields(uri = %params.text_document_position_params.text_document.uri.as_str()))]
854    pub async fn goto_type_definition(
855        &self,
856        params: GotoTypeDefinitionParams,
857    ) -> Result<Option<GotoTypeDefinitionResponse>> {
858        if self.is_disabled(Disabled::GotoTypeDefinition).await {
859            return Ok(None);
860        }
861        let Some(doc) = self
862            .document(
863                params
864                    .text_document_position_params
865                    .text_document
866                    .uri
867                    .as_str(),
868            )
869            .await
870        else {
871            return Ok(None);
872        };
873
874        let pos = params.text_document_position_params.position;
875
876        let arr = self
877            .run_schedule::<GotoTypeRequest>(
878                doc,
879                GotoTypeLabel,
880                (PositionComponent(pos), GotoTypeRequest(Vec::new())),
881            )
882            .await
883            .map(|x| GotoTypeDefinitionResponse::Array(x.0));
884
885        Ok(arr)
886    }
887
888    #[instrument(skip(self, params), fields(uri = %params.text_document.uri.as_str()))]
889    pub async fn code_action(
890        &self,
891        params: CodeActionParams,
892    ) -> Result<Option<CodeActionResponse>> {
893        if self.is_disabled(Disabled::CodeAction).await {
894            return Ok(None);
895        }
896        let uri = params.text_document.uri.as_str();
897        let Some(doc) = self.document(uri).await else {
898            return Ok(None);
899        };
900
901        let pos = params.range.start;
902        let request = self
903            .run_schedule::<CodeActionRequest>(
904                doc,
905                CodeActionLabel,
906                (CodeActionRequest::default(), PositionComponent(pos)),
907            )
908            .await;
909
910        Ok(request.map(|r| {
911            r.0.into_iter()
912                .map(CodeActionOrCommand::CodeAction)
913                .collect()
914        }))
915    }
916
917    /// Handle `workspace/executeCommand`.
918    ///
919    /// Currently only `swls.allowProperty`: adds the given property IRI to the
920    /// user's `allowed_properties`, both at runtime (clearing the warning) and on
921    /// disk (so the choice survives restarts), then refreshes diagnostics.
922    #[instrument(skip(self, params), fields(command = %params.command))]
923    pub async fn execute_command(
924        &self,
925        params: ExecuteCommandParams,
926    ) -> Result<Option<serde_json::Value>> {
927        if params.command == crate::systems::ALLOW_PROPERTY_COMMAND {
928            let Some(iri) = params
929                .arguments
930                .first()
931                .and_then(|v| v.as_str())
932                .map(String::from)
933            else {
934                return Ok(None);
935            };
936
937            // 1. Update the in-memory config so the warning clears immediately.
938            self.run({
939                let iri = iri.clone();
940                move |world| {
941                    world
942                        .resource_mut::<ServerConfig>()
943                        .config
944                        .local
945                        .allowed_properties
946                        .insert(iri);
947                }
948            })
949            .await;
950
951            // 2. Persist to the global config file.
952            if let Some(fs) = self.run(|w| w.resource::<Fs>().clone()).await {
953                LocalConfig::persist_allowed_property(&fs, &iri).await;
954            }
955
956            // 3. Re-run diagnostics for all open documents.
957            self.run(|world| {
958                world.run_schedule(ParseLabel);
959                world.flush();
960            })
961            .await;
962        }
963
964        Ok(None)
965    }
966
967    #[instrument(skip(self, params), fields(uri = %params.text_document_position.text_document.uri.as_str()))]
968    pub async fn completion(&self, params: CompletionParams) -> Result<Option<CompletionResponse>> {
969        if self.is_disabled(Disabled::Completion).await {
970            return Ok(None);
971        }
972        let Some(doc) = self
973            .document(params.text_document_position.text_document.uri.as_str())
974            .await
975        else {
976            return Ok(None);
977        };
978
979        let pos = params.text_document_position.position;
980
981        let completions: Option<Vec<crate::lsp_types::CompletionItem>> = self
982            .run_schedule::<CompletionRequest>(
983                doc,
984                CompletionLabel,
985                (CompletionRequest(vec![]), PositionComponent(pos)),
986            )
987            .await
988            .map(|mut x| {
989                crate::feature::completion::sort_completions(&mut x.0);
990                x.0.into_iter().map(|x| x.into()).collect()
991            });
992
993        Ok(completions.map(CompletionResponse::Array))
994    }
995
996    /// `textDocument/documentLink`.
997    pub async fn document_link(
998        &self,
999        params: DocumentLinkParams,
1000    ) -> Result<Option<Vec<DocumentLink>>> {
1001        if self.is_disabled(Disabled::DocumentLink).await {
1002            return Ok(None);
1003        }
1004        let url = params.text_document.uri;
1005        Ok(self
1006            .run(move |world| crate::navigation::document_links(world, &url))
1007            .await)
1008    }
1009
1010    /// `textDocument/documentSymbol`.
1011    pub async fn document_symbol(
1012        &self,
1013        params: DocumentSymbolParams,
1014    ) -> Result<Option<DocumentSymbolResponse>> {
1015        if self.is_disabled(Disabled::DocumentSymbol).await {
1016            return Ok(None);
1017        }
1018        let url = params.text_document.uri;
1019        Ok(self
1020            .run(move |world| crate::navigation::document_symbols(world, &url))
1021            .await
1022            .map(DocumentSymbolResponse::Nested))
1023    }
1024
1025    /// `textDocument/foldingRange`.
1026    pub async fn folding_range(
1027        &self,
1028        params: FoldingRangeParams,
1029    ) -> Result<Option<Vec<FoldingRange>>> {
1030        if self.is_disabled(Disabled::FoldingRange).await {
1031            return Ok(None);
1032        }
1033        let url = params.text_document.uri;
1034        Ok(self
1035            .run(move |world| crate::navigation::folding_ranges(world, &url))
1036            .await)
1037    }
1038
1039    /// `workspace/symbol`.
1040    pub async fn symbol(
1041        &self,
1042        params: WorkspaceSymbolParams,
1043    ) -> Result<Option<Vec<SymbolInformation>>> {
1044        if self.is_disabled(Disabled::WorkspaceSymbol).await {
1045            return Ok(None);
1046        }
1047        let query = params.query;
1048        Ok(self
1049            .run(move |world| crate::navigation::workspace_symbols(world, &query))
1050            .await)
1051    }
1052}