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_queue.request_op()
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_queue.request_op();
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)) {
113 pub(crate) fn current_status(&self) -> lsp_ext::ServerStatusParams {
114 let mut status = lsp_ext::ServerStatusParams {
115 health: lsp_ext::Health::Ok,
116 quiescent: self.is_quiescent(),
120 if let Some(error) = self.fetch_build_data_error() {
121 status.health = lsp_ext::Health::Warning;
122 status.message = Some(error)
124 if !self.config.cargo_autoreload()
125 && self.is_quiescent()
126 && self.fetch_workspaces_queue.op_requested()
128 status.health = lsp_ext::Health::Warning;
129 status.message = Some("Workspace reload required".to_string())
132 if let Some(error) = self.fetch_workspace_error() {
133 status.health = lsp_ext::Health::Error;
134 status.message = Some(error)
139 pub(crate) fn fetch_workspaces(&mut self) {
140 tracing::info!("will fetch workspaces");
142 self.task_pool.handle.spawn_with_sender({
143 let linked_projects = self.config.linked_projects();
144 let detached_files = self.config.detached_files().to_vec();
145 let cargo_config = self.config.cargo();
149 let sender = sender.clone();
152 .send(Task::FetchWorkspace(ProjectWorkspaceProgress::Report(msg)))
157 sender.send(Task::FetchWorkspace(ProjectWorkspaceProgress::Begin)).unwrap();
159 let mut workspaces = linked_projects
161 .map(|project| match project {
162 LinkedProject::ProjectManifest(manifest) => {
163 project_model::ProjectWorkspace::load(
169 LinkedProject::InlineJsonProject(it) => {
170 project_model::ProjectWorkspace::load_inline(
172 cargo_config.target.as_deref(),
176 .collect::<Vec<_>>();
178 if !detached_files.is_empty() {
180 .push(project_model::ProjectWorkspace::load_detached_files(detached_files));
183 tracing::info!("did fetch workspaces {:?}", workspaces);
185 .send(Task::FetchWorkspace(ProjectWorkspaceProgress::End(workspaces)))
191 pub(crate) fn fetch_build_data(&mut self) {
192 let workspaces = Arc::clone(&self.workspaces);
193 let config = self.config.cargo();
194 self.task_pool.handle.spawn_with_sender(move |sender| {
195 sender.send(Task::FetchBuildData(BuildDataProgress::Begin)).unwrap();
198 let sender = sender.clone();
200 sender.send(Task::FetchBuildData(BuildDataProgress::Report(msg))).unwrap()
203 let mut res = Vec::new();
204 for ws in workspaces.iter() {
205 res.push(ws.run_build_scripts(&config, &progress));
207 sender.send(Task::FetchBuildData(BuildDataProgress::End((workspaces, res)))).unwrap();
211 pub(crate) fn switch_workspaces(&mut self) {
212 let _p = profile::span("GlobalState::switch_workspaces");
213 tracing::info!("will switch workspaces");
215 if let Some(error_message) = self.fetch_workspace_error() {
216 tracing::error!("failed to switch workspaces: {}", error_message);
217 if !self.workspaces.is_empty() {
218 // It only makes sense to switch to a partially broken workspace
219 // if we don't have any workspace at all yet.
224 if let Some(error_message) = self.fetch_build_data_error() {
225 tracing::error!("failed to switch build data: {}", error_message);
228 let workspaces = self
229 .fetch_workspaces_queue
232 .filter_map(|res| res.as_ref().ok().cloned())
233 .collect::<Vec<_>>();
235 fn eq_ignore_build_data<'a>(
236 left: &'a ProjectWorkspace,
237 right: &'a ProjectWorkspace,
239 let key = |p: &'a ProjectWorkspace| match p {
240 ProjectWorkspace::Cargo {
248 } => Some((cargo, sysroot, rustc, rustc_cfg, cfg_overrides)),
251 match (key(left), key(right)) {
252 (Some(lk), Some(rk)) => lk == rk,
257 let same_workspaces = workspaces.len() == self.workspaces.len()
260 .zip(self.workspaces.iter())
261 .all(|(l, r)| eq_ignore_build_data(l, r));
264 let (workspaces, build_scripts) = self.fetch_build_data_queue.last_op_result();
265 if Arc::ptr_eq(&workspaces, &self.workspaces) {
266 let workspaces = workspaces
270 .map(|(mut ws, bs)| {
271 ws.set_build_scripts(bs.as_ref().ok().cloned().unwrap_or_default());
274 .collect::<Vec<_>>();
276 // Workspaces are the same, but we've updated build data.
277 self.workspaces = Arc::new(workspaces);
279 // Current build scripts do not match the version of the active
280 // workspace, so there's nothing for us to update.
284 // Here, we completely changed the workspace (Cargo.toml edit), so
285 // we don't care about build-script results, they are stale.
286 self.workspaces = Arc::new(workspaces)
289 if let FilesWatcher::Client = self.config.files().watcher {
290 if self.config.did_change_watched_files_dynamic_registration() {
291 let registration_options = lsp_types::DidChangeWatchedFilesRegistrationOptions {
295 .flat_map(|ws| ws.to_roots())
296 .filter(|it| it.is_member)
298 root.include.into_iter().flat_map(|it| {
300 format!("{}/**/*.rs", it.display()),
301 format!("{}/**/Cargo.toml", it.display()),
302 format!("{}/**/Cargo.lock", it.display()),
306 .map(|glob_pattern| lsp_types::FileSystemWatcher {
312 let registration = lsp_types::Registration {
313 id: "workspace/didChangeWatchedFiles".to_string(),
314 method: "workspace/didChangeWatchedFiles".to_string(),
315 register_options: Some(serde_json::to_value(registration_options).unwrap()),
317 self.send_request::<lsp_types::request::RegisterCapability>(
318 lsp_types::RegistrationParams { registrations: vec![registration] },
324 let mut change = Change::new();
326 let files_config = self.config.files();
327 let project_folders = ProjectFolders::new(&self.workspaces, &files_config.exclude);
329 if self.proc_macro_client.is_none() {
330 self.proc_macro_client = match self.config.proc_macro_srv() {
332 Some((path, args)) => match ProcMacroClient::extern_process(path.clone(), args) {
336 "Failed to run proc_macro_srv from path {}, error: {:?}",
346 let watch = match files_config.watcher {
347 FilesWatcher::Client => vec![],
348 FilesWatcher::Notify => project_folders.watch,
350 self.vfs_config_version += 1;
351 self.loader.handle.set_config(vfs::loader::Config {
352 load: project_folders.load,
354 version: self.vfs_config_version,
357 // Create crate graph from all the workspaces
359 let proc_macro_client = self.proc_macro_client.as_ref();
360 let mut load_proc_macro =
361 move |path: &AbsPath| load_proc_macro(proc_macro_client, path);
363 let vfs = &mut self.vfs.write().0;
364 let loader = &mut self.loader;
365 let mem_docs = &self.mem_docs;
366 let mut load = move |path: &AbsPath| {
367 let _p = profile::span("GlobalState::load");
368 let vfs_path = vfs::VfsPath::from(path.to_path_buf());
369 if !mem_docs.contains(&vfs_path) {
370 let contents = loader.handle.load_sync(path);
371 vfs.set_file_contents(vfs_path.clone(), contents);
373 let res = vfs.file_id(&vfs_path);
375 tracing::warn!("failed to load {}", path.display())
380 let mut crate_graph = CrateGraph::default();
381 for ws in self.workspaces.iter() {
382 crate_graph.extend(ws.to_crate_graph(&mut load_proc_macro, &mut load));
386 change.set_crate_graph(crate_graph);
388 self.source_root_config = project_folders.source_root_config;
390 self.analysis_host.apply_change(change);
391 self.process_changes();
392 self.reload_flycheck();
393 tracing::info!("did switch workspaces");
396 fn fetch_workspace_error(&self) -> Option<String> {
397 let mut buf = String::new();
399 for ws in self.fetch_workspaces_queue.last_op_result() {
400 if let Err(err) = ws {
401 stdx::format_to!(buf, "rust-analyzer failed to load workspace: {:#}\n", err);
412 fn fetch_build_data_error(&self) -> Option<String> {
413 let mut buf = "rust-analyzer failed to run build scripts:\n".to_string();
414 let mut has_errors = false;
416 for ws in &self.fetch_build_data_queue.last_op_result().1 {
419 if let Some(err) = data.error() {
421 stdx::format_to!(buf, "{:#}\n", err);
426 stdx::format_to!(buf, "{:#}\n", err);
438 fn reload_flycheck(&mut self) {
439 let _p = profile::span("GlobalState::reload_flycheck");
440 let config = match self.config.flycheck() {
443 self.flycheck = Vec::new();
448 let sender = self.flycheck_sender.clone();
453 .filter_map(|(id, w)| match w {
454 ProjectWorkspace::Cargo { cargo, .. } => Some((id, cargo.workspace_root())),
455 ProjectWorkspace::Json { project, .. } => {
456 // Enable flychecks for json projects if a custom flycheck command was supplied
457 // in the workspace configuration.
459 FlycheckConfig::CustomCommand { .. } => Some((id, project.path())),
463 ProjectWorkspace::DetachedFiles { .. } => None,
466 let sender = sender.clone();
467 FlycheckHandle::spawn(
469 Box::new(move |msg| sender.send(msg).unwrap()),
471 root.to_path_buf().into(),
479 pub(crate) struct ProjectFolders {
480 pub(crate) load: Vec<vfs::loader::Entry>,
481 pub(crate) watch: Vec<usize>,
482 pub(crate) source_root_config: SourceRootConfig,
485 impl ProjectFolders {
487 workspaces: &[ProjectWorkspace],
488 global_excludes: &[AbsPathBuf],
489 ) -> ProjectFolders {
490 let mut res = ProjectFolders::default();
491 let mut fsc = FileSetConfig::builder();
492 let mut local_filesets = vec![];
494 for root in workspaces.iter().flat_map(|ws| ws.to_roots()) {
495 let file_set_roots: Vec<VfsPath> =
496 root.include.iter().cloned().map(VfsPath::from).collect();
499 let mut dirs = vfs::loader::Directories::default();
500 dirs.extensions.push("rs".into());
501 dirs.include.extend(root.include);
502 dirs.exclude.extend(root.exclude);
503 for excl in global_excludes {
507 .any(|incl| incl.starts_with(excl) || excl.starts_with(incl))
509 dirs.exclude.push(excl.clone());
513 vfs::loader::Entry::Directories(dirs)
517 res.watch.push(res.load.len());
519 res.load.push(entry);
522 local_filesets.push(fsc.len());
524 fsc.add_file_set(file_set_roots)
527 let fsc = fsc.build();
528 res.source_root_config = SourceRootConfig { fsc, local_filesets };
534 #[derive(Default, Debug)]
535 pub(crate) struct SourceRootConfig {
536 pub(crate) fsc: FileSetConfig,
537 pub(crate) local_filesets: Vec<usize>,
540 impl SourceRootConfig {
541 pub(crate) fn partition(&self, vfs: &vfs::Vfs) -> Vec<SourceRoot> {
542 let _p = profile::span("SourceRootConfig::partition");
547 .map(|(idx, file_set)| {
548 let is_local = self.local_filesets.contains(&idx);
550 SourceRoot::new_local(file_set)
552 SourceRoot::new_library(file_set)
559 pub(crate) fn load_proc_macro(client: Option<&ProcMacroClient>, path: &AbsPath) -> Vec<ProcMacro> {
561 .map(|it| it.by_dylib_path(path))
564 .map(expander_to_proc_macro)
567 fn expander_to_proc_macro(expander: proc_macro_api::ProcMacroProcessExpander) -> ProcMacro {
568 let name = expander.name().into();
569 let kind = match expander.kind() {
570 proc_macro_api::ProcMacroKind::CustomDerive => ProcMacroKind::CustomDerive,
571 proc_macro_api::ProcMacroKind::FuncLike => ProcMacroKind::FuncLike,
572 proc_macro_api::ProcMacroKind::Attr => ProcMacroKind::Attr,
574 let expander = Arc::new(Expander(expander));
575 ProcMacro { name, kind, expander }
579 struct Expander(proc_macro_api::ProcMacroProcessExpander);
581 impl ProcMacroExpander for Expander {
584 subtree: &tt::Subtree,
585 attrs: Option<&tt::Subtree>,
587 ) -> Result<tt::Subtree, tt::ExpansionError> {
588 let env = env.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
589 self.0.expand(subtree, attrs, env)