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