Skip to main content

rust_analyzer/
reload.rs

1//! Project loading & configuration updates.
2//!
3//! This is quite tricky. The main problem is time and changes -- there's no
4//! fixed "project" rust-analyzer is working with, "current project" is itself
5//! mutable state. For example, when the user edits `Cargo.toml` by adding a new
6//! dependency, project model changes. What's more, switching project model is
7//! not instantaneous -- it takes time to run `cargo metadata` and (for proc
8//! macros) `cargo check`.
9//!
10//! The main guiding principle here is, as elsewhere in rust-analyzer,
11//! robustness. We try not to assume that the project model exists or is
12//! correct. Instead, we try to provide a best-effort service. Even if the
13//! project is currently loading and we don't have a full project model, we
14//! still want to respond to various  requests.
15// FIXME: This is a mess that needs some untangling work
16use std::{iter, mem, sync::atomic::AtomicUsize, time::Duration};
17
18use hir::{ChangeWithProcMacros, ProcMacrosBuilder};
19use ide_db::{
20    FxHashMap,
21    base_db::{CrateGraphBuilder, ProcMacroLoadingError, ProcMacroPaths},
22};
23use itertools::Itertools;
24use load_cargo::{ProjectFolders, load_proc_macro};
25use lsp_types::FileSystemWatcher;
26use paths::Utf8Path;
27use proc_macro_api::client::ProcMacroClient;
28use project_model::{
29    ManifestPath, ProjectWorkspace, ProjectWorkspaceKind, WorkspaceBuildScripts, project_json,
30};
31use stdx::{format_to, thread::ThreadIntent};
32use triomphe::Arc;
33use vfs::{AbsPath, AbsPathBuf, ChangeKind};
34
35use crate::{
36    config::{Config, FilesWatcher, LinkedProject},
37    flycheck::{FlycheckConfig, FlycheckHandle},
38    global_state::{
39        FetchBuildDataResponse, FetchWorkspaceRequest, FetchWorkspaceResponse, GlobalState,
40    },
41    lsp_ext,
42    main_loop::{DiscoverProjectParam, Task},
43    op_queue::Cause,
44};
45use tracing::{debug, info};
46
47#[derive(Debug)]
48pub(crate) enum ProjectWorkspaceProgress {
49    Begin,
50    Report(String),
51    End(Vec<anyhow::Result<ProjectWorkspace>>, bool),
52}
53
54#[derive(Debug)]
55pub(crate) enum BuildDataProgress {
56    Begin,
57    Report(String),
58    End((Arc<Vec<ProjectWorkspace>>, Vec<anyhow::Result<WorkspaceBuildScripts>>)),
59}
60
61#[derive(Debug)]
62pub(crate) enum ProcMacroProgress {
63    Begin,
64    Report(String),
65    End(ChangeWithProcMacros),
66}
67
68impl GlobalState {
69    /// Is the server quiescent?
70    ///
71    /// This indicates that we've fully loaded the projects and
72    /// are ready to do semantic work.
73    pub(crate) fn is_quiescent(&self) -> bool {
74        self.vfs_done
75            && self.fetch_ws_receiver.is_none()
76            && !self.fetch_workspaces_queue.op_in_progress()
77            && !self.fetch_build_data_queue.op_in_progress()
78            && !self.fetch_proc_macros_queue.op_in_progress()
79            && self.discover_jobs_active == 0
80            && self.vfs_progress_config_version >= self.vfs_config_version
81    }
82
83    /// Is the server ready to respond to analysis dependent LSP requests?
84    ///
85    /// Unlike `is_quiescent`, this returns false when we're indexing
86    /// the project, because we're holding the salsa lock and cannot
87    /// respond to LSP requests that depend on salsa data.
88    fn is_fully_ready(&self) -> bool {
89        self.is_quiescent() && !self.prime_caches_queue.op_in_progress()
90    }
91
92    pub(crate) fn update_configuration(&mut self, config: Config) {
93        let _p = tracing::info_span!("GlobalState::update_configuration").entered();
94        let old_config = mem::replace(&mut self.config, Arc::new(config));
95        if self.config.lru_parse_query_capacity() != old_config.lru_parse_query_capacity() {
96            self.analysis_host.update_lru_capacity(self.config.lru_parse_query_capacity());
97        }
98        if self.config.lru_query_capacities_config() != old_config.lru_query_capacities_config() {
99            self.analysis_host.update_lru_capacities(
100                &self.config.lru_query_capacities_config().cloned().unwrap_or_default(),
101            );
102        }
103
104        if self.config.linked_or_discovered_projects() != old_config.linked_or_discovered_projects()
105        {
106            let req = FetchWorkspaceRequest { path: None, force_crate_graph_reload: false };
107            self.fetch_workspaces_queue.request_op("discovered projects changed".to_owned(), req)
108        } else if self.config.flycheck(None) != old_config.flycheck(None) {
109            self.reload_flycheck();
110        }
111
112        hir::db::set_expand_proc_attr_macros(
113            self.analysis_host.raw_database_mut(),
114            self.config.expand_proc_attr_macros(),
115        );
116
117        if self.config.cargo(None) != old_config.cargo(None) {
118            let req = FetchWorkspaceRequest { path: None, force_crate_graph_reload: false };
119            self.fetch_workspaces_queue.request_op("cargo config changed".to_owned(), req)
120        }
121
122        if self.config.cfg_set_test(None) != old_config.cfg_set_test(None) {
123            let req = FetchWorkspaceRequest { path: None, force_crate_graph_reload: false };
124            self.fetch_workspaces_queue.request_op("cfg_set_test config changed".to_owned(), req)
125        }
126    }
127
128    pub(crate) fn current_status(&self) -> lsp_ext::ServerStatusParams {
129        let mut status = lsp_ext::ServerStatusParams {
130            health: lsp_ext::Health::Ok,
131            quiescent: self.is_fully_ready(),
132            message: None,
133        };
134        let mut message = String::new();
135
136        if !self.config.cargo_autoreload_config(None)
137            && self.is_quiescent()
138            && self.fetch_workspaces_queue.op_requested()
139            && self.config.discover_workspace_config().is_none()
140        {
141            status.health |= lsp_ext::Health::Warning;
142            message.push_str("Auto-reloading is disabled and the workspace has changed, a manual workspace reload is required.\n\n");
143        }
144
145        if self.build_deps_changed {
146            status.health |= lsp_ext::Health::Warning;
147            message.push_str(
148                "Proc-macros and/or build scripts have changed and need to be rebuilt.\n\n",
149            );
150        }
151        if self.fetch_build_data_error().is_err() {
152            status.health |= lsp_ext::Health::Warning;
153            message.push_str("Failed to run build scripts of some packages.\n\n");
154            message.push_str(
155                "Please refer to the language server logs for more details on the errors.",
156            );
157        }
158        if let Some(err) = &self.config_errors {
159            status.health |= lsp_ext::Health::Warning;
160            format_to!(message, "{err}\n");
161        }
162        if let Some(err) = &self.last_flycheck_error {
163            status.health |= lsp_ext::Health::Warning;
164            message.push_str(err);
165            message.push('\n');
166        }
167
168        if self.config.linked_or_discovered_projects().is_empty()
169            && self.config.detached_files().is_empty()
170        {
171            status.health |= lsp_ext::Health::Warning;
172            message.push_str("Failed to discover workspace.\n");
173            message.push_str("Consider adding the `Cargo.toml` of the workspace to the [`linkedProjects`](https://rust-analyzer.github.io/book/configuration.html#linkedProjects) setting.\n\n");
174        }
175        if self.fetch_workspace_error().is_err() {
176            status.health |= lsp_ext::Health::Error;
177            message.push_str("Failed to load workspaces.");
178
179            if self.config.has_linked_projects() {
180                message.push_str(
181                    "`rust-analyzer.linkedProjects` have been specified, which may be incorrect. Specified project paths:\n",
182                );
183                message
184                    .push_str(&format!("    {}", self.config.linked_manifests().format("\n    ")));
185                if self.config.has_linked_project_jsons() {
186                    message.push_str("\nAdditionally, one or more project jsons are specified")
187                }
188            }
189            message.push_str("\n\n");
190        }
191
192        if !self.workspaces.is_empty() {
193            self.check_workspaces_msrv().for_each(|e| {
194                status.health |= lsp_ext::Health::Warning;
195                format_to!(message, "{e}");
196            });
197
198            let proc_macro_clients = self.proc_macro_clients.iter().chain(iter::repeat(&None));
199
200            for (ws, proc_macro_client) in self.workspaces.iter().zip(proc_macro_clients) {
201                if let ProjectWorkspaceKind::Cargo { error: Some(error), .. }
202                | ProjectWorkspaceKind::DetachedFile {
203                    cargo: Some((_, _, Some(error))), ..
204                } = &ws.kind
205                {
206                    status.health |= lsp_ext::Health::Warning;
207                    format_to!(
208                        message,
209                        "Failed to read Cargo metadata with dependencies for `{}`: {:#}\n\n",
210                        ws.manifest_or_root(),
211                        error
212                    );
213                }
214                if let Some(err) = ws.sysroot.error() {
215                    status.health |= lsp_ext::Health::Warning;
216                    format_to!(
217                        message,
218                        "Workspace `{}` has sysroot errors: ",
219                        ws.manifest_or_root()
220                    );
221                    message.push_str(err);
222                    message.push_str("\n\n");
223                }
224                if let Some(err) = ws.sysroot.metadata_error() {
225                    status.health |= lsp_ext::Health::Warning;
226                    format_to!(
227                        message,
228                        "Failed to read Cargo metadata with dependencies for sysroot of `{}`: ",
229                        ws.manifest_or_root()
230                    );
231                    message.push_str(err);
232                    message.push_str("\n\n");
233                }
234                if let ProjectWorkspaceKind::Cargo { rustc: Err(Some(err)), .. } = &ws.kind {
235                    status.health |= lsp_ext::Health::Warning;
236                    format_to!(
237                        message,
238                        "Failed loading rustc_private crates for workspace `{}`: ",
239                        ws.manifest_or_root()
240                    );
241                    message.push_str(err);
242                    message.push_str("\n\n");
243                };
244                match proc_macro_client {
245                    Some(Err(err)) => {
246                        status.health |= lsp_ext::Health::Warning;
247                        format_to!(
248                            message,
249                            "Failed spawning proc-macro server for workspace `{}`: {err}",
250                            ws.manifest_or_root()
251                        );
252                        message.push_str("\n\n");
253                    }
254                    Some(Ok(client)) => {
255                        if let Some(err) = client.exited() {
256                            status.health |= lsp_ext::Health::Warning;
257                            format_to!(
258                                message,
259                                "proc-macro server for workspace `{}` exited: {err}",
260                                ws.manifest_or_root()
261                            );
262                            message.push_str("\n\n");
263                        }
264                    }
265                    // sysroot was explicitly not set so we didn't discover a server
266                    None => {}
267                }
268            }
269        }
270
271        if !message.is_empty() {
272            status.message = Some(message.trim_end().to_owned());
273        }
274
275        status
276    }
277
278    pub(crate) fn fetch_workspaces(
279        &mut self,
280        cause: Cause,
281        path: Option<AbsPathBuf>,
282        force_crate_graph_reload: bool,
283    ) {
284        info!(%cause, "will fetch workspaces");
285
286        self.task_pool.handle.spawn_with_sender(ThreadIntent::Worker, {
287            let linked_projects = self.config.linked_or_discovered_projects();
288            let detached_files: Vec<_> = self
289                .config
290                .detached_files()
291                .iter()
292                .cloned()
293                .map(ManifestPath::try_from)
294                .filter_map(Result::ok)
295                .collect();
296            let cargo_config = self.config.cargo(None);
297            let discover_command = self.config.discover_workspace_config().cloned();
298            let is_quiescent = !(self.discover_jobs_active > 0
299                || self.vfs_progress_config_version < self.vfs_config_version
300                || !self.vfs_done);
301
302            move |sender| {
303                let progress = {
304                    let sender = sender.clone();
305                    move |msg| {
306                        sender
307                            .send(Task::FetchWorkspace(ProjectWorkspaceProgress::Report(msg)))
308                            .unwrap()
309                    }
310                };
311
312                sender.send(Task::FetchWorkspace(ProjectWorkspaceProgress::Begin)).unwrap();
313
314                if let (Some(_command), Some(path)) = (&discover_command, &path) {
315                    let build = linked_projects.iter().find_map(|project| match project {
316                        LinkedProject::InlineProjectJson(it) => it.crate_by_buildfile(path),
317                        _ => None,
318                    });
319
320                    if let Some(build) = build
321                        && is_quiescent
322                    {
323                        let path = AbsPathBuf::try_from(build.build_file)
324                            .expect("Unable to convert to an AbsPath");
325                        let arg = DiscoverProjectParam::Buildfile(path);
326                        sender.send(Task::DiscoverLinkedProjects(arg)).unwrap();
327                    }
328                }
329
330                let mut workspaces: Vec<_> = linked_projects
331                    .iter()
332                    .map(|project| match project {
333                        LinkedProject::ProjectManifest(manifest) => {
334                            debug!(path = %manifest, "loading project from manifest");
335
336                            project_model::ProjectWorkspace::load(
337                                manifest.clone(),
338                                &cargo_config,
339                                &progress,
340                            )
341                        }
342                        LinkedProject::InlineProjectJson(it) => {
343                            let workspace = project_model::ProjectWorkspace::load_inline(
344                                it.clone(),
345                                &cargo_config,
346                                &progress,
347                            );
348                            Ok(workspace)
349                        }
350                    })
351                    .collect();
352
353                let mut i = 0;
354                while i < workspaces.len() {
355                    if let Ok(w) = &workspaces[i] {
356                        let dupes: Vec<_> = workspaces[i + 1..]
357                            .iter()
358                            .positions(|it| it.as_ref().is_ok_and(|ws| ws.eq_ignore_build_data(w)))
359                            .collect();
360                        dupes.into_iter().rev().for_each(|d| {
361                            _ = workspaces.remove(d + i + 1);
362                        });
363                    }
364                    i += 1;
365                }
366
367                if !detached_files.is_empty() {
368                    workspaces.extend(project_model::ProjectWorkspace::load_detached_files(
369                        detached_files,
370                        &cargo_config,
371                    ));
372                }
373
374                info!(?workspaces, "did fetch workspaces");
375                sender
376                    .send(Task::FetchWorkspace(ProjectWorkspaceProgress::End(
377                        workspaces,
378                        force_crate_graph_reload,
379                    )))
380                    .unwrap();
381            }
382        });
383    }
384
385    pub(crate) fn fetch_build_data(&mut self, cause: Cause) {
386        info!(%cause, "will fetch build data");
387        let workspaces = Arc::clone(&self.workspaces);
388        let config = self.config.cargo(None);
389        let root_path = self.config.default_root_path().clone();
390
391        self.task_pool.handle.spawn_with_sender(ThreadIntent::Worker, move |sender| {
392            sender.send(Task::FetchBuildData(BuildDataProgress::Begin)).unwrap();
393
394            let progress = {
395                let sender = sender.clone();
396                move |msg| {
397                    sender.send(Task::FetchBuildData(BuildDataProgress::Report(msg))).unwrap()
398                }
399            };
400            let res = ProjectWorkspace::run_all_build_scripts(
401                &workspaces,
402                &config,
403                &progress,
404                &root_path,
405            );
406
407            sender.send(Task::FetchBuildData(BuildDataProgress::End((workspaces, res)))).unwrap();
408        });
409    }
410
411    pub(crate) fn fetch_proc_macros(
412        &mut self,
413        cause: Cause,
414        mut change: ChangeWithProcMacros,
415        paths: Vec<ProcMacroPaths>,
416    ) {
417        info!(%cause, "will load proc macros");
418        let ignored_proc_macros = self.config.ignored_proc_macros(None).clone();
419        let proc_macro_clients = self.proc_macro_clients.clone();
420
421        self.task_pool.handle.spawn_with_sender(ThreadIntent::Worker, move |sender| {
422            sender.send(Task::LoadProcMacros(ProcMacroProgress::Begin)).unwrap();
423
424            let ignored_proc_macros = &ignored_proc_macros;
425            let progress = {
426                let sender = sender.clone();
427                &move |msg| {
428                    sender.send(Task::LoadProcMacros(ProcMacroProgress::Report(msg))).unwrap()
429                }
430            };
431
432            let mut builder = ProcMacrosBuilder::default();
433            let proc_macro_clients = proc_macro_clients.iter().chain(iter::repeat(&None));
434            for (client, paths) in proc_macro_clients.zip(paths) {
435                for (crate_id, res) in paths.iter() {
436                    let expansion_res = match client {
437                        Some(Ok(client)) => match res {
438                            Ok((crate_name, path)) => {
439                                progress(path.to_string());
440                                let ignored_proc_macros = ignored_proc_macros
441                                    .iter()
442                                    .find_map(|(name, macros)| {
443                                        eq_ignore_underscore(name, crate_name).then_some(&**macros)
444                                    })
445                                    .unwrap_or_default();
446
447                                load_proc_macro(client, path, ignored_proc_macros)
448                            }
449                            Err(e) => Err(e.clone()),
450                        },
451                        Some(Err(e)) => Err(ProcMacroLoadingError::ProcMacroSrvError(
452                            e.to_string().into_boxed_str(),
453                        )),
454                        None => Err(ProcMacroLoadingError::ProcMacroSrvError(
455                            "proc-macro-srv is not running".into(),
456                        )),
457                    };
458                    builder.insert(*crate_id, expansion_res)
459                }
460            }
461
462            change.set_proc_macros(builder);
463            sender.send(Task::LoadProcMacros(ProcMacroProgress::End(change))).unwrap();
464        });
465    }
466
467    pub(crate) fn switch_workspaces(&mut self, cause: Cause) -> Option<Duration> {
468        let _p = tracing::info_span!("GlobalState::switch_workspaces").entered();
469        tracing::info!(%cause, "will switch workspaces");
470
471        let FetchWorkspaceResponse { workspaces, force_crate_graph_reload } =
472            self.fetch_workspaces_queue.last_op_result()?;
473        let switching_from_empty_workspace = self.workspaces.is_empty();
474
475        info!(%cause, ?force_crate_graph_reload, %switching_from_empty_workspace);
476        if self.fetch_workspace_error().is_err() && !switching_from_empty_workspace {
477            if *force_crate_graph_reload {
478                return self.recreate_crate_graph(cause, false);
479            }
480            // It only makes sense to switch to a partially broken workspace
481            // if we don't have any workspace at all yet.
482            return None;
483        }
484
485        let workspaces =
486            workspaces.iter().filter_map(|res| res.as_ref().ok().cloned()).collect::<Vec<_>>();
487
488        let same_workspaces = workspaces.len() == self.workspaces.len()
489            && workspaces
490                .iter()
491                .zip(self.workspaces.iter())
492                .all(|(l, r)| l.eq_ignore_build_data(r));
493
494        if same_workspaces {
495            if switching_from_empty_workspace {
496                // Switching from empty to empty is a no-op
497                return None;
498            }
499            if let Some(FetchBuildDataResponse { workspaces, build_scripts }) =
500                self.fetch_build_data_queue.last_op_result()
501            {
502                if Arc::ptr_eq(workspaces, &self.workspaces) {
503                    info!("set build scripts to workspaces");
504
505                    let workspaces = workspaces
506                        .iter()
507                        .cloned()
508                        .zip(build_scripts)
509                        .map(|(mut ws, bs)| {
510                            ws.set_build_scripts(bs.as_ref().ok().cloned().unwrap_or_default());
511                            ws
512                        })
513                        .collect::<Vec<_>>();
514                    // Workspaces are the same, but we've updated build data.
515                    info!("same workspace, but new build data");
516                    self.workspaces = Arc::new(workspaces);
517                } else {
518                    info!("build scripts do not match the version of the active workspace");
519                    if *force_crate_graph_reload {
520                        return self.recreate_crate_graph(cause, switching_from_empty_workspace);
521                    }
522
523                    // Current build scripts do not match the version of the active
524                    // workspace, so there's nothing for us to update.
525                    return None;
526                }
527            } else {
528                if *force_crate_graph_reload {
529                    return self.recreate_crate_graph(cause, switching_from_empty_workspace);
530                }
531
532                // No build scripts but unchanged workspaces, nothing to do here
533                return None;
534            }
535        } else {
536            info!("abandon build scripts for workspaces");
537
538            // Here, we completely changed the workspace (Cargo.toml edit), so
539            // we don't care about build-script results, they are stale.
540            // FIXME: can we abort the build scripts here if they are already running?
541            self.workspaces = Arc::new(workspaces);
542            self.check_workspaces_msrv().for_each(|message| {
543                self.send_notification::<lsp_types::ShowMessageNotification>(
544                    lsp_types::ShowMessageParams { kind: lsp_types::MessageType::Warning, message },
545                );
546            });
547
548            if self.config.run_build_scripts(None) {
549                self.build_deps_changed = false;
550                self.fetch_build_data_queue.request_op("workspace updated".to_owned(), ());
551
552                if !switching_from_empty_workspace {
553                    // `switch_workspaces()` will be called again when build scripts already run, which should
554                    // take a short time. If we update the workspace now we will invalidate proc macros and cfgs,
555                    // and then when build scripts complete we will invalidate them again.
556                    return None;
557                }
558            }
559        }
560
561        if let FilesWatcher::Client = self.config.files().watcher {
562            let filter = self
563                .workspaces
564                .iter()
565                .flat_map(|ws| ws.to_roots())
566                .filter(|it| it.is_local)
567                .map(|it| it.include);
568
569            let mut watchers: Vec<FileSystemWatcher> =
570                if self.config.did_change_watched_files_relative_pattern_support() {
571                    // When relative patterns are supported by the client, prefer using them
572                    filter
573                        .flat_map(|include| {
574                            include.into_iter().flat_map(|base| {
575                                [
576                                    (base.clone(), "**/*.rs"),
577                                    (base.clone(), "**/Cargo.{lock,toml}"),
578                                    (base.clone(), "**/rust-analyzer.toml"),
579                                    (base, "**/*.md"),
580                                ]
581                            })
582                        })
583                        .map(|(base, pat)| lsp_types::FileSystemWatcher {
584                            glob_pattern: lsp_types::GlobPattern::RelativePattern(
585                                lsp_types::RelativePattern {
586                                    base_uri: lsp_types::BaseUri::Uri(
587                                        lsp_types::Uri::from_file_path(base).unwrap(),
588                                    ),
589                                    pattern: pat.to_owned(),
590                                },
591                            ),
592                            kind: None,
593                        })
594                        .collect()
595                } else {
596                    // When they're not, integrate the base to make them into absolute patterns
597                    filter
598                        .flat_map(|include| {
599                            include.into_iter().flat_map(|base| {
600                                [
601                                    format!("{base}/**/*.rs"),
602                                    format!("{base}/**/Cargo.{{toml,lock}}"),
603                                    format!("{base}/**/rust-analyzer.toml"),
604                                    format!("{base}/**/*.md"),
605                                ]
606                            })
607                        })
608                        .map(|glob_pattern| lsp_types::FileSystemWatcher {
609                            glob_pattern: lsp_types::GlobPattern::Pattern(glob_pattern),
610                            kind: None,
611                        })
612                        .collect()
613                };
614
615            // Also explicitly watch any build files configured in JSON project files.
616            for ws in self.workspaces.iter() {
617                if let ProjectWorkspaceKind::Json(project_json) = &ws.kind {
618                    for (_, krate) in project_json.crates() {
619                        let Some(build) = &krate.build else {
620                            continue;
621                        };
622                        watchers.push(lsp_types::FileSystemWatcher {
623                            glob_pattern: lsp_types::GlobPattern::Pattern(
624                                build.build_file.to_string(),
625                            ),
626                            kind: None,
627                        });
628                    }
629                }
630            }
631
632            watchers.extend(
633                iter::once(Config::user_config_dir_path().as_deref())
634                    .chain(self.workspaces.iter().map(|ws| ws.manifest().map(ManifestPath::as_ref)))
635                    .flatten()
636                    .map(|glob_pattern| lsp_types::FileSystemWatcher {
637                        glob_pattern: lsp_types::GlobPattern::Pattern(glob_pattern.to_string()),
638                        kind: None,
639                    }),
640            );
641
642            let registration_options =
643                lsp_types::DidChangeWatchedFilesRegistrationOptions { watchers };
644            let registration = lsp_types::Registration {
645                id: "workspace/didChangeWatchedFiles".to_owned(),
646                method: "workspace/didChangeWatchedFiles".to_owned(),
647                register_options: Some(serde_json::to_value(registration_options).unwrap()),
648            };
649            self.send_request::<lsp_types::RegistrationRequest>(
650                lsp_types::RegistrationParams { registrations: vec![registration] },
651                |_, _| (),
652            );
653        }
654
655        let files_config = self.config.files();
656        let project_folders = ProjectFolders::new(
657            &self.workspaces,
658            &files_config.exclude,
659            Config::user_config_dir_path().as_deref(),
660        );
661
662        if (self.proc_macro_clients.len() < self.workspaces.len() || !same_workspaces)
663            && self.config.expand_proc_macros()
664        {
665            info!("Spawning proc-macro servers");
666
667            // Workspaces referring to the same proc-macro server executable (i.e. the same
668            // sysroot) with an identical spawn environment share a single client, and thereby
669            // a single set of server processes.
670            let mut clients: Vec<(
671                (AbsPathBuf, Option<semver::Version>, FxHashMap<String, Option<String>>),
672                ProcMacroClient,
673            )> = Vec::new();
674            self.proc_macro_clients = Arc::from_iter(self.workspaces.iter().map(|ws| {
675                let path = match self.config.proc_macro_srv() {
676                    Some(path) => path,
677                    None => match ws.find_sysroot_proc_macro_srv()? {
678                        Ok(path) => path,
679                        Err(e) => return Some(Err(e)),
680                    },
681                };
682
683                let env: FxHashMap<_, _> = match &ws.kind {
684                    ProjectWorkspaceKind::Cargo { cargo, .. }
685                    | ProjectWorkspaceKind::DetachedFile { cargo: Some((cargo, ..)), .. } => cargo
686                        .env()
687                        .into_iter()
688                        .map(|(k, v)| (k.clone(), Some(v.clone())))
689                        .chain(
690                            self.config.extra_env(None).iter().map(|(k, v)| (k.clone(), v.clone())),
691                        )
692                        .chain(
693                            ws.sysroot
694                                .root()
695                                .filter(|_| {
696                                    !self.config.extra_env(None).contains_key("RUSTUP_TOOLCHAIN")
697                                        && std::env::var_os("RUSTUP_TOOLCHAIN").is_none()
698                                })
699                                .map(|it| ("RUSTUP_TOOLCHAIN".to_owned(), Some(it.to_string()))),
700                        )
701                        .collect(),
702
703                    _ => Default::default(),
704                };
705
706                let key = (path, ws.toolchain.clone(), env);
707                if let Some((_, client)) = clients.iter().find(|(k, _)| *k == key) {
708                    return Some(Ok(client.clone()));
709                }
710
711                let (path, toolchain, env) = &key;
712                info!("Spawning proc-macro server at {path}");
713                let num_process = self.config.proc_macro_num_processes();
714
715                Some(match ProcMacroClient::spawn(path, env, toolchain.as_ref(), num_process) {
716                    Ok(client) => {
717                        clients.push((key.clone(), client.clone()));
718                        Ok(client)
719                    }
720                    Err(err) => {
721                        tracing::error!(
722                            "Failed to run proc-macro server from path {path}, error: {err:?}",
723                        );
724                        Err(anyhow::format_err!(
725                            "Failed to run proc-macro server from path {path}, error: {err:?}",
726                        ))
727                    }
728                })
729            }))
730        }
731
732        let watch = match files_config.watcher {
733            FilesWatcher::Client => vec![],
734            FilesWatcher::Server => project_folders.watch,
735        };
736        self.vfs_config_version += 1;
737        self.loader.handle.set_config(vfs::loader::Config {
738            load: project_folders.load,
739            watch,
740            version: self.vfs_config_version,
741        });
742        self.source_root_config = project_folders.source_root_config;
743        self.local_roots_parent_map = Arc::new(self.source_root_config.source_root_parent_map());
744
745        info!(?cause, "recreating the crate graph");
746        let cancellation_time = self.recreate_crate_graph(cause, switching_from_empty_workspace);
747
748        info!("did switch workspaces");
749        cancellation_time
750    }
751
752    fn recreate_crate_graph(&mut self, cause: String, initial_build: bool) -> Option<Duration> {
753        info!(?cause, "Building Crate Graph");
754        let mut cancellation_time = None;
755        self.report_progress(
756            "Building CrateGraph",
757            crate::lsp::utils::Progress::Begin,
758            None,
759            None,
760            None,
761        );
762
763        // crate graph construction relies on these paths, record them so when one of them gets
764        // deleted or created we trigger a reconstruction of the crate graph
765        self.crate_graph_file_dependencies.clear();
766        self.detached_files = self
767            .workspaces
768            .iter()
769            .filter_map(|ws| match &ws.kind {
770                ProjectWorkspaceKind::DetachedFile { file, .. } => Some(file.clone()),
771                _ => None,
772            })
773            .collect();
774
775        self.incomplete_crate_graph = false;
776        let (crate_graph, proc_macro_paths) = {
777            // Create crate graph from all the workspaces
778            let vfs = &self.vfs.read().0;
779            let load = |path: &AbsPath| {
780                let vfs_path = vfs::VfsPath::from(path.to_path_buf());
781                self.crate_graph_file_dependencies.insert(vfs_path.clone());
782                let file_id = vfs.file_id(&vfs_path);
783                self.incomplete_crate_graph |= file_id.is_none();
784                file_id.and_then(|(file_id, excluded)| {
785                    (excluded == vfs::FileExcluded::No).then_some(file_id)
786                })
787            };
788
789            ws_to_crate_graph(&self.workspaces, self.config.extra_env(None), load)
790        };
791        let mut change = ChangeWithProcMacros::default();
792        if initial_build || !self.config.expand_proc_macros() {
793            if self.config.expand_proc_macros() {
794                change.set_proc_macros(
795                    crate_graph
796                        .iter()
797                        .map(|id| (id, Err(ProcMacroLoadingError::NotYetBuilt)))
798                        .collect(),
799                );
800            } else {
801                change.set_proc_macros(
802                    crate_graph
803                        .iter()
804                        .map(|id| (id, Err(ProcMacroLoadingError::Disabled)))
805                        .collect(),
806                );
807            }
808
809            change.set_crate_graph(crate_graph);
810            cancellation_time = Some(self.analysis_host.apply_change(change));
811            _ = self.finish_loading_crate_graph();
812        } else {
813            change.set_crate_graph(crate_graph);
814            self.fetch_proc_macros_queue.request_op(cause, (change, proc_macro_paths));
815        }
816
817        self.report_progress(
818            "Building CrateGraph",
819            crate::lsp::utils::Progress::End,
820            None,
821            None,
822            None,
823        );
824        cancellation_time
825    }
826
827    pub(crate) fn finish_loading_crate_graph(&mut self) -> Option<Duration> {
828        let (_, cancellation_time) = self.process_changes();
829        self.reload_flycheck();
830        cancellation_time
831    }
832
833    pub(super) fn fetch_workspace_error(&self) -> Result<(), String> {
834        let mut buf = String::new();
835
836        let Some(FetchWorkspaceResponse { workspaces, .. }) =
837            self.fetch_workspaces_queue.last_op_result()
838        else {
839            return Ok(());
840        };
841
842        if workspaces.is_empty() && self.config.discover_workspace_config().is_none() {
843            stdx::format_to!(buf, "rust-analyzer failed to fetch workspace");
844        } else {
845            for ws in workspaces {
846                if let Err(err) = ws {
847                    stdx::format_to!(buf, "rust-analyzer failed to load workspace: {:#}\n", err);
848                }
849            }
850        }
851
852        if buf.is_empty() {
853            return Ok(());
854        }
855
856        Err(buf)
857    }
858
859    pub(super) fn fetch_build_data_error(&self) -> Result<(), String> {
860        let mut buf = String::new();
861
862        let Some(FetchBuildDataResponse { build_scripts, .. }) =
863            &self.fetch_build_data_queue.last_op_result()
864        else {
865            return Ok(());
866        };
867
868        for script in build_scripts {
869            match script {
870                Ok(data) => {
871                    if let Some(stderr) = data.error() {
872                        stdx::format_to!(buf, "{:#}\n", stderr)
873                    }
874                }
875                // io errors
876                Err(err) => stdx::format_to!(buf, "{:#}\n", err),
877            }
878        }
879
880        if buf.is_empty() { Ok(()) } else { Err(buf) }
881    }
882
883    fn reload_flycheck(&mut self) {
884        let _p = tracing::info_span!("GlobalState::reload_flycheck").entered();
885        let config = self.config.flycheck(None);
886        let sender = &self.flycheck_sender;
887        let invocation_strategy = config.invocation_strategy();
888        let next_gen =
889            self.flycheck.iter().map(FlycheckHandle::generation).max().unwrap_or_default() + 1;
890        let generation = Arc::new(AtomicUsize::new(next_gen));
891
892        self.flycheck = match invocation_strategy {
893            crate::flycheck::InvocationStrategy::Once => {
894                vec![FlycheckHandle::spawn(
895                    0,
896                    generation.clone(),
897                    sender.clone(),
898                    config,
899                    crate::flycheck::FlycheckConfigJson::default(),
900                    None,
901                    self.config.default_root_path().clone(),
902                    None,
903                    None,
904                    None,
905                    None,
906                )]
907            }
908            crate::flycheck::InvocationStrategy::PerWorkspace => {
909                self.workspaces
910                    .iter()
911                    .enumerate()
912                    .filter_map(|(id, ws)| {
913                        Some((
914                            id,
915                            match &ws.kind {
916                                ProjectWorkspaceKind::Cargo { cargo, .. }
917                                | ProjectWorkspaceKind::DetachedFile {
918                                    cargo: Some((cargo, _, _)),
919                                    ..
920                                } => (
921                                    crate::flycheck::FlycheckConfigJson::default(),
922                                    cargo.workspace_root(),
923                                    Some(cargo.manifest_path()),
924                                    Some(cargo.target_directory()),
925                                    cargo.build_directory(),
926                                ),
927                                ProjectWorkspaceKind::Json(project) => {
928                                    let config_json = crate::flycheck::FlycheckConfigJson {
929                                        single_template: project
930                                            .runnable_template(project_json::RunnableKind::Flycheck)
931                                            .cloned(),
932                                    };
933                                    // Enable flychecks for json projects if a custom flycheck command was supplied
934                                    // in the workspace configuration.
935                                    match config {
936                                        _ if config_json.any_configured() => {
937                                            (config_json, project.path(), None, None, None)
938                                        }
939                                        FlycheckConfig::CustomCommand { .. } => {
940                                            (config_json, project.path(), None, None, None)
941                                        }
942                                        _ => return None,
943                                    }
944                                }
945                                ProjectWorkspaceKind::DetachedFile { .. } => return None,
946                            },
947                            ws.sysroot.root().map(ToOwned::to_owned),
948                            ws.toolchain.clone(),
949                        ))
950                    })
951                    .map(
952                        |(
953                            id,
954                            (config_json, root, manifest_path, target_dir, build_dir),
955                            sysroot_root,
956                            toolchain,
957                        )| {
958                            FlycheckHandle::spawn(
959                                id,
960                                generation.clone(),
961                                sender.clone(),
962                                config.clone(),
963                                config_json,
964                                sysroot_root,
965                                root.to_path_buf(),
966                                manifest_path.map(|it| it.to_path_buf()),
967                                target_dir.map(|it| AsRef::<Utf8Path>::as_ref(it).to_path_buf()),
968                                build_dir.map(|it| AsRef::<Utf8Path>::as_ref(it).to_path_buf()),
969                                toolchain,
970                            )
971                        },
972                    )
973                    .collect()
974            }
975        }
976        .into();
977        self.flycheck_formatted_commands = vec![];
978    }
979}
980
981// FIXME: Move this into load-cargo?
982pub fn ws_to_crate_graph(
983    workspaces: &[ProjectWorkspace],
984    extra_env: &FxHashMap<String, Option<String>>,
985    mut load: impl FnMut(&AbsPath) -> Option<vfs::FileId>,
986) -> (CrateGraphBuilder, Vec<ProcMacroPaths>) {
987    let mut crate_graph = CrateGraphBuilder::default();
988    let mut proc_macro_paths = Vec::default();
989    for ws in workspaces {
990        let (other, mut crate_proc_macros) = ws.to_crate_graph(&mut load, extra_env);
991
992        crate_graph.extend(other, &mut crate_proc_macros);
993        proc_macro_paths.push(crate_proc_macros);
994    }
995
996    crate_graph.shrink_to_fit();
997    proc_macro_paths.shrink_to_fit();
998    (crate_graph, proc_macro_paths)
999}
1000
1001pub(crate) fn should_refresh_for_change(
1002    path: &AbsPath,
1003    change_kind: ChangeKind,
1004    additional_paths: &[&str],
1005) -> bool {
1006    // Note: build scripts are retriggered on file save, no refresh is necessary
1007    const IMPLICIT_TARGET_FILES: &[&str] = &["build.rs", "src/main.rs", "src/lib.rs"];
1008    const IMPLICIT_TARGET_DIRS: &[&str] = &["src/bin", "examples", "tests", "benches"];
1009
1010    let file_name = match path.file_name() {
1011        Some(it) => it,
1012        None => return false,
1013    };
1014
1015    if let "Cargo.toml" | "Cargo.lock" = file_name {
1016        return true;
1017    }
1018
1019    if additional_paths.contains(&file_name) {
1020        return true;
1021    }
1022
1023    // .cargo/config{.toml}
1024    if matches!(file_name, "config.toml" | "config")
1025        && path.parent().map(|parent| parent.as_str().ends_with(".cargo")).unwrap_or(false)
1026    {
1027        return true;
1028    }
1029
1030    // Everything below only matters when files are created or deleted
1031    if change_kind == ChangeKind::Modify {
1032        return false;
1033    }
1034
1035    if path.extension().unwrap_or_default() != "rs" {
1036        return false;
1037    }
1038
1039    if IMPLICIT_TARGET_FILES.iter().any(|it| path.as_str().ends_with(it)) {
1040        return true;
1041    }
1042    let parent = match path.parent() {
1043        Some(it) => it,
1044        None => return false,
1045    };
1046    if IMPLICIT_TARGET_DIRS.iter().any(|it| parent.as_str().ends_with(it)) {
1047        return true;
1048    }
1049    if file_name == "main.rs" {
1050        let grand_parent = match parent.parent() {
1051            Some(it) => it,
1052            None => return false,
1053        };
1054        if IMPLICIT_TARGET_DIRS.iter().any(|it| grand_parent.as_str().ends_with(it)) {
1055            return true;
1056        }
1057    }
1058    false
1059}
1060
1061/// Similar to [`str::eq_ignore_ascii_case`] but instead of ignoring
1062/// case, we say that `-` and `_` are equal.
1063fn eq_ignore_underscore(s1: &str, s2: &str) -> bool {
1064    if s1.len() != s2.len() {
1065        return false;
1066    }
1067
1068    s1.as_bytes().iter().zip(s2.as_bytes()).all(|(c1, c2)| {
1069        let c1_underscore = c1 == &b'_' || c1 == &b'-';
1070        let c2_underscore = c2 == &b'_' || c2 == &b'-';
1071
1072        c1 == c2 || (c1_underscore && c2_underscore)
1073    })
1074}