]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/main_loop.rs
0518a17f3073885f31ce24d23dadd67a9a9b02c7
[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};
14 use lsp_types::notification::Notification as _;
15 use vfs::ChangeKind;
16
17 use crate::{
18     config::Config,
19     dispatch::{NotificationDispatcher, RequestDispatcher},
20     from_proto,
21     global_state::{file_id_to_url, url_to_file_id, GlobalState},
22     handlers, lsp_ext,
23     lsp_utils::{apply_document_changes, is_cancelled, notification_is, Progress},
24     mem_docs::DocumentData,
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(lsp_server::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.detached_files().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                                         self.fetch_build_data_request()
239                                     }
240
241                                     (Progress::End, None)
242                                 }
243                             };
244
245                             self.report_progress("Fetching", state, msg, None);
246                         }
247                         Task::FetchBuildData(progress) => {
248                             let (state, msg) = match progress {
249                                 BuildDataProgress::Begin => (Some(Progress::Begin), None),
250                                 BuildDataProgress::Report(msg) => {
251                                     (Some(Progress::Report), Some(msg))
252                                 }
253                                 BuildDataProgress::End(build_data_result) => {
254                                     self.fetch_build_data_completed(build_data_result);
255
256                                     self.switch_workspaces();
257
258                                     (Some(Progress::End), None)
259                                 }
260                             };
261
262                             if let Some(state) = state {
263                                 self.report_progress("Loading", state, msg, None);
264                             }
265                         }
266                     }
267
268                     // Coalesce multiple task events into one loop turn
269                     task = match self.task_pool.receiver.try_recv() {
270                         Ok(task) => task,
271                         Err(_) => break,
272                     };
273                 }
274
275                 for progress in prime_caches_progress {
276                     let (state, message, fraction);
277                     match progress {
278                         PrimeCachesProgress::Started => {
279                             state = Progress::Begin;
280                             message = None;
281                             fraction = 0.0;
282                         }
283                         PrimeCachesProgress::StartedOnCrate { on_crate, n_done, n_total } => {
284                             state = Progress::Report;
285                             message = Some(format!("{}/{} ({})", n_done, n_total, on_crate));
286                             fraction = Progress::fraction(n_done, n_total);
287                         }
288                         PrimeCachesProgress::Finished => {
289                             state = Progress::End;
290                             message = None;
291                             fraction = 1.0;
292
293                             self.prime_caches_queue.op_completed(());
294                         }
295                     };
296
297                     self.report_progress("Indexing", state, message, Some(fraction));
298                 }
299             }
300             Event::Vfs(mut task) => {
301                 let _p = profile::span("GlobalState::handle_event/vfs");
302                 loop {
303                     match task {
304                         vfs::loader::Message::Loaded { files } => {
305                             let vfs = &mut self.vfs.write().0;
306                             for (path, contents) in files {
307                                 let path = VfsPath::from(path);
308                                 if !self.mem_docs.contains(&path) {
309                                     vfs.set_file_contents(path, contents);
310                                 }
311                             }
312                         }
313                         vfs::loader::Message::Progress { n_total, n_done, config_version } => {
314                             always!(config_version <= self.vfs_config_version);
315
316                             self.vfs_progress_config_version = config_version;
317                             self.vfs_progress_n_total = n_total;
318                             self.vfs_progress_n_done = n_done;
319
320                             let state = if n_done == 0 {
321                                 Progress::Begin
322                             } else if n_done < n_total {
323                                 Progress::Report
324                             } else {
325                                 assert_eq!(n_done, n_total);
326                                 Progress::End
327                             };
328                             self.report_progress(
329                                 "Roots Scanned",
330                                 state,
331                                 Some(format!("{}/{}", n_done, n_total)),
332                                 Some(Progress::fraction(n_done, n_total)),
333                             )
334                         }
335                     }
336                     // Coalesce many VFS event into a single loop turn
337                     task = match self.loader.receiver.try_recv() {
338                         Ok(task) => task,
339                         Err(_) => break,
340                     }
341                 }
342             }
343             Event::Flycheck(mut task) => {
344                 let _p = profile::span("GlobalState::handle_event/flycheck");
345                 loop {
346                     match task {
347                         flycheck::Message::AddDiagnostic { workspace_root, diagnostic } => {
348                             let diagnostics =
349                                 crate::diagnostics::to_proto::map_rust_diagnostic_to_lsp(
350                                     &self.config.diagnostics_map(),
351                                     &diagnostic,
352                                     &workspace_root,
353                                 );
354                             for diag in diagnostics {
355                                 match url_to_file_id(&self.vfs.read().0, &diag.url) {
356                                     Ok(file_id) => self.diagnostics.add_check_diagnostic(
357                                         file_id,
358                                         diag.diagnostic,
359                                         diag.fixes,
360                                     ),
361                                     Err(err) => {
362                                         log::error!(
363                                             "File with cargo diagnostic not found in VFS: {}",
364                                             err
365                                         );
366                                     }
367                                 };
368                             }
369                         }
370
371                         flycheck::Message::Progress { id, progress } => {
372                             let (state, message) = match progress {
373                                 flycheck::Progress::DidStart => {
374                                     self.diagnostics.clear_check();
375                                     (Progress::Begin, None)
376                                 }
377                                 flycheck::Progress::DidCheckCrate(target) => {
378                                     (Progress::Report, Some(target))
379                                 }
380                                 flycheck::Progress::DidCancel => (Progress::End, None),
381                                 flycheck::Progress::DidFinish(result) => {
382                                     if let Err(err) = result {
383                                         log::error!("cargo check failed: {}", err)
384                                     }
385                                     (Progress::End, None)
386                                 }
387                             };
388
389                             // When we're running multiple flychecks, we have to include a disambiguator in
390                             // the title, or the editor complains. Note that this is a user-facing string.
391                             let title = if self.flycheck.len() == 1 {
392                                 "cargo check".to_string()
393                             } else {
394                                 format!("cargo check (#{})", id + 1)
395                             };
396                             self.report_progress(&title, state, message, None);
397                         }
398                     }
399                     // Coalesce many flycheck updates into a single loop turn
400                     task = match self.flycheck_receiver.try_recv() {
401                         Ok(task) => task,
402                         Err(_) => break,
403                     }
404                 }
405             }
406         }
407
408         let state_changed = self.process_changes();
409
410         if self.is_quiescent() && !was_quiescent {
411             for flycheck in &self.flycheck {
412                 flycheck.update();
413             }
414         }
415
416         if self.is_quiescent() && (!was_quiescent || state_changed) {
417             self.update_file_notifications_on_threadpool();
418
419             // Refresh semantic tokens if the client supports it.
420             if self.config.semantic_tokens_refresh() {
421                 self.semantic_tokens_cache.lock().clear();
422                 self.send_request::<lsp_types::request::SemanticTokensRefesh>((), |_, _| ());
423             }
424
425             // Refresh code lens if the client supports it.
426             if self.config.code_lens_refresh() {
427                 self.send_request::<lsp_types::request::CodeLensRefresh>((), |_, _| ());
428             }
429         }
430
431         if let Some(diagnostic_changes) = self.diagnostics.take_changes() {
432             for file_id in diagnostic_changes {
433                 let url = file_id_to_url(&self.vfs.read().0, file_id);
434                 let diagnostics = self.diagnostics.diagnostics_for(file_id).cloned().collect();
435                 let version = from_proto::vfs_path(&url)
436                     .map(|path| self.mem_docs.get(&path).map(|it| it.version))
437                     .unwrap_or_default();
438
439                 self.send_notification::<lsp_types::notification::PublishDiagnostics>(
440                     lsp_types::PublishDiagnosticsParams { uri: url, diagnostics, version },
441                 );
442             }
443         }
444
445         if self.config.cargo_autoreload() {
446             self.fetch_workspaces_if_needed();
447         }
448         self.fetch_build_data_if_needed();
449
450         self.report_new_status_if_needed();
451
452         let loop_duration = loop_start.elapsed();
453         if loop_duration > Duration::from_millis(100) {
454             log::warn!("overly long loop turn: {:?}", loop_duration);
455             if env::var("RA_PROFILE").is_ok() {
456                 self.show_message(
457                     lsp_types::MessageType::Error,
458                     format!("overly long loop turn: {:?}", loop_duration),
459                 )
460             }
461         }
462         Ok(())
463     }
464
465     fn on_request(&mut self, request_received: Instant, req: Request) -> Result<()> {
466         self.register_request(&req, request_received);
467
468         if self.shutdown_requested {
469             self.respond(lsp_server::Response::new_err(
470                 req.id,
471                 lsp_server::ErrorCode::InvalidRequest as i32,
472                 "Shutdown already requested.".to_owned(),
473             ));
474
475             return Ok(());
476         }
477
478         // Avoid flashing a bunch of unresolved references during initial load.
479         if self.workspaces.is_empty() && !self.is_quiescent() {
480             self.respond(lsp_server::Response::new_err(
481                 req.id,
482                 // FIXME: i32 should impl From<ErrorCode> (from() guarantees lossless conversion)
483                 lsp_server::ErrorCode::ContentModified as i32,
484                 "waiting for cargo metadata or cargo check".to_owned(),
485             ));
486             return Ok(());
487         }
488
489         RequestDispatcher { req: Some(req), global_state: self }
490             .on_sync::<lsp_ext::ReloadWorkspace>(|s, ()| {
491                 s.fetch_workspaces_request();
492                 s.fetch_workspaces_if_needed();
493                 Ok(())
494             })?
495             .on_sync::<lsp_ext::JoinLines>(|s, p| handlers::handle_join_lines(s.snapshot(), p))?
496             .on_sync::<lsp_ext::OnEnter>(|s, p| handlers::handle_on_enter(s.snapshot(), p))?
497             .on_sync::<lsp_types::request::Shutdown>(|s, ()| {
498                 s.shutdown_requested = true;
499                 Ok(())
500             })?
501             .on_sync::<lsp_types::request::SelectionRangeRequest>(|s, p| {
502                 handlers::handle_selection_range(s.snapshot(), p)
503             })?
504             .on_sync::<lsp_ext::MatchingBrace>(|s, p| {
505                 handlers::handle_matching_brace(s.snapshot(), p)
506             })?
507             .on_sync::<lsp_ext::MemoryUsage>(|s, p| handlers::handle_memory_usage(s, p))?
508             .on::<lsp_ext::AnalyzerStatus>(handlers::handle_analyzer_status)
509             .on::<lsp_ext::SyntaxTree>(handlers::handle_syntax_tree)
510             .on::<lsp_ext::ViewHir>(handlers::handle_view_hir)
511             .on::<lsp_ext::ViewCrateGraph>(handlers::handle_view_crate_graph)
512             .on::<lsp_ext::ViewItemTree>(handlers::handle_view_item_tree)
513             .on::<lsp_ext::ExpandMacro>(handlers::handle_expand_macro)
514             .on::<lsp_ext::ParentModule>(handlers::handle_parent_module)
515             .on::<lsp_ext::Runnables>(handlers::handle_runnables)
516             .on::<lsp_ext::RelatedTests>(handlers::handle_related_tests)
517             .on::<lsp_ext::InlayHints>(handlers::handle_inlay_hints)
518             .on::<lsp_ext::CodeActionRequest>(handlers::handle_code_action)
519             .on::<lsp_ext::CodeActionResolveRequest>(handlers::handle_code_action_resolve)
520             .on::<lsp_ext::HoverRequest>(handlers::handle_hover)
521             .on::<lsp_ext::ExternalDocs>(handlers::handle_open_docs)
522             .on::<lsp_ext::OpenCargoToml>(handlers::handle_open_cargo_toml)
523             .on::<lsp_ext::MoveItem>(handlers::handle_move_item)
524             .on::<lsp_ext::WorkspaceSymbol>(handlers::handle_workspace_symbol)
525             .on::<lsp_types::request::OnTypeFormatting>(handlers::handle_on_type_formatting)
526             .on::<lsp_types::request::DocumentSymbolRequest>(handlers::handle_document_symbol)
527             .on::<lsp_types::request::GotoDefinition>(handlers::handle_goto_definition)
528             .on::<lsp_types::request::GotoDeclaration>(handlers::handle_goto_declaration)
529             .on::<lsp_types::request::GotoImplementation>(handlers::handle_goto_implementation)
530             .on::<lsp_types::request::GotoTypeDefinition>(handlers::handle_goto_type_definition)
531             .on::<lsp_types::request::Completion>(handlers::handle_completion)
532             .on::<lsp_types::request::ResolveCompletionItem>(handlers::handle_completion_resolve)
533             .on::<lsp_types::request::CodeLensRequest>(handlers::handle_code_lens)
534             .on::<lsp_types::request::CodeLensResolve>(handlers::handle_code_lens_resolve)
535             .on::<lsp_types::request::FoldingRangeRequest>(handlers::handle_folding_range)
536             .on::<lsp_types::request::SignatureHelpRequest>(handlers::handle_signature_help)
537             .on::<lsp_types::request::PrepareRenameRequest>(handlers::handle_prepare_rename)
538             .on::<lsp_types::request::Rename>(handlers::handle_rename)
539             .on::<lsp_types::request::References>(handlers::handle_references)
540             .on::<lsp_types::request::Formatting>(handlers::handle_formatting)
541             .on::<lsp_types::request::RangeFormatting>(handlers::handle_range_formatting)
542             .on::<lsp_types::request::DocumentHighlightRequest>(handlers::handle_document_highlight)
543             .on::<lsp_types::request::CallHierarchyPrepare>(handlers::handle_call_hierarchy_prepare)
544             .on::<lsp_types::request::CallHierarchyIncomingCalls>(
545                 handlers::handle_call_hierarchy_incoming,
546             )
547             .on::<lsp_types::request::CallHierarchyOutgoingCalls>(
548                 handlers::handle_call_hierarchy_outgoing,
549             )
550             .on::<lsp_types::request::SemanticTokensFullRequest>(
551                 handlers::handle_semantic_tokens_full,
552             )
553             .on::<lsp_types::request::SemanticTokensFullDeltaRequest>(
554                 handlers::handle_semantic_tokens_full_delta,
555             )
556             .on::<lsp_types::request::SemanticTokensRangeRequest>(
557                 handlers::handle_semantic_tokens_range,
558             )
559             .on::<lsp_types::request::WillRenameFiles>(handlers::handle_will_rename_files)
560             .on::<lsp_ext::Ssr>(handlers::handle_ssr)
561             .finish();
562         Ok(())
563     }
564     fn on_notification(&mut self, not: Notification) -> Result<()> {
565         NotificationDispatcher { not: Some(not), global_state: self }
566             .on::<lsp_types::notification::Cancel>(|this, params| {
567                 let id: lsp_server::RequestId = match params.id {
568                     lsp_types::NumberOrString::Number(id) => id.into(),
569                     lsp_types::NumberOrString::String(id) => id.into(),
570                 };
571                 this.cancel(id);
572                 Ok(())
573             })?
574             .on::<lsp_types::notification::WorkDoneProgressCancel>(|_this, _params| {
575                 // Just ignore this. It is OK to continue sending progress
576                 // notifications for this token, as the client can't know when
577                 // we accepted notification.
578                 Ok(())
579             })?
580             .on::<lsp_types::notification::DidOpenTextDocument>(|this, params| {
581                 if let Ok(path) = from_proto::vfs_path(&params.text_document.uri) {
582                     if this
583                         .mem_docs
584                         .insert(path.clone(), DocumentData::new(params.text_document.version))
585                         .is_err()
586                     {
587                         log::error!("duplicate DidOpenTextDocument: {}", path)
588                     }
589                     let changed = this
590                         .vfs
591                         .write()
592                         .0
593                         .set_file_contents(path, Some(params.text_document.text.into_bytes()));
594
595                     // If the VFS contents are unchanged, update diagnostics, since `handle_event`
596                     // won't see any changes. This avoids missing diagnostics when opening a file.
597                     //
598                     // If the file *was* changed, `handle_event` will already recompute and send
599                     // diagnostics. We can't do it here, since the *current* file contents might be
600                     // unset in salsa, since the VFS change hasn't been applied to the database yet.
601                     if !changed {
602                         this.maybe_update_diagnostics();
603                     }
604                 }
605                 Ok(())
606             })?
607             .on::<lsp_types::notification::DidChangeTextDocument>(|this, params| {
608                 if let Ok(path) = from_proto::vfs_path(&params.text_document.uri) {
609                     let doc = match this.mem_docs.get_mut(&path) {
610                         Some(doc) => doc,
611                         None => {
612                             log::error!("expected DidChangeTextDocument: {}", path);
613                             return Ok(());
614                         }
615                     };
616                     let vfs = &mut this.vfs.write().0;
617                     let file_id = vfs.file_id(&path).unwrap();
618                     let mut text = String::from_utf8(vfs.file_contents(file_id).to_vec()).unwrap();
619                     apply_document_changes(&mut text, params.content_changes);
620
621                     // The version passed in DidChangeTextDocument is the version after all edits are applied
622                     // so we should apply it before the vfs is notified.
623                     doc.version = params.text_document.version;
624
625                     vfs.set_file_contents(path.clone(), Some(text.into_bytes()));
626                 }
627                 Ok(())
628             })?
629             .on::<lsp_types::notification::DidCloseTextDocument>(|this, params| {
630                 if let Ok(path) = from_proto::vfs_path(&params.text_document.uri) {
631                     if this.mem_docs.remove(&path).is_err() {
632                         log::error!("orphan DidCloseTextDocument: {}", path);
633                     }
634
635                     this.semantic_tokens_cache.lock().remove(&params.text_document.uri);
636
637                     if let Some(path) = path.as_path() {
638                         this.loader.handle.invalidate(path.to_path_buf());
639                     }
640                 }
641                 Ok(())
642             })?
643             .on::<lsp_types::notification::DidSaveTextDocument>(|this, params| {
644                 for flycheck in &this.flycheck {
645                     flycheck.update();
646                 }
647                 if let Ok(abs_path) = from_proto::abs_path(&params.text_document.uri) {
648                     this.maybe_refresh(&[(abs_path, ChangeKind::Modify)]);
649                 }
650                 Ok(())
651             })?
652             .on::<lsp_types::notification::DidChangeConfiguration>(|this, _params| {
653                 // As stated in https://github.com/microsoft/language-server-protocol/issues/676,
654                 // this notification's parameters should be ignored and the actual config queried separately.
655                 this.send_request::<lsp_types::request::WorkspaceConfiguration>(
656                     lsp_types::ConfigurationParams {
657                         items: vec![lsp_types::ConfigurationItem {
658                             scope_uri: None,
659                             section: Some("rust-analyzer".to_string()),
660                         }],
661                     },
662                     |this, resp| {
663                         log::debug!("config update response: '{:?}", resp);
664                         let lsp_server::Response { error, result, .. } = resp;
665
666                         match (error, result) {
667                             (Some(err), _) => {
668                                 log::error!("failed to fetch the server settings: {:?}", err)
669                             }
670                             (None, Some(mut configs)) => {
671                                 if let Some(json) = configs.get_mut(0) {
672                                     // Note that json can be null according to the spec if the client can't
673                                     // provide a configuration. This is handled in Config::update below.
674                                     let mut config = Config::clone(&*this.config);
675                                     config.update(json.take());
676                                     this.update_configuration(config);
677                                 }
678                             }
679                             (None, None) => log::error!(
680                                 "received empty server settings response from the client"
681                             ),
682                         }
683                     },
684                 );
685
686                 Ok(())
687             })?
688             .on::<lsp_types::notification::DidChangeWatchedFiles>(|this, params| {
689                 for change in params.changes {
690                     if let Ok(path) = from_proto::abs_path(&change.uri) {
691                         this.loader.handle.invalidate(path);
692                     }
693                 }
694                 Ok(())
695             })?
696             .finish();
697         Ok(())
698     }
699     fn update_file_notifications_on_threadpool(&mut self) {
700         self.maybe_update_diagnostics();
701
702         // Ensure that only one cache priming task can run at a time
703         self.prime_caches_queue.request_op();
704         if self.prime_caches_queue.should_start_op() {
705             self.task_pool.handle.spawn_with_sender({
706                 let snap = self.snapshot();
707                 move |sender| {
708                     let cb = |progress| {
709                         sender.send(Task::PrimeCaches(progress)).unwrap();
710                     };
711                     match snap.analysis.prime_caches(cb) {
712                         Ok(()) => (),
713                         Err(_canceled) => (),
714                     }
715                 }
716             });
717         }
718     }
719     fn maybe_update_diagnostics(&mut self) {
720         let subscriptions = self
721             .mem_docs
722             .iter()
723             .map(|path| self.vfs.read().0.file_id(path).unwrap())
724             .collect::<Vec<_>>();
725
726         log::trace!("updating notifications for {:?}", subscriptions);
727         if self.config.publish_diagnostics() {
728             let snapshot = self.snapshot();
729             self.task_pool.handle.spawn(move || {
730                 let diagnostics = subscriptions
731                     .into_iter()
732                     .filter_map(|file_id| {
733                         handlers::publish_diagnostics(&snapshot, file_id)
734                             .map_err(|err| {
735                                 if !is_cancelled(&*err) {
736                                     log::error!("failed to compute diagnostics: {:?}", err);
737                                 }
738                                 ()
739                             })
740                             .ok()
741                             .map(|diags| (file_id, diags))
742                     })
743                     .collect::<Vec<_>>();
744                 Task::Diagnostics(diagnostics)
745             })
746         }
747     }
748 }