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