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 let Some(error) = self.fetch_build_data_error() {
70 status.health = lsp_ext::Health::Warning;
71 status.message = Some(error)
73 if !self.config.cargo_autoreload()
74 && self.is_quiescent()
75 && self.fetch_workspaces_queue.op_requested()
77 status.health = lsp_ext::Health::Warning;
78 status.message = Some("Workspace reload required".to_string())
81 if let Some(error) = self.fetch_workspace_error() {
82 status.health = lsp_ext::Health::Error;
83 status.message = Some(error)
88 pub(crate) fn fetch_workspaces(&mut self) {
89 tracing::info!("will fetch workspaces");
91 self.task_pool.handle.spawn_with_sender({
92 let linked_projects = self.config.linked_projects();
93 let detached_files = self.config.detached_files().to_vec();
94 let cargo_config = self.config.cargo();
98 let sender = sender.clone();
101 .send(Task::FetchWorkspace(ProjectWorkspaceProgress::Report(msg)))
106 sender.send(Task::FetchWorkspace(ProjectWorkspaceProgress::Begin)).unwrap();
108 let mut workspaces = linked_projects
110 .map(|project| match project {
111 LinkedProject::ProjectManifest(manifest) => {
112 project_model::ProjectWorkspace::load(
118 LinkedProject::InlineJsonProject(it) => {
119 project_model::ProjectWorkspace::load_inline(
121 cargo_config.target.as_deref(),
125 .collect::<Vec<_>>();
127 if !detached_files.is_empty() {
129 .push(project_model::ProjectWorkspace::load_detached_files(detached_files));
132 tracing::info!("did fetch workspaces {:?}", workspaces);
134 .send(Task::FetchWorkspace(ProjectWorkspaceProgress::End(workspaces)))
140 pub(crate) fn fetch_build_data(&mut self) {
141 let workspaces = Arc::clone(&self.workspaces);
142 let config = self.config.cargo();
143 self.task_pool.handle.spawn_with_sender(move |sender| {
144 sender.send(Task::FetchBuildData(BuildDataProgress::Begin)).unwrap();
147 let sender = sender.clone();
149 sender.send(Task::FetchBuildData(BuildDataProgress::Report(msg))).unwrap()
152 let mut res = Vec::new();
153 for ws in workspaces.iter() {
154 res.push(ws.run_build_scripts(&config, &progress));
156 sender.send(Task::FetchBuildData(BuildDataProgress::End((workspaces, res)))).unwrap();
160 pub(crate) fn switch_workspaces(&mut self) {
161 let _p = profile::span("GlobalState::switch_workspaces");
162 tracing::info!("will switch workspaces");
164 if let Some(error_message) = self.fetch_workspace_error() {
165 tracing::error!("failed to switch workspaces: {}", error_message);
166 if !self.workspaces.is_empty() {
167 // It only makes sense to switch to a partially broken workspace
168 // if we don't have any workspace at all yet.
173 if let Some(error_message) = self.fetch_build_data_error() {
174 tracing::error!("failed to switch build data: {}", error_message);
177 let workspaces = self
178 .fetch_workspaces_queue
181 .filter_map(|res| res.as_ref().ok().cloned())
182 .collect::<Vec<_>>();
184 fn eq_ignore_build_data<'a>(
185 left: &'a ProjectWorkspace,
186 right: &'a ProjectWorkspace,
188 let key = |p: &'a ProjectWorkspace| match p {
189 ProjectWorkspace::Cargo {
197 } => Some((cargo, sysroot, rustc, rustc_cfg, cfg_overrides)),
200 match (key(left), key(right)) {
201 (Some(lk), Some(rk)) => lk == rk,
206 let same_workspaces = workspaces.len() == self.workspaces.len()
209 .zip(self.workspaces.iter())
210 .all(|(l, r)| eq_ignore_build_data(l, r));
213 let (workspaces, build_scripts) = self.fetch_build_data_queue.last_op_result();
214 if Arc::ptr_eq(&workspaces, &self.workspaces) {
215 let workspaces = workspaces
219 .map(|(mut ws, bs)| {
220 ws.set_build_scripts(bs.as_ref().ok().cloned().unwrap_or_default());
223 .collect::<Vec<_>>();
225 // Workspaces are the same, but we've updated build data.
226 self.workspaces = Arc::new(workspaces);
228 // Current build scripts do not match the version of the active
229 // workspace, so there's nothing for us to update.
233 // Here, we completely changed the workspace (Cargo.toml edit), so
234 // we don't care about build-script results, they are stale.
235 self.workspaces = Arc::new(workspaces)
238 if let FilesWatcher::Client = self.config.files().watcher {
239 if self.config.did_change_watched_files_dynamic_registration() {
240 let registration_options = lsp_types::DidChangeWatchedFilesRegistrationOptions {
244 .flat_map(|ws| ws.to_roots())
245 .filter(|it| it.is_member)
247 root.include.into_iter().flat_map(|it| {
249 format!("{}/**/*.rs", it.display()),
250 format!("{}/**/Cargo.toml", it.display()),
251 format!("{}/**/Cargo.lock", it.display()),
255 .map(|glob_pattern| lsp_types::FileSystemWatcher {
261 let registration = lsp_types::Registration {
262 id: "workspace/didChangeWatchedFiles".to_string(),
263 method: "workspace/didChangeWatchedFiles".to_string(),
264 register_options: Some(serde_json::to_value(registration_options).unwrap()),
266 self.send_request::<lsp_types::request::RegisterCapability>(
267 lsp_types::RegistrationParams { registrations: vec![registration] },
273 let mut change = Change::new();
275 let files_config = self.config.files();
276 let project_folders = ProjectFolders::new(&self.workspaces, &files_config.exclude);
278 if self.proc_macro_client.is_none() {
279 self.proc_macro_client = match self.config.proc_macro_srv() {
281 Some((path, args)) => match ProcMacroServer::spawn(path.clone(), args) {
285 "Failed to run proc_macro_srv from path {}, error: {:?}",
295 let watch = match files_config.watcher {
296 FilesWatcher::Client => vec![],
297 FilesWatcher::Notify => project_folders.watch,
299 self.vfs_config_version += 1;
300 self.loader.handle.set_config(vfs::loader::Config {
301 load: project_folders.load,
303 version: self.vfs_config_version,
306 // Create crate graph from all the workspaces
308 let proc_macro_client = self.proc_macro_client.as_ref();
309 let mut load_proc_macro =
310 move |path: &AbsPath| load_proc_macro(proc_macro_client, path);
312 let vfs = &mut self.vfs.write().0;
313 let loader = &mut self.loader;
314 let mem_docs = &self.mem_docs;
315 let mut load = move |path: &AbsPath| {
316 let _p = profile::span("GlobalState::load");
317 let vfs_path = vfs::VfsPath::from(path.to_path_buf());
318 if !mem_docs.contains(&vfs_path) {
319 let contents = loader.handle.load_sync(path);
320 vfs.set_file_contents(vfs_path.clone(), contents);
322 let res = vfs.file_id(&vfs_path);
324 tracing::warn!("failed to load {}", path.display())
329 let mut crate_graph = CrateGraph::default();
330 for ws in self.workspaces.iter() {
331 crate_graph.extend(ws.to_crate_graph(&mut load_proc_macro, &mut load));
335 change.set_crate_graph(crate_graph);
337 self.source_root_config = project_folders.source_root_config;
339 self.analysis_host.apply_change(change);
340 self.process_changes();
341 self.reload_flycheck();
342 tracing::info!("did switch workspaces");
345 fn fetch_workspace_error(&self) -> Option<String> {
346 let mut buf = String::new();
348 for ws in self.fetch_workspaces_queue.last_op_result() {
349 if let Err(err) = ws {
350 stdx::format_to!(buf, "rust-analyzer failed to load workspace: {:#}\n", err);
361 fn fetch_build_data_error(&self) -> Option<String> {
362 let mut buf = "rust-analyzer failed to run build scripts:\n".to_string();
363 let mut has_errors = false;
365 for ws in &self.fetch_build_data_queue.last_op_result().1 {
368 if let Some(err) = data.error() {
370 stdx::format_to!(buf, "{:#}\n", err);
375 stdx::format_to!(buf, "{:#}\n", err);
387 fn reload_flycheck(&mut self) {
388 let _p = profile::span("GlobalState::reload_flycheck");
389 let config = match self.config.flycheck() {
392 self.flycheck = Vec::new();
397 let sender = self.flycheck_sender.clone();
402 .filter_map(|(id, w)| match w {
403 ProjectWorkspace::Cargo { cargo, .. } => Some((id, cargo.workspace_root())),
404 ProjectWorkspace::Json { project, .. } => {
405 // Enable flychecks for json projects if a custom flycheck command was supplied
406 // in the workspace configuration.
408 FlycheckConfig::CustomCommand { .. } => Some((id, project.path())),
412 ProjectWorkspace::DetachedFiles { .. } => None,
415 let sender = sender.clone();
416 FlycheckHandle::spawn(
418 Box::new(move |msg| sender.send(msg).unwrap()),
420 root.to_path_buf().into(),
428 pub(crate) struct ProjectFolders {
429 pub(crate) load: Vec<vfs::loader::Entry>,
430 pub(crate) watch: Vec<usize>,
431 pub(crate) source_root_config: SourceRootConfig,
434 impl ProjectFolders {
436 workspaces: &[ProjectWorkspace],
437 global_excludes: &[AbsPathBuf],
438 ) -> ProjectFolders {
439 let mut res = ProjectFolders::default();
440 let mut fsc = FileSetConfig::builder();
441 let mut local_filesets = vec![];
443 for root in workspaces.iter().flat_map(|ws| ws.to_roots()) {
444 let file_set_roots: Vec<VfsPath> =
445 root.include.iter().cloned().map(VfsPath::from).collect();
448 let mut dirs = vfs::loader::Directories::default();
449 dirs.extensions.push("rs".into());
450 dirs.include.extend(root.include);
451 dirs.exclude.extend(root.exclude);
452 for excl in global_excludes {
456 .any(|incl| incl.starts_with(excl) || excl.starts_with(incl))
458 dirs.exclude.push(excl.clone());
462 vfs::loader::Entry::Directories(dirs)
466 res.watch.push(res.load.len());
468 res.load.push(entry);
471 local_filesets.push(fsc.len());
473 fsc.add_file_set(file_set_roots)
476 let fsc = fsc.build();
477 res.source_root_config = SourceRootConfig { fsc, local_filesets };
483 #[derive(Default, Debug)]
484 pub(crate) struct SourceRootConfig {
485 pub(crate) fsc: FileSetConfig,
486 pub(crate) local_filesets: Vec<usize>,
489 impl SourceRootConfig {
490 pub(crate) fn partition(&self, vfs: &vfs::Vfs) -> Vec<SourceRoot> {
491 let _p = profile::span("SourceRootConfig::partition");
496 .map(|(idx, file_set)| {
497 let is_local = self.local_filesets.contains(&idx);
499 SourceRoot::new_local(file_set)
501 SourceRoot::new_library(file_set)
508 pub(crate) fn load_proc_macro(client: Option<&ProcMacroServer>, path: &AbsPath) -> Vec<ProcMacro> {
509 let dylib = match MacroDylib::new(path.to_path_buf()) {
512 // FIXME: that's not really right -- we store this error in a
513 // persistent status.
514 tracing::warn!("failed to load proc macro: {}", err);
520 .map(|it| it.load_dylib(dylib))
522 .flat_map(|it| match it {
523 Ok(Ok(macros)) => macros,
525 tracing::error!("proc macro server crashed: {}", err);
529 // FIXME: that's not really right -- we store this error in a
530 // persistent status.
531 tracing::warn!("failed to load proc macro: {}", err);
535 .map(expander_to_proc_macro)
538 fn expander_to_proc_macro(expander: proc_macro_api::ProcMacro) -> ProcMacro {
539 let name = expander.name().into();
540 let kind = match expander.kind() {
541 proc_macro_api::ProcMacroKind::CustomDerive => ProcMacroKind::CustomDerive,
542 proc_macro_api::ProcMacroKind::FuncLike => ProcMacroKind::FuncLike,
543 proc_macro_api::ProcMacroKind::Attr => ProcMacroKind::Attr,
545 let expander = Arc::new(Expander(expander));
546 ProcMacro { name, kind, expander }
550 struct Expander(proc_macro_api::ProcMacro);
552 impl ProcMacroExpander for Expander {
555 subtree: &tt::Subtree,
556 attrs: Option<&tt::Subtree>,
558 ) -> Result<tt::Subtree, ProcMacroExpansionError> {
559 let env = env.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
560 match self.0.expand(subtree, attrs, env) {
561 Ok(Ok(subtree)) => Ok(subtree),
562 Ok(Err(err)) => Err(ProcMacroExpansionError::Panic(err.0)),
563 Err(err) => Err(ProcMacroExpansionError::System(err.to_string())),
569 pub(crate) fn should_refresh_for_change(path: &AbsPath, change_kind: ChangeKind) -> bool {
570 const IMPLICIT_TARGET_FILES: &[&str] = &["build.rs", "src/main.rs", "src/lib.rs"];
571 const IMPLICIT_TARGET_DIRS: &[&str] = &["src/bin", "examples", "tests", "benches"];
572 let file_name = path.file_name().unwrap_or_default();
574 if file_name == "Cargo.toml" || file_name == "Cargo.lock" {
577 if change_kind == ChangeKind::Modify {
580 if path.extension().unwrap_or_default() != "rs" {
583 if IMPLICIT_TARGET_FILES.iter().any(|it| path.as_ref().ends_with(it)) {
586 let parent = match path.parent() {
588 None => return false,
590 if IMPLICIT_TARGET_DIRS.iter().any(|it| parent.as_ref().ends_with(it)) {
593 if file_name == "main.rs" {
594 let grand_parent = match parent.parent() {
596 None => return false,
598 if IMPLICIT_TARGET_DIRS.iter().any(|it| grand_parent.as_ref().ends_with(it)) {