1 //! Project loading & configuration updates
2 use std::{mem, sync::Arc};
4 use flycheck::{FlycheckConfig, FlycheckHandle};
5 use hir::db::DefDatabase;
8 CrateGraph, Env, ProcMacro, ProcMacroExpander, ProcMacroExpansionError, ProcMacroKind,
11 use proc_macro_api::{MacroDylib, ProcMacroServer};
12 use project_model::{ProjectWorkspace, WorkspaceBuildScripts};
13 use vfs::{file_set::FileSetConfig, AbsPath, AbsPathBuf, ChangeKind};
16 config::{Config, FilesWatcher, LinkedProject},
17 global_state::GlobalState,
23 pub(crate) enum ProjectWorkspaceProgress {
26 End(Vec<anyhow::Result<ProjectWorkspace>>),
30 pub(crate) enum BuildDataProgress {
33 End((Arc<Vec<ProjectWorkspace>>, Vec<anyhow::Result<WorkspaceBuildScripts>>)),
37 pub(crate) fn is_quiescent(&self) -> bool {
38 !(self.fetch_workspaces_queue.op_in_progress()
39 || self.fetch_build_data_queue.op_in_progress()
40 || self.vfs_progress_config_version < self.vfs_config_version
41 || self.vfs_progress_n_done < self.vfs_progress_n_total)
44 pub(crate) fn update_configuration(&mut self, config: Config) {
45 let _p = profile::span("GlobalState::update_configuration");
46 let old_config = mem::replace(&mut self.config, Arc::new(config));
47 if self.config.lru_capacity() != old_config.lru_capacity() {
48 self.analysis_host.update_lru_capacity(self.config.lru_capacity());
50 if self.config.linked_projects() != old_config.linked_projects() {
51 self.fetch_workspaces_queue.request_op()
52 } else if self.config.flycheck() != old_config.flycheck() {
53 self.reload_flycheck();
56 // Apply experimental feature flags.
59 .set_enable_proc_attr_macros(self.config.expand_proc_attr_macros());
62 pub(crate) fn current_status(&self) -> lsp_ext::ServerStatusParams {
63 let mut status = lsp_ext::ServerStatusParams {
64 health: lsp_ext::Health::Ok,
65 quiescent: self.is_quiescent(),
69 if self.proc_macro_changed {
70 status.health = lsp_ext::Health::Warning;
72 Some("Reload required due to source changes of a procedural macro.".into())
74 if let Some(error) = self.fetch_build_data_error() {
75 status.health = lsp_ext::Health::Warning;
76 status.message = Some(error)
78 if !self.config.cargo_autoreload()
79 && self.is_quiescent()
80 && self.fetch_workspaces_queue.op_requested()
82 status.health = lsp_ext::Health::Warning;
83 status.message = Some("Workspace reload required".to_string())
86 if let Some(error) = self.fetch_workspace_error() {
87 status.health = lsp_ext::Health::Error;
88 status.message = Some(error)
93 pub(crate) fn fetch_workspaces(&mut self) {
94 tracing::info!("will fetch workspaces");
96 self.task_pool.handle.spawn_with_sender({
97 let linked_projects = self.config.linked_projects();
98 let detached_files = self.config.detached_files().to_vec();
99 let cargo_config = self.config.cargo();
103 let sender = sender.clone();
106 .send(Task::FetchWorkspace(ProjectWorkspaceProgress::Report(msg)))
111 sender.send(Task::FetchWorkspace(ProjectWorkspaceProgress::Begin)).unwrap();
113 let mut workspaces = linked_projects
115 .map(|project| match project {
116 LinkedProject::ProjectManifest(manifest) => {
117 project_model::ProjectWorkspace::load(
123 LinkedProject::InlineJsonProject(it) => {
124 project_model::ProjectWorkspace::load_inline(
126 cargo_config.target.as_deref(),
130 .collect::<Vec<_>>();
132 if !detached_files.is_empty() {
134 .push(project_model::ProjectWorkspace::load_detached_files(detached_files));
137 tracing::info!("did fetch workspaces {:?}", workspaces);
139 .send(Task::FetchWorkspace(ProjectWorkspaceProgress::End(workspaces)))
145 pub(crate) fn fetch_build_data(&mut self) {
146 let workspaces = Arc::clone(&self.workspaces);
147 let config = self.config.cargo();
148 self.task_pool.handle.spawn_with_sender(move |sender| {
149 sender.send(Task::FetchBuildData(BuildDataProgress::Begin)).unwrap();
152 let sender = sender.clone();
154 sender.send(Task::FetchBuildData(BuildDataProgress::Report(msg))).unwrap()
157 let mut res = Vec::new();
158 for ws in workspaces.iter() {
159 res.push(ws.run_build_scripts(&config, &progress));
161 sender.send(Task::FetchBuildData(BuildDataProgress::End((workspaces, res)))).unwrap();
165 pub(crate) fn switch_workspaces(&mut self) {
166 let _p = profile::span("GlobalState::switch_workspaces");
167 tracing::info!("will switch workspaces");
169 if let Some(error_message) = self.fetch_workspace_error() {
170 tracing::error!("failed to switch workspaces: {}", error_message);
171 if !self.workspaces.is_empty() {
172 // It only makes sense to switch to a partially broken workspace
173 // if we don't have any workspace at all yet.
178 if let Some(error_message) = self.fetch_build_data_error() {
179 tracing::error!("failed to switch build data: {}", error_message);
182 let workspaces = self
183 .fetch_workspaces_queue
186 .filter_map(|res| res.as_ref().ok().cloned())
187 .collect::<Vec<_>>();
189 fn eq_ignore_build_data<'a>(
190 left: &'a ProjectWorkspace,
191 right: &'a ProjectWorkspace,
193 let key = |p: &'a ProjectWorkspace| match p {
194 ProjectWorkspace::Cargo {
202 } => Some((cargo, sysroot, rustc, rustc_cfg, cfg_overrides)),
205 match (key(left), key(right)) {
206 (Some(lk), Some(rk)) => lk == rk,
211 let same_workspaces = workspaces.len() == self.workspaces.len()
214 .zip(self.workspaces.iter())
215 .all(|(l, r)| eq_ignore_build_data(l, r));
218 let (workspaces, build_scripts) = self.fetch_build_data_queue.last_op_result();
219 if Arc::ptr_eq(workspaces, &self.workspaces) {
220 let workspaces = workspaces
224 .map(|(mut ws, bs)| {
225 ws.set_build_scripts(bs.as_ref().ok().cloned().unwrap_or_default());
228 .collect::<Vec<_>>();
230 // Workspaces are the same, but we've updated build data.
231 self.workspaces = Arc::new(workspaces);
233 // Current build scripts do not match the version of the active
234 // workspace, so there's nothing for us to update.
238 // Here, we completely changed the workspace (Cargo.toml edit), so
239 // we don't care about build-script results, they are stale.
240 self.workspaces = Arc::new(workspaces)
243 if let FilesWatcher::Client = self.config.files().watcher {
244 if self.config.did_change_watched_files_dynamic_registration() {
245 let registration_options = lsp_types::DidChangeWatchedFilesRegistrationOptions {
249 .flat_map(|ws| ws.to_roots())
250 .filter(|it| it.is_local)
252 root.include.into_iter().flat_map(|it| {
254 format!("{}/**/*.rs", it.display()),
255 format!("{}/**/Cargo.toml", it.display()),
256 format!("{}/**/Cargo.lock", it.display()),
260 .map(|glob_pattern| lsp_types::FileSystemWatcher {
266 let registration = lsp_types::Registration {
267 id: "workspace/didChangeWatchedFiles".to_string(),
268 method: "workspace/didChangeWatchedFiles".to_string(),
269 register_options: Some(serde_json::to_value(registration_options).unwrap()),
271 self.send_request::<lsp_types::request::RegisterCapability>(
272 lsp_types::RegistrationParams { registrations: vec![registration] },
278 let mut change = Change::new();
280 let files_config = self.config.files();
281 let project_folders = ProjectFolders::new(&self.workspaces, &files_config.exclude);
283 if self.proc_macro_client.is_none() {
284 self.proc_macro_client = match self.config.proc_macro_srv() {
286 Some((path, args)) => match ProcMacroServer::spawn(path.clone(), args) {
290 "Failed to run proc_macro_srv from path {}, error: {:?}",
300 let watch = match files_config.watcher {
301 FilesWatcher::Client => vec![],
302 FilesWatcher::Notify => project_folders.watch,
304 self.vfs_config_version += 1;
305 self.loader.handle.set_config(vfs::loader::Config {
306 load: project_folders.load,
308 version: self.vfs_config_version,
311 // Create crate graph from all the workspaces
313 let proc_macro_client = self.proc_macro_client.as_ref();
314 let mut load_proc_macro =
315 move |path: &AbsPath| load_proc_macro(proc_macro_client, path);
317 let vfs = &mut self.vfs.write().0;
318 let loader = &mut self.loader;
319 let mem_docs = &self.mem_docs;
320 let mut load = move |path: &AbsPath| {
321 let _p = profile::span("GlobalState::load");
322 let vfs_path = vfs::VfsPath::from(path.to_path_buf());
323 if !mem_docs.contains(&vfs_path) {
324 let contents = loader.handle.load_sync(path);
325 vfs.set_file_contents(vfs_path.clone(), contents);
327 let res = vfs.file_id(&vfs_path);
329 tracing::warn!("failed to load {}", path.display())
334 let mut crate_graph = CrateGraph::default();
335 for ws in self.workspaces.iter() {
336 crate_graph.extend(ws.to_crate_graph(&mut load_proc_macro, &mut load));
340 change.set_crate_graph(crate_graph);
342 self.source_root_config = project_folders.source_root_config;
344 self.analysis_host.apply_change(change);
345 self.process_changes();
346 self.reload_flycheck();
347 tracing::info!("did switch workspaces");
350 fn fetch_workspace_error(&self) -> Option<String> {
351 let mut buf = String::new();
353 for ws in self.fetch_workspaces_queue.last_op_result() {
354 if let Err(err) = ws {
355 stdx::format_to!(buf, "rust-analyzer failed to load workspace: {:#}\n", err);
366 fn fetch_build_data_error(&self) -> Option<String> {
367 let mut buf = "rust-analyzer failed to run build scripts:\n".to_string();
368 let mut has_errors = false;
370 for ws in &self.fetch_build_data_queue.last_op_result().1 {
373 if let Some(err) = data.error() {
375 stdx::format_to!(buf, "{:#}\n", err);
380 stdx::format_to!(buf, "{:#}\n", err);
392 fn reload_flycheck(&mut self) {
393 let _p = profile::span("GlobalState::reload_flycheck");
394 let config = match self.config.flycheck() {
397 self.flycheck = Vec::new();
402 let sender = self.flycheck_sender.clone();
407 .filter_map(|(id, w)| match w {
408 ProjectWorkspace::Cargo { cargo, .. } => Some((id, cargo.workspace_root())),
409 ProjectWorkspace::Json { project, .. } => {
410 // Enable flychecks for json projects if a custom flycheck command was supplied
411 // in the workspace configuration.
413 FlycheckConfig::CustomCommand { .. } => Some((id, project.path())),
417 ProjectWorkspace::DetachedFiles { .. } => None,
420 let sender = sender.clone();
421 FlycheckHandle::spawn(
423 Box::new(move |msg| sender.send(msg).unwrap()),
433 pub(crate) struct ProjectFolders {
434 pub(crate) load: Vec<vfs::loader::Entry>,
435 pub(crate) watch: Vec<usize>,
436 pub(crate) source_root_config: SourceRootConfig,
439 impl ProjectFolders {
441 workspaces: &[ProjectWorkspace],
442 global_excludes: &[AbsPathBuf],
443 ) -> ProjectFolders {
444 let mut res = ProjectFolders::default();
445 let mut fsc = FileSetConfig::builder();
446 let mut local_filesets = vec![];
448 for root in workspaces.iter().flat_map(|ws| ws.to_roots()) {
449 let file_set_roots: Vec<VfsPath> =
450 root.include.iter().cloned().map(VfsPath::from).collect();
453 let mut dirs = vfs::loader::Directories::default();
454 dirs.extensions.push("rs".into());
455 dirs.include.extend(root.include);
456 dirs.exclude.extend(root.exclude);
457 for excl in global_excludes {
461 .any(|incl| incl.starts_with(excl) || excl.starts_with(incl))
463 dirs.exclude.push(excl.clone());
467 vfs::loader::Entry::Directories(dirs)
471 res.watch.push(res.load.len());
473 res.load.push(entry);
476 local_filesets.push(fsc.len());
478 fsc.add_file_set(file_set_roots)
481 let fsc = fsc.build();
482 res.source_root_config = SourceRootConfig { fsc, local_filesets };
488 #[derive(Default, Debug)]
489 pub(crate) struct SourceRootConfig {
490 pub(crate) fsc: FileSetConfig,
491 pub(crate) local_filesets: Vec<usize>,
494 impl SourceRootConfig {
495 pub(crate) fn partition(&self, vfs: &vfs::Vfs) -> Vec<SourceRoot> {
496 let _p = profile::span("SourceRootConfig::partition");
501 .map(|(idx, file_set)| {
502 let is_local = self.local_filesets.contains(&idx);
504 SourceRoot::new_local(file_set)
506 SourceRoot::new_library(file_set)
513 pub(crate) fn load_proc_macro(client: Option<&ProcMacroServer>, path: &AbsPath) -> Vec<ProcMacro> {
514 let dylib = match MacroDylib::new(path.to_path_buf()) {
517 // FIXME: that's not really right -- we store this error in a
518 // persistent status.
519 tracing::warn!("failed to load proc macro: {}", err);
525 .map(|it| it.load_dylib(dylib))
527 .flat_map(|it| match it {
528 Ok(Ok(macros)) => macros,
530 tracing::error!("proc macro server crashed: {}", err);
534 // FIXME: that's not really right -- we store this error in a
535 // persistent status.
536 tracing::warn!("failed to load proc macro: {}", err);
540 .map(expander_to_proc_macro)
543 fn expander_to_proc_macro(expander: proc_macro_api::ProcMacro) -> ProcMacro {
544 let name = expander.name().into();
545 let kind = match expander.kind() {
546 proc_macro_api::ProcMacroKind::CustomDerive => ProcMacroKind::CustomDerive,
547 proc_macro_api::ProcMacroKind::FuncLike => ProcMacroKind::FuncLike,
548 proc_macro_api::ProcMacroKind::Attr => ProcMacroKind::Attr,
550 let expander = Arc::new(Expander(expander));
551 ProcMacro { name, kind, expander }
555 struct Expander(proc_macro_api::ProcMacro);
557 impl ProcMacroExpander for Expander {
560 subtree: &tt::Subtree,
561 attrs: Option<&tt::Subtree>,
563 ) -> Result<tt::Subtree, ProcMacroExpansionError> {
564 let env = env.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
565 match self.0.expand(subtree, attrs, env) {
566 Ok(Ok(subtree)) => Ok(subtree),
567 Ok(Err(err)) => Err(ProcMacroExpansionError::Panic(err.0)),
568 Err(err) => Err(ProcMacroExpansionError::System(err.to_string())),
574 pub(crate) fn should_refresh_for_change(path: &AbsPath, change_kind: ChangeKind) -> bool {
575 const IMPLICIT_TARGET_FILES: &[&str] = &["build.rs", "src/main.rs", "src/lib.rs"];
576 const IMPLICIT_TARGET_DIRS: &[&str] = &["src/bin", "examples", "tests", "benches"];
577 let file_name = path.file_name().unwrap_or_default();
579 if file_name == "Cargo.toml" || file_name == "Cargo.lock" {
582 if change_kind == ChangeKind::Modify {
585 if path.extension().unwrap_or_default() != "rs" {
588 if IMPLICIT_TARGET_FILES.iter().any(|it| path.as_ref().ends_with(it)) {
591 let parent = match path.parent() {
593 None => return false,
595 if IMPLICIT_TARGET_DIRS.iter().any(|it| parent.as_ref().ends_with(it)) {
598 if file_name == "main.rs" {
599 let grand_parent = match parent.parent() {
601 None => return false,
603 if IMPLICIT_TARGET_DIRS.iter().any(|it| grand_parent.as_ref().ends_with(it)) {