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