1 //! Project loading & configuration updates
2 use std::{mem, sync::Arc};
4 use flycheck::{FlycheckConfig, FlycheckHandle};
6 use ide_db::base_db::{CrateGraph, SourceRoot, VfsPath};
7 use project_model::{BuildDataCollector, BuildDataResult, ProcMacroClient, ProjectWorkspace};
8 use vfs::{file_set::FileSetConfig, AbsPath, AbsPathBuf, ChangeKind};
11 config::{Config, FilesWatcher, LinkedProject},
12 global_state::{GlobalState, Status},
16 use lsp_ext::StatusParams;
19 pub(crate) enum ProjectWorkspaceProgress {
22 End(Vec<anyhow::Result<ProjectWorkspace>>),
26 pub(crate) enum BuildDataProgress {
29 End(anyhow::Result<BuildDataResult>),
33 pub(crate) fn update_configuration(&mut self, config: Config) {
34 let _p = profile::span("GlobalState::update_configuration");
35 let old_config = mem::replace(&mut self.config, Arc::new(config));
36 if self.config.lru_capacity() != old_config.lru_capacity() {
37 self.analysis_host.update_lru_capacity(self.config.lru_capacity());
39 if self.config.linked_projects() != old_config.linked_projects() {
40 self.fetch_workspaces_request()
41 } else if self.config.flycheck() != old_config.flycheck() {
42 self.reload_flycheck();
45 pub(crate) fn maybe_refresh(&mut self, changes: &[(AbsPathBuf, ChangeKind)]) {
46 if !changes.iter().any(|(path, kind)| is_interesting(path, *kind)) {
50 Status::Loading | Status::NeedsReload => return,
51 Status::Ready { .. } | Status::Invalid => (),
54 "Reloading workspace because of the following changes: {}",
58 .filter(|(path, kind)| is_interesting(path, *kind))
59 .map(|(path, kind)| format!("{}/{:?}", path.display(), kind)),
63 if self.config.cargo_autoreload() {
64 self.fetch_workspaces_request();
66 self.transition(Status::NeedsReload);
69 fn is_interesting(path: &AbsPath, change_kind: ChangeKind) -> bool {
70 const IMPLICIT_TARGET_FILES: &[&str] = &["build.rs", "src/main.rs", "src/lib.rs"];
71 const IMPLICIT_TARGET_DIRS: &[&str] = &["src/bin", "examples", "tests", "benches"];
73 if path.ends_with("Cargo.toml") || path.ends_with("Cargo.lock") {
76 if change_kind == ChangeKind::Modify {
79 if path.extension().unwrap_or_default() != "rs" {
82 if IMPLICIT_TARGET_FILES.iter().any(|it| path.ends_with(it)) {
85 let parent = match path.parent() {
89 if IMPLICIT_TARGET_DIRS.iter().any(|it| parent.ends_with(it)) {
92 if path.ends_with("main.rs") {
93 let grand_parent = match parent.parent() {
97 if IMPLICIT_TARGET_DIRS.iter().any(|it| grand_parent.ends_with(it)) {
104 pub(crate) fn transition(&mut self, new_status: Status) {
105 self.status = new_status;
106 if self.config.status_notification() {
107 let lsp_status = match new_status {
108 Status::Loading => lsp_ext::Status::Loading,
109 Status::Ready { partial: true } => lsp_ext::Status::ReadyPartial,
110 Status::Ready { partial: false } => lsp_ext::Status::Ready,
111 Status::Invalid => lsp_ext::Status::Invalid,
112 Status::NeedsReload => lsp_ext::Status::NeedsReload,
114 self.send_notification::<lsp_ext::StatusNotification>(StatusParams {
120 pub(crate) fn fetch_build_data_request(&mut self, build_data_collector: BuildDataCollector) {
121 self.fetch_build_data_queue.request_op(build_data_collector);
124 pub(crate) fn fetch_build_data_if_needed(&mut self) {
125 let mut build_data_collector = match self.fetch_build_data_queue.should_start_op() {
129 self.task_pool.handle.spawn_with_sender(move |sender| {
130 sender.send(Task::FetchBuildData(BuildDataProgress::Begin)).unwrap();
133 let sender = sender.clone();
135 sender.send(Task::FetchBuildData(BuildDataProgress::Report(msg))).unwrap()
138 let res = build_data_collector.collect(&progress);
139 sender.send(Task::FetchBuildData(BuildDataProgress::End(res))).unwrap();
142 pub(crate) fn fetch_build_data_completed(&mut self) {
143 self.fetch_build_data_queue.op_completed()
146 pub(crate) fn fetch_workspaces_request(&mut self) {
147 self.fetch_workspaces_queue.request_op(())
149 pub(crate) fn fetch_workspaces_if_needed(&mut self) {
150 if self.fetch_workspaces_queue.should_start_op().is_none() {
153 log::info!("will fetch workspaces");
155 self.task_pool.handle.spawn_with_sender({
156 let linked_projects = self.config.linked_projects();
157 let cargo_config = self.config.cargo();
161 let sender = sender.clone();
164 .send(Task::FetchWorkspace(ProjectWorkspaceProgress::Report(msg)))
169 sender.send(Task::FetchWorkspace(ProjectWorkspaceProgress::Begin)).unwrap();
171 let workspaces = linked_projects
173 .map(|project| match project {
174 LinkedProject::ProjectManifest(manifest) => {
175 project_model::ProjectWorkspace::load(
181 LinkedProject::InlineJsonProject(it) => {
182 project_model::ProjectWorkspace::load_inline(
184 cargo_config.target.as_deref(),
188 .collect::<Vec<_>>();
190 log::info!("did fetch workspaces {:?}", workspaces);
192 .send(Task::FetchWorkspace(ProjectWorkspaceProgress::End(workspaces)))
197 pub(crate) fn fetch_workspaces_completed(&mut self) {
198 self.fetch_workspaces_queue.op_completed()
201 pub(crate) fn switch_workspaces(
203 workspaces: Vec<anyhow::Result<ProjectWorkspace>>,
204 workspace_build_data: Option<anyhow::Result<BuildDataResult>>,
206 let _p = profile::span("GlobalState::switch_workspaces");
207 log::info!("will switch workspaces: {:?}", workspaces);
209 let mut has_errors = false;
210 let workspaces = workspaces
215 log::error!("failed to load workspace: {:#}", err);
216 if self.workspaces.is_empty() {
218 lsp_types::MessageType::Error,
219 format!("rust-analyzer failed to load workspace: {:#}", err),
225 .collect::<Vec<_>>();
227 let workspace_build_data = match workspace_build_data {
228 Some(Ok(it)) => Some(it),
230 log::error!("failed to fetch build data: {:#}", err);
232 lsp_types::MessageType::Error,
233 format!("rust-analyzer failed to fetch build data: {:#}", err),
240 if &*self.workspaces == &workspaces && self.workspace_build_data == workspace_build_data {
244 if !self.workspaces.is_empty() && has_errors {
248 if let FilesWatcher::Client = self.config.files().watcher {
249 if self.config.did_change_watched_files_dynamic_registration() {
250 let registration_options = lsp_types::DidChangeWatchedFilesRegistrationOptions {
253 .flat_map(|it| it.to_roots(workspace_build_data.as_ref()))
254 .filter(|it| it.is_member)
256 root.include.into_iter().map(|it| format!("{}/**/*.rs", it.display()))
258 .map(|glob_pattern| lsp_types::FileSystemWatcher {
264 let registration = lsp_types::Registration {
265 id: "workspace/didChangeWatchedFiles".to_string(),
266 method: "workspace/didChangeWatchedFiles".to_string(),
267 register_options: Some(serde_json::to_value(registration_options).unwrap()),
269 self.send_request::<lsp_types::request::RegisterCapability>(
270 lsp_types::RegistrationParams { registrations: vec![registration] },
276 let mut change = Change::new();
278 let files_config = self.config.files();
279 let project_folders =
280 ProjectFolders::new(&workspaces, &files_config.exclude, workspace_build_data.as_ref());
282 if self.proc_macro_client.is_none() {
283 self.proc_macro_client = match self.config.proc_macro_srv() {
285 Some((path, args)) => match ProcMacroClient::extern_process(path.clone(), args) {
289 "Failed to run proc_macro_srv from path {}, error: {:?}",
299 let watch = match files_config.watcher {
300 FilesWatcher::Client => vec![],
301 FilesWatcher::Notify => project_folders.watch,
303 self.vfs_config_version += 1;
304 self.loader.handle.set_config(vfs::loader::Config {
305 load: project_folders.load,
307 version: self.vfs_config_version,
310 // Create crate graph from all the workspaces
312 let mut crate_graph = CrateGraph::default();
313 let vfs = &mut self.vfs.write().0;
314 let loader = &mut self.loader;
315 let mem_docs = &self.mem_docs;
316 let mut load = |path: &AbsPath| {
317 let vfs_path = vfs::VfsPath::from(path.to_path_buf());
318 if !mem_docs.contains_key(&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 log::warn!("failed to load {}", path.display())
328 for ws in workspaces.iter() {
329 crate_graph.extend(ws.to_crate_graph(
330 workspace_build_data.as_ref(),
331 self.proc_macro_client.as_ref(),
338 change.set_crate_graph(crate_graph);
340 if self.config.load_out_dirs_from_check() && workspace_build_data.is_none() {
341 let mut collector = BuildDataCollector::default();
342 for ws in &workspaces {
343 ws.collect_build_data_configs(&mut collector);
345 self.fetch_build_data_request(collector)
348 self.source_root_config = project_folders.source_root_config;
349 self.workspaces = Arc::new(workspaces);
350 self.workspace_build_data = workspace_build_data;
352 self.analysis_host.apply_change(change);
353 self.process_changes();
354 self.reload_flycheck();
355 log::info!("did switch workspaces");
358 fn reload_flycheck(&mut self) {
359 let _p = profile::span("GlobalState::reload_flycheck");
360 let config = match self.config.flycheck() {
363 self.flycheck = Vec::new();
368 let sender = self.flycheck_sender.clone();
373 .filter_map(|(id, w)| match w {
374 ProjectWorkspace::Cargo { cargo, .. } => Some((id, cargo.workspace_root())),
375 ProjectWorkspace::Json { project, .. } => {
376 // Enable flychecks for json projects if a custom flycheck command was supplied
377 // in the workspace configuration.
379 FlycheckConfig::CustomCommand { .. } => Some((id, project.path())),
385 let sender = sender.clone();
386 FlycheckHandle::spawn(
388 Box::new(move |msg| sender.send(msg).unwrap()),
390 root.to_path_buf().into(),
398 pub(crate) struct ProjectFolders {
399 pub(crate) load: Vec<vfs::loader::Entry>,
400 pub(crate) watch: Vec<usize>,
401 pub(crate) source_root_config: SourceRootConfig,
404 impl ProjectFolders {
406 workspaces: &[ProjectWorkspace],
407 global_excludes: &[AbsPathBuf],
408 build_data: Option<&BuildDataResult>,
409 ) -> ProjectFolders {
410 let mut res = ProjectFolders::default();
411 let mut fsc = FileSetConfig::builder();
412 let mut local_filesets = vec![];
414 for root in workspaces.iter().flat_map(|it| it.to_roots(build_data)) {
415 let file_set_roots: Vec<VfsPath> =
416 root.include.iter().cloned().map(VfsPath::from).collect();
419 let mut dirs = vfs::loader::Directories::default();
420 dirs.extensions.push("rs".into());
421 dirs.include.extend(root.include);
422 dirs.exclude.extend(root.exclude);
423 for excl in global_excludes {
424 if dirs.include.iter().any(|incl| incl.starts_with(excl)) {
425 dirs.exclude.push(excl.clone());
429 vfs::loader::Entry::Directories(dirs)
433 res.watch.push(res.load.len());
435 res.load.push(entry);
438 local_filesets.push(fsc.len());
440 fsc.add_file_set(file_set_roots)
443 let fsc = fsc.build();
444 res.source_root_config = SourceRootConfig { fsc, local_filesets };
450 #[derive(Default, Debug)]
451 pub(crate) struct SourceRootConfig {
452 pub(crate) fsc: FileSetConfig,
453 pub(crate) local_filesets: Vec<usize>,
456 impl SourceRootConfig {
457 pub(crate) fn partition(&self, vfs: &vfs::Vfs) -> Vec<SourceRoot> {
458 let _p = profile::span("SourceRootConfig::partition");
463 .map(|(idx, file_set)| {
464 let is_local = self.local_filesets.contains(&idx);
466 SourceRoot::new_local(file_set)
468 SourceRoot::new_library(file_set)