]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/main_loop.rs
Merge #8536
[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::PrimeCachesProgress;
12 use ide::{Canceled, FileId};
13 use ide_db::base_db::VfsPath;
14 use lsp_server::{Connection, Notification, Request, Response};
15 use lsp_types::notification::Notification as _;
16 use project_model::BuildDataCollector;
17 use vfs::ChangeKind;
18
19 use crate::{
20     config::Config,
21     dispatch::{NotificationDispatcher, RequestDispatcher},
22     document::DocumentData,
23     from_proto,
24     global_state::{file_id_to_url, url_to_file_id, GlobalState},
25     handlers, lsp_ext,
26     lsp_utils::{apply_document_changes, is_canceled, notification_is, Progress},
27     reload::{BuildDataProgress, ProjectWorkspaceProgress},
28     Result,
29 };
30
31 pub fn main_loop(config: Config, connection: Connection) -> Result<()> {
32     log::info!("initial config: {:#?}", config);
33
34     // Windows scheduler implements priority boosts: if thread waits for an
35     // event (like a condvar), and event fires, priority of the thread is
36     // temporary bumped. This optimization backfires in our case: each time the
37     // `main_loop` schedules a task to run on a threadpool, the worker threads
38     // gets a higher priority, and (on a machine with fewer cores) displaces the
39     // main loop! We work-around this by marking the main loop as a
40     // higher-priority thread.
41     //
42     // https://docs.microsoft.com/en-us/windows/win32/procthread/scheduling-priorities
43     // https://docs.microsoft.com/en-us/windows/win32/procthread/priority-boosts
44     // https://github.com/rust-analyzer/rust-analyzer/issues/2835
45     #[cfg(windows)]
46     unsafe {
47         use winapi::um::processthreadsapi::*;
48         let thread = GetCurrentThread();
49         let thread_priority_above_normal = 1;
50         SetThreadPriority(thread, thread_priority_above_normal);
51     }
52
53     GlobalState::new(connection.sender, config).run(connection.receiver)
54 }
55
56 enum Event {
57     Lsp(lsp_server::Message),
58     Task(Task),
59     Vfs(vfs::loader::Message),
60     Flycheck(flycheck::Message),
61 }
62
63 #[derive(Debug)]
64 pub(crate) enum Task {
65     Response(Response),
66     Diagnostics(Vec<(FileId, Vec<lsp_types::Diagnostic>)>),
67     PrimeCaches(PrimeCachesProgress),
68     FetchWorkspace(ProjectWorkspaceProgress),
69     FetchBuildData(BuildDataProgress),
70 }
71
72 impl fmt::Debug for Event {
73     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
74         let debug_verbose_not = |not: &Notification, f: &mut fmt::Formatter| {
75             f.debug_struct("Notification").field("method", &not.method).finish()
76         };
77
78         match self {
79             Event::Lsp(lsp_server::Message::Notification(not)) => {
80                 if notification_is::<lsp_types::notification::DidOpenTextDocument>(not)
81                     || notification_is::<lsp_types::notification::DidChangeTextDocument>(not)
82                 {
83                     return debug_verbose_not(not, f);
84                 }
85             }
86             Event::Task(Task::Response(resp)) => {
87                 return f
88                     .debug_struct("Response")
89                     .field("id", &resp.id)
90                     .field("error", &resp.error)
91                     .finish();
92             }
93             _ => (),
94         }
95         match self {
96             Event::Lsp(it) => fmt::Debug::fmt(it, f),
97             Event::Task(it) => fmt::Debug::fmt(it, f),
98             Event::Vfs(it) => fmt::Debug::fmt(it, f),
99             Event::Flycheck(it) => fmt::Debug::fmt(it, f),
100         }
101     }
102 }
103
104 impl GlobalState {
105     fn run(mut self, inbox: Receiver<lsp_server::Message>) -> Result<()> {
106         if self.config.linked_projects().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                     };
300
301                     self.report_progress("Indexing", state, message, Some(fraction));
302                 }
303             }
304             Event::Vfs(mut task) => {
305                 let _p = profile::span("GlobalState::handle_event/vfs");
306                 loop {
307                     match task {
308                         vfs::loader::Message::Loaded { files } => {
309                             let vfs = &mut self.vfs.write().0;
310                             for (path, contents) in files {
311                                 let path = VfsPath::from(path);
312                                 if !self.mem_docs.contains_key(&path) {
313                                     vfs.set_file_contents(path, contents);
314                                 }
315                             }
316                         }
317                         vfs::loader::Message::Progress { n_total, n_done, config_version } => {
318                             always!(config_version <= self.vfs_config_version);
319
320                             self.vfs_progress_config_version = config_version;
321                             self.vfs_progress_n_total = n_total;
322                             self.vfs_progress_n_done = n_done;
323
324                             let state = if n_done == 0 {
325                                 Progress::Begin
326                             } else if n_done < n_total {
327                                 Progress::Report
328                             } else {
329                                 assert_eq!(n_done, n_total);
330                                 Progress::End
331                             };
332                             self.report_progress(
333                                 "Roots Scanned",
334                                 state,
335                                 Some(format!("{}/{}", n_done, n_total)),
336                                 Some(Progress::fraction(n_done, n_total)),
337                             )
338                         }
339                     }
340                     // Coalesce many VFS event into a single loop turn
341                     task = match self.loader.receiver.try_recv() {
342                         Ok(task) => task,
343                         Err(_) => break,
344                     }
345                 }
346             }
347             Event::Flycheck(mut task) => {
348                 let _p = profile::span("GlobalState::handle_event/flycheck");
349                 loop {
350                     match task {
351                         flycheck::Message::AddDiagnostic { workspace_root, diagnostic } => {
352                             let diagnostics =
353                                 crate::diagnostics::to_proto::map_rust_diagnostic_to_lsp(
354                                     &self.config.diagnostics_map(),
355                                     &diagnostic,
356                                     &workspace_root,
357                                 );
358                             for diag in diagnostics {
359                                 match url_to_file_id(&self.vfs.read().0, &diag.url) {
360                                     Ok(file_id) => self.diagnostics.add_check_diagnostic(
361                                         file_id,
362                                         diag.diagnostic,
363                                         diag.fixes,
364                                     ),
365                                     Err(err) => {
366                                         log::error!(
367                                             "File with cargo diagnostic not found in VFS: {}",
368                                             err
369                                         );
370                                     }
371                                 };
372                             }
373                         }
374
375                         flycheck::Message::Progress { id, progress } => {
376                             let (state, message) = match progress {
377                                 flycheck::Progress::DidStart => {
378                                     self.diagnostics.clear_check();
379                                     (Progress::Begin, None)
380                                 }
381                                 flycheck::Progress::DidCheckCrate(target) => {
382                                     (Progress::Report, Some(target))
383                                 }
384                                 flycheck::Progress::DidCancel => (Progress::End, None),
385                                 flycheck::Progress::DidFinish(result) => {
386                                     if let Err(err) = result {
387                                         log::error!("cargo check failed: {}", err)
388                                     }
389                                     (Progress::End, None)
390                                 }
391                             };
392
393                             // When we're running multiple flychecks, we have to include a disambiguator in
394                             // the title, or the editor complains. Note that this is a user-facing string.
395                             let title = if self.flycheck.len() == 1 {
396                                 "cargo check".to_string()
397                             } else {
398                                 format!("cargo check (#{})", id + 1)
399                             };
400                             self.report_progress(&title, state, message, None);
401                         }
402                     }
403                     // Coalesce many flycheck updates into a single loop turn
404                     task = match self.flycheck_receiver.try_recv() {
405                         Ok(task) => task,
406                         Err(_) => break,
407                     }
408                 }
409             }
410         }
411
412         let state_changed = self.process_changes();
413
414         if self.is_quiescent() && !was_quiescent {
415             for flycheck in &self.flycheck {
416                 flycheck.update();
417             }
418         }
419
420         if self.is_quiescent() && (!was_quiescent || state_changed) {
421             self.update_file_notifications_on_threadpool();
422
423             // Refresh semantic tokens if the client supports it.
424             if self.config.semantic_tokens_refresh() {
425                 self.semantic_tokens_cache.lock().clear();
426                 self.send_request::<lsp_types::request::SemanticTokensRefesh>((), |_, _| ());
427             }
428
429             // Refresh code lens if the client supports it.
430             if self.config.code_lens_refresh() {
431                 self.send_request::<lsp_types::request::CodeLensRefresh>((), |_, _| ());
432             }
433         }
434
435         if let Some(diagnostic_changes) = self.diagnostics.take_changes() {
436             for file_id in diagnostic_changes {
437                 let url = file_id_to_url(&self.vfs.read().0, file_id);
438                 let diagnostics = self.diagnostics.diagnostics_for(file_id).cloned().collect();
439                 let version = from_proto::vfs_path(&url)
440                     .map(|path| self.mem_docs.get(&path).map(|it| it.version))
441                     .unwrap_or_default();
442
443                 self.send_notification::<lsp_types::notification::PublishDiagnostics>(
444                     lsp_types::PublishDiagnosticsParams { uri: url, diagnostics, version },
445                 );
446             }
447         }
448
449         if self.config.cargo_autoreload() {
450             self.fetch_workspaces_if_needed();
451         }
452         self.fetch_build_data_if_needed();
453
454         self.report_new_status_if_needed();
455
456         let loop_duration = loop_start.elapsed();
457         if loop_duration > Duration::from_millis(100) {
458             log::warn!("overly long loop turn: {:?}", loop_duration);
459             if env::var("RA_PROFILE").is_ok() {
460                 self.show_message(
461                     lsp_types::MessageType::Error,
462                     format!("overly long loop turn: {:?}", loop_duration),
463                 )
464             }
465         }
466         Ok(())
467     }
468
469     fn on_request(&mut self, request_received: Instant, req: Request) -> Result<()> {
470         self.register_request(&req, request_received);
471
472         if self.shutdown_requested {
473             self.respond(Response::new_err(
474                 req.id,
475                 lsp_server::ErrorCode::InvalidRequest as i32,
476                 "Shutdown already requested.".to_owned(),
477             ));
478
479             return Ok(());
480         }
481
482         // Avoid flashing a bunch of unresolved references during initial load.
483         if self.workspaces.is_empty() && !self.is_quiescent() {
484             self.respond(lsp_server::Response::new_err(
485                 req.id,
486                 // FIXME: i32 should impl From<ErrorCode> (from() guarantees lossless conversion)
487                 lsp_server::ErrorCode::ContentModified as i32,
488                 "waiting for cargo metadata or cargo check".to_owned(),
489             ));
490             return Ok(());
491         }
492
493         RequestDispatcher { req: Some(req), global_state: self }
494             .on_sync::<lsp_ext::ReloadWorkspace>(|s, ()| {
495                 s.fetch_workspaces_request();
496                 s.fetch_workspaces_if_needed();
497                 Ok(())
498             })?
499             .on_sync::<lsp_ext::JoinLines>(|s, p| handlers::handle_join_lines(s.snapshot(), p))?
500             .on_sync::<lsp_ext::OnEnter>(|s, p| handlers::handle_on_enter(s.snapshot(), p))?
501             .on_sync::<lsp_types::request::Shutdown>(|s, ()| {
502                 s.shutdown_requested = true;
503                 Ok(())
504             })?
505             .on_sync::<lsp_types::request::SelectionRangeRequest>(|s, p| {
506                 handlers::handle_selection_range(s.snapshot(), p)
507             })?
508             .on_sync::<lsp_ext::MatchingBrace>(|s, p| {
509                 handlers::handle_matching_brace(s.snapshot(), p)
510             })?
511             .on_sync::<lsp_ext::MemoryUsage>(|s, p| handlers::handle_memory_usage(s, p))?
512             .on::<lsp_ext::AnalyzerStatus>(handlers::handle_analyzer_status)
513             .on::<lsp_ext::SyntaxTree>(handlers::handle_syntax_tree)
514             .on::<lsp_ext::ViewHir>(handlers::handle_view_hir)
515             .on::<lsp_ext::ExpandMacro>(handlers::handle_expand_macro)
516             .on::<lsp_ext::ParentModule>(handlers::handle_parent_module)
517             .on::<lsp_ext::Runnables>(handlers::handle_runnables)
518             .on::<lsp_ext::RelatedTests>(handlers::handle_related_tests)
519             .on::<lsp_ext::InlayHints>(handlers::handle_inlay_hints)
520             .on::<lsp_ext::CodeActionRequest>(handlers::handle_code_action)
521             .on::<lsp_ext::CodeActionResolveRequest>(handlers::handle_code_action_resolve)
522             .on::<lsp_ext::HoverRequest>(handlers::handle_hover)
523             .on::<lsp_ext::ExternalDocs>(handlers::handle_open_docs)
524             .on::<lsp_ext::OpenCargoToml>(handlers::handle_open_cargo_toml)
525             .on::<lsp_ext::MoveItem>(handlers::handle_move_item)
526             .on::<lsp_types::request::OnTypeFormatting>(handlers::handle_on_type_formatting)
527             .on::<lsp_types::request::DocumentSymbolRequest>(handlers::handle_document_symbol)
528             .on::<lsp_types::request::WorkspaceSymbol>(handlers::handle_workspace_symbol)
529             .on::<lsp_types::request::GotoDefinition>(handlers::handle_goto_definition)
530             .on::<lsp_types::request::GotoImplementation>(handlers::handle_goto_implementation)
531             .on::<lsp_types::request::GotoTypeDefinition>(handlers::handle_goto_type_definition)
532             .on::<lsp_types::request::Completion>(handlers::handle_completion)
533             .on::<lsp_types::request::ResolveCompletionItem>(handlers::handle_completion_resolve)
534             .on::<lsp_types::request::CodeLensRequest>(handlers::handle_code_lens)
535             .on::<lsp_types::request::CodeLensResolve>(handlers::handle_code_lens_resolve)
536             .on::<lsp_types::request::FoldingRangeRequest>(handlers::handle_folding_range)
537             .on::<lsp_types::request::SignatureHelpRequest>(handlers::handle_signature_help)
538             .on::<lsp_types::request::PrepareRenameRequest>(handlers::handle_prepare_rename)
539             .on::<lsp_types::request::Rename>(handlers::handle_rename)
540             .on::<lsp_types::request::References>(handlers::handle_references)
541             .on::<lsp_types::request::Formatting>(handlers::handle_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::DidOpenTextDocument>(|this, params| {
575                 if let Ok(path) = from_proto::vfs_path(&params.text_document.uri) {
576                     if this
577                         .mem_docs
578                         .insert(path.clone(), DocumentData::new(params.text_document.version))
579                         .is_some()
580                     {
581                         log::error!("duplicate DidOpenTextDocument: {}", path)
582                     }
583                     let changed = this
584                         .vfs
585                         .write()
586                         .0
587                         .set_file_contents(path, Some(params.text_document.text.into_bytes()));
588
589                     // If the VFS contents are unchanged, update diagnostics, since `handle_event`
590                     // won't see any changes. This avoids missing diagnostics when opening a file.
591                     //
592                     // If the file *was* changed, `handle_event` will already recompute and send
593                     // diagnostics. We can't do it here, since the *current* file contents might be
594                     // unset in salsa, since the VFS change hasn't been applied to the database yet.
595                     if !changed {
596                         this.maybe_update_diagnostics();
597                     }
598                 }
599                 Ok(())
600             })?
601             .on::<lsp_types::notification::DidChangeTextDocument>(|this, params| {
602                 if let Ok(path) = from_proto::vfs_path(&params.text_document.uri) {
603                     let doc = match this.mem_docs.get_mut(&path) {
604                         Some(doc) => doc,
605                         None => {
606                             log::error!("expected DidChangeTextDocument: {}", path);
607                             return Ok(());
608                         }
609                     };
610                     let vfs = &mut this.vfs.write().0;
611                     let file_id = vfs.file_id(&path).unwrap();
612                     let mut text = String::from_utf8(vfs.file_contents(file_id).to_vec()).unwrap();
613                     apply_document_changes(&mut text, params.content_changes);
614
615                     // The version passed in DidChangeTextDocument is the version after all edits are applied
616                     // so we should apply it before the vfs is notified.
617                     doc.version = params.text_document.version;
618
619                     vfs.set_file_contents(path.clone(), Some(text.into_bytes()));
620                 }
621                 Ok(())
622             })?
623             .on::<lsp_types::notification::DidCloseTextDocument>(|this, params| {
624                 let mut version = None;
625                 if let Ok(path) = from_proto::vfs_path(&params.text_document.uri) {
626                     match this.mem_docs.remove(&path) {
627                         Some(doc) => version = Some(doc.version),
628                         None => log::error!("orphan DidCloseTextDocument: {}", path),
629                     }
630
631                     this.semantic_tokens_cache.lock().remove(&params.text_document.uri);
632
633                     if let Some(path) = path.as_path() {
634                         this.loader.handle.invalidate(path.to_path_buf());
635                     }
636                 }
637
638                 // Clear the diagnostics for the previously known version of the file.
639                 // This prevents stale "cargo check" diagnostics if the file is
640                 // closed, "cargo check" is run and then the file is reopened.
641                 this.send_notification::<lsp_types::notification::PublishDiagnostics>(
642                     lsp_types::PublishDiagnosticsParams {
643                         uri: params.text_document.uri,
644                         diagnostics: Vec::new(),
645                         version,
646                     },
647                 );
648                 Ok(())
649             })?
650             .on::<lsp_types::notification::DidSaveTextDocument>(|this, params| {
651                 for flycheck in &this.flycheck {
652                     flycheck.update();
653                 }
654                 if let Ok(abs_path) = from_proto::abs_path(&params.text_document.uri) {
655                     this.maybe_refresh(&[(abs_path, ChangeKind::Modify)]);
656                 }
657                 Ok(())
658             })?
659             .on::<lsp_types::notification::DidChangeConfiguration>(|this, _params| {
660                 // As stated in https://github.com/microsoft/language-server-protocol/issues/676,
661                 // this notification's parameters should be ignored and the actual config queried separately.
662                 this.send_request::<lsp_types::request::WorkspaceConfiguration>(
663                     lsp_types::ConfigurationParams {
664                         items: vec![lsp_types::ConfigurationItem {
665                             scope_uri: None,
666                             section: Some("rust-analyzer".to_string()),
667                         }],
668                     },
669                     |this, resp| {
670                         log::debug!("config update response: '{:?}", resp);
671                         let Response { error, result, .. } = resp;
672
673                         match (error, result) {
674                             (Some(err), _) => {
675                                 log::error!("failed to fetch the server settings: {:?}", err)
676                             }
677                             (None, Some(mut configs)) => {
678                                 if let Some(json) = configs.get_mut(0) {
679                                     // Note that json can be null according to the spec if the client can't
680                                     // provide a configuration. This is handled in Config::update below.
681                                     let mut config = Config::clone(&*this.config);
682                                     config.update(json.take());
683                                     this.update_configuration(config);
684                                 }
685                             }
686                             (None, None) => log::error!(
687                                 "received empty server settings response from the client"
688                             ),
689                         }
690                     },
691                 );
692
693                 return Ok(());
694             })?
695             .on::<lsp_types::notification::DidChangeWatchedFiles>(|this, params| {
696                 for change in params.changes {
697                     if let Ok(path) = from_proto::abs_path(&change.uri) {
698                         this.loader.handle.invalidate(path);
699                     }
700                 }
701                 Ok(())
702             })?
703             .finish();
704         Ok(())
705     }
706     fn update_file_notifications_on_threadpool(&mut self) {
707         self.maybe_update_diagnostics();
708         self.task_pool.handle.spawn_with_sender({
709             let snap = self.snapshot();
710             move |sender| {
711                 snap.analysis
712                     .prime_caches(|progress| {
713                         sender.send(Task::PrimeCaches(progress)).unwrap();
714                     })
715                     .unwrap_or_else(|_: Canceled| {
716                         // Pretend that we're done, so that the progress bar is removed. Otherwise
717                         // the editor may complain about it already existing.
718                         sender.send(Task::PrimeCaches(PrimeCachesProgress::Finished)).unwrap()
719                     });
720             }
721         });
722     }
723     fn maybe_update_diagnostics(&mut self) {
724         let subscriptions = self
725             .mem_docs
726             .keys()
727             .map(|path| self.vfs.read().0.file_id(&path).unwrap())
728             .collect::<Vec<_>>();
729
730         log::trace!("updating notifications for {:?}", subscriptions);
731         if self.config.publish_diagnostics() {
732             let snapshot = self.snapshot();
733             self.task_pool.handle.spawn(move || {
734                 let diagnostics = subscriptions
735                     .into_iter()
736                     .filter_map(|file_id| {
737                         handlers::publish_diagnostics(&snapshot, file_id)
738                             .map_err(|err| {
739                                 if !is_canceled(&*err) {
740                                     log::error!("failed to compute diagnostics: {:?}", err);
741                                 }
742                                 ()
743                             })
744                             .ok()
745                             .map(|diags| (file_id, diags))
746                     })
747                     .collect::<Vec<_>>();
748                 Task::Diagnostics(diagnostics)
749             })
750         }
751     }
752 }