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