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