]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/main_loop.rs
Draft the new lsp handler
[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     time::{Duration, Instant},
6 };
7
8 use crossbeam_channel::{select, Receiver};
9 use ide::PrimeCachesProgress;
10 use ide::{Canceled, FileId};
11 use ide_db::base_db::VfsPath;
12 use lsp_server::{Connection, Notification, Request, Response};
13 use lsp_types::notification::Notification as _;
14 use project_model::ProjectWorkspace;
15 use vfs::ChangeKind;
16
17 use crate::{
18     config::Config,
19     dispatch::{NotificationDispatcher, RequestDispatcher},
20     document::DocumentData,
21     from_proto,
22     global_state::{file_id_to_url, url_to_file_id, GlobalState, Status},
23     handlers, lsp_ext,
24     lsp_utils::{apply_document_changes, is_canceled, notification_is, Progress},
25     Result,
26 };
27
28 pub fn main_loop(config: Config, connection: Connection) -> Result<()> {
29     log::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(Response),
63     Diagnostics(Vec<(FileId, Vec<lsp_types::Diagnostic>)>),
64     Workspaces(Vec<anyhow::Result<ProjectWorkspace>>),
65     PrimeCaches(PrimeCachesProgress),
66 }
67
68 impl fmt::Debug for Event {
69     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
70         let debug_verbose_not = |not: &Notification, f: &mut fmt::Formatter| {
71             f.debug_struct("Notification").field("method", &not.method).finish()
72         };
73
74         match self {
75             Event::Lsp(lsp_server::Message::Notification(not)) => {
76                 if notification_is::<lsp_types::notification::DidOpenTextDocument>(not)
77                     || notification_is::<lsp_types::notification::DidChangeTextDocument>(not)
78                 {
79                     return debug_verbose_not(not, f);
80                 }
81             }
82             Event::Task(Task::Response(resp)) => {
83                 return f
84                     .debug_struct("Response")
85                     .field("id", &resp.id)
86                     .field("error", &resp.error)
87                     .finish();
88             }
89             _ => (),
90         }
91         match self {
92             Event::Lsp(it) => fmt::Debug::fmt(it, f),
93             Event::Task(it) => fmt::Debug::fmt(it, f),
94             Event::Vfs(it) => fmt::Debug::fmt(it, f),
95             Event::Flycheck(it) => fmt::Debug::fmt(it, f),
96         }
97     }
98 }
99
100 impl GlobalState {
101     fn run(mut self, inbox: Receiver<lsp_server::Message>) -> Result<()> {
102         if self.config.linked_projects.is_empty() && self.config.notifications.cargo_toml_not_found
103         {
104             self.show_message(
105                 lsp_types::MessageType::Error,
106                 "rust-analyzer failed to discover workspace".to_string(),
107             );
108         };
109
110         let save_registration_options = lsp_types::TextDocumentSaveRegistrationOptions {
111             include_text: Some(false),
112             text_document_registration_options: lsp_types::TextDocumentRegistrationOptions {
113                 document_selector: Some(vec![
114                     lsp_types::DocumentFilter {
115                         language: None,
116                         scheme: None,
117                         pattern: Some("**/*.rs".into()),
118                     },
119                     lsp_types::DocumentFilter {
120                         language: None,
121                         scheme: None,
122                         pattern: Some("**/Cargo.toml".into()),
123                     },
124                     lsp_types::DocumentFilter {
125                         language: None,
126                         scheme: None,
127                         pattern: Some("**/Cargo.lock".into()),
128                     },
129                 ]),
130             },
131         };
132
133         let registration = lsp_types::Registration {
134             id: "textDocument/didSave".to_string(),
135             method: "textDocument/didSave".to_string(),
136             register_options: Some(serde_json::to_value(save_registration_options).unwrap()),
137         };
138         self.send_request::<lsp_types::request::RegisterCapability>(
139             lsp_types::RegistrationParams { registrations: vec![registration] },
140             |_, _| (),
141         );
142
143         self.fetch_workspaces();
144
145         while let Some(event) = self.next_event(&inbox) {
146             if let Event::Lsp(lsp_server::Message::Notification(not)) = &event {
147                 if not.method == lsp_types::notification::Exit::METHOD {
148                     return Ok(());
149                 }
150             }
151             self.handle_event(event)?
152         }
153
154         Err("client exited without proper shutdown sequence")?
155     }
156
157     fn next_event(&self, inbox: &Receiver<lsp_server::Message>) -> Option<Event> {
158         select! {
159             recv(inbox) -> msg =>
160                 msg.ok().map(Event::Lsp),
161
162             recv(self.task_pool.receiver) -> task =>
163                 Some(Event::Task(task.unwrap())),
164
165             recv(self.loader.receiver) -> task =>
166                 Some(Event::Vfs(task.unwrap())),
167
168             recv(self.flycheck_receiver) -> task =>
169                 Some(Event::Flycheck(task.unwrap())),
170         }
171     }
172
173     fn handle_event(&mut self, event: Event) -> Result<()> {
174         let loop_start = Instant::now();
175         // NOTE: don't count blocking select! call as a loop-turn time
176         let _p = profile::span("GlobalState::handle_event");
177
178         log::info!("handle_event({:?})", event);
179         let task_queue_len = self.task_pool.handle.len();
180         if task_queue_len > 0 {
181             log::info!("task queue len: {}", task_queue_len);
182         }
183
184         let prev_status = self.status;
185         match event {
186             Event::Lsp(msg) => match msg {
187                 lsp_server::Message::Request(req) => self.on_request(loop_start, req)?,
188                 lsp_server::Message::Notification(not) => {
189                     self.on_notification(not)?;
190                 }
191                 lsp_server::Message::Response(resp) => self.complete_request(resp),
192             },
193             Event::Task(mut task) => {
194                 let _p = profile::span("GlobalState::handle_event/task");
195                 let mut prime_caches_progress = Vec::new();
196                 loop {
197                     match task {
198                         Task::Response(response) => self.respond(response),
199                         Task::Diagnostics(diagnostics_per_file) => {
200                             for (file_id, diagnostics) in diagnostics_per_file {
201                                 self.diagnostics.set_native_diagnostics(file_id, diagnostics)
202                             }
203                         }
204                         Task::Workspaces(workspaces) => self.switch_workspaces(workspaces),
205                         Task::PrimeCaches(progress) => match progress {
206                             PrimeCachesProgress::Started => prime_caches_progress.push(progress),
207                             PrimeCachesProgress::StartedOnCrate { .. } => {
208                                 match prime_caches_progress.last_mut() {
209                                     Some(last @ PrimeCachesProgress::StartedOnCrate { .. }) => {
210                                         // Coalesce subsequent update events.
211                                         *last = progress;
212                                     }
213                                     _ => prime_caches_progress.push(progress),
214                                 }
215                             }
216                             PrimeCachesProgress::Finished => prime_caches_progress.push(progress),
217                         },
218                     }
219                     // Coalesce multiple task events into one loop turn
220                     task = match self.task_pool.receiver.try_recv() {
221                         Ok(task) => task,
222                         Err(_) => break,
223                     };
224                 }
225
226                 for progress in prime_caches_progress {
227                     let (state, message, fraction);
228                     match progress {
229                         PrimeCachesProgress::Started => {
230                             state = Progress::Begin;
231                             message = None;
232                             fraction = 0.0;
233                         }
234                         PrimeCachesProgress::StartedOnCrate { on_crate, n_done, n_total } => {
235                             state = Progress::Report;
236                             message = Some(format!("{}/{} ({})", n_done, n_total, on_crate));
237                             fraction = Progress::fraction(n_done, n_total);
238                         }
239                         PrimeCachesProgress::Finished => {
240                             state = Progress::End;
241                             message = None;
242                             fraction = 1.0;
243                         }
244                     };
245
246                     self.report_progress("indexing", state, message, Some(fraction));
247                 }
248             }
249             Event::Vfs(mut task) => {
250                 let _p = profile::span("GlobalState::handle_event/vfs");
251                 loop {
252                     match task {
253                         vfs::loader::Message::Loaded { files } => {
254                             let vfs = &mut self.vfs.write().0;
255                             for (path, contents) in files {
256                                 let path = VfsPath::from(path);
257                                 if !self.mem_docs.contains_key(&path) {
258                                     vfs.set_file_contents(path, contents)
259                                 }
260                             }
261                         }
262                         vfs::loader::Message::Progress { n_total, n_done } => {
263                             if n_total == 0 {
264                                 self.transition(Status::Invalid);
265                             } else {
266                                 let state = if n_done == 0 {
267                                     self.transition(Status::Loading);
268                                     Progress::Begin
269                                 } else if n_done < n_total {
270                                     Progress::Report
271                                 } else {
272                                     assert_eq!(n_done, n_total);
273                                     self.transition(Status::Ready);
274                                     Progress::End
275                                 };
276                                 self.report_progress(
277                                     "roots scanned",
278                                     state,
279                                     Some(format!("{}/{}", n_done, n_total)),
280                                     Some(Progress::fraction(n_done, n_total)),
281                                 )
282                             }
283                         }
284                     }
285                     // Coalesce many VFS event into a single loop turn
286                     task = match self.loader.receiver.try_recv() {
287                         Ok(task) => task,
288                         Err(_) => break,
289                     }
290                 }
291             }
292             Event::Flycheck(mut task) => {
293                 let _p = profile::span("GlobalState::handle_event/flycheck");
294                 loop {
295                     match task {
296                         flycheck::Message::AddDiagnostic { workspace_root, diagnostic } => {
297                             let diagnostics =
298                                 crate::diagnostics::to_proto::map_rust_diagnostic_to_lsp(
299                                     &self.config.diagnostics_map,
300                                     &diagnostic,
301                                     &workspace_root,
302                                 );
303                             for diag in diagnostics {
304                                 match url_to_file_id(&self.vfs.read().0, &diag.url) {
305                                     Ok(file_id) => self.diagnostics.add_check_diagnostic(
306                                         file_id,
307                                         diag.diagnostic,
308                                         diag.fixes,
309                                     ),
310                                     Err(err) => {
311                                         log::error!(
312                                             "File with cargo diagnostic not found in VFS: {}",
313                                             err
314                                         );
315                                     }
316                                 };
317                             }
318                         }
319
320                         flycheck::Message::Progress { id, progress } => {
321                             let (state, message) = match progress {
322                                 flycheck::Progress::DidStart => {
323                                     self.diagnostics.clear_check();
324                                     (Progress::Begin, None)
325                                 }
326                                 flycheck::Progress::DidCheckCrate(target) => {
327                                     (Progress::Report, Some(target))
328                                 }
329                                 flycheck::Progress::DidCancel => (Progress::End, None),
330                                 flycheck::Progress::DidFinish(result) => {
331                                     if let Err(err) = result {
332                                         log::error!("cargo check failed: {}", err)
333                                     }
334                                     (Progress::End, None)
335                                 }
336                             };
337
338                             // When we're running multiple flychecks, we have to include a disambiguator in
339                             // the title, or the editor complains. Note that this is a user-facing string.
340                             let title = if self.flycheck.len() == 1 {
341                                 "cargo check".to_string()
342                             } else {
343                                 format!("cargo check (#{})", id + 1)
344                             };
345                             self.report_progress(&title, state, message, None);
346                         }
347                     }
348                     // Coalesce many flycheck updates into a single loop turn
349                     task = match self.flycheck_receiver.try_recv() {
350                         Ok(task) => task,
351                         Err(_) => break,
352                     }
353                 }
354             }
355         }
356
357         let state_changed = self.process_changes();
358         if prev_status == Status::Loading && self.status == Status::Ready {
359             for flycheck in &self.flycheck {
360                 flycheck.update();
361             }
362         }
363
364         if self.status == Status::Ready && (state_changed || prev_status == Status::Loading) {
365             self.update_file_notifications_on_threadpool();
366
367             // Refresh semantic tokens if the client supports it.
368             if self.config.semantic_tokens_refresh {
369                 self.semantic_tokens_cache.lock().clear();
370                 self.send_request::<lsp_types::request::SemanticTokensRefesh>((), |_, _| ());
371             }
372         }
373
374         if let Some(diagnostic_changes) = self.diagnostics.take_changes() {
375             for file_id in diagnostic_changes {
376                 let url = file_id_to_url(&self.vfs.read().0, file_id);
377                 let diagnostics = self.diagnostics.diagnostics_for(file_id).cloned().collect();
378                 let version = from_proto::vfs_path(&url)
379                     .map(|path| self.mem_docs.get(&path).map(|it| it.version))
380                     .unwrap_or_default();
381
382                 self.send_notification::<lsp_types::notification::PublishDiagnostics>(
383                     lsp_types::PublishDiagnosticsParams { uri: url, diagnostics, version },
384                 );
385             }
386         }
387
388         let loop_duration = loop_start.elapsed();
389         if loop_duration > Duration::from_millis(100) {
390             log::warn!("overly long loop turn: {:?}", loop_duration);
391             if env::var("RA_PROFILE").is_ok() {
392                 self.show_message(
393                     lsp_types::MessageType::Error,
394                     format!("overly long loop turn: {:?}", loop_duration),
395                 )
396             }
397         }
398         Ok(())
399     }
400
401     fn on_request(&mut self, request_received: Instant, req: Request) -> Result<()> {
402         self.register_request(&req, request_received);
403
404         if self.shutdown_requested {
405             self.respond(Response::new_err(
406                 req.id,
407                 lsp_server::ErrorCode::InvalidRequest as i32,
408                 "Shutdown already requested.".to_owned(),
409             ));
410
411             return Ok(());
412         }
413
414         if self.status == Status::Loading && req.method != "shutdown" {
415             self.respond(lsp_server::Response::new_err(
416                 req.id,
417                 // FIXME: i32 should impl From<ErrorCode> (from() guarantees lossless conversion)
418                 lsp_server::ErrorCode::ContentModified as i32,
419                 "Rust Analyzer is still loading...".to_owned(),
420             ));
421             return Ok(());
422         }
423
424         RequestDispatcher { req: Some(req), global_state: self }
425             .on_sync::<lsp_ext::ReloadWorkspace>(|s, ()| Ok(s.fetch_workspaces()))?
426             .on_sync::<lsp_ext::JoinLines>(|s, p| handlers::handle_join_lines(s.snapshot(), p))?
427             .on_sync::<lsp_ext::OnEnter>(|s, p| handlers::handle_on_enter(s.snapshot(), p))?
428             .on_sync::<lsp_types::request::Shutdown>(|s, ()| {
429                 s.shutdown_requested = true;
430                 Ok(())
431             })?
432             .on_sync::<lsp_types::request::SelectionRangeRequest>(|s, p| {
433                 handlers::handle_selection_range(s.snapshot(), p)
434             })?
435             .on_sync::<lsp_ext::MatchingBrace>(|s, p| {
436                 handlers::handle_matching_brace(s.snapshot(), p)
437             })?
438             .on_sync::<lsp_ext::MemoryUsage>(|s, p| handlers::handle_memory_usage(s, p))?
439             .on::<lsp_ext::AnalyzerStatus>(handlers::handle_analyzer_status)
440             .on::<lsp_ext::SyntaxTree>(handlers::handle_syntax_tree)
441             .on::<lsp_ext::ExpandMacro>(handlers::handle_expand_macro)
442             .on::<lsp_ext::ParentModule>(handlers::handle_parent_module)
443             .on::<lsp_ext::Runnables>(handlers::handle_runnables)
444             .on::<lsp_ext::InlayHints>(handlers::handle_inlay_hints)
445             .on::<lsp_ext::CodeActionRequest>(handlers::handle_code_action)
446             .on::<lsp_ext::CodeActionResolveRequest>(handlers::handle_code_action_resolve)
447             .on::<lsp_ext::HoverRequest>(handlers::handle_hover)
448             .on::<lsp_ext::ExternalDocs>(handlers::handle_open_docs)
449             .on::<lsp_ext::OpenCargoToml>(handlers::handle_open_cargo_toml)
450             .on::<lsp_types::request::OnTypeFormatting>(handlers::handle_on_type_formatting)
451             .on::<lsp_types::request::DocumentSymbolRequest>(handlers::handle_document_symbol)
452             .on::<lsp_types::request::WorkspaceSymbol>(handlers::handle_workspace_symbol)
453             .on::<lsp_types::request::GotoDefinition>(handlers::handle_goto_definition)
454             .on::<lsp_types::request::GotoImplementation>(handlers::handle_goto_implementation)
455             .on::<lsp_types::request::GotoTypeDefinition>(handlers::handle_goto_type_definition)
456             .on::<lsp_types::request::Completion>(handlers::handle_completion)
457             .on::<lsp_types::request::ResolveCompletionItem>(handlers::handle_resolve_completion)
458             .on::<lsp_types::request::CodeLensRequest>(handlers::handle_code_lens)
459             .on::<lsp_types::request::CodeLensResolve>(handlers::handle_code_lens_resolve)
460             .on::<lsp_types::request::FoldingRangeRequest>(handlers::handle_folding_range)
461             .on::<lsp_types::request::SignatureHelpRequest>(handlers::handle_signature_help)
462             .on::<lsp_types::request::PrepareRenameRequest>(handlers::handle_prepare_rename)
463             .on::<lsp_types::request::Rename>(handlers::handle_rename)
464             .on::<lsp_types::request::References>(handlers::handle_references)
465             .on::<lsp_types::request::Formatting>(handlers::handle_formatting)
466             .on::<lsp_types::request::DocumentHighlightRequest>(handlers::handle_document_highlight)
467             .on::<lsp_types::request::CallHierarchyPrepare>(handlers::handle_call_hierarchy_prepare)
468             .on::<lsp_types::request::CallHierarchyIncomingCalls>(
469                 handlers::handle_call_hierarchy_incoming,
470             )
471             .on::<lsp_types::request::CallHierarchyOutgoingCalls>(
472                 handlers::handle_call_hierarchy_outgoing,
473             )
474             .on::<lsp_types::request::SemanticTokensFullRequest>(
475                 handlers::handle_semantic_tokens_full,
476             )
477             .on::<lsp_types::request::SemanticTokensFullDeltaRequest>(
478                 handlers::handle_semantic_tokens_full_delta,
479             )
480             .on::<lsp_types::request::SemanticTokensRangeRequest>(
481                 handlers::handle_semantic_tokens_range,
482             )
483             .on::<lsp_ext::Ssr>(handlers::handle_ssr)
484             .finish();
485         Ok(())
486     }
487     fn on_notification(&mut self, not: Notification) -> Result<()> {
488         NotificationDispatcher { not: Some(not), global_state: self }
489             .on::<lsp_types::notification::Cancel>(|this, params| {
490                 let id: lsp_server::RequestId = match params.id {
491                     lsp_types::NumberOrString::Number(id) => id.into(),
492                     lsp_types::NumberOrString::String(id) => id.into(),
493                 };
494                 this.cancel(id);
495                 Ok(())
496             })?
497             .on::<lsp_types::notification::DidOpenTextDocument>(|this, params| {
498                 if let Ok(path) = from_proto::vfs_path(&params.text_document.uri) {
499                     if this
500                         .mem_docs
501                         .insert(path.clone(), DocumentData::new(params.text_document.version))
502                         .is_some()
503                     {
504                         log::error!("duplicate DidOpenTextDocument: {}", path)
505                     }
506                     this.vfs
507                         .write()
508                         .0
509                         .set_file_contents(path, Some(params.text_document.text.into_bytes()));
510                     this.maybe_update_diagnostics();
511                 }
512                 Ok(())
513             })?
514             .on::<lsp_types::notification::DidChangeTextDocument>(|this, params| {
515                 if let Ok(path) = from_proto::vfs_path(&params.text_document.uri) {
516                     let doc = match this.mem_docs.get_mut(&path) {
517                         Some(doc) => doc,
518                         None => {
519                             log::error!("expected DidChangeTextDocument: {}", path);
520                             return Ok(());
521                         }
522                     };
523                     let vfs = &mut this.vfs.write().0;
524                     let file_id = vfs.file_id(&path).unwrap();
525                     let mut text = String::from_utf8(vfs.file_contents(file_id).to_vec()).unwrap();
526                     apply_document_changes(&mut text, params.content_changes);
527
528                     // The version passed in DidChangeTextDocument is the version after all edits are applied
529                     // so we should apply it before the vfs is notified.
530                     doc.version = params.text_document.version;
531
532                     vfs.set_file_contents(path.clone(), Some(text.into_bytes()));
533                 }
534                 Ok(())
535             })?
536             .on::<lsp_types::notification::DidCloseTextDocument>(|this, params| {
537                 let mut version = None;
538                 if let Ok(path) = from_proto::vfs_path(&params.text_document.uri) {
539                     match this.mem_docs.remove(&path) {
540                         Some(doc) => version = Some(doc.version),
541                         None => log::error!("orphan DidCloseTextDocument: {}", path),
542                     }
543
544                     this.semantic_tokens_cache.lock().remove(&params.text_document.uri);
545
546                     if let Some(path) = path.as_path() {
547                         this.loader.handle.invalidate(path.to_path_buf());
548                     }
549                 }
550
551                 // Clear the diagnostics for the previously known version of the file.
552                 // This prevents stale "cargo check" diagnostics if the file is
553                 // closed, "cargo check" is run and then the file is reopened.
554                 this.send_notification::<lsp_types::notification::PublishDiagnostics>(
555                     lsp_types::PublishDiagnosticsParams {
556                         uri: params.text_document.uri,
557                         diagnostics: Vec::new(),
558                         version,
559                     },
560                 );
561                 Ok(())
562             })?
563             .on::<lsp_types::notification::DidSaveTextDocument>(|this, params| {
564                 for flycheck in &this.flycheck {
565                     flycheck.update();
566                 }
567                 if let Ok(abs_path) = from_proto::abs_path(&params.text_document.uri) {
568                     this.maybe_refresh(&[(abs_path, ChangeKind::Modify)]);
569                 }
570                 Ok(())
571             })?
572             .on::<lsp_types::notification::DidChangeConfiguration>(|this, _params| {
573                 // As stated in https://github.com/microsoft/language-server-protocol/issues/676,
574                 // this notification's parameters should be ignored and the actual config queried separately.
575                 this.send_request::<lsp_types::request::WorkspaceConfiguration>(
576                     lsp_types::ConfigurationParams {
577                         items: vec![lsp_types::ConfigurationItem {
578                             scope_uri: None,
579                             section: Some("rust-analyzer".to_string()),
580                         }],
581                     },
582                     |this, resp| {
583                         log::debug!("config update response: '{:?}", resp);
584                         let Response { error, result, .. } = resp;
585
586                         match (error, result) {
587                             (Some(err), _) => {
588                                 log::error!("failed to fetch the server settings: {:?}", err)
589                             }
590                             (None, Some(mut configs)) => {
591                                 if let Some(json) = configs.get_mut(0) {
592                                     // Note that json can be null according to the spec if the client can't
593                                     // provide a configuration. This is handled in Config::update below.
594                                     let mut config = this.config.clone();
595                                     config.update(json.take());
596                                     this.update_configuration(config);
597                                 }
598                             }
599                             (None, None) => log::error!(
600                                 "received empty server settings response from the client"
601                             ),
602                         }
603                     },
604                 );
605
606                 return Ok(());
607             })?
608             .on::<lsp_types::notification::DidChangeWatchedFiles>(|this, params| {
609                 for change in params.changes {
610                     if let Ok(path) = from_proto::abs_path(&change.uri) {
611                         this.loader.handle.invalidate(path);
612                     }
613                 }
614                 Ok(())
615             })?
616             .finish();
617         Ok(())
618     }
619     fn update_file_notifications_on_threadpool(&mut self) {
620         self.maybe_update_diagnostics();
621         self.task_pool.handle.spawn_with_sender({
622             let snap = self.snapshot();
623             move |sender| {
624                 snap.analysis
625                     .prime_caches(|progress| {
626                         sender.send(Task::PrimeCaches(progress)).unwrap();
627                     })
628                     .unwrap_or_else(|_: Canceled| {
629                         // Pretend that we're done, so that the progress bar is removed. Otherwise
630                         // the editor may complain about it already existing.
631                         sender.send(Task::PrimeCaches(PrimeCachesProgress::Finished)).unwrap()
632                     });
633             }
634         });
635     }
636     fn maybe_update_diagnostics(&mut self) {
637         let subscriptions = self
638             .mem_docs
639             .keys()
640             .map(|path| self.vfs.read().0.file_id(&path).unwrap())
641             .collect::<Vec<_>>();
642
643         log::trace!("updating notifications for {:?}", subscriptions);
644         if self.config.publish_diagnostics {
645             let snapshot = self.snapshot();
646             let subscriptions = subscriptions.clone();
647             self.task_pool.handle.spawn(move || {
648                 let diagnostics = subscriptions
649                     .into_iter()
650                     .filter_map(|file_id| {
651                         handlers::publish_diagnostics(&snapshot, file_id)
652                             .map_err(|err| {
653                                 if !is_canceled(&*err) {
654                                     log::error!("failed to compute diagnostics: {:?}", err);
655                                 }
656                                 ()
657                             })
658                             .ok()
659                             .map(|diags| (file_id, diags))
660                     })
661                     .collect::<Vec<_>>();
662                 Task::Diagnostics(diagnostics)
663             })
664         }
665     }
666 }