Skip to main content

rust_analyzer/
main_loop.rs

1//! The main loop of `rust-analyzer` responsible for dispatching LSP
2//! requests/replies and notifications back to the client.
3
4use std::{
5    fmt,
6    ops::Div as _,
7    panic::AssertUnwindSafe,
8    time::{Duration, Instant},
9};
10
11use crossbeam_channel::{Receiver, never, select};
12use ide_db::base_db::{SourceDatabase, VfsPath};
13use lsp_server::{Connection, Notification, Request};
14use lsp_types::{Notification as _, TextDocumentIdentifier};
15use stdx::thread::ThreadIntent;
16use tracing::{Level, error, span};
17use vfs::{AbsPathBuf, FileId, loader::LoadingProgress};
18
19use crate::{
20    config::Config,
21    diagnostics::{DiagnosticsGeneration, NativeDiagnosticsFetchKind, fetch_native_diagnostics},
22    discover::{DiscoverArgument, DiscoverCommand, DiscoverProjectMessage},
23    flycheck::{self, ClearDiagnosticsKind, ClearScope, FlycheckMessage},
24    global_state::{
25        FetchBuildDataResponse, FetchWorkspaceRequest, FetchWorkspaceResponse, GlobalState,
26        file_id_to_url, url_to_file_id,
27    },
28    handlers::{
29        dispatch::{NotificationDispatcher, RequestDispatcher},
30        request::empty_diagnostic_report,
31    },
32    lsp::{
33        from_proto, to_proto,
34        utils::{Progress, notification_is},
35    },
36    lsp_ext,
37    reload::{BuildDataProgress, ProcMacroProgress, ProjectWorkspaceProgress},
38    test_runner::{CargoTestMessage, CargoTestOutput, TestState},
39};
40
41pub fn main_loop(config: Config, connection: Connection) -> anyhow::Result<()> {
42    tracing::info!("initial config: {:#?}", config);
43
44    // Windows scheduler implements priority boosts: if thread waits for an
45    // event (like a condvar), and event fires, priority of the thread is
46    // temporary bumped. This optimization backfires in our case: each time the
47    // `main_loop` schedules a task to run on a threadpool, the worker threads
48    // gets a higher priority, and (on a machine with fewer cores) displaces the
49    // main loop! We work around this by marking the main loop as a
50    // higher-priority thread.
51    //
52    // https://docs.microsoft.com/en-us/windows/win32/procthread/scheduling-priorities
53    // https://docs.microsoft.com/en-us/windows/win32/procthread/priority-boosts
54    // https://github.com/rust-lang/rust-analyzer/issues/2835
55    #[cfg(windows)]
56    unsafe {
57        use windows_sys::Win32::System::Threading::*;
58        let thread = GetCurrentThread();
59        let thread_priority_above_normal = 1;
60        SetThreadPriority(thread, thread_priority_above_normal);
61    }
62
63    #[cfg(feature = "dhat")]
64    {
65        if let Some(dhat_output_file) = config.dhat_output_file() {
66            *crate::DHAT_PROFILER.lock().unwrap() =
67                Some(dhat::Profiler::builder().file_name(&dhat_output_file).build());
68        }
69    }
70
71    GlobalState::new(connection.sender, config).run(connection.receiver)
72}
73
74enum Event {
75    Lsp(lsp_server::Message),
76    Task(Task),
77    DeferredTask(DeferredTask),
78    Vfs(vfs::loader::Message),
79    Flycheck(FlycheckMessage),
80    TestResult(CargoTestMessage),
81    DiscoverProject(DiscoverProjectMessage),
82    FetchWorkspaces(FetchWorkspaceRequest),
83}
84
85impl fmt::Display for Event {
86    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87        match self {
88            Event::Lsp(_) => write!(f, "Event::Lsp"),
89            Event::Task(_) => write!(f, "Event::Task"),
90            Event::Vfs(_) => write!(f, "Event::Vfs"),
91            Event::Flycheck(_) => write!(f, "Event::Flycheck"),
92            Event::DeferredTask(_) => write!(f, "Event::DeferredTask"),
93            Event::TestResult(_) => write!(f, "Event::TestResult"),
94            Event::DiscoverProject(_) => write!(f, "Event::DiscoverProject"),
95            Event::FetchWorkspaces(_) => write!(f, "Event::FetchWorkspaces"),
96        }
97    }
98}
99
100#[derive(Debug)]
101pub(crate) enum DeferredTask {
102    CheckIfIndexed(lsp_types::Uri),
103    CheckProcMacroSources(Vec<FileId>),
104}
105
106#[derive(Debug)]
107pub(crate) enum DiagnosticsTaskKind {
108    Syntax(DiagnosticsGeneration, Vec<(FileId, Vec<lsp_types::Diagnostic>)>),
109    Semantic(DiagnosticsGeneration, Vec<(FileId, Vec<lsp_types::Diagnostic>)>),
110}
111
112#[derive(Debug)]
113pub(crate) enum Task {
114    Response(lsp_server::Response),
115    DiscoverLinkedProjects(DiscoverProjectParam),
116    Retry(lsp_server::Request),
117    Diagnostics(DiagnosticsTaskKind),
118    DiscoverTest(lsp_ext::DiscoverTestResults),
119    PrimeCaches(PrimeCachesProgress),
120    FetchWorkspace(ProjectWorkspaceProgress),
121    FetchBuildData(BuildDataProgress),
122    LoadProcMacros(ProcMacroProgress),
123    // FIXME: Remove this in favor of a more general QueuedTask, see `handle_did_save_text_document`
124    BuildDepsHaveChanged,
125}
126
127#[derive(Debug)]
128pub(crate) enum DiscoverProjectParam {
129    Buildfile(AbsPathBuf),
130    Path(AbsPathBuf),
131}
132
133#[derive(Debug)]
134pub(crate) enum PrimeCachesProgress {
135    Begin,
136    Report(ide::ParallelPrimeCachesProgress),
137    End { cancelled: bool },
138}
139
140impl fmt::Debug for Event {
141    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142        let debug_non_verbose = |not: &Notification, f: &mut fmt::Formatter<'_>| {
143            f.debug_struct("Notification").field("method", &not.method).finish()
144        };
145
146        match self {
147            Event::Lsp(lsp_server::Message::Notification(not))
148                if (notification_is::<lsp_types::DidOpenTextDocumentNotification>(not)
149                    || notification_is::<lsp_types::DidChangeTextDocumentNotification>(not)) =>
150            {
151                return debug_non_verbose(not, f);
152            }
153            Event::Task(Task::Response(resp)) => {
154                return f
155                    .debug_struct("Response")
156                    .field("id", &resp.id)
157                    .field("error", &resp.error)
158                    .finish();
159            }
160            _ => (),
161        }
162
163        match self {
164            Event::Lsp(it) => fmt::Debug::fmt(it, f),
165            Event::Task(it) => fmt::Debug::fmt(it, f),
166            Event::DeferredTask(it) => fmt::Debug::fmt(it, f),
167            Event::Vfs(it) => fmt::Debug::fmt(it, f),
168            Event::Flycheck(it) => fmt::Debug::fmt(it, f),
169            Event::TestResult(it) => fmt::Debug::fmt(it, f),
170            Event::DiscoverProject(it) => fmt::Debug::fmt(it, f),
171            Event::FetchWorkspaces(it) => fmt::Debug::fmt(it, f),
172        }
173    }
174}
175
176impl GlobalState {
177    fn run(mut self, inbox: Receiver<lsp_server::Message>) -> anyhow::Result<()> {
178        self.update_status_or_notify();
179
180        if self.config.did_save_text_document_dynamic_registration() {
181            let additional_patterns = self
182                .config
183                .discover_workspace_config()
184                .map(|cfg| cfg.files_to_watch.clone().into_iter())
185                .into_iter()
186                .flatten()
187                .map(|f| format!("**/{f}"));
188            self.register_did_save_capability(additional_patterns);
189        }
190
191        if self.config.discover_workspace_config().is_none() {
192            self.fetch_workspaces_queue.request_op(
193                "startup".to_owned(),
194                FetchWorkspaceRequest { path: None, force_crate_graph_reload: false },
195            );
196            if let Some((cause, FetchWorkspaceRequest { path, force_crate_graph_reload })) =
197                self.fetch_workspaces_queue.should_start_op()
198            {
199                self.fetch_workspaces(cause, path, force_crate_graph_reload);
200            }
201        }
202
203        while let Ok(event) = self.next_event(&inbox) {
204            let Some(event) = event else {
205                anyhow::bail!("client exited without proper shutdown sequence");
206            };
207            if matches!(
208                &event,
209                Event::Lsp(lsp_server::Message::Notification(Notification { method, .. }))
210                if method == lsp_types::ExitNotification::METHOD.as_str()
211            ) {
212                return Ok(());
213            }
214            self.handle_event(event);
215        }
216
217        Err(anyhow::anyhow!("A receiver has been dropped, something panicked!"))
218    }
219
220    fn register_did_save_capability(&mut self, additional_patterns: impl Iterator<Item = String>) {
221        let additional_filters = additional_patterns.map(|pattern| {
222            lsp_types::DocumentFilter::TextDocumentFilter(lsp_types::TextDocumentFilter::Pattern(
223                lsp_types::TextDocumentFilterPattern {
224                    language: None,
225                    scheme: None,
226                    pattern: pattern.into(),
227                },
228            ))
229        });
230
231        let mut selectors = vec![
232            lsp_types::DocumentFilter::TextDocumentFilter(lsp_types::TextDocumentFilter::Pattern(
233                lsp_types::TextDocumentFilterPattern {
234                    language: None,
235                    scheme: None,
236                    pattern: "**/*.rs".to_owned().into(),
237                },
238            )),
239            lsp_types::DocumentFilter::TextDocumentFilter(lsp_types::TextDocumentFilter::Pattern(
240                lsp_types::TextDocumentFilterPattern {
241                    language: None,
242                    scheme: None,
243                    pattern: "**/Cargo.toml".to_owned().into(),
244                },
245            )),
246            lsp_types::DocumentFilter::TextDocumentFilter(lsp_types::TextDocumentFilter::Pattern(
247                lsp_types::TextDocumentFilterPattern {
248                    language: None,
249                    scheme: None,
250                    pattern: "**/Cargo.lock".to_owned().into(),
251                },
252            )),
253        ];
254        selectors.extend(additional_filters);
255
256        let save_registration_options = lsp_types::TextDocumentSaveRegistrationOptions {
257            save_options: lsp_types::SaveOptions { include_text: Some(false) },
258            text_document_registration_options: lsp_types::TextDocumentRegistrationOptions {
259                document_selector: Some(selectors),
260            },
261        };
262
263        let registration = lsp_types::Registration {
264            id: "textDocument/didSave".to_owned(),
265            method: "textDocument/didSave".to_owned(),
266            register_options: Some(serde_json::to_value(save_registration_options).unwrap()),
267        };
268        self.send_request::<lsp_types::RegistrationRequest>(
269            lsp_types::RegistrationParams { registrations: vec![registration] },
270            |_, _| (),
271        );
272    }
273
274    fn next_event(
275        &mut self,
276        inbox: &Receiver<lsp_server::Message>,
277    ) -> Result<Option<Event>, crossbeam_channel::RecvError> {
278        // Make sure we reply to formatting requests ASAP so the editor doesn't block
279        if let Ok(task) = self.fmt_pool.receiver.try_recv() {
280            return Ok(Some(Event::Task(task)));
281        }
282
283        select! {
284            recv(inbox) -> msg =>
285                return Ok(msg.ok().map(Event::Lsp)),
286
287            recv(self.task_pool.receiver) -> task =>
288                task.map(Event::Task),
289
290            recv(self.deferred_task_queue.receiver) -> task =>
291                task.map(Event::DeferredTask),
292
293            recv(self.fmt_pool.receiver) -> task =>
294                task.map(Event::Task),
295
296            recv(self.loader.receiver) -> task =>
297                task.map(Event::Vfs),
298
299            recv(self.flycheck_receiver) -> task =>
300                task.map(Event::Flycheck),
301
302            recv(self.test_run_receiver) -> task =>
303                task.map(Event::TestResult),
304
305            recv(self.discover_receiver) -> task =>
306                task.map(Event::DiscoverProject),
307
308            recv(self.fetch_ws_receiver.as_ref().map_or(&never(), |(chan, _)| chan)) -> _instant => {
309                Ok(Event::FetchWorkspaces(self.fetch_ws_receiver.take().unwrap().1))
310            },
311        }
312        .map(Some)
313    }
314
315    fn handle_event(&mut self, event: Event) {
316        let loop_start = Instant::now();
317        let _p = tracing::info_span!("GlobalState::handle_event", event = %event).entered();
318
319        let event_dbg_msg = format!("{event:?}");
320        tracing::debug!(?event, "handle_event");
321
322        let was_quiescent = self.is_quiescent();
323
324        let mut cancellation_time = None;
325        match event {
326            Event::Lsp(msg) => match msg {
327                lsp_server::Message::Request(req) => self.on_new_request(loop_start, req),
328                lsp_server::Message::Notification(not) => self.on_notification(not),
329                lsp_server::Message::Response(resp) => self.complete_request(resp),
330            },
331            Event::DeferredTask(task) => {
332                let _p = tracing::info_span!("GlobalState::handle_event/queued_task").entered();
333                self.handle_deferred_task(task);
334                // Coalesce multiple deferred task events into one loop turn
335                while loop_start.elapsed() < Duration::from_millis(50)
336                    && let Ok(task) = self.deferred_task_queue.receiver.try_recv()
337                {
338                    self.handle_deferred_task(task);
339                }
340            }
341            Event::Task(task) => {
342                let _p = tracing::info_span!("GlobalState::handle_event/task").entered();
343                let mut prime_caches_progress = Vec::new();
344
345                cancellation_time = self.handle_task(&mut prime_caches_progress, task);
346                // Coalesce multiple task events into one loop turn
347                while loop_start.elapsed() < Duration::from_millis(50)
348                    && let Ok(task) = self.task_pool.receiver.try_recv()
349                {
350                    self.handle_task(&mut prime_caches_progress, task);
351                }
352
353                let title = "Indexing";
354                let cancel_token = || Some("rustAnalyzer/cachePriming".to_owned());
355
356                let mut last_report = None;
357                for progress in prime_caches_progress {
358                    match progress {
359                        PrimeCachesProgress::Begin => {
360                            self.report_progress(
361                                title,
362                                Progress::Begin,
363                                None,
364                                Some(0.0),
365                                cancel_token(),
366                            );
367                        }
368                        PrimeCachesProgress::Report(report) => {
369                            let message = match &*report.crates_currently_indexing {
370                                [crate_name] => Some(format!(
371                                    "{}/{} ({})",
372                                    report.crates_done,
373                                    report.crates_total,
374                                    crate_name.as_str(),
375                                )),
376                                [crate_name, rest @ ..] => Some(format!(
377                                    "{}/{} ({} + {} more)",
378                                    report.crates_done,
379                                    report.crates_total,
380                                    crate_name.as_str(),
381                                    rest.len()
382                                )),
383                                _ => None,
384                            };
385
386                            // Don't send too many notifications while batching, sending progress reports
387                            // serializes notifications on the mainthread at the moment which slows us down
388                            last_report = Some((
389                                message,
390                                Progress::fraction(report.crates_done, report.crates_total),
391                                report.work_type,
392                            ));
393                        }
394                        PrimeCachesProgress::End { cancelled } => {
395                            self.analysis_host.trigger_garbage_collection();
396                            self.prime_caches_queue.op_completed(());
397                            if cancelled {
398                                self.prime_caches_queue
399                                    .request_op("restart after cancellation".to_owned(), ());
400                            } else {
401                                if self.config.check_on_save(None)
402                                    && self.config.flycheck_workspace(None)
403                                    && !self.fetch_build_data_queue.op_requested()
404                                {
405                                    // Priming finished; now run the deferred initial workspace flycheck
406                                    // (kept off the critical path so `cargo check` doesn't contend with
407                                    // cache priming for CPU).
408                                    self.flycheck
409                                        .iter()
410                                        .for_each(|flycheck| flycheck.restart_workspace(None));
411                                }
412                                tracing::info!("cache priming completed successfully");
413                            }
414                            if let Some((message, fraction, title)) = last_report.take() {
415                                self.report_progress(
416                                    title,
417                                    Progress::Report,
418                                    message,
419                                    Some(fraction),
420                                    cancel_token(),
421                                );
422                            }
423                            self.report_progress(
424                                title,
425                                Progress::End,
426                                None,
427                                Some(1.0),
428                                cancel_token(),
429                            );
430                        }
431                    };
432                }
433                if let Some((message, fraction, title)) = last_report.take() {
434                    self.report_progress(
435                        title,
436                        Progress::Report,
437                        message,
438                        Some(fraction),
439                        cancel_token(),
440                    );
441                }
442            }
443            Event::Vfs(message) => {
444                let _p = tracing::info_span!("GlobalState::handle_event/vfs").entered();
445                let mut last_progress_report = None;
446                self.handle_vfs_msg(message, &mut last_progress_report);
447                // Coalesce many VFS event into a single loop turn
448                while loop_start.elapsed() < Duration::from_millis(50)
449                    && let Ok(message) = self.loader.receiver.try_recv()
450                {
451                    self.handle_vfs_msg(message, &mut last_progress_report);
452                }
453                if let Some((message, fraction)) = last_progress_report {
454                    self.report_progress(
455                        "Roots Scanned",
456                        Progress::Report,
457                        Some(message),
458                        Some(fraction),
459                        None,
460                    );
461                }
462            }
463            Event::Flycheck(message) => {
464                let mut cargo_finished = false;
465                self.handle_flycheck_msg(message, &mut cargo_finished);
466                // Coalesce many flycheck updates into a single loop turn
467                while loop_start.elapsed() < Duration::from_millis(50)
468                    && let Ok(message) = self.flycheck_receiver.try_recv()
469                {
470                    self.handle_flycheck_msg(message, &mut cargo_finished);
471                }
472                if cargo_finished {
473                    self.send_request::<lsp_types::DiagnosticRefreshRequest>((), |_, _| ());
474                }
475            }
476            Event::TestResult(message) => {
477                let _p = tracing::info_span!("GlobalState::handle_event/test_result").entered();
478                self.handle_cargo_test_msg(message);
479                // Coalesce many test result event into a single loop turn
480                while loop_start.elapsed() < Duration::from_millis(50)
481                    && let Ok(message) = self.test_run_receiver.try_recv()
482                {
483                    self.handle_cargo_test_msg(message);
484                }
485            }
486            Event::DiscoverProject(message) => {
487                self.handle_discover_msg(message);
488                // Coalesce many project discovery events into a single loop turn.
489                while loop_start.elapsed() < Duration::from_millis(50)
490                    && let Ok(message) = self.discover_receiver.try_recv()
491                {
492                    self.handle_discover_msg(message);
493                }
494            }
495            Event::FetchWorkspaces(req) => {
496                self.fetch_workspaces_queue.request_op("project structure change".to_owned(), req)
497            }
498        }
499        let event_handling_duration = loop_start.elapsed();
500        let ((state_changed, changes_cancellation_time), memdocs_added_or_removed) =
501            if self.vfs_done {
502                if let Some(cause) = self.wants_to_switch.take() {
503                    cancellation_time = match (cancellation_time, self.switch_workspaces(cause)) {
504                        (Some(a), Some(b)) => Some(a + b),
505                        (Some(d), None) | (None, Some(d)) => Some(d),
506                        (None, None) => None,
507                    };
508                }
509                (self.process_changes(), self.mem_docs.take_changes())
510            } else {
511                ((false, None), false)
512            };
513        cancellation_time = match (cancellation_time, changes_cancellation_time) {
514            (Some(a), Some(b)) => Some(a + b),
515            (Some(d), None) | (None, Some(d)) => Some(d),
516            (None, None) => None,
517        };
518
519        let mut gc_elapsed = None;
520        if self.is_quiescent() {
521            let became_quiescent = !was_quiescent;
522            if became_quiescent {
523                // delay initial cache priming until proc macros are loaded, or we will load up a bunch of garbage into salsa
524                let proc_macros_loaded = self.config.prefill_caches()
525                    && (!self.config.expand_proc_macros()
526                        || self.fetch_proc_macros_queue.last_op_result().copied().unwrap_or(false));
527                if proc_macros_loaded {
528                    self.prime_caches_queue.request_op("became quiescent".to_owned(), ());
529                }
530                if self.config.check_on_save(None)
531                    && self.config.flycheck_workspace(None)
532                    && !self.fetch_build_data_queue.op_requested()
533                {
534                    if !self.config.prefill_caches() {
535                        self.flycheck.iter().for_each(|flycheck| flycheck.restart_workspace(None));
536                    } else if proc_macros_loaded
537                        && !self.prime_caches_queue.op_in_progress()
538                        && !self.prime_caches_queue.op_requested()
539                    {
540                        self.flycheck.iter().for_each(|flycheck| flycheck.restart_workspace(None));
541                    }
542                }
543            }
544
545            let client_refresh = became_quiescent || state_changed;
546            if client_refresh {
547                // Refresh semantic tokens if the client supports it.
548                if self.config.semantic_tokens_refresh() {
549                    self.send_request::<lsp_types::SemanticTokensRefreshRequest>((), |_, _| ());
550                }
551
552                // Refresh code lens if the client supports it.
553                if self.config.code_lens_refresh() {
554                    self.send_request::<lsp_types::CodeLensRefreshRequest>((), |_, _| ());
555                }
556
557                // Refresh inlay hints if the client supports it.
558                if self.config.inlay_hints_refresh() {
559                    self.send_request::<lsp_types::InlayHintRefreshRequest>((), |_, _| ());
560                }
561
562                if self.config.diagnostics_refresh() {
563                    self.send_request::<lsp_types::DiagnosticRefreshRequest>((), |_, _| ());
564                }
565            }
566
567            let project_or_mem_docs_changed =
568                became_quiescent || state_changed || memdocs_added_or_removed;
569            if project_or_mem_docs_changed
570                && !self.config.text_document_diagnostic()
571                && self.config.publish_diagnostics(None)
572            {
573                self.update_diagnostics();
574            }
575            if project_or_mem_docs_changed && self.config.test_explorer() {
576                self.update_tests();
577            }
578
579            let current_revision = self.analysis_host.raw_database().nonce_and_revision().1;
580            // no work is currently being done, now we can block a bit and clean up our garbage
581            if self.task_pool.handle.is_empty()
582                && self.fmt_pool.handle.is_empty()
583                && current_revision != self.last_gc_revision
584            {
585                let gc_start = Instant::now();
586                self.analysis_host.trigger_garbage_collection();
587                self.last_gc_revision = self.analysis_host.raw_database().nonce_and_revision().1;
588                gc_elapsed = Some(gc_start.elapsed());
589            }
590        }
591
592        self.cleanup_discover_handles();
593
594        if let Some(diagnostic_changes) = self.diagnostics.take_changes() {
595            for file_id in diagnostic_changes {
596                let uri = file_id_to_url(&self.vfs.read().0, file_id);
597                let version = from_proto::vfs_path(&uri)
598                    .ok()
599                    .and_then(|path| self.mem_docs.get(&path).map(|it| it.version));
600
601                let diagnostics =
602                    self.diagnostics.diagnostics_for(file_id).cloned().collect::<Vec<_>>();
603                self.publish_diagnostics(uri, version, diagnostics);
604            }
605        }
606
607        if (self.config.cargo_autoreload_config(None)
608            || self.config.discover_workspace_config().is_some())
609            && let Some((cause, FetchWorkspaceRequest { path, force_crate_graph_reload })) =
610                self.fetch_workspaces_queue.should_start_op()
611        {
612            self.fetch_workspaces(cause, path, force_crate_graph_reload);
613        }
614
615        if !self.fetch_workspaces_queue.op_in_progress() {
616            if let Some((cause, ())) = self.fetch_build_data_queue.should_start_op() {
617                self.fetch_build_data(cause);
618            } else if let Some((cause, (change, paths))) =
619                self.fetch_proc_macros_queue.should_start_op()
620            {
621                self.fetch_proc_macros(cause, change, paths);
622            }
623        }
624
625        if let Some((cause, ())) = self.prime_caches_queue.should_start_op() {
626            self.prime_caches(cause);
627        }
628
629        self.update_status_or_notify();
630
631        let loop_duration = loop_start.elapsed();
632        if loop_duration > Duration::from_millis(100) && was_quiescent {
633            tracing::warn!(
634                "overly long loop turn took {loop_duration:?}: \
635                (event handling took {event_handling_duration:?}): {event_dbg_msg} \
636                (cancellation took {cancellation_time:?}) \
637                (garbage collection took {gc_elapsed:?})"
638            );
639            self.poke_rust_analyzer_developer(format!(
640                "overly long loop turn took {loop_duration:?}: \
641                (event handling took {event_handling_duration:?}): {event_dbg_msg} \
642                (cancellation took {cancellation_time:?}) \
643                (garbage collection took {gc_elapsed:?})"
644            ));
645        }
646    }
647
648    fn prime_caches(&mut self, cause: String) {
649        let scope = self.compute_priming_scope();
650        tracing::debug!(%cause, scope_size = scope.len(), "will prime caches");
651        let num_worker_threads = self.config.prime_caches_num_threads();
652
653        self.task_pool.handle.spawn_with_sender(ThreadIntent::Worker, {
654            let analysis = AssertUnwindSafe(self.snapshot().analysis);
655            move |sender| {
656                sender.send(Task::PrimeCaches(PrimeCachesProgress::Begin)).unwrap();
657                let res = analysis.parallel_prime_caches(&scope, num_worker_threads, |progress| {
658                    let report = PrimeCachesProgress::Report(progress);
659                    sender.send(Task::PrimeCaches(report)).unwrap();
660                });
661                sender
662                    .send(Task::PrimeCaches(PrimeCachesProgress::End { cancelled: res.is_err() }))
663                    .unwrap();
664            }
665        });
666    }
667
668    fn update_diagnostics(&mut self) {
669        let db = self.analysis_host.raw_database();
670        let generation = self.diagnostics.next_generation();
671        let subscriptions = {
672            let vfs = &self.vfs.read().0;
673            self.mem_docs
674                .iter()
675                .map(|path| vfs.file_id(path).unwrap())
676                .filter_map(|(file_id, excluded)| {
677                    (excluded == vfs::FileExcluded::No).then_some(file_id)
678                })
679                .filter(|&file_id| {
680                    let source_root_id = db.file_source_root(file_id).source_root_id(db);
681                    let source_root = db.source_root(source_root_id).source_root(db);
682                    // Only publish diagnostics for files in the workspace, not from crates.io deps
683                    // or the sysroot.
684                    // While theoretically these should never have errors, we have quite a few false
685                    // positives particularly in the stdlib, and those diagnostics would stay around
686                    // forever if we emitted them here.
687                    !source_root.is_library
688                })
689                .collect::<std::sync::Arc<_>>()
690        };
691        tracing::trace!("updating notifications for {:?}", subscriptions);
692        // Split up the work on multiple threads, but we don't wanna fill the entire task pool with
693        // diagnostic tasks, so we limit the number of tasks to a quarter of the total thread pool.
694        let max_tasks = self.config.main_loop_num_threads().div(4).max(1);
695        let chunk_length = subscriptions.len() / max_tasks;
696        let remainder = subscriptions.len() % max_tasks;
697
698        let mut start = 0;
699        for task_idx in 0..max_tasks {
700            let extra = if task_idx < remainder { 1 } else { 0 };
701            let end = start + chunk_length + extra;
702            let slice = start..end;
703            if slice.is_empty() {
704                break;
705            }
706            // Diagnostics are triggered by the user typing
707            // so we run them on a latency sensitive thread.
708            let snapshot = self.snapshot();
709            self.task_pool.handle.spawn_with_sender(ThreadIntent::LatencySensitive, {
710                let subscriptions = subscriptions.clone();
711                // Do not fetch semantic diagnostics (and populate query results) if we haven't even
712                // loaded the initial workspace yet.
713                //
714                // Only fetch semantic diagnostics when
715                // - we have fully populated the VFS
716                // - have a workspace
717                // - have finished fetching the build data once
718                // - and have finished loading the proc-macros once
719                let fetch_semantic = self.vfs_done
720                    && self.fetch_workspaces_queue.last_op_result().is_some()
721                    && (!self.config.run_build_scripts(None)
722                        || (self.fetch_build_data_queue.last_op_result().is_some()
723                            && !self.fetch_build_data_queue.op_in_progress()))
724                    && (!self.config.expand_proc_macros()
725                        || (self.fetch_proc_macros_queue.last_op_result().is_some()
726                            && !self.fetch_proc_macros_queue.op_in_progress()));
727                move |sender| {
728                    // We aren't observing the semantics token cache here
729                    let snapshot = AssertUnwindSafe(&snapshot);
730                    let diags = std::panic::catch_unwind(|| {
731                        fetch_native_diagnostics(
732                            &snapshot,
733                            subscriptions.clone(),
734                            slice.clone(),
735                            NativeDiagnosticsFetchKind::Syntax,
736                        )
737                    })
738                    .unwrap_or_else(|_| {
739                        subscriptions.iter().map(|&id| (id, Vec::new())).collect::<Vec<_>>()
740                    });
741                    sender
742                        .send(Task::Diagnostics(DiagnosticsTaskKind::Syntax(generation, diags)))
743                        .unwrap();
744
745                    if fetch_semantic {
746                        let diags = std::panic::catch_unwind(|| {
747                            fetch_native_diagnostics(
748                                &snapshot,
749                                subscriptions.clone(),
750                                slice.clone(),
751                                NativeDiagnosticsFetchKind::Semantic,
752                            )
753                        })
754                        .unwrap_or_else(|_| {
755                            subscriptions.iter().map(|&id| (id, Vec::new())).collect::<Vec<_>>()
756                        });
757                        sender
758                            .send(Task::Diagnostics(DiagnosticsTaskKind::Semantic(
759                                generation, diags,
760                            )))
761                            .unwrap();
762                    }
763                }
764            });
765            start = end;
766        }
767    }
768
769    fn update_tests(&mut self) {
770        if !self.vfs_done {
771            return;
772        }
773        let db = self.analysis_host.raw_database();
774        let subscriptions = self
775            .mem_docs
776            .iter()
777            .map(|path| self.vfs.read().0.file_id(path).unwrap())
778            .filter_map(|(file_id, excluded)| {
779                (excluded == vfs::FileExcluded::No).then_some(file_id)
780            })
781            .filter(|&file_id| {
782                let source_root_id = db.file_source_root(file_id).source_root_id(db);
783                let source_root = db.source_root(source_root_id).source_root(db);
784                !source_root.is_library
785            })
786            .collect::<Vec<_>>();
787        tracing::trace!("updating tests for {:?}", subscriptions);
788
789        // Updating tests are triggered by the user typing
790        // so we run them on a latency sensitive thread.
791        self.task_pool.handle.spawn(ThreadIntent::LatencySensitive, {
792            let snapshot = self.snapshot();
793            move || {
794                let tests = subscriptions
795                    .iter()
796                    .copied()
797                    .filter_map(|f| snapshot.analysis.discover_tests_in_file(f).ok())
798                    .flatten()
799                    .collect::<Vec<_>>();
800
801                Task::DiscoverTest(lsp_ext::DiscoverTestResults {
802                    tests: tests
803                        .into_iter()
804                        .filter_map(|t| {
805                            let line_index = t.file.and_then(|f| snapshot.file_line_index(f).ok());
806                            to_proto::test_item(&snapshot, t, line_index.as_ref())
807                        })
808                        .collect(),
809                    scope: None,
810                    scope_file: Some(
811                        subscriptions
812                            .into_iter()
813                            .map(|f| TextDocumentIdentifier { uri: to_proto::url(&snapshot, f) })
814                            .collect(),
815                    ),
816                })
817            }
818        });
819    }
820
821    fn update_status_or_notify(&mut self) {
822        let status = self.current_status();
823        if self.last_reported_status != status {
824            let old_status = std::mem::replace(&mut self.last_reported_status, status.clone());
825
826            if self.config.server_status_notification() {
827                self.send_notification::<lsp_ext::ServerStatusNotification>(status);
828            } else if let (
829                health @ (lsp_ext::Health::Warning | lsp_ext::Health::Error),
830                Some(message),
831            ) = (status.health, &status.message)
832                && old_status.message != status.message
833            {
834                let open_log_button = tracing::enabled!(tracing::Level::ERROR)
835                    && (self.fetch_build_data_error().is_err()
836                        || self.fetch_workspace_error().is_err());
837                self.show_message(
838                    match health {
839                        lsp_ext::Health::Ok => lsp_types::MessageType::Info,
840                        lsp_ext::Health::Warning => lsp_types::MessageType::Warning,
841                        lsp_ext::Health::Error => lsp_types::MessageType::Error,
842                    },
843                    message.clone(),
844                    open_log_button,
845                );
846            }
847        }
848    }
849
850    fn handle_task(
851        &mut self,
852        prime_caches_progress: &mut Vec<PrimeCachesProgress>,
853        task: Task,
854    ) -> Option<Duration> {
855        let mut cancellation_time = None;
856        match task {
857            Task::Response(response) => self.respond(response),
858            // Only retry requests that haven't been cancelled. Otherwise we do unnecessary work.
859            Task::Retry(req) if !self.is_completed(&req) => self.on_request(req),
860            Task::Retry(_) => (),
861            Task::Diagnostics(kind) => {
862                self.diagnostics.set_native_diagnostics(kind);
863            }
864            Task::PrimeCaches(progress) => match progress {
865                PrimeCachesProgress::Begin => prime_caches_progress.push(progress),
866                PrimeCachesProgress::Report(_) => {
867                    match prime_caches_progress.last_mut() {
868                        Some(last @ PrimeCachesProgress::Report(_)) => {
869                            // Coalesce subsequent update events.
870                            *last = progress;
871                        }
872                        _ => prime_caches_progress.push(progress),
873                    }
874                }
875                PrimeCachesProgress::End { .. } => prime_caches_progress.push(progress),
876            },
877            Task::FetchWorkspace(progress) => {
878                let (state, msg) = match progress {
879                    ProjectWorkspaceProgress::Begin => (Progress::Begin, None),
880                    ProjectWorkspaceProgress::Report(msg) => (Progress::Report, Some(msg)),
881                    ProjectWorkspaceProgress::End(workspaces, force_crate_graph_reload) => {
882                        let resp = FetchWorkspaceResponse { workspaces, force_crate_graph_reload };
883                        self.fetch_workspaces_queue.op_completed(resp);
884                        if let Err(e) = self.fetch_workspace_error() {
885                            error!("FetchWorkspaceError: {e}");
886                        }
887                        self.wants_to_switch = Some("fetched workspace".to_owned());
888                        self.diagnostics.clear_check_all();
889                        (Progress::End, None)
890                    }
891                };
892
893                self.report_progress("Fetching", state, msg, None, None);
894            }
895            Task::DiscoverLinkedProjects(arg) => {
896                if let Some(cfg) = self.config.discover_workspace_config() {
897                    let command = cfg.command.clone();
898                    let discover = DiscoverCommand::new(self.discover_sender.clone(), command);
899
900                    let discover_path = match &arg {
901                        DiscoverProjectParam::Buildfile(it) => it,
902                        DiscoverProjectParam::Path(it) => it,
903                    };
904                    let current_dir =
905                        self.config.workspace_root_for(discover_path.as_path()).clone();
906
907                    let arg = match arg {
908                        DiscoverProjectParam::Buildfile(it) => DiscoverArgument::Buildfile(it),
909                        DiscoverProjectParam::Path(it) => DiscoverArgument::Path(it),
910                    };
911
912                    match discover.spawn(arg, current_dir.as_ref()) {
913                        Ok(handle) => {
914                            if self.discover_jobs_active == 0 {
915                                let title = &cfg.progress_label.clone();
916                                self.report_progress(title, Progress::Begin, None, None, None);
917                            }
918                            self.discover_jobs_active += 1;
919                            self.discover_handles.push(handle)
920                        }
921                        Err(e) => self.show_message(
922                            lsp_types::MessageType::Error,
923                            format!(
924                                "Failed to spawn project discovery command in {}: {e:#}",
925                                current_dir,
926                            ),
927                            false,
928                        ),
929                    }
930                }
931            }
932            Task::FetchBuildData(progress) => {
933                let (state, msg) = match progress {
934                    BuildDataProgress::Begin => (Some(Progress::Begin), None),
935                    BuildDataProgress::Report(msg) => (Some(Progress::Report), Some(msg)),
936                    BuildDataProgress::End((workspaces, build_scripts)) => {
937                        let resp = FetchBuildDataResponse { workspaces, build_scripts };
938                        self.fetch_build_data_queue.op_completed(resp);
939
940                        if let Err(e) = self.fetch_build_data_error() {
941                            error!("FetchBuildDataError: {e}");
942                        }
943
944                        if self.wants_to_switch.is_none() {
945                            self.wants_to_switch = Some("fetched build data".to_owned());
946                        }
947                        (Some(Progress::End), None)
948                    }
949                };
950
951                if let Some(state) = state {
952                    self.report_progress("Building compile-time-deps", state, msg, None, None);
953                }
954            }
955            Task::LoadProcMacros(progress) => {
956                let (state, msg) = match progress {
957                    ProcMacroProgress::Begin => (Some(Progress::Begin), None),
958                    ProcMacroProgress::Report(msg) => (Some(Progress::Report), Some(msg)),
959                    ProcMacroProgress::End(change) => {
960                        self.fetch_proc_macros_queue.op_completed(true);
961                        cancellation_time = Some(self.analysis_host.apply_change(change));
962                        // FIXME This feels a bit off, this should go through similar machinery as build scripts?
963                        _ = self.finish_loading_crate_graph();
964                        (Some(Progress::End), None)
965                    }
966                };
967
968                if let Some(state) = state {
969                    self.report_progress("Loading proc-macros", state, msg, None, None);
970                }
971            }
972            Task::BuildDepsHaveChanged => self.build_deps_changed = true,
973            Task::DiscoverTest(tests) => {
974                self.send_notification::<lsp_ext::DiscoveredTestsNotification>(tests);
975            }
976        }
977        cancellation_time
978    }
979
980    fn handle_vfs_msg(
981        &mut self,
982        message: vfs::loader::Message,
983        last_progress_report: &mut Option<(String, f64)>,
984    ) {
985        let _p = tracing::info_span!("GlobalState::handle_vfs_msg").entered();
986        let is_changed = matches!(message, vfs::loader::Message::Changed { .. });
987        match message {
988            vfs::loader::Message::Changed { files } | vfs::loader::Message::Loaded { files } => {
989                let _p = tracing::info_span!("GlobalState::handle_vfs_msg{changed/load}").entered();
990                self.debounce_workspace_fetch();
991                let vfs = &mut self.vfs.write().0;
992                for (path, contents) in files {
993                    if matches!(path.name_and_extension(), Some(("minicore", Some("rs")))) {
994                        // Not a lot of bad can happen from mistakenly identifying `minicore`, so proceed with that.
995                        self.minicore.minicore_text = contents
996                            .as_ref()
997                            .and_then(|contents| str::from_utf8(contents).ok())
998                            .map(triomphe::Arc::from);
999                    }
1000
1001                    let path = VfsPath::from(path);
1002                    // If the file is in mem docs, it's managed by the client via
1003                    // notifications so only set it if it's not in there. Library files are
1004                    // exempt from that authority as they are considered immutable, for
1005                    // them disk is always the source of truth.
1006                    let is_library = self.source_root_config.path_is_library(&path);
1007                    let client_is_authoritative = !is_library && self.mem_docs.contains(&path);
1008                    if !client_is_authoritative
1009                        && (is_changed || is_library || vfs.file_id(&path).is_none())
1010                    {
1011                        vfs.set_file_contents(path, contents);
1012                    }
1013                }
1014            }
1015            vfs::loader::Message::Progress { n_total, n_done, dir, config_version } => {
1016                let _p = span!(Level::INFO, "GlobalState::handle_vfs_msg/progress").entered();
1017                stdx::always!(config_version <= self.vfs_config_version);
1018
1019                let (n_done, state) = match n_done {
1020                    LoadingProgress::Started => {
1021                        self.vfs_span =
1022                            Some(span!(Level::INFO, "vfs_load", total = n_total).entered());
1023                        (0, Progress::Begin)
1024                    }
1025                    LoadingProgress::Progress(n_done) => (n_done.min(n_total), Progress::Report),
1026                    LoadingProgress::Finished => {
1027                        self.vfs_span = None;
1028                        (n_total, Progress::End)
1029                    }
1030                };
1031
1032                self.vfs_progress_config_version = config_version;
1033                self.vfs_done = state == Progress::End;
1034
1035                let mut message = format!("{n_done}/{n_total}");
1036                if let Some(dir) = dir {
1037                    let common_std = "lib/rustlib/src/rust";
1038                    message += &format!(
1039                        ": {}",
1040                        match dir.strip_prefix(self.config.workspace_root_for(&dir)) {
1041                            Some(relative_path) => relative_path.as_utf8_path(),
1042                            None => match dir.short_relative_by(common_std) {
1043                                Some(short) => short.as_ref(),
1044                                None => dir.as_ref(),
1045                            },
1046                        }
1047                    );
1048                }
1049
1050                match state {
1051                    Progress::Begin => self.report_progress(
1052                        "Roots Scanned",
1053                        state,
1054                        Some(message),
1055                        Some(Progress::fraction(n_done, n_total)),
1056                        None,
1057                    ),
1058                    // Don't send too many notifications while batching, sending progress reports
1059                    // serializes notifications on the mainthread at the moment which slows us down
1060                    Progress::Report => {
1061                        if last_progress_report.is_none() {
1062                            self.report_progress(
1063                                "Roots Scanned",
1064                                state,
1065                                Some(message.clone()),
1066                                Some(Progress::fraction(n_done, n_total)),
1067                                None,
1068                            );
1069                        }
1070
1071                        *last_progress_report =
1072                            Some((message, Progress::fraction(n_done, n_total)));
1073                    }
1074                    Progress::End => {
1075                        last_progress_report.take();
1076                        self.report_progress(
1077                            "Roots Scanned",
1078                            state,
1079                            Some(message),
1080                            Some(Progress::fraction(n_done, n_total)),
1081                            None,
1082                        )
1083                    }
1084                }
1085            }
1086        }
1087    }
1088
1089    fn handle_deferred_task(&mut self, task: DeferredTask) {
1090        match task {
1091            DeferredTask::CheckIfIndexed(uri) => {
1092                let snap = self.snapshot();
1093
1094                self.task_pool.handle.spawn_with_sender(ThreadIntent::Worker, move |sender| {
1095                    let _p = tracing::info_span!("GlobalState::check_if_indexed").entered();
1096                    tracing::debug!(?uri, "handling uri");
1097                    let Some(id) = from_proto::file_id(&snap, &uri).expect("unable to get FileId")
1098                    else {
1099                        return;
1100                    };
1101                    if let Ok(crates) = &snap.analysis.crates_for(id) {
1102                        if crates.is_empty() {
1103                            if snap.config.discover_workspace_config().is_some() {
1104                                let path =
1105                                    from_proto::abs_path(&uri).expect("Unable to get AbsPath");
1106                                let arg = DiscoverProjectParam::Path(path);
1107                                sender.send(Task::DiscoverLinkedProjects(arg)).unwrap();
1108                            }
1109                        } else {
1110                            tracing::debug!(?uri, "is indexed");
1111                        }
1112                    }
1113                });
1114            }
1115            DeferredTask::CheckProcMacroSources(modified_rust_files) => {
1116                let analysis = AssertUnwindSafe(self.snapshot().analysis);
1117                self.task_pool.handle.spawn_with_sender(stdx::thread::ThreadIntent::Worker, {
1118                    move |sender| {
1119                        if modified_rust_files.into_iter().any(|file_id| {
1120                            // FIXME: Check whether these files could be build script related
1121                            match analysis.crates_for(file_id) {
1122                                Ok(crates) => crates.iter().any(|&krate| {
1123                                    analysis.is_proc_macro_crate(krate).is_ok_and(|it| it)
1124                                }),
1125                                _ => false,
1126                            }
1127                        }) {
1128                            sender.send(Task::BuildDepsHaveChanged).unwrap();
1129                        }
1130                    }
1131                });
1132            }
1133        }
1134    }
1135
1136    fn handle_discover_msg(&mut self, message: DiscoverProjectMessage) {
1137        let title = self
1138            .config
1139            .discover_workspace_config()
1140            .map(|cfg| cfg.progress_label.clone())
1141            .expect("No title could be found; this is a bug");
1142        match message {
1143            DiscoverProjectMessage::Finished { project, buildfile } => {
1144                self.discover_jobs_active = self.discover_jobs_active.saturating_sub(1);
1145                if self.discover_jobs_active == 0 {
1146                    self.report_progress(&title, Progress::End, None, None, None);
1147                }
1148
1149                let mut config = Config::clone(&*self.config);
1150                config.add_discovered_project_from_command(project, buildfile);
1151                self.update_configuration(config);
1152            }
1153            DiscoverProjectMessage::Progress { message } => {
1154                if self.discover_jobs_active > 0 {
1155                    self.report_progress(&title, Progress::Report, Some(message), None, None)
1156                }
1157            }
1158            DiscoverProjectMessage::Error { error, source } => {
1159                let message = format!("Project discovery failed: {error}");
1160                self.show_and_log_error(message.clone(), source);
1161
1162                self.discover_jobs_active = self.discover_jobs_active.saturating_sub(1);
1163                if self.discover_jobs_active == 0 {
1164                    self.report_progress(&title, Progress::End, Some(message), None, None)
1165                }
1166            }
1167        }
1168    }
1169
1170    /// Drop any discover command processes that have exited, due to
1171    /// finishing or erroring.
1172    fn cleanup_discover_handles(&mut self) {
1173        let mut active_handles = vec![];
1174
1175        for mut discover_handle in self.discover_handles.drain(..) {
1176            if !discover_handle.handle.has_exited() {
1177                active_handles.push(discover_handle);
1178            }
1179        }
1180        self.discover_handles = active_handles;
1181    }
1182
1183    fn handle_cargo_test_msg(&mut self, message: CargoTestMessage) {
1184        match message.output {
1185            CargoTestOutput::Test { name, state } => {
1186                let state = match state {
1187                    TestState::Started => lsp_ext::TestState::Started,
1188                    TestState::Ignored => lsp_ext::TestState::Skipped,
1189                    TestState::Ok => lsp_ext::TestState::Passed,
1190                    TestState::Failed { stdout } => lsp_ext::TestState::Failed { message: stdout },
1191                };
1192
1193                // The notification requires the namespace form (with underscores) of the target
1194                let test_id = format!("{}::{name}", message.target.target.replace('-', "_"));
1195
1196                self.send_notification::<lsp_ext::ChangeTestStateNotification>(
1197                    lsp_ext::ChangeTestStateParams { test_id, state },
1198                );
1199            }
1200            CargoTestOutput::Suite => (),
1201            CargoTestOutput::Finished => {
1202                self.test_run_remaining_jobs = self.test_run_remaining_jobs.saturating_sub(1);
1203                if self.test_run_remaining_jobs == 0 {
1204                    self.send_notification::<lsp_ext::EndRunTestNotification>(());
1205                    self.test_run_session = None;
1206                }
1207            }
1208            CargoTestOutput::Custom { text } => {
1209                self.send_notification::<lsp_ext::AppendOutputToRunTestNotification>(text);
1210            }
1211        }
1212    }
1213
1214    fn handle_flycheck_msg(&mut self, message: FlycheckMessage, cargo_finished: &mut bool) {
1215        match message {
1216            FlycheckMessage::AddDiagnostic {
1217                id,
1218                generation,
1219                workspace_root,
1220                diagnostic,
1221                package_id,
1222            } => {
1223                let snap = self.snapshot();
1224                let diagnostics = crate::diagnostics::flycheck_to_proto::map_rust_diagnostic_to_lsp(
1225                    &self.config.diagnostics_map(None),
1226                    diagnostic,
1227                    &workspace_root,
1228                    &snap,
1229                );
1230                for diag in diagnostics {
1231                    match url_to_file_id(&self.vfs.read().0, &diag.url) {
1232                        Ok(Some(file_id)) => self.diagnostics.add_check_diagnostic(
1233                            id,
1234                            generation,
1235                            &package_id,
1236                            file_id,
1237                            diag.diagnostic,
1238                            diag.fix,
1239                        ),
1240                        Ok(None) => {}
1241                        Err(err) => {
1242                            error!(
1243                                "flycheck {id}: File with cargo diagnostic not found in VFS: {}",
1244                                err
1245                            );
1246                        }
1247                    };
1248                }
1249            }
1250            FlycheckMessage::ClearDiagnostics {
1251                id,
1252                kind: ClearDiagnosticsKind::All(ClearScope::Workspace),
1253            } => self.diagnostics.clear_check(id),
1254            FlycheckMessage::ClearDiagnostics {
1255                id,
1256                kind: ClearDiagnosticsKind::All(ClearScope::Package(package_id)),
1257            } => self.diagnostics.clear_check_for_package(id, package_id),
1258            FlycheckMessage::ClearDiagnostics {
1259                id,
1260                kind: ClearDiagnosticsKind::OlderThan(generation, ClearScope::Workspace),
1261            } => self.diagnostics.clear_check_older_than(id, generation),
1262            FlycheckMessage::ClearDiagnostics {
1263                id,
1264                kind: ClearDiagnosticsKind::OlderThan(generation, ClearScope::Package(package_id)),
1265            } => self.diagnostics.clear_check_older_than_for_package(id, package_id, generation),
1266            FlycheckMessage::Progress { id, progress } => {
1267                let format_with_id = |user_facing_command: String| {
1268                    // When we're running multiple flychecks, we have to include a disambiguator in
1269                    // the title, or the editor complains. Note that this is a user-facing string.
1270                    if self.flycheck.len() == 1 {
1271                        user_facing_command
1272                    } else {
1273                        format!("{user_facing_command} (#{})", id + 1)
1274                    }
1275                };
1276
1277                self.flycheck_formatted_commands
1278                    .resize_with(self.flycheck.len().max(id + 1), || {
1279                        format_with_id(self.config.flycheck(None).to_string())
1280                    });
1281
1282                let (state, message) = match progress {
1283                    flycheck::Progress::DidStart { user_facing_command } => {
1284                        self.flycheck_formatted_commands[id] = format_with_id(user_facing_command);
1285                        (Progress::Begin, None)
1286                    }
1287                    flycheck::Progress::DidCheckCrate(target) => (Progress::Report, Some(target)),
1288                    flycheck::Progress::DidCancel => {
1289                        self.last_flycheck_error = None;
1290                        *cargo_finished = true;
1291                        (Progress::End, None)
1292                    }
1293                    flycheck::Progress::DidFailToRestart(err) => {
1294                        self.last_flycheck_error =
1295                            Some(format!("cargo check failed to start: {err}"));
1296                        return;
1297                    }
1298                    flycheck::Progress::DidFinish(result) => {
1299                        self.last_flycheck_error =
1300                            result.err().map(|err| format!("cargo check failed to start: {err}"));
1301                        *cargo_finished = true;
1302                        (Progress::End, None)
1303                    }
1304                };
1305
1306                // Clone because we &mut self for report_progress
1307                let title = self.flycheck_formatted_commands[id].clone();
1308                self.report_progress(
1309                    &title,
1310                    state,
1311                    message,
1312                    None,
1313                    Some(format!("rust-analyzer/flycheck/{id}")),
1314                );
1315            }
1316        }
1317    }
1318
1319    /// Registers and handles a request. This should only be called once per incoming request.
1320    fn on_new_request(&mut self, request_received: Instant, req: Request) {
1321        let _p =
1322            span!(Level::INFO, "GlobalState::on_new_request", req.method = ?req.method).entered();
1323        self.register_request(&req, request_received);
1324        self.on_request(req);
1325    }
1326
1327    /// Handles a request.
1328    fn on_request(&mut self, req: Request) {
1329        let mut dispatcher = RequestDispatcher { req: Some(req), global_state: self };
1330        dispatcher.on_sync_mut::<lsp_types::ShutdownRequest>(|s, ()| {
1331            s.shutdown_requested = true;
1332            s.proc_macro_clients =
1333                std::iter::repeat_with(|| None).take(s.proc_macro_clients.len()).collect();
1334            s.flycheck.iter().for_each(|handle| handle.cancel());
1335            s.discover_handles.clear();
1336            Ok(())
1337        });
1338
1339        match &mut dispatcher {
1340            RequestDispatcher { req: Some(req), global_state: this } if this.shutdown_requested => {
1341                this.respond(lsp_server::Response::new_err(
1342                    req.id.clone(),
1343                    lsp_server::ErrorCode::InvalidRequest as i32,
1344                    "Shutdown already requested.".to_owned(),
1345                ));
1346                return;
1347            }
1348            _ => (),
1349        }
1350
1351        use crate::handlers::request as handlers;
1352
1353        const RETRY: bool = true;
1354        const NO_RETRY: bool = false;
1355
1356        #[rustfmt::skip]
1357        dispatcher
1358            // Request handlers that must run on the main thread
1359            // because they mutate GlobalState:
1360            .on_sync_mut::<lsp_ext::ReloadWorkspaceRequest>(handlers::handle_workspace_reload)
1361            .on_sync_mut::<lsp_ext::RebuildProcMacrosRequest>(handlers::handle_proc_macros_rebuild)
1362            .on_sync_mut::<lsp_ext::MemoryUsageRequest>(handlers::handle_memory_usage)
1363            .on_sync_mut::<lsp_ext::RunTestRequest>(handlers::handle_run_test)
1364            // Request handlers which are related to the user typing
1365            // are run on the main thread to reduce latency:
1366            .on_sync::<lsp_ext::JoinLinesRequest>(handlers::handle_join_lines)
1367            .on_sync::<lsp_ext::OnEnterRequest>(handlers::handle_on_enter)
1368            .on_sync::<lsp_types::SelectionRangeRequest>(handlers::handle_selection_range)
1369            .on_sync::<lsp_ext::MatchingBraceRequest>(handlers::handle_matching_brace)
1370            .on_sync::<lsp_ext::DocumentOnTypeFormattingRequest>(handlers::handle_on_type_formatting)
1371            // Formatting should be done immediately as the editor might wait on it, but we can't
1372            // put it on the main thread as we do not want the main thread to block on rustfmt.
1373            // So we have an extra thread just for formatting requests to make sure it gets handled
1374            // as fast as possible.
1375            .on_fmt_thread::<lsp_types::DocumentFormattingRequest>(handlers::handle_formatting)
1376            .on_fmt_thread::<lsp_types::DocumentRangeFormattingRequest>(handlers::handle_range_formatting)
1377            // We can’t run latency-sensitive request handlers which do semantic
1378            // analysis on the main thread because that would block other
1379            // requests. Instead, we run these request handlers on higher priority
1380            // threads in the threadpool.
1381            // FIXME: Retrying can make the result of this stale?
1382            .on_latency_sensitive::<RETRY, lsp_types::CompletionRequest>(handlers::handle_completion)
1383            // FIXME: Retrying can make the result of this stale
1384            .on_latency_sensitive::<RETRY, lsp_types::CompletionResolveRequest>(handlers::handle_completion_resolve)
1385            .on_latency_sensitive::<RETRY, lsp_types::SemanticTokensRequest>(handlers::handle_semantic_tokens_full)
1386            .on_latency_sensitive::<RETRY, lsp_types::SemanticTokensDeltaRequest>(handlers::handle_semantic_tokens_full_delta)
1387            .on_latency_sensitive::<NO_RETRY, lsp_types::SemanticTokensRangeRequest>(handlers::handle_semantic_tokens_range)
1388            // FIXME: Some of these NO_RETRY could be retries if the file they are interested didn't change.
1389            // All other request handlers
1390            .on_with_vfs_default::<lsp_types::DocumentDiagnosticRequest>(handlers::handle_document_diagnostics, empty_diagnostic_report, || lsp_server::ResponseError {
1391                code: lsp_server::ErrorCode::ServerCancelled as i32,
1392                message: "server cancelled the request".to_owned(),
1393                data: serde_json::to_value(lsp_types::DiagnosticServerCancellationData {
1394                    retrigger_request: true
1395                }).ok(),
1396            })
1397            .on::<RETRY, lsp_types::DocumentSymbolRequest>(handlers::handle_document_symbol)
1398            .on::<RETRY, lsp_types::FoldingRangeRequest>(handlers::handle_folding_range)
1399            .on::<NO_RETRY, lsp_types::SignatureHelpRequest>(handlers::handle_signature_help)
1400            .on::<RETRY, lsp_types::WillRenameFilesRequest>(handlers::handle_will_rename_files)
1401            .on::<NO_RETRY, lsp_types::DefinitionRequest>(handlers::handle_goto_definition)
1402            .on::<NO_RETRY, lsp_types::DeclarationRequest>(handlers::handle_goto_declaration)
1403            .on::<NO_RETRY, lsp_types::ImplementationRequest>(handlers::handle_goto_implementation)
1404            .on::<NO_RETRY, lsp_types::TypeDefinitionRequest>(handlers::handle_goto_type_definition)
1405            .on::<NO_RETRY, lsp_types::InlayHintRequest>(handlers::handle_inlay_hints)
1406            .on_identity::<NO_RETRY, lsp_types::InlayHintResolveRequest, _>(handlers::handle_inlay_hints_resolve)
1407            .on::<NO_RETRY, lsp_types::CodeLensRequest>(handlers::handle_code_lens)
1408            .on_identity::<NO_RETRY, lsp_types::CodeLensResolveRequest, _>(handlers::handle_code_lens_resolve)
1409            .on::<NO_RETRY, lsp_types::PrepareRenameRequest>(handlers::handle_prepare_rename)
1410            .on::<NO_RETRY, lsp_types::RenameRequest>(handlers::handle_rename)
1411            .on::<NO_RETRY, lsp_types::ReferencesRequest>(handlers::handle_references)
1412            .on::<NO_RETRY, lsp_types::DocumentHighlightRequest>(handlers::handle_document_highlight)
1413            .on::<NO_RETRY, lsp_types::CallHierarchyPrepareRequest>(handlers::handle_call_hierarchy_prepare)
1414            .on::<NO_RETRY, lsp_types::CallHierarchyIncomingCallsRequest>(handlers::handle_call_hierarchy_incoming)
1415            .on::<NO_RETRY, lsp_types::CallHierarchyOutgoingCallsRequest>(handlers::handle_call_hierarchy_outgoing)
1416            // All other request handlers (lsp extension)
1417            .on::<RETRY, lsp_ext::FetchDependencyListRequest>(handlers::fetch_dependency_list)
1418            .on::<RETRY, lsp_ext::AnalyzerStatusRequest>(handlers::handle_analyzer_status)
1419            .on::<RETRY, lsp_ext::ViewFileTextRequest>(handlers::handle_view_file_text)
1420            .on::<RETRY, lsp_ext::ViewCrateGraphRequest>(handlers::handle_view_crate_graph)
1421            .on::<RETRY, lsp_ext::ViewItemTreeRequest>(handlers::handle_view_item_tree)
1422            .on::<RETRY, lsp_ext::DiscoverTestRequest>(handlers::handle_discover_test)
1423            .on::<RETRY, lsp_ext::WorkspaceSymbolRequest>(handlers::handle_workspace_symbol)
1424            .on::<NO_RETRY, lsp_ext::SsrRequest>(handlers::handle_ssr)
1425            .on::<NO_RETRY, lsp_ext::ViewRecursiveMemoryLayoutRequest>(handlers::handle_view_recursive_memory_layout)
1426            .on::<NO_RETRY, lsp_ext::ViewSyntaxTreeRequest>(handlers::handle_view_syntax_tree)
1427            .on::<NO_RETRY, lsp_ext::ViewHirRequest>(handlers::handle_view_hir)
1428            .on::<NO_RETRY, lsp_ext::ViewMirRequest>(handlers::handle_view_mir)
1429            .on::<NO_RETRY, lsp_ext::InterpretFunctionRequest>(handlers::handle_interpret_function)
1430            .on::<NO_RETRY, lsp_ext::ExpandMacroRequest>(handlers::handle_expand_macro)
1431            .on::<NO_RETRY, lsp_ext::ParentModuleRequest>(handlers::handle_parent_module)
1432            .on::<NO_RETRY, lsp_ext::ChildModulesRequest>(handlers::handle_child_modules)
1433            .on::<NO_RETRY, lsp_ext::RunnablesRequest>(handlers::handle_runnables)
1434            .on::<NO_RETRY, lsp_ext::RelatedTestsRequest>(handlers::handle_related_tests)
1435            .on::<NO_RETRY, lsp_ext::CodeActionRequest>(handlers::handle_code_action)
1436            .on_identity::<RETRY, lsp_ext::CodeActionResolveRequest, _>(handlers::handle_code_action_resolve)
1437            .on::<NO_RETRY, lsp_ext::HoverRequest>(handlers::handle_hover)
1438            .on::<NO_RETRY, lsp_ext::ExternalDocsRequest>(handlers::handle_open_docs)
1439            .on::<NO_RETRY, lsp_ext::OpenCargoTomlRequest>(handlers::handle_open_cargo_toml)
1440            .on::<NO_RETRY, lsp_ext::MoveItemRequest>(handlers::handle_move_item)
1441            //
1442            .on::<NO_RETRY, lsp_ext::InternalTestingFetchConfigRequest>(handlers::internal_testing_fetch_config)
1443            .on::<RETRY, lsp_ext::EvaluatePredicateRequest>(handlers::handle_evaluate_predicate)
1444            .on::<RETRY, lsp_ext::GetFailedObligationsRequest>(handlers::get_failed_obligations)
1445            .finish();
1446    }
1447
1448    /// Handles an incoming notification.
1449    fn on_notification(&mut self, not: Notification) {
1450        let _p =
1451            span!(Level::INFO, "GlobalState::on_notification", not.method = ?not.method).entered();
1452        use crate::handlers::notification as handlers;
1453
1454        NotificationDispatcher { not: Some(not), global_state: self }
1455            .on_sync_mut::<lsp_types::CancelNotification>(handlers::handle_cancel)
1456            .on_sync_mut::<lsp_types::WorkDoneProgressCancelNotification>(
1457                handlers::handle_work_done_progress_cancel,
1458            )
1459            .on_sync_mut::<lsp_types::DidOpenTextDocumentNotification>(
1460                handlers::handle_did_open_text_document,
1461            )
1462            .on_sync_mut::<lsp_types::DidChangeTextDocumentNotification>(
1463                handlers::handle_did_change_text_document,
1464            )
1465            .on_sync_mut::<lsp_types::DidCloseTextDocumentNotification>(
1466                handlers::handle_did_close_text_document,
1467            )
1468            .on_sync_mut::<lsp_types::DidSaveTextDocumentNotification>(
1469                handlers::handle_did_save_text_document,
1470            )
1471            .on_sync_mut::<lsp_types::DidChangeConfigurationNotification>(
1472                handlers::handle_did_change_configuration,
1473            )
1474            .on_sync_mut::<lsp_types::DidChangeWorkspaceFoldersNotification>(
1475                handlers::handle_did_change_workspace_folders,
1476            )
1477            .on_sync_mut::<lsp_types::DidChangeWatchedFilesNotification>(
1478                handlers::handle_did_change_watched_files,
1479            )
1480            .on_sync_mut::<lsp_ext::CancelFlycheckNotification>(handlers::handle_cancel_flycheck)
1481            .on_sync_mut::<lsp_ext::ClearFlycheckNotification>(handlers::handle_clear_flycheck)
1482            .on_sync_mut::<lsp_ext::RunFlycheckNotification>(handlers::handle_run_flycheck)
1483            .on_sync_mut::<lsp_ext::AbortRunTestNotification>(handlers::handle_abort_run_test)
1484            .finish();
1485    }
1486}