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