]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/main_loop.rs
ec3d5e0600ffdab656cbe66861d26894c4eb7222
[rust.git] / crates / rust-analyzer / src / main_loop.rs
1 //! The main loop of `rust-analyzer` responsible for dispatching LSP
2 //! requests/replies and notifications back to the client.
3 use std::{
4     env, fmt,
5     time::{Duration, Instant},
6 };
7
8 use crossbeam_channel::{select, Receiver};
9 use ide::PrimeCachesProgress;
10 use ide::{Canceled, FileId};
11 use ide_db::base_db::VfsPath;
12 use lsp_server::{Connection, Notification, Request, Response};
13 use lsp_types::notification::Notification as _;
14 use project_model::ProjectWorkspace;
15 use vfs::ChangeKind;
16
17 use crate::{
18     config::Config,
19     dispatch::{NotificationDispatcher, RequestDispatcher},
20     document::DocumentData,
21     from_proto,
22     global_state::{file_id_to_url, url_to_file_id, GlobalState, Status},
23     handlers, lsp_ext,
24     lsp_utils::{apply_document_changes, is_canceled, notification_is, Progress},
25     Result,
26 };
27
28 pub fn main_loop(config: Config, connection: Connection) -> Result<()> {
29     log::info!("initial config: {:#?}", config);
30
31     // Windows scheduler implements priority boosts: if thread waits for an
32     // event (like a condvar), and event fires, priority of the thread is
33     // temporary bumped. This optimization backfires in our case: each time the
34     // `main_loop` schedules a task to run on a threadpool, the worker threads
35     // gets a higher priority, and (on a machine with fewer cores) displaces the
36     // main loop! We work-around this by marking the main loop as a
37     // higher-priority thread.
38     //
39     // https://docs.microsoft.com/en-us/windows/win32/procthread/scheduling-priorities
40     // https://docs.microsoft.com/en-us/windows/win32/procthread/priority-boosts
41     // https://github.com/rust-analyzer/rust-analyzer/issues/2835
42     #[cfg(windows)]
43     unsafe {
44         use winapi::um::processthreadsapi::*;
45         let thread = GetCurrentThread();
46         let thread_priority_above_normal = 1;
47         SetThreadPriority(thread, thread_priority_above_normal);
48     }
49
50     GlobalState::new(connection.sender, config).run(connection.receiver)
51 }
52
53 enum Event {
54     Lsp(lsp_server::Message),
55     Task(Task),
56     Vfs(vfs::loader::Message),
57     Flycheck(flycheck::Message),
58 }
59
60 #[derive(Debug)]
61 pub(crate) enum Task {
62     Response(Response),
63     Diagnostics(Vec<(FileId, Vec<lsp_types::Diagnostic>)>),
64     Workspaces(Vec<anyhow::Result<ProjectWorkspace>>),
65     PrimeCaches(PrimeCachesProgress),
66 }
67
68 impl fmt::Debug for Event {
69     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
70         let debug_verbose_not = |not: &Notification, f: &mut fmt::Formatter| {
71             f.debug_struct("Notification").field("method", &not.method).finish()
72         };
73
74         match self {
75             Event::Lsp(lsp_server::Message::Notification(not)) => {
76                 if notification_is::<lsp_types::notification::DidOpenTextDocument>(not)
77                     || notification_is::<lsp_types::notification::DidChangeTextDocument>(not)
78                 {
79                     return debug_verbose_not(not, f);
80                 }
81             }
82             Event::Task(Task::Response(resp)) => {
83                 return f
84                     .debug_struct("Response")
85                     .field("id", &resp.id)
86                     .field("error", &resp.error)
87                     .finish();
88             }
89             _ => (),
90         }
91         match self {
92             Event::Lsp(it) => fmt::Debug::fmt(it, f),
93             Event::Task(it) => fmt::Debug::fmt(it, f),
94             Event::Vfs(it) => fmt::Debug::fmt(it, f),
95             Event::Flycheck(it) => fmt::Debug::fmt(it, f),
96         }
97     }
98 }
99
100 impl GlobalState {
101     fn run(mut self, inbox: Receiver<lsp_server::Message>) -> Result<()> {
102         if self.config.linked_projects.is_empty() && self.config.notifications.cargo_toml_not_found
103         {
104             self.show_message(
105                 lsp_types::MessageType::Error,
106                 "rust-analyzer failed to discover workspace".to_string(),
107             );
108         };
109
110         let save_registration_options = lsp_types::TextDocumentSaveRegistrationOptions {
111             include_text: Some(false),
112             text_document_registration_options: lsp_types::TextDocumentRegistrationOptions {
113                 document_selector: Some(vec![
114                     lsp_types::DocumentFilter {
115                         language: None,
116                         scheme: None,
117                         pattern: Some("**/*.rs".into()),
118                     },
119                     lsp_types::DocumentFilter {
120                         language: None,
121                         scheme: None,
122                         pattern: Some("**/Cargo.toml".into()),
123                     },
124                     lsp_types::DocumentFilter {
125                         language: None,
126                         scheme: None,
127                         pattern: Some("**/Cargo.lock".into()),
128                     },
129                 ]),
130             },
131         };
132
133         let registration = lsp_types::Registration {
134             id: "textDocument/didSave".to_string(),
135             method: "textDocument/didSave".to_string(),
136             register_options: Some(serde_json::to_value(save_registration_options).unwrap()),
137         };
138         self.send_request::<lsp_types::request::RegisterCapability>(
139             lsp_types::RegistrationParams { registrations: vec![registration] },
140             |_, _| (),
141         );
142
143         self.fetch_workspaces();
144
145         while let Some(event) = self.next_event(&inbox) {
146             if let Event::Lsp(lsp_server::Message::Notification(not)) = &event {
147                 if not.method == lsp_types::notification::Exit::METHOD {
148                     return Ok(());
149                 }
150             }
151             self.handle_event(event)?
152         }
153
154         Err("client exited without proper shutdown sequence")?
155     }
156
157     fn next_event(&self, inbox: &Receiver<lsp_server::Message>) -> Option<Event> {
158         select! {
159             recv(inbox) -> msg =>
160                 msg.ok().map(Event::Lsp),
161
162             recv(self.task_pool.receiver) -> task =>
163                 Some(Event::Task(task.unwrap())),
164
165             recv(self.loader.receiver) -> task =>
166                 Some(Event::Vfs(task.unwrap())),
167
168             recv(self.flycheck_receiver) -> task =>
169                 Some(Event::Flycheck(task.unwrap())),
170         }
171     }
172
173     fn handle_event(&mut self, event: Event) -> Result<()> {
174         let loop_start = Instant::now();
175         // NOTE: don't count blocking select! call as a loop-turn time
176         let _p = profile::span("GlobalState::handle_event");
177
178         log::info!("handle_event({:?})", event);
179         let task_queue_len = self.task_pool.handle.len();
180         if task_queue_len > 0 {
181             log::info!("task queue len: {}", task_queue_len);
182         }
183
184         let prev_status = self.status;
185         match event {
186             Event::Lsp(msg) => match msg {
187                 lsp_server::Message::Request(req) => self.on_request(loop_start, req)?,
188                 lsp_server::Message::Notification(not) => {
189                     self.on_notification(not)?;
190                 }
191                 lsp_server::Message::Response(resp) => self.complete_request(resp),
192             },
193             Event::Task(mut task) => {
194                 let _p = profile::span("GlobalState::handle_event/task");
195                 let mut prime_caches_progress = Vec::new();
196                 loop {
197                     match task {
198                         Task::Response(response) => self.respond(response),
199                         Task::Diagnostics(diagnostics_per_file) => {
200                             for (file_id, diagnostics) in diagnostics_per_file {
201                                 self.diagnostics.set_native_diagnostics(file_id, diagnostics)
202                             }
203                         }
204                         Task::Workspaces(workspaces) => self.switch_workspaces(workspaces),
205                         Task::PrimeCaches(progress) => match progress {
206                             PrimeCachesProgress::Started => prime_caches_progress.push(progress),
207                             PrimeCachesProgress::StartedOnCrate { .. } => {
208                                 match prime_caches_progress.last_mut() {
209                                     Some(last @ PrimeCachesProgress::StartedOnCrate { .. }) => {
210                                         // Coalesce subsequent update events.
211                                         *last = progress;
212                                     }
213                                     _ => prime_caches_progress.push(progress),
214                                 }
215                             }
216                             PrimeCachesProgress::Finished => prime_caches_progress.push(progress),
217                         },
218                     }
219                     // Coalesce multiple task events into one loop turn
220                     task = match self.task_pool.receiver.try_recv() {
221                         Ok(task) => task,
222                         Err(_) => break,
223                     };
224                 }
225
226                 for progress in prime_caches_progress {
227                     let (state, message, fraction);
228                     match progress {
229                         PrimeCachesProgress::Started => {
230                             state = Progress::Begin;
231                             message = None;
232                             fraction = 0.0;
233                         }
234                         PrimeCachesProgress::StartedOnCrate { on_crate, n_done, n_total } => {
235                             state = Progress::Report;
236                             message = Some(format!("{}/{} ({})", n_done, n_total, on_crate));
237                             fraction = Progress::fraction(n_done, n_total);
238                         }
239                         PrimeCachesProgress::Finished => {
240                             state = Progress::End;
241                             message = None;
242                             fraction = 1.0;
243                         }
244                     };
245
246                     self.report_progress("indexing", state, message, Some(fraction));
247                 }
248             }
249             Event::Vfs(mut task) => {
250                 let _p = profile::span("GlobalState::handle_event/vfs");
251                 loop {
252                     match task {
253                         vfs::loader::Message::Loaded { files } => {
254                             let vfs = &mut self.vfs.write().0;
255                             for (path, contents) in files {
256                                 let path = VfsPath::from(path);
257                                 if !self.mem_docs.contains_key(&path) {
258                                     vfs.set_file_contents(path, contents);
259                                 }
260                             }
261                         }
262                         vfs::loader::Message::Progress { n_total, n_done } => {
263                             if n_total == 0 {
264                                 self.transition(Status::Invalid);
265                             } else {
266                                 let state = if n_done == 0 {
267                                     self.transition(Status::Loading);
268                                     Progress::Begin
269                                 } else if n_done < n_total {
270                                     Progress::Report
271                                 } else {
272                                     assert_eq!(n_done, n_total);
273                                     self.transition(Status::Ready);
274                                     Progress::End
275                                 };
276                                 self.report_progress(
277                                     "roots scanned",
278                                     state,
279                                     Some(format!("{}/{}", n_done, n_total)),
280                                     Some(Progress::fraction(n_done, n_total)),
281                                 )
282                             }
283                         }
284                     }
285                     // Coalesce many VFS event into a single loop turn
286                     task = match self.loader.receiver.try_recv() {
287                         Ok(task) => task,
288                         Err(_) => break,
289                     }
290                 }
291             }
292             Event::Flycheck(mut task) => {
293                 let _p = profile::span("GlobalState::handle_event/flycheck");
294                 loop {
295                     match task {
296                         flycheck::Message::AddDiagnostic { workspace_root, diagnostic } => {
297                             let diagnostics =
298                                 crate::diagnostics::to_proto::map_rust_diagnostic_to_lsp(
299                                     &self.config.diagnostics_map,
300                                     &diagnostic,
301                                     &workspace_root,
302                                 );
303                             for diag in diagnostics {
304                                 match url_to_file_id(&self.vfs.read().0, &diag.url) {
305                                     Ok(file_id) => self.diagnostics.add_check_diagnostic(
306                                         file_id,
307                                         diag.diagnostic,
308                                         diag.fixes,
309                                     ),
310                                     Err(err) => {
311                                         log::error!(
312                                             "File with cargo diagnostic not found in VFS: {}",
313                                             err
314                                         );
315                                     }
316                                 };
317                             }
318                         }
319
320                         flycheck::Message::Progress { id, progress } => {
321                             let (state, message) = match progress {
322                                 flycheck::Progress::DidStart => {
323                                     self.diagnostics.clear_check();
324                                     (Progress::Begin, None)
325                                 }
326                                 flycheck::Progress::DidCheckCrate(target) => {
327                                     (Progress::Report, Some(target))
328                                 }
329                                 flycheck::Progress::DidCancel => (Progress::End, None),
330                                 flycheck::Progress::DidFinish(result) => {
331                                     if let Err(err) = result {
332                                         log::error!("cargo check failed: {}", err)
333                                     }
334                                     (Progress::End, None)
335                                 }
336                             };
337
338                             // When we're running multiple flychecks, we have to include a disambiguator in
339                             // the title, or the editor complains. Note that this is a user-facing string.
340                             let title = if self.flycheck.len() == 1 {
341                                 "cargo check".to_string()
342                             } else {
343                                 format!("cargo check (#{})", id + 1)
344                             };
345                             self.report_progress(&title, state, message, None);
346                         }
347                     }
348                     // Coalesce many flycheck updates into a single loop turn
349                     task = match self.flycheck_receiver.try_recv() {
350                         Ok(task) => task,
351                         Err(_) => break,
352                     }
353                 }
354             }
355         }
356
357         let state_changed = self.process_changes();
358         if prev_status == Status::Loading && self.status == Status::Ready {
359             for flycheck in &self.flycheck {
360                 flycheck.update();
361             }
362         }
363
364         if self.status == Status::Ready && (state_changed || prev_status == Status::Loading) {
365             self.update_file_notifications_on_threadpool();
366
367             // Refresh semantic tokens if the client supports it.
368             if self.config.semantic_tokens_refresh {
369                 self.semantic_tokens_cache.lock().clear();
370                 self.send_request::<lsp_types::request::SemanticTokensRefesh>((), |_, _| ());
371             }
372
373             // Refresh code lens if the client supports it.
374             if self.config.code_lens_refresh {
375                 self.send_request::<lsp_types::request::CodeLensRefresh>((), |_, _| ());
376             }
377         }
378
379         if let Some(diagnostic_changes) = self.diagnostics.take_changes() {
380             for file_id in diagnostic_changes {
381                 let url = file_id_to_url(&self.vfs.read().0, file_id);
382                 let diagnostics = self.diagnostics.diagnostics_for(file_id).cloned().collect();
383                 let version = from_proto::vfs_path(&url)
384                     .map(|path| self.mem_docs.get(&path).map(|it| it.version))
385                     .unwrap_or_default();
386
387                 self.send_notification::<lsp_types::notification::PublishDiagnostics>(
388                     lsp_types::PublishDiagnosticsParams { uri: url, diagnostics, version },
389                 );
390             }
391         }
392
393         let loop_duration = loop_start.elapsed();
394         if loop_duration > Duration::from_millis(100) {
395             log::warn!("overly long loop turn: {:?}", loop_duration);
396             if env::var("RA_PROFILE").is_ok() {
397                 self.show_message(
398                     lsp_types::MessageType::Error,
399                     format!("overly long loop turn: {:?}", loop_duration),
400                 )
401             }
402         }
403         Ok(())
404     }
405
406     fn on_request(&mut self, request_received: Instant, req: Request) -> Result<()> {
407         self.register_request(&req, request_received);
408
409         if self.shutdown_requested {
410             self.respond(Response::new_err(
411                 req.id,
412                 lsp_server::ErrorCode::InvalidRequest as i32,
413                 "Shutdown already requested.".to_owned(),
414             ));
415
416             return Ok(());
417         }
418
419         if self.status == Status::Loading && req.method != "shutdown" {
420             self.respond(lsp_server::Response::new_err(
421                 req.id,
422                 // FIXME: i32 should impl From<ErrorCode> (from() guarantees lossless conversion)
423                 lsp_server::ErrorCode::ContentModified as i32,
424                 "Rust Analyzer is still loading...".to_owned(),
425             ));
426             return Ok(());
427         }
428
429         RequestDispatcher { req: Some(req), global_state: self }
430             .on_sync::<lsp_ext::ReloadWorkspace>(|s, ()| Ok(s.fetch_workspaces()))?
431             .on_sync::<lsp_ext::JoinLines>(|s, p| handlers::handle_join_lines(s.snapshot(), p))?
432             .on_sync::<lsp_ext::OnEnter>(|s, p| handlers::handle_on_enter(s.snapshot(), p))?
433             .on_sync::<lsp_types::request::Shutdown>(|s, ()| {
434                 s.shutdown_requested = true;
435                 Ok(())
436             })?
437             .on_sync::<lsp_types::request::SelectionRangeRequest>(|s, p| {
438                 handlers::handle_selection_range(s.snapshot(), p)
439             })?
440             .on_sync::<lsp_ext::MatchingBrace>(|s, p| {
441                 handlers::handle_matching_brace(s.snapshot(), p)
442             })?
443             .on_sync::<lsp_ext::MemoryUsage>(|s, p| handlers::handle_memory_usage(s, p))?
444             .on::<lsp_ext::AnalyzerStatus>(handlers::handle_analyzer_status)
445             .on::<lsp_ext::SyntaxTree>(handlers::handle_syntax_tree)
446             .on::<lsp_ext::ExpandMacro>(handlers::handle_expand_macro)
447             .on::<lsp_ext::ParentModule>(handlers::handle_parent_module)
448             .on::<lsp_ext::Runnables>(handlers::handle_runnables)
449             .on::<lsp_ext::InlayHints>(handlers::handle_inlay_hints)
450             .on::<lsp_ext::CodeActionRequest>(handlers::handle_code_action)
451             .on::<lsp_ext::CodeActionResolveRequest>(handlers::handle_code_action_resolve)
452             .on::<lsp_ext::HoverRequest>(handlers::handle_hover)
453             .on::<lsp_ext::ExternalDocs>(handlers::handle_open_docs)
454             .on::<lsp_ext::OpenCargoToml>(handlers::handle_open_cargo_toml)
455             .on::<lsp_types::request::OnTypeFormatting>(handlers::handle_on_type_formatting)
456             .on::<lsp_types::request::DocumentSymbolRequest>(handlers::handle_document_symbol)
457             .on::<lsp_types::request::WorkspaceSymbol>(handlers::handle_workspace_symbol)
458             .on::<lsp_types::request::GotoDefinition>(handlers::handle_goto_definition)
459             .on::<lsp_types::request::GotoImplementation>(handlers::handle_goto_implementation)
460             .on::<lsp_types::request::GotoTypeDefinition>(handlers::handle_goto_type_definition)
461             .on::<lsp_types::request::Completion>(handlers::handle_completion)
462             .on::<lsp_types::request::ResolveCompletionItem>(handlers::handle_completion_resolve)
463             .on::<lsp_types::request::CodeLensRequest>(handlers::handle_code_lens)
464             .on::<lsp_types::request::CodeLensResolve>(handlers::handle_code_lens_resolve)
465             .on::<lsp_types::request::FoldingRangeRequest>(handlers::handle_folding_range)
466             .on::<lsp_types::request::SignatureHelpRequest>(handlers::handle_signature_help)
467             .on::<lsp_types::request::PrepareRenameRequest>(handlers::handle_prepare_rename)
468             .on::<lsp_types::request::Rename>(handlers::handle_rename)
469             .on::<lsp_types::request::References>(handlers::handle_references)
470             .on::<lsp_types::request::Formatting>(handlers::handle_formatting)
471             .on::<lsp_types::request::DocumentHighlightRequest>(handlers::handle_document_highlight)
472             .on::<lsp_types::request::CallHierarchyPrepare>(handlers::handle_call_hierarchy_prepare)
473             .on::<lsp_types::request::CallHierarchyIncomingCalls>(
474                 handlers::handle_call_hierarchy_incoming,
475             )
476             .on::<lsp_types::request::CallHierarchyOutgoingCalls>(
477                 handlers::handle_call_hierarchy_outgoing,
478             )
479             .on::<lsp_types::request::SemanticTokensFullRequest>(
480                 handlers::handle_semantic_tokens_full,
481             )
482             .on::<lsp_types::request::SemanticTokensFullDeltaRequest>(
483                 handlers::handle_semantic_tokens_full_delta,
484             )
485             .on::<lsp_types::request::SemanticTokensRangeRequest>(
486                 handlers::handle_semantic_tokens_range,
487             )
488             .on::<lsp_ext::Ssr>(handlers::handle_ssr)
489             .finish();
490         Ok(())
491     }
492     fn on_notification(&mut self, not: Notification) -> Result<()> {
493         NotificationDispatcher { not: Some(not), global_state: self }
494             .on::<lsp_types::notification::Cancel>(|this, params| {
495                 let id: lsp_server::RequestId = match params.id {
496                     lsp_types::NumberOrString::Number(id) => id.into(),
497                     lsp_types::NumberOrString::String(id) => id.into(),
498                 };
499                 this.cancel(id);
500                 Ok(())
501             })?
502             .on::<lsp_types::notification::DidOpenTextDocument>(|this, params| {
503                 if let Ok(path) = from_proto::vfs_path(&params.text_document.uri) {
504                     if this
505                         .mem_docs
506                         .insert(path.clone(), DocumentData::new(params.text_document.version))
507                         .is_some()
508                     {
509                         log::error!("duplicate DidOpenTextDocument: {}", path)
510                     }
511                     let changed = this
512                         .vfs
513                         .write()
514                         .0
515                         .set_file_contents(path, Some(params.text_document.text.into_bytes()));
516
517                     // If the VFS contents are unchanged, update diagnostics, since `handle_event`
518                     // won't see any changes. This avoids missing diagnostics when opening a file.
519                     //
520                     // If the file *was* changed, `handle_event` will already recompute and send
521                     // diagnostics. We can't do it here, since the *current* file contents might be
522                     // unset in salsa, since the VFS change hasn't been applied to the database yet.
523                     if !changed {
524                         this.maybe_update_diagnostics();
525                     }
526                 }
527                 Ok(())
528             })?
529             .on::<lsp_types::notification::DidChangeTextDocument>(|this, params| {
530                 if let Ok(path) = from_proto::vfs_path(&params.text_document.uri) {
531                     let doc = match this.mem_docs.get_mut(&path) {
532                         Some(doc) => doc,
533                         None => {
534                             log::error!("expected DidChangeTextDocument: {}", path);
535                             return Ok(());
536                         }
537                     };
538                     let vfs = &mut this.vfs.write().0;
539                     let file_id = vfs.file_id(&path).unwrap();
540                     let mut text = String::from_utf8(vfs.file_contents(file_id).to_vec()).unwrap();
541                     apply_document_changes(&mut text, params.content_changes);
542
543                     // The version passed in DidChangeTextDocument is the version after all edits are applied
544                     // so we should apply it before the vfs is notified.
545                     doc.version = params.text_document.version;
546
547                     vfs.set_file_contents(path.clone(), Some(text.into_bytes()));
548                 }
549                 Ok(())
550             })?
551             .on::<lsp_types::notification::DidCloseTextDocument>(|this, params| {
552                 let mut version = None;
553                 if let Ok(path) = from_proto::vfs_path(&params.text_document.uri) {
554                     match this.mem_docs.remove(&path) {
555                         Some(doc) => version = Some(doc.version),
556                         None => log::error!("orphan DidCloseTextDocument: {}", path),
557                     }
558
559                     this.semantic_tokens_cache.lock().remove(&params.text_document.uri);
560
561                     if let Some(path) = path.as_path() {
562                         this.loader.handle.invalidate(path.to_path_buf());
563                     }
564                 }
565
566                 // Clear the diagnostics for the previously known version of the file.
567                 // This prevents stale "cargo check" diagnostics if the file is
568                 // closed, "cargo check" is run and then the file is reopened.
569                 this.send_notification::<lsp_types::notification::PublishDiagnostics>(
570                     lsp_types::PublishDiagnosticsParams {
571                         uri: params.text_document.uri,
572                         diagnostics: Vec::new(),
573                         version,
574                     },
575                 );
576                 Ok(())
577             })?
578             .on::<lsp_types::notification::DidSaveTextDocument>(|this, params| {
579                 for flycheck in &this.flycheck {
580                     flycheck.update();
581                 }
582                 if let Ok(abs_path) = from_proto::abs_path(&params.text_document.uri) {
583                     this.maybe_refresh(&[(abs_path, ChangeKind::Modify)]);
584                 }
585                 Ok(())
586             })?
587             .on::<lsp_types::notification::DidChangeConfiguration>(|this, _params| {
588                 // As stated in https://github.com/microsoft/language-server-protocol/issues/676,
589                 // this notification's parameters should be ignored and the actual config queried separately.
590                 this.send_request::<lsp_types::request::WorkspaceConfiguration>(
591                     lsp_types::ConfigurationParams {
592                         items: vec![lsp_types::ConfigurationItem {
593                             scope_uri: None,
594                             section: Some("rust-analyzer".to_string()),
595                         }],
596                     },
597                     |this, resp| {
598                         log::debug!("config update response: '{:?}", resp);
599                         let Response { error, result, .. } = resp;
600
601                         match (error, result) {
602                             (Some(err), _) => {
603                                 log::error!("failed to fetch the server settings: {:?}", err)
604                             }
605                             (None, Some(mut configs)) => {
606                                 if let Some(json) = configs.get_mut(0) {
607                                     // Note that json can be null according to the spec if the client can't
608                                     // provide a configuration. This is handled in Config::update below.
609                                     let mut config = this.config.clone();
610                                     config.update(json.take());
611                                     this.update_configuration(config);
612                                 }
613                             }
614                             (None, None) => log::error!(
615                                 "received empty server settings response from the client"
616                             ),
617                         }
618                     },
619                 );
620
621                 return Ok(());
622             })?
623             .on::<lsp_types::notification::DidChangeWatchedFiles>(|this, params| {
624                 for change in params.changes {
625                     if let Ok(path) = from_proto::abs_path(&change.uri) {
626                         this.loader.handle.invalidate(path);
627                     }
628                 }
629                 Ok(())
630             })?
631             .finish();
632         Ok(())
633     }
634     fn update_file_notifications_on_threadpool(&mut self) {
635         self.maybe_update_diagnostics();
636         self.task_pool.handle.spawn_with_sender({
637             let snap = self.snapshot();
638             move |sender| {
639                 snap.analysis
640                     .prime_caches(|progress| {
641                         sender.send(Task::PrimeCaches(progress)).unwrap();
642                     })
643                     .unwrap_or_else(|_: Canceled| {
644                         // Pretend that we're done, so that the progress bar is removed. Otherwise
645                         // the editor may complain about it already existing.
646                         sender.send(Task::PrimeCaches(PrimeCachesProgress::Finished)).unwrap()
647                     });
648             }
649         });
650     }
651     fn maybe_update_diagnostics(&mut self) {
652         let subscriptions = self
653             .mem_docs
654             .keys()
655             .map(|path| self.vfs.read().0.file_id(&path).unwrap())
656             .collect::<Vec<_>>();
657
658         log::trace!("updating notifications for {:?}", subscriptions);
659         if self.config.publish_diagnostics {
660             let snapshot = self.snapshot();
661             self.task_pool.handle.spawn(move || {
662                 let diagnostics = subscriptions
663                     .into_iter()
664                     .filter_map(|file_id| {
665                         handlers::publish_diagnostics(&snapshot, file_id)
666                             .map_err(|err| {
667                                 if !is_canceled(&*err) {
668                                     log::error!("failed to compute diagnostics: {:?}", err);
669                                 }
670                                 ()
671                             })
672                             .ok()
673                             .map(|diags| (file_id, diags))
674                     })
675                     .collect::<Vec<_>>();
676                 Task::Diagnostics(diagnostics)
677             })
678         }
679     }
680 }