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