1 //! Project loading & configuration updates.
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`.
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 use std::{mem, sync::Arc};
17 use flycheck::{FlycheckConfig, FlycheckHandle};
18 use hir::db::DefDatabase;
20 use ide_db::base_db::{
21 CrateGraph, Env, ProcMacro, ProcMacroExpander, ProcMacroExpansionError, ProcMacroKind,
22 ProcMacroLoadResult, SourceRoot, VfsPath,
24 use proc_macro_api::{MacroDylib, ProcMacroServer};
25 use project_model::{ProjectWorkspace, WorkspaceBuildScripts};
27 use vfs::{file_set::FileSetConfig, AbsPath, AbsPathBuf, ChangeKind};
30 config::{Config, FilesWatcher, LinkedProject},
31 global_state::GlobalState,
38 pub(crate) enum ProjectWorkspaceProgress {
41 End(Vec<anyhow::Result<ProjectWorkspace>>),
45 pub(crate) enum BuildDataProgress {
48 End((Arc<Vec<ProjectWorkspace>>, Vec<anyhow::Result<WorkspaceBuildScripts>>)),
52 pub(crate) fn is_quiescent(&self) -> bool {
53 !(self.fetch_workspaces_queue.op_in_progress()
54 || self.fetch_build_data_queue.op_in_progress()
55 || self.vfs_progress_config_version < self.vfs_config_version
56 || self.vfs_progress_n_done < self.vfs_progress_n_total)
59 pub(crate) fn update_configuration(&mut self, config: Config) {
60 let _p = profile::span("GlobalState::update_configuration");
61 let old_config = mem::replace(&mut self.config, Arc::new(config));
62 if self.config.lru_capacity() != old_config.lru_capacity() {
63 self.analysis_host.update_lru_capacity(self.config.lru_capacity());
65 if self.config.linked_projects() != old_config.linked_projects() {
66 self.fetch_workspaces_queue.request_op("linked projects changed".to_string())
67 } else if self.config.flycheck() != old_config.flycheck() {
68 self.reload_flycheck();
71 if self.analysis_host.raw_database().enable_proc_attr_macros()
72 != self.config.expand_proc_attr_macros()
76 .set_enable_proc_attr_macros(self.config.expand_proc_attr_macros());
80 pub(crate) fn current_status(&self) -> lsp_ext::ServerStatusParams {
81 let mut status = lsp_ext::ServerStatusParams {
82 health: lsp_ext::Health::Ok,
83 quiescent: self.is_quiescent(),
87 if self.proc_macro_changed {
88 status.health = lsp_ext::Health::Warning;
90 Some("Reload required due to source changes of a procedural macro.".into())
92 if let Err(_) = self.fetch_build_data_error() {
93 status.health = lsp_ext::Health::Warning;
95 Some("Failed to run build scripts of some packages, check the logs.".to_string());
97 if !self.config.cargo_autoreload()
98 && self.is_quiescent()
99 && self.fetch_workspaces_queue.op_requested()
101 status.health = lsp_ext::Health::Warning;
102 status.message = Some("Workspace reload required".to_string())
105 if let Err(error) = self.fetch_workspace_error() {
106 status.health = lsp_ext::Health::Error;
107 status.message = Some(error)
112 pub(crate) fn fetch_workspaces(&mut self, cause: Cause) {
113 tracing::info!(%cause, "will fetch workspaces");
115 self.task_pool.handle.spawn_with_sender({
116 let linked_projects = self.config.linked_projects();
117 let detached_files = self.config.detached_files().to_vec();
118 let cargo_config = self.config.cargo();
122 let sender = sender.clone();
125 .send(Task::FetchWorkspace(ProjectWorkspaceProgress::Report(msg)))
130 sender.send(Task::FetchWorkspace(ProjectWorkspaceProgress::Begin)).unwrap();
132 let mut workspaces = linked_projects
134 .map(|project| match project {
135 LinkedProject::ProjectManifest(manifest) => {
136 project_model::ProjectWorkspace::load(
142 LinkedProject::InlineJsonProject(it) => {
143 project_model::ProjectWorkspace::load_inline(
145 cargo_config.target.as_deref(),
149 .collect::<Vec<_>>();
151 if !detached_files.is_empty() {
153 .push(project_model::ProjectWorkspace::load_detached_files(detached_files));
156 tracing::info!("did fetch workspaces {:?}", workspaces);
158 .send(Task::FetchWorkspace(ProjectWorkspaceProgress::End(workspaces)))
164 pub(crate) fn fetch_build_data(&mut self, cause: Cause) {
165 tracing::info!(%cause, "will fetch build data");
166 let workspaces = Arc::clone(&self.workspaces);
167 let config = self.config.cargo();
168 self.task_pool.handle.spawn_with_sender(move |sender| {
169 sender.send(Task::FetchBuildData(BuildDataProgress::Begin)).unwrap();
172 let sender = sender.clone();
174 sender.send(Task::FetchBuildData(BuildDataProgress::Report(msg))).unwrap()
177 let mut res = Vec::new();
178 for ws in workspaces.iter() {
179 res.push(ws.run_build_scripts(&config, &progress));
181 sender.send(Task::FetchBuildData(BuildDataProgress::End((workspaces, res)))).unwrap();
185 pub(crate) fn switch_workspaces(&mut self, cause: Cause) {
186 let _p = profile::span("GlobalState::switch_workspaces");
187 tracing::info!(%cause, "will switch workspaces");
189 if let Err(error_message) = self.fetch_workspace_error() {
190 self.show_and_log_error(error_message, None);
191 if !self.workspaces.is_empty() {
192 // It only makes sense to switch to a partially broken workspace
193 // if we don't have any workspace at all yet.
198 if let Err(error) = self.fetch_build_data_error() {
199 self.show_and_log_error(
200 "rust-analyzer failed to run build scripts".to_string(),
205 let workspaces = self
206 .fetch_workspaces_queue
209 .filter_map(|res| res.as_ref().ok().cloned())
210 .collect::<Vec<_>>();
212 fn eq_ignore_build_data<'a>(
213 left: &'a ProjectWorkspace,
214 right: &'a ProjectWorkspace,
216 let key = |p: &'a ProjectWorkspace| match p {
217 ProjectWorkspace::Cargo {
225 } => Some((cargo, sysroot, rustc, rustc_cfg, cfg_overrides)),
228 match (key(left), key(right)) {
229 (Some(lk), Some(rk)) => lk == rk,
234 let same_workspaces = workspaces.len() == self.workspaces.len()
237 .zip(self.workspaces.iter())
238 .all(|(l, r)| eq_ignore_build_data(l, r));
241 let (workspaces, build_scripts) = self.fetch_build_data_queue.last_op_result();
242 if Arc::ptr_eq(workspaces, &self.workspaces) {
243 tracing::debug!("set build scripts to workspaces");
245 let workspaces = workspaces
249 .map(|(mut ws, bs)| {
250 ws.set_build_scripts(bs.as_ref().ok().cloned().unwrap_or_default());
253 .collect::<Vec<_>>();
255 // Workspaces are the same, but we've updated build data.
256 self.workspaces = Arc::new(workspaces);
258 tracing::info!("build scripts do not match the version of the active workspace");
259 // Current build scripts do not match the version of the active
260 // workspace, so there's nothing for us to update.
264 tracing::debug!("abandon build scripts for workspaces");
266 // Here, we completely changed the workspace (Cargo.toml edit), so
267 // we don't care about build-script results, they are stale.
268 self.workspaces = Arc::new(workspaces)
271 if let FilesWatcher::Client = self.config.files().watcher {
272 let registration_options = lsp_types::DidChangeWatchedFilesRegistrationOptions {
276 .flat_map(|ws| ws.to_roots())
277 .filter(|it| it.is_local)
279 root.include.into_iter().flat_map(|it| {
281 format!("{}/**/*.rs", it.display()),
282 format!("{}/**/Cargo.toml", it.display()),
283 format!("{}/**/Cargo.lock", it.display()),
287 .map(|glob_pattern| lsp_types::FileSystemWatcher { glob_pattern, kind: None })
290 let registration = lsp_types::Registration {
291 id: "workspace/didChangeWatchedFiles".to_string(),
292 method: "workspace/didChangeWatchedFiles".to_string(),
293 register_options: Some(serde_json::to_value(registration_options).unwrap()),
295 self.send_request::<lsp_types::request::RegisterCapability>(
296 lsp_types::RegistrationParams { registrations: vec![registration] },
301 let mut change = Change::new();
303 let files_config = self.config.files();
304 let project_folders = ProjectFolders::new(&self.workspaces, &files_config.exclude);
306 if self.proc_macro_clients.is_empty() {
307 if let Some((path, args)) = self.config.proc_macro_srv() {
308 self.proc_macro_clients = self
312 let mut args = args.clone();
313 let mut path = path.clone();
315 if let ProjectWorkspace::Cargo { sysroot, .. } = ws {
316 tracing::info!("Found a cargo workspace...");
317 if let Some(sysroot) = sysroot.as_ref() {
318 tracing::info!("Found a cargo workspace with a sysroot...");
319 let server_path = sysroot
322 .join("rust-analyzer-proc-macro-srv");
323 if std::fs::metadata(&server_path).is_ok() {
325 "And the server exists at {}",
326 server_path.display()
332 "And the server does not exist at {}",
333 server_path.display()
340 "Using proc-macro server at {} with args {:?}",
344 ProcMacroServer::spawn(path.clone(), args.clone()).map_err(|err| {
346 "Failed to run proc_macro_srv from path {}, error: {:?}",
350 tracing::error!(error);
358 let watch = match files_config.watcher {
359 FilesWatcher::Client => vec![],
360 FilesWatcher::Server => project_folders.watch,
362 self.vfs_config_version += 1;
363 self.loader.handle.set_config(vfs::loader::Config {
364 load: project_folders.load,
366 version: self.vfs_config_version,
369 // Create crate graph from all the workspaces
371 let dummy_replacements = self.config.dummy_replacements();
373 let vfs = &mut self.vfs.write().0;
374 let loader = &mut self.loader;
375 let mem_docs = &self.mem_docs;
376 let mut load = move |path: &AbsPath| {
377 let _p = profile::span("GlobalState::load");
378 let vfs_path = vfs::VfsPath::from(path.to_path_buf());
379 if !mem_docs.contains(&vfs_path) {
380 let contents = loader.handle.load_sync(path);
381 vfs.set_file_contents(vfs_path.clone(), contents);
383 let res = vfs.file_id(&vfs_path);
385 tracing::warn!("failed to load {}", path.display())
390 let mut crate_graph = CrateGraph::default();
391 for (idx, ws) in self.workspaces.iter().enumerate() {
392 let proc_macro_client = self.proc_macro_clients[idx].as_ref();
393 let mut load_proc_macro = move |crate_name: &str, path: &AbsPath| {
397 dummy_replacements.get(crate_name).map(|v| &**v).unwrap_or_default(),
400 crate_graph.extend(ws.to_crate_graph(&mut load_proc_macro, &mut load));
404 change.set_crate_graph(crate_graph);
406 self.source_root_config = project_folders.source_root_config;
408 self.analysis_host.apply_change(change);
409 self.process_changes();
410 self.reload_flycheck();
411 tracing::info!("did switch workspaces");
414 fn fetch_workspace_error(&self) -> Result<(), String> {
415 let mut buf = String::new();
417 for ws in self.fetch_workspaces_queue.last_op_result() {
418 if let Err(err) = ws {
419 stdx::format_to!(buf, "rust-analyzer failed to load workspace: {:#}\n", err);
430 fn fetch_build_data_error(&self) -> Result<(), String> {
431 let mut buf = String::new();
433 for ws in &self.fetch_build_data_queue.last_op_result().1 {
435 Ok(data) => match data.error() {
436 Some(stderr) => stdx::format_to!(buf, "{:#}\n", stderr),
440 Err(err) => stdx::format_to!(buf, "{:#}\n", err),
451 fn reload_flycheck(&mut self) {
452 let _p = profile::span("GlobalState::reload_flycheck");
453 let config = match self.config.flycheck() {
456 self.flycheck = Vec::new();
457 self.diagnostics.clear_check();
462 let sender = self.flycheck_sender.clone();
467 .filter_map(|(id, w)| match w {
468 ProjectWorkspace::Cargo { cargo, .. } => Some((id, cargo.workspace_root())),
469 ProjectWorkspace::Json { project, .. } => {
470 // Enable flychecks for json projects if a custom flycheck command was supplied
471 // in the workspace configuration.
473 FlycheckConfig::CustomCommand { .. } => Some((id, project.path())),
477 ProjectWorkspace::DetachedFiles { .. } => None,
480 let sender = sender.clone();
481 FlycheckHandle::spawn(
483 Box::new(move |msg| sender.send(msg).unwrap()),
493 pub(crate) struct ProjectFolders {
494 pub(crate) load: Vec<vfs::loader::Entry>,
495 pub(crate) watch: Vec<usize>,
496 pub(crate) source_root_config: SourceRootConfig,
499 impl ProjectFolders {
501 workspaces: &[ProjectWorkspace],
502 global_excludes: &[AbsPathBuf],
503 ) -> ProjectFolders {
504 let mut res = ProjectFolders::default();
505 let mut fsc = FileSetConfig::builder();
506 let mut local_filesets = vec![];
508 for root in workspaces.iter().flat_map(|ws| ws.to_roots()) {
509 let file_set_roots: Vec<VfsPath> =
510 root.include.iter().cloned().map(VfsPath::from).collect();
513 let mut dirs = vfs::loader::Directories::default();
514 dirs.extensions.push("rs".into());
515 dirs.include.extend(root.include);
516 dirs.exclude.extend(root.exclude);
517 for excl in global_excludes {
521 .any(|incl| incl.starts_with(excl) || excl.starts_with(incl))
523 dirs.exclude.push(excl.clone());
527 vfs::loader::Entry::Directories(dirs)
531 res.watch.push(res.load.len());
533 res.load.push(entry);
536 local_filesets.push(fsc.len());
538 fsc.add_file_set(file_set_roots)
541 let fsc = fsc.build();
542 res.source_root_config = SourceRootConfig { fsc, local_filesets };
548 #[derive(Default, Debug)]
549 pub(crate) struct SourceRootConfig {
550 pub(crate) fsc: FileSetConfig,
551 pub(crate) local_filesets: Vec<usize>,
554 impl SourceRootConfig {
555 pub(crate) fn partition(&self, vfs: &vfs::Vfs) -> Vec<SourceRoot> {
556 let _p = profile::span("SourceRootConfig::partition");
561 .map(|(idx, file_set)| {
562 let is_local = self.local_filesets.contains(&idx);
564 SourceRoot::new_local(file_set)
566 SourceRoot::new_library(file_set)
573 /// Load the proc-macros for the given lib path, replacing all expanders whose names are in `dummy_replace`
574 /// with an identity dummy expander.
575 pub(crate) fn load_proc_macro(
576 server: Result<&ProcMacroServer, &String>,
578 dummy_replace: &[Box<str>],
579 ) -> ProcMacroLoadResult {
580 let res: Result<Vec<_>, String> = (|| {
581 let dylib = MacroDylib::new(path.to_path_buf())
582 .map_err(|io| format!("Proc-macro dylib loading failed: {io}"))?;
583 let server = server.map_err(ToOwned::to_owned)?;
584 let vec = server.load_dylib(dylib).map_err(|e| format!("{e}"))?;
586 return Err("proc macro library returned no proc macros".to_string());
590 .map(|expander| expander_to_proc_macro(expander, dummy_replace))
596 "Loaded proc-macros for {}: {:?}",
598 proc_macros.iter().map(|it| it.name.clone()).collect::<Vec<_>>()
603 tracing::warn!("proc-macro loading for {} failed: {e}", path.display());
608 fn expander_to_proc_macro(
609 expander: proc_macro_api::ProcMacro,
610 dummy_replace: &[Box<str>],
612 let name = SmolStr::from(expander.name());
613 let kind = match expander.kind() {
614 proc_macro_api::ProcMacroKind::CustomDerive => ProcMacroKind::CustomDerive,
615 proc_macro_api::ProcMacroKind::FuncLike => ProcMacroKind::FuncLike,
616 proc_macro_api::ProcMacroKind::Attr => ProcMacroKind::Attr,
618 let expander: Arc<dyn ProcMacroExpander> =
619 if dummy_replace.iter().any(|replace| &**replace == name) {
620 Arc::new(DummyExpander)
622 Arc::new(Expander(expander))
624 ProcMacro { name, kind, expander }
628 struct Expander(proc_macro_api::ProcMacro);
630 impl ProcMacroExpander for Expander {
633 subtree: &tt::Subtree,
634 attrs: Option<&tt::Subtree>,
636 ) -> Result<tt::Subtree, ProcMacroExpansionError> {
637 let env = env.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
638 match self.0.expand(subtree, attrs, env) {
639 Ok(Ok(subtree)) => Ok(subtree),
640 Ok(Err(err)) => Err(ProcMacroExpansionError::Panic(err.0)),
641 Err(err) => Err(ProcMacroExpansionError::System(err.to_string())),
646 /// Dummy identity expander, used for proc-macros that are deliberately ignored by the user.
648 struct DummyExpander;
650 impl ProcMacroExpander for DummyExpander {
653 subtree: &tt::Subtree,
654 _: Option<&tt::Subtree>,
656 ) -> Result<tt::Subtree, ProcMacroExpansionError> {
662 pub(crate) fn should_refresh_for_change(path: &AbsPath, change_kind: ChangeKind) -> bool {
663 const IMPLICIT_TARGET_FILES: &[&str] = &["build.rs", "src/main.rs", "src/lib.rs"];
664 const IMPLICIT_TARGET_DIRS: &[&str] = &["src/bin", "examples", "tests", "benches"];
665 let file_name = path.file_name().unwrap_or_default();
667 if file_name == "Cargo.toml" || file_name == "Cargo.lock" {
670 if change_kind == ChangeKind::Modify {
673 if path.extension().unwrap_or_default() != "rs" {
674 if (file_name == "config.toml" || file_name == "config")
675 && path.parent().map(|parent| parent.as_ref().ends_with(".cargo")) == Some(true)
681 if IMPLICIT_TARGET_FILES.iter().any(|it| path.as_ref().ends_with(it)) {
684 let parent = match path.parent() {
686 None => return false,
688 if IMPLICIT_TARGET_DIRS.iter().any(|it| parent.as_ref().ends_with(it)) {
691 if file_name == "main.rs" {
692 let grand_parent = match parent.parent() {
694 None => return false,
696 if IMPLICIT_TARGET_DIRS.iter().any(|it| grand_parent.as_ref().ends_with(it)) {