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 => (),
53 if self.config.cargo_autoreload() {
54 self.fetch_workspaces_request();
56 self.transition(Status::NeedsReload);
59 fn is_interesting(path: &AbsPath, change_kind: ChangeKind) -> bool {
60 const IMPLICIT_TARGET_FILES: &[&str] = &["build.rs", "src/main.rs", "src/lib.rs"];
61 const IMPLICIT_TARGET_DIRS: &[&str] = &["src/bin", "examples", "tests", "benches"];
63 if path.ends_with("Cargo.toml") || path.ends_with("Cargo.lock") {
66 if change_kind == ChangeKind::Modify {
69 if path.extension().unwrap_or_default() != "rs" {
72 if IMPLICIT_TARGET_FILES.iter().any(|it| path.ends_with(it)) {
75 let parent = match path.parent() {
79 if IMPLICIT_TARGET_DIRS.iter().any(|it| parent.ends_with(it)) {
82 if path.ends_with("main.rs") {
83 let grand_parent = match parent.parent() {
87 if IMPLICIT_TARGET_DIRS.iter().any(|it| grand_parent.ends_with(it)) {
94 pub(crate) fn transition(&mut self, new_status: Status) {
95 self.status = new_status;
96 if self.config.status_notification() {
97 let lsp_status = match new_status {
98 Status::Loading => lsp_ext::Status::Loading,
99 Status::Ready { partial: true } => lsp_ext::Status::ReadyPartial,
100 Status::Ready { partial: false } => lsp_ext::Status::Ready,
101 Status::Invalid => lsp_ext::Status::Invalid,
102 Status::NeedsReload => lsp_ext::Status::NeedsReload,
104 self.send_notification::<lsp_ext::StatusNotification>(StatusParams {
110 pub(crate) fn fetch_build_data_request(&mut self, build_data_collector: BuildDataCollector) {
111 self.fetch_build_data_queue.request_op(build_data_collector);
114 pub(crate) fn fetch_build_data_if_needed(&mut self) {
115 let mut build_data_collector = match self.fetch_build_data_queue.should_start_op() {
119 self.task_pool.handle.spawn_with_sender(move |sender| {
120 sender.send(Task::FetchBuildData(BuildDataProgress::Begin)).unwrap();
123 let sender = sender.clone();
125 sender.send(Task::FetchBuildData(BuildDataProgress::Report(msg))).unwrap()
128 let res = build_data_collector.collect(&progress);
129 sender.send(Task::FetchBuildData(BuildDataProgress::End(res))).unwrap();
132 pub(crate) fn fetch_build_data_completed(&mut self) {
133 self.fetch_build_data_queue.op_completed()
136 pub(crate) fn fetch_workspaces_request(&mut self) {
137 self.fetch_workspaces_queue.request_op(())
139 pub(crate) fn fetch_workspaces_if_needed(&mut self) {
140 if self.fetch_workspaces_queue.should_start_op().is_none() {
143 log::info!("will fetch workspaces");
145 self.task_pool.handle.spawn_with_sender({
146 let linked_projects = self.config.linked_projects();
147 let cargo_config = self.config.cargo();
151 let sender = sender.clone();
154 .send(Task::FetchWorkspace(ProjectWorkspaceProgress::Report(msg)))
159 sender.send(Task::FetchWorkspace(ProjectWorkspaceProgress::Begin)).unwrap();
161 let workspaces = linked_projects
163 .map(|project| match project {
164 LinkedProject::ProjectManifest(manifest) => {
165 project_model::ProjectWorkspace::load(
171 LinkedProject::InlineJsonProject(it) => {
172 project_model::ProjectWorkspace::load_inline(
174 cargo_config.target.as_deref(),
178 .collect::<Vec<_>>();
180 log::info!("did fetch workspaces {:?}", workspaces);
182 .send(Task::FetchWorkspace(ProjectWorkspaceProgress::End(workspaces)))
187 pub(crate) fn fetch_workspaces_completed(&mut self) {
188 self.fetch_workspaces_queue.op_completed()
191 pub(crate) fn switch_workspaces(
193 workspaces: Vec<anyhow::Result<ProjectWorkspace>>,
194 workspace_build_data: Option<anyhow::Result<BuildDataResult>>,
196 let _p = profile::span("GlobalState::switch_workspaces");
197 log::info!("will switch workspaces: {:?}", workspaces);
199 let mut has_errors = false;
200 let workspaces = workspaces
205 log::error!("failed to load workspace: {:#}", err);
206 if self.workspaces.is_empty() {
208 lsp_types::MessageType::Error,
209 format!("rust-analyzer failed to load workspace: {:#}", err),
215 .collect::<Vec<_>>();
217 let workspace_build_data = match workspace_build_data {
218 Some(Ok(it)) => Some(it),
220 log::error!("failed to fetch build data: {:#}", err);
222 lsp_types::MessageType::Error,
223 format!("rust-analyzer failed to fetch build data: {:#}", err),
230 if &*self.workspaces == &workspaces && self.workspace_build_data == workspace_build_data {
234 if !self.workspaces.is_empty() && has_errors {
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 {
243 .flat_map(|it| it.to_roots(workspace_build_data.as_ref()))
244 .filter(|it| it.is_member)
246 root.include.into_iter().map(|it| format!("{}/**/*.rs", it.display()))
248 .map(|glob_pattern| lsp_types::FileSystemWatcher {
254 let registration = lsp_types::Registration {
255 id: "workspace/didChangeWatchedFiles".to_string(),
256 method: "workspace/didChangeWatchedFiles".to_string(),
257 register_options: Some(serde_json::to_value(registration_options).unwrap()),
259 self.send_request::<lsp_types::request::RegisterCapability>(
260 lsp_types::RegistrationParams { registrations: vec![registration] },
266 let mut change = Change::new();
268 let files_config = self.config.files();
269 let project_folders =
270 ProjectFolders::new(&workspaces, &files_config.exclude, workspace_build_data.as_ref());
272 if self.proc_macro_client.is_none() {
273 self.proc_macro_client = match self.config.proc_macro_srv() {
275 Some((path, args)) => match ProcMacroClient::extern_process(path.clone(), args) {
279 "Failed to run proc_macro_srv from path {}, error: {:?}",
289 let watch = match files_config.watcher {
290 FilesWatcher::Client => vec![],
291 FilesWatcher::Notify => project_folders.watch,
293 self.loader.handle.set_config(vfs::loader::Config { load: project_folders.load, watch });
295 // Create crate graph from all the workspaces
297 let mut crate_graph = CrateGraph::default();
298 let vfs = &mut self.vfs.write().0;
299 let loader = &mut self.loader;
300 let mem_docs = &self.mem_docs;
301 let mut load = |path: &AbsPath| {
302 let vfs_path = vfs::VfsPath::from(path.to_path_buf());
303 if !mem_docs.contains_key(&vfs_path) {
304 let contents = loader.handle.load_sync(path);
305 vfs.set_file_contents(vfs_path.clone(), contents);
307 let res = vfs.file_id(&vfs_path);
309 log::warn!("failed to load {}", path.display())
313 for ws in workspaces.iter() {
314 crate_graph.extend(ws.to_crate_graph(
315 workspace_build_data.as_ref(),
316 self.proc_macro_client.as_ref(),
323 change.set_crate_graph(crate_graph);
325 if self.config.load_out_dirs_from_check() && workspace_build_data.is_none() {
326 let mut collector = BuildDataCollector::default();
327 for ws in &workspaces {
328 ws.collect_build_data_configs(&mut collector);
330 self.fetch_build_data_request(collector)
333 self.source_root_config = project_folders.source_root_config;
334 self.workspaces = Arc::new(workspaces);
335 self.workspace_build_data = workspace_build_data;
337 self.analysis_host.apply_change(change);
338 self.process_changes();
339 self.reload_flycheck();
340 log::info!("did switch workspaces");
343 fn reload_flycheck(&mut self) {
344 let _p = profile::span("GlobalState::reload_flycheck");
345 let config = match self.config.flycheck() {
348 self.flycheck = Vec::new();
353 let sender = self.flycheck_sender.clone();
358 .filter_map(|(id, w)| match w {
359 ProjectWorkspace::Cargo { cargo, .. } => Some((id, cargo.workspace_root())),
360 ProjectWorkspace::Json { project, .. } => {
361 // Enable flychecks for json projects if a custom flycheck command was supplied
362 // in the workspace configuration.
364 FlycheckConfig::CustomCommand { .. } => Some((id, project.path())),
370 let sender = sender.clone();
371 FlycheckHandle::spawn(
373 Box::new(move |msg| sender.send(msg).unwrap()),
375 root.to_path_buf().into(),
383 pub(crate) struct ProjectFolders {
384 pub(crate) load: Vec<vfs::loader::Entry>,
385 pub(crate) watch: Vec<usize>,
386 pub(crate) source_root_config: SourceRootConfig,
389 impl ProjectFolders {
391 workspaces: &[ProjectWorkspace],
392 global_excludes: &[AbsPathBuf],
393 build_data: Option<&BuildDataResult>,
394 ) -> ProjectFolders {
395 let mut res = ProjectFolders::default();
396 let mut fsc = FileSetConfig::builder();
397 let mut local_filesets = vec![];
399 for root in workspaces.iter().flat_map(|it| it.to_roots(build_data)) {
400 let file_set_roots: Vec<VfsPath> =
401 root.include.iter().cloned().map(VfsPath::from).collect();
404 let mut dirs = vfs::loader::Directories::default();
405 dirs.extensions.push("rs".into());
406 dirs.include.extend(root.include);
407 dirs.exclude.extend(root.exclude);
408 for excl in global_excludes {
409 if dirs.include.iter().any(|incl| incl.starts_with(excl)) {
410 dirs.exclude.push(excl.clone());
414 vfs::loader::Entry::Directories(dirs)
418 res.watch.push(res.load.len());
420 res.load.push(entry);
423 local_filesets.push(fsc.len());
425 fsc.add_file_set(file_set_roots)
428 let fsc = fsc.build();
429 res.source_root_config = SourceRootConfig { fsc, local_filesets };
435 #[derive(Default, Debug)]
436 pub(crate) struct SourceRootConfig {
437 pub(crate) fsc: FileSetConfig,
438 pub(crate) local_filesets: Vec<usize>,
441 impl SourceRootConfig {
442 pub(crate) fn partition(&self, vfs: &vfs::Vfs) -> Vec<SourceRoot> {
443 let _p = profile::span("SourceRootConfig::partition");
448 .map(|(idx, file_set)| {
449 let is_local = self.local_filesets.contains(&idx);
451 SourceRoot::new_local(file_set)
453 SourceRoot::new_library(file_set)