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, ProcMacroKind, SourceRoot, VfsPath,
10 use proc_macro_api::ProcMacroClient;
11 use project_model::{ProjectWorkspace, WorkspaceBuildScripts};
12 use vfs::{file_set::FileSetConfig, AbsPath, AbsPathBuf, ChangeKind};
15 config::{Config, FilesWatcher, LinkedProject},
16 global_state::GlobalState,
22 pub(crate) enum ProjectWorkspaceProgress {
25 End(Vec<anyhow::Result<ProjectWorkspace>>),
29 pub(crate) enum BuildDataProgress {
32 End((Arc<Vec<ProjectWorkspace>>, Vec<anyhow::Result<WorkspaceBuildScripts>>)),
36 pub(crate) fn is_quiescent(&self) -> bool {
37 !(self.fetch_workspaces_queue.op_in_progress()
38 || self.fetch_build_data_queue.op_in_progress()
39 || self.vfs_progress_config_version < self.vfs_config_version
40 || self.vfs_progress_n_done < self.vfs_progress_n_total)
43 pub(crate) fn update_configuration(&mut self, config: Config) {
44 let _p = profile::span("GlobalState::update_configuration");
45 let old_config = mem::replace(&mut self.config, Arc::new(config));
46 if self.config.lru_capacity() != old_config.lru_capacity() {
47 self.analysis_host.update_lru_capacity(self.config.lru_capacity());
49 if self.config.linked_projects() != old_config.linked_projects() {
50 self.fetch_workspaces_request()
51 } else if self.config.flycheck() != old_config.flycheck() {
52 self.reload_flycheck();
55 // Apply experimental feature flags.
58 .set_enable_proc_attr_macros(self.config.expand_proc_attr_macros());
60 pub(crate) fn maybe_refresh(&mut self, changes: &[(AbsPathBuf, ChangeKind)]) {
61 if !changes.iter().any(|(path, kind)| is_interesting(path, *kind)) {
65 "Requesting workspace reload because of the following changes: {}",
69 .filter(|(path, kind)| is_interesting(path, *kind))
70 .map(|(path, kind)| format!("{}: {:?}", path.display(), kind)),
74 self.fetch_workspaces_request();
76 fn is_interesting(path: &AbsPath, change_kind: ChangeKind) -> bool {
77 const IMPLICIT_TARGET_FILES: &[&str] = &["build.rs", "src/main.rs", "src/lib.rs"];
78 const IMPLICIT_TARGET_DIRS: &[&str] = &["src/bin", "examples", "tests", "benches"];
79 let file_name = path.file_name().unwrap_or_default();
81 if file_name == "Cargo.toml" || file_name == "Cargo.lock" {
84 if change_kind == ChangeKind::Modify {
87 if path.extension().unwrap_or_default() != "rs" {
90 if IMPLICIT_TARGET_FILES.iter().any(|it| path.as_ref().ends_with(it)) {
93 let parent = match path.parent() {
97 if IMPLICIT_TARGET_DIRS.iter().any(|it| parent.as_ref().ends_with(it)) {
100 if file_name == "main.rs" {
101 let grand_parent = match parent.parent() {
103 None => return false,
105 if IMPLICIT_TARGET_DIRS.iter().any(|it| grand_parent.as_ref().ends_with(it)) {
112 pub(crate) fn report_new_status_if_needed(&mut self) {
113 let mut status = lsp_ext::ServerStatusParams {
114 health: lsp_ext::Health::Ok,
115 quiescent: self.is_quiescent(),
119 if let Some(error) = self.fetch_build_data_error() {
120 status.health = lsp_ext::Health::Warning;
121 status.message = Some(error)
123 if !self.config.cargo_autoreload()
124 && self.is_quiescent()
125 && self.fetch_workspaces_queue.op_requested()
127 status.health = lsp_ext::Health::Warning;
128 status.message = Some("Workspace reload required".to_string())
131 if let Some(error) = self.fetch_workspace_error() {
132 status.health = lsp_ext::Health::Error;
133 status.message = Some(error)
136 if self.last_reported_status.as_ref() != Some(&status) {
137 self.last_reported_status = Some(status.clone());
139 if let (lsp_ext::Health::Error, Some(message)) = (status.health, &status.message) {
140 self.show_message(lsp_types::MessageType::Error, message.clone());
143 if self.config.server_status_notification() {
144 self.send_notification::<lsp_ext::ServerStatusNotification>(status);
149 pub(crate) fn fetch_workspaces_request(&mut self) {
150 self.fetch_workspaces_queue.request_op()
152 pub(crate) fn fetch_workspaces_if_needed(&mut self) {
153 if !self.fetch_workspaces_queue.should_start_op() {
156 log::info!("will fetch workspaces");
158 self.task_pool.handle.spawn_with_sender({
159 let linked_projects = self.config.linked_projects();
160 let detached_files = self.config.detached_files().to_vec();
161 let cargo_config = self.config.cargo();
165 let sender = sender.clone();
168 .send(Task::FetchWorkspace(ProjectWorkspaceProgress::Report(msg)))
173 sender.send(Task::FetchWorkspace(ProjectWorkspaceProgress::Begin)).unwrap();
175 let mut workspaces = linked_projects
177 .map(|project| match project {
178 LinkedProject::ProjectManifest(manifest) => {
179 project_model::ProjectWorkspace::load(
185 LinkedProject::InlineJsonProject(it) => {
186 project_model::ProjectWorkspace::load_inline(
188 cargo_config.target.as_deref(),
192 .collect::<Vec<_>>();
194 if !detached_files.is_empty() {
196 .push(project_model::ProjectWorkspace::load_detached_files(detached_files));
199 log::info!("did fetch workspaces {:?}", workspaces);
201 .send(Task::FetchWorkspace(ProjectWorkspaceProgress::End(workspaces)))
206 pub(crate) fn fetch_workspaces_completed(
208 workspaces: Vec<anyhow::Result<ProjectWorkspace>>,
210 self.fetch_workspaces_queue.op_completed(workspaces)
213 pub(crate) fn fetch_build_data_request(&mut self) {
214 self.fetch_build_data_queue.request_op();
216 pub(crate) fn fetch_build_data_if_needed(&mut self) {
217 if !self.fetch_build_data_queue.should_start_op() {
221 let workspaces = Arc::clone(&self.workspaces);
222 let config = self.config.cargo();
223 self.task_pool.handle.spawn_with_sender(move |sender| {
224 sender.send(Task::FetchBuildData(BuildDataProgress::Begin)).unwrap();
227 let sender = sender.clone();
229 sender.send(Task::FetchBuildData(BuildDataProgress::Report(msg))).unwrap()
232 let mut res = Vec::new();
233 for ws in workspaces.iter() {
234 res.push(ws.run_build_scripts(&config, &progress));
236 sender.send(Task::FetchBuildData(BuildDataProgress::End((workspaces, res)))).unwrap();
239 pub(crate) fn fetch_build_data_completed(
241 build_data: (Arc<Vec<ProjectWorkspace>>, Vec<anyhow::Result<WorkspaceBuildScripts>>),
243 self.fetch_build_data_queue.op_completed(build_data)
246 pub(crate) fn switch_workspaces(&mut self) {
247 let _p = profile::span("GlobalState::switch_workspaces");
248 log::info!("will switch workspaces");
250 if let Some(error_message) = self.fetch_workspace_error() {
251 log::error!("failed to switch workspaces: {}", error_message);
252 if !self.workspaces.is_empty() {
253 // It only makes sense to switch to a partially broken workspace
254 // if we don't have any workspace at all yet.
259 if let Some(error_message) = self.fetch_build_data_error() {
260 log::error!("failed to switch build data: {}", error_message);
263 let workspaces = self
264 .fetch_workspaces_queue
267 .filter_map(|res| res.as_ref().ok().cloned())
268 .collect::<Vec<_>>();
270 fn eq_ignore_build_data<'a>(
271 left: &'a ProjectWorkspace,
272 right: &'a ProjectWorkspace,
274 let key = |p: &'a ProjectWorkspace| match p {
275 ProjectWorkspace::Cargo {
283 } => Some((cargo, sysroot, rustc, rustc_cfg, cfg_overrides)),
286 match (key(left), key(right)) {
287 (Some(lk), Some(rk)) => lk == rk,
292 let same_workspaces = workspaces.len() == self.workspaces.len()
295 .zip(self.workspaces.iter())
296 .all(|(l, r)| eq_ignore_build_data(l, r));
299 let (workspaces, build_scripts) = self.fetch_build_data_queue.last_op_result();
300 if Arc::ptr_eq(&workspaces, &self.workspaces) {
301 let workspaces = workspaces
305 .map(|(mut ws, bs)| {
306 ws.set_build_scripts(bs.as_ref().ok().cloned().unwrap_or_default());
309 .collect::<Vec<_>>();
311 // Workspaces are the same, but we've updated build data.
312 self.workspaces = Arc::new(workspaces);
314 // Current build scripts do not match the version of the active
315 // workspace, so there's nothing for us to update.
319 // Here, we completely changed the workspace (Cargo.toml edit), so
320 // we don't care about build-script results, they are stale.
321 self.workspaces = Arc::new(workspaces)
324 if let FilesWatcher::Client = self.config.files().watcher {
325 if self.config.did_change_watched_files_dynamic_registration() {
326 let registration_options = lsp_types::DidChangeWatchedFilesRegistrationOptions {
330 .flat_map(|ws| ws.to_roots())
331 .filter(|it| it.is_member)
333 root.include.into_iter().flat_map(|it| {
335 format!("{}/**/*.rs", it.display()),
336 format!("{}/**/Cargo.toml", it.display()),
337 format!("{}/**/Cargo.lock", it.display()),
341 .map(|glob_pattern| lsp_types::FileSystemWatcher {
347 let registration = lsp_types::Registration {
348 id: "workspace/didChangeWatchedFiles".to_string(),
349 method: "workspace/didChangeWatchedFiles".to_string(),
350 register_options: Some(serde_json::to_value(registration_options).unwrap()),
352 self.send_request::<lsp_types::request::RegisterCapability>(
353 lsp_types::RegistrationParams { registrations: vec![registration] },
359 let mut change = Change::new();
361 let files_config = self.config.files();
362 let project_folders = ProjectFolders::new(&self.workspaces, &files_config.exclude);
364 if self.proc_macro_client.is_none() {
365 self.proc_macro_client = match self.config.proc_macro_srv() {
367 Some((path, args)) => match ProcMacroClient::extern_process(path.clone(), args) {
371 "Failed to run proc_macro_srv from path {}, error: {:?}",
381 let watch = match files_config.watcher {
382 FilesWatcher::Client => vec![],
383 FilesWatcher::Notify => project_folders.watch,
385 self.vfs_config_version += 1;
386 self.loader.handle.set_config(vfs::loader::Config {
387 load: project_folders.load,
389 version: self.vfs_config_version,
392 // Create crate graph from all the workspaces
394 let proc_macro_client = self.proc_macro_client.as_ref();
395 let mut load_proc_macro =
396 move |path: &AbsPath| load_proc_macro(proc_macro_client, path);
398 let vfs = &mut self.vfs.write().0;
399 let loader = &mut self.loader;
400 let mem_docs = &self.mem_docs;
401 let mut load = move |path: &AbsPath| {
402 let _p = profile::span("GlobalState::load");
403 let vfs_path = vfs::VfsPath::from(path.to_path_buf());
404 if !mem_docs.contains(&vfs_path) {
405 let contents = loader.handle.load_sync(path);
406 vfs.set_file_contents(vfs_path.clone(), contents);
408 let res = vfs.file_id(&vfs_path);
410 log::warn!("failed to load {}", path.display())
415 let mut crate_graph = CrateGraph::default();
416 for ws in self.workspaces.iter() {
417 crate_graph.extend(ws.to_crate_graph(&mut load_proc_macro, &mut load));
421 change.set_crate_graph(crate_graph);
423 self.source_root_config = project_folders.source_root_config;
425 self.analysis_host.apply_change(change);
426 self.process_changes();
427 self.reload_flycheck();
428 log::info!("did switch workspaces");
431 fn fetch_workspace_error(&self) -> Option<String> {
432 let mut buf = String::new();
434 for ws in self.fetch_workspaces_queue.last_op_result() {
435 if let Err(err) = ws {
436 stdx::format_to!(buf, "rust-analyzer failed to load workspace: {:#}\n", err);
447 fn fetch_build_data_error(&self) -> Option<String> {
448 let mut buf = String::new();
450 for ws in &self.fetch_build_data_queue.last_op_result().1 {
451 if let Err(err) = ws {
452 stdx::format_to!(buf, "rust-analyzer failed to run custom build: {:#}\n", err);
463 fn reload_flycheck(&mut self) {
464 let _p = profile::span("GlobalState::reload_flycheck");
465 let config = match self.config.flycheck() {
468 self.flycheck = Vec::new();
473 let sender = self.flycheck_sender.clone();
478 .filter_map(|(id, w)| match w {
479 ProjectWorkspace::Cargo { cargo, .. } => Some((id, cargo.workspace_root())),
480 ProjectWorkspace::Json { project, .. } => {
481 // Enable flychecks for json projects if a custom flycheck command was supplied
482 // in the workspace configuration.
484 FlycheckConfig::CustomCommand { .. } => Some((id, project.path())),
488 ProjectWorkspace::DetachedFiles { .. } => None,
491 let sender = sender.clone();
492 FlycheckHandle::spawn(
494 Box::new(move |msg| sender.send(msg).unwrap()),
496 root.to_path_buf().into(),
504 pub(crate) struct ProjectFolders {
505 pub(crate) load: Vec<vfs::loader::Entry>,
506 pub(crate) watch: Vec<usize>,
507 pub(crate) source_root_config: SourceRootConfig,
510 impl ProjectFolders {
512 workspaces: &[ProjectWorkspace],
513 global_excludes: &[AbsPathBuf],
514 ) -> ProjectFolders {
515 let mut res = ProjectFolders::default();
516 let mut fsc = FileSetConfig::builder();
517 let mut local_filesets = vec![];
519 for root in workspaces.iter().flat_map(|ws| ws.to_roots()) {
520 let file_set_roots: Vec<VfsPath> =
521 root.include.iter().cloned().map(VfsPath::from).collect();
524 let mut dirs = vfs::loader::Directories::default();
525 dirs.extensions.push("rs".into());
526 dirs.include.extend(root.include);
527 dirs.exclude.extend(root.exclude);
528 for excl in global_excludes {
532 .any(|incl| incl.starts_with(excl) || excl.starts_with(incl))
534 dirs.exclude.push(excl.clone());
538 vfs::loader::Entry::Directories(dirs)
542 res.watch.push(res.load.len());
544 res.load.push(entry);
547 local_filesets.push(fsc.len());
549 fsc.add_file_set(file_set_roots)
552 let fsc = fsc.build();
553 res.source_root_config = SourceRootConfig { fsc, local_filesets };
559 #[derive(Default, Debug)]
560 pub(crate) struct SourceRootConfig {
561 pub(crate) fsc: FileSetConfig,
562 pub(crate) local_filesets: Vec<usize>,
565 impl SourceRootConfig {
566 pub(crate) fn partition(&self, vfs: &vfs::Vfs) -> Vec<SourceRoot> {
567 let _p = profile::span("SourceRootConfig::partition");
572 .map(|(idx, file_set)| {
573 let is_local = self.local_filesets.contains(&idx);
575 SourceRoot::new_local(file_set)
577 SourceRoot::new_library(file_set)
584 pub(crate) fn load_proc_macro(client: Option<&ProcMacroClient>, path: &AbsPath) -> Vec<ProcMacro> {
586 .map(|it| it.by_dylib_path(path))
589 .map(expander_to_proc_macro)
592 fn expander_to_proc_macro(expander: proc_macro_api::ProcMacroProcessExpander) -> ProcMacro {
593 let name = expander.name().into();
594 let kind = match expander.kind() {
595 proc_macro_api::ProcMacroKind::CustomDerive => ProcMacroKind::CustomDerive,
596 proc_macro_api::ProcMacroKind::FuncLike => ProcMacroKind::FuncLike,
597 proc_macro_api::ProcMacroKind::Attr => ProcMacroKind::Attr,
599 let expander = Arc::new(Expander(expander));
600 ProcMacro { name, kind, expander }
604 struct Expander(proc_macro_api::ProcMacroProcessExpander);
606 impl ProcMacroExpander for Expander {
609 subtree: &tt::Subtree,
610 attrs: Option<&tt::Subtree>,
612 ) -> Result<tt::Subtree, tt::ExpansionError> {
613 let env = env.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
614 self.0.expand(subtree, attrs, env)