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 ProjectWorkspace::Cargo { cargo, .. } => cargo,
237 ProjectWorkspace::DetachedFiles { .. } | ProjectWorkspace::Json { .. } => {
238 res.push(Ok(WorkspaceBuildScripts::default()));
242 res.push(WorkspaceBuildScripts::run(&config, ws, &progress))
244 sender.send(Task::FetchBuildData(BuildDataProgress::End((workspaces, res)))).unwrap();
247 pub(crate) fn fetch_build_data_completed(
249 build_data: (Arc<Vec<ProjectWorkspace>>, Vec<anyhow::Result<WorkspaceBuildScripts>>),
251 self.fetch_build_data_queue.op_completed(build_data)
254 pub(crate) fn switch_workspaces(&mut self) {
255 let _p = profile::span("GlobalState::switch_workspaces");
256 log::info!("will switch workspaces");
258 if let Some(error_message) = self.fetch_workspace_error() {
259 log::error!("failed to switch workspaces: {}", error_message);
260 if !self.workspaces.is_empty() {
261 // It only makes sense to switch to a partially broken workspace
262 // if we don't have any workspace at all yet.
267 if let Some(error_message) = self.fetch_build_data_error() {
268 log::error!("failed to switch build data: {}", error_message);
271 let workspaces = self
272 .fetch_workspaces_queue
275 .filter_map(|res| res.as_ref().ok().cloned())
276 .collect::<Vec<_>>();
278 fn eq_ignore_build_data<'a>(
279 left: &'a ProjectWorkspace,
280 right: &'a ProjectWorkspace,
282 let key = |p: &'a ProjectWorkspace| match p {
283 ProjectWorkspace::Cargo {
291 } => Some((cargo, sysroot, rustc, rustc_cfg, cfg_overrides)),
294 match (key(left), key(right)) {
295 (Some(lk), Some(rk)) => lk == rk,
300 let same_workspaces = workspaces.len() == self.workspaces.len()
303 .zip(self.workspaces.iter())
304 .all(|(l, r)| eq_ignore_build_data(l, r));
307 let (workspaces, build_scripts) = self.fetch_build_data_queue.last_op_result();
308 if Arc::ptr_eq(&workspaces, &self.workspaces) {
309 let workspaces = workspaces
313 .map(|(mut ws, bs)| {
314 ws.set_build_scripts(bs.as_ref().ok().cloned().unwrap_or_default());
317 .collect::<Vec<_>>();
319 // Workspaces are the same, but we've updated build data.
320 self.workspaces = Arc::new(workspaces);
322 // Current build scripts do not match the version of the active
323 // workspace, so there's nothing for us to update.
327 // Here, we completely changed the workspace (Cargo.toml edit), so
328 // we don't care about build-script results, they are stale.
329 self.workspaces = Arc::new(workspaces)
332 if let FilesWatcher::Client = self.config.files().watcher {
333 if self.config.did_change_watched_files_dynamic_registration() {
334 let registration_options = lsp_types::DidChangeWatchedFilesRegistrationOptions {
338 .flat_map(|ws| ws.to_roots())
339 .filter(|it| it.is_member)
341 root.include.into_iter().flat_map(|it| {
343 format!("{}/**/*.rs", it.display()),
344 format!("{}/**/Cargo.toml", it.display()),
345 format!("{}/**/Cargo.lock", it.display()),
349 .map(|glob_pattern| lsp_types::FileSystemWatcher {
355 let registration = lsp_types::Registration {
356 id: "workspace/didChangeWatchedFiles".to_string(),
357 method: "workspace/didChangeWatchedFiles".to_string(),
358 register_options: Some(serde_json::to_value(registration_options).unwrap()),
360 self.send_request::<lsp_types::request::RegisterCapability>(
361 lsp_types::RegistrationParams { registrations: vec![registration] },
367 let mut change = Change::new();
369 let files_config = self.config.files();
370 let project_folders = ProjectFolders::new(&self.workspaces, &files_config.exclude);
372 if self.proc_macro_client.is_none() {
373 self.proc_macro_client = match self.config.proc_macro_srv() {
375 Some((path, args)) => match ProcMacroClient::extern_process(path.clone(), args) {
379 "Failed to run proc_macro_srv from path {}, error: {:?}",
389 let watch = match files_config.watcher {
390 FilesWatcher::Client => vec![],
391 FilesWatcher::Notify => project_folders.watch,
393 self.vfs_config_version += 1;
394 self.loader.handle.set_config(vfs::loader::Config {
395 load: project_folders.load,
397 version: self.vfs_config_version,
400 // Create crate graph from all the workspaces
402 let proc_macro_client = self.proc_macro_client.as_ref();
403 let mut load_proc_macro =
404 move |path: &AbsPath| load_proc_macro(proc_macro_client, path);
406 let vfs = &mut self.vfs.write().0;
407 let loader = &mut self.loader;
408 let mem_docs = &self.mem_docs;
409 let mut load = move |path: &AbsPath| {
410 let _p = profile::span("GlobalState::load");
411 let vfs_path = vfs::VfsPath::from(path.to_path_buf());
412 if !mem_docs.contains(&vfs_path) {
413 let contents = loader.handle.load_sync(path);
414 vfs.set_file_contents(vfs_path.clone(), contents);
416 let res = vfs.file_id(&vfs_path);
418 log::warn!("failed to load {}", path.display())
423 let mut crate_graph = CrateGraph::default();
424 for ws in self.workspaces.iter() {
425 crate_graph.extend(ws.to_crate_graph(&mut load_proc_macro, &mut load));
429 change.set_crate_graph(crate_graph);
431 self.source_root_config = project_folders.source_root_config;
433 self.analysis_host.apply_change(change);
434 self.process_changes();
435 self.reload_flycheck();
436 log::info!("did switch workspaces");
439 fn fetch_workspace_error(&self) -> Option<String> {
440 let mut buf = String::new();
442 for ws in self.fetch_workspaces_queue.last_op_result() {
443 if let Err(err) = ws {
444 stdx::format_to!(buf, "rust-analyzer failed to load workspace: {:#}\n", err);
455 fn fetch_build_data_error(&self) -> Option<String> {
456 let mut buf = String::new();
458 for ws in &self.fetch_build_data_queue.last_op_result().1 {
459 if let Err(err) = ws {
460 stdx::format_to!(buf, "rust-analyzer failed to run custom build: {:#}\n", err);
471 fn reload_flycheck(&mut self) {
472 let _p = profile::span("GlobalState::reload_flycheck");
473 let config = match self.config.flycheck() {
476 self.flycheck = Vec::new();
481 let sender = self.flycheck_sender.clone();
486 .filter_map(|(id, w)| match w {
487 ProjectWorkspace::Cargo { cargo, .. } => Some((id, cargo.workspace_root())),
488 ProjectWorkspace::Json { project, .. } => {
489 // Enable flychecks for json projects if a custom flycheck command was supplied
490 // in the workspace configuration.
492 FlycheckConfig::CustomCommand { .. } => Some((id, project.path())),
496 ProjectWorkspace::DetachedFiles { .. } => None,
499 let sender = sender.clone();
500 FlycheckHandle::spawn(
502 Box::new(move |msg| sender.send(msg).unwrap()),
504 root.to_path_buf().into(),
512 pub(crate) struct ProjectFolders {
513 pub(crate) load: Vec<vfs::loader::Entry>,
514 pub(crate) watch: Vec<usize>,
515 pub(crate) source_root_config: SourceRootConfig,
518 impl ProjectFolders {
520 workspaces: &[ProjectWorkspace],
521 global_excludes: &[AbsPathBuf],
522 ) -> ProjectFolders {
523 let mut res = ProjectFolders::default();
524 let mut fsc = FileSetConfig::builder();
525 let mut local_filesets = vec![];
527 for root in workspaces.iter().flat_map(|ws| ws.to_roots()) {
528 let file_set_roots: Vec<VfsPath> =
529 root.include.iter().cloned().map(VfsPath::from).collect();
532 let mut dirs = vfs::loader::Directories::default();
533 dirs.extensions.push("rs".into());
534 dirs.include.extend(root.include);
535 dirs.exclude.extend(root.exclude);
536 for excl in global_excludes {
540 .any(|incl| incl.starts_with(excl) || excl.starts_with(incl))
542 dirs.exclude.push(excl.clone());
546 vfs::loader::Entry::Directories(dirs)
550 res.watch.push(res.load.len());
552 res.load.push(entry);
555 local_filesets.push(fsc.len());
557 fsc.add_file_set(file_set_roots)
560 let fsc = fsc.build();
561 res.source_root_config = SourceRootConfig { fsc, local_filesets };
567 #[derive(Default, Debug)]
568 pub(crate) struct SourceRootConfig {
569 pub(crate) fsc: FileSetConfig,
570 pub(crate) local_filesets: Vec<usize>,
573 impl SourceRootConfig {
574 pub(crate) fn partition(&self, vfs: &vfs::Vfs) -> Vec<SourceRoot> {
575 let _p = profile::span("SourceRootConfig::partition");
580 .map(|(idx, file_set)| {
581 let is_local = self.local_filesets.contains(&idx);
583 SourceRoot::new_local(file_set)
585 SourceRoot::new_library(file_set)
592 pub(crate) fn load_proc_macro(client: Option<&ProcMacroClient>, path: &AbsPath) -> Vec<ProcMacro> {
594 .map(|it| it.by_dylib_path(path))
597 .map(expander_to_proc_macro)
600 fn expander_to_proc_macro(expander: proc_macro_api::ProcMacroProcessExpander) -> ProcMacro {
601 let name = expander.name().into();
602 let kind = match expander.kind() {
603 proc_macro_api::ProcMacroKind::CustomDerive => ProcMacroKind::CustomDerive,
604 proc_macro_api::ProcMacroKind::FuncLike => ProcMacroKind::FuncLike,
605 proc_macro_api::ProcMacroKind::Attr => ProcMacroKind::Attr,
607 let expander = Arc::new(Expander(expander));
608 ProcMacro { name, kind, expander }
612 struct Expander(proc_macro_api::ProcMacroProcessExpander);
614 impl ProcMacroExpander for Expander {
617 subtree: &tt::Subtree,
618 attrs: Option<&tt::Subtree>,
620 ) -> Result<tt::Subtree, tt::ExpansionError> {
621 let env = env.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
622 self.0.expand(subtree, attrs, env)