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