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