]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/reload.rs
Merge #9242
[rust.git] / crates / rust-analyzer / src / reload.rs
1 //! Project loading & configuration updates
2 use std::{mem, sync::Arc};
3
4 use flycheck::{FlycheckConfig, FlycheckHandle};
5 use hir::db::DefDatabase;
6 use ide::Change;
7 use ide_db::base_db::{CrateGraph, SourceRoot, VfsPath};
8 use project_model::{BuildDataCollector, BuildDataResult, ProcMacroClient, ProjectWorkspace};
9 use vfs::{file_set::FileSetConfig, AbsPath, AbsPathBuf, ChangeKind};
10
11 use crate::{
12     config::{Config, FilesWatcher, LinkedProject},
13     global_state::GlobalState,
14     lsp_ext,
15     main_loop::Task,
16 };
17
18 #[derive(Debug)]
19 pub(crate) enum ProjectWorkspaceProgress {
20     Begin,
21     Report(String),
22     End(Vec<anyhow::Result<ProjectWorkspace>>),
23 }
24
25 #[derive(Debug)]
26 pub(crate) enum BuildDataProgress {
27     Begin,
28     Report(String),
29     End(anyhow::Result<BuildDataResult>),
30 }
31
32 impl GlobalState {
33     pub(crate) fn is_quiescent(&self) -> bool {
34         !(self.fetch_workspaces_queue.op_in_progress()
35             || self.fetch_build_data_queue.op_in_progress()
36             || self.vfs_progress_config_version < self.vfs_config_version
37             || self.vfs_progress_n_done < self.vfs_progress_n_total)
38     }
39
40     pub(crate) fn update_configuration(&mut self, config: Config) {
41         let _p = profile::span("GlobalState::update_configuration");
42         let old_config = mem::replace(&mut self.config, Arc::new(config));
43         if self.config.lru_capacity() != old_config.lru_capacity() {
44             self.analysis_host.update_lru_capacity(self.config.lru_capacity());
45         }
46         if self.config.linked_projects() != old_config.linked_projects() {
47             self.fetch_workspaces_request()
48         } else if self.config.flycheck() != old_config.flycheck() {
49             self.reload_flycheck();
50         }
51
52         // Apply experimental feature flags.
53         self.analysis_host
54             .raw_database_mut()
55             .set_enable_proc_attr_macros(self.config.expand_proc_attr_macros());
56     }
57     pub(crate) fn maybe_refresh(&mut self, changes: &[(AbsPathBuf, ChangeKind)]) {
58         if !changes.iter().any(|(path, kind)| is_interesting(path, *kind)) {
59             return;
60         }
61         log::info!(
62             "Requesting workspace reload because of the following changes: {}",
63             itertools::join(
64                 changes
65                     .iter()
66                     .filter(|(path, kind)| is_interesting(path, *kind))
67                     .map(|(path, kind)| format!("{}: {:?}", path.display(), kind)),
68                 ", "
69             )
70         );
71         self.fetch_workspaces_request();
72
73         fn is_interesting(path: &AbsPath, change_kind: ChangeKind) -> bool {
74             const IMPLICIT_TARGET_FILES: &[&str] = &["build.rs", "src/main.rs", "src/lib.rs"];
75             const IMPLICIT_TARGET_DIRS: &[&str] = &["src/bin", "examples", "tests", "benches"];
76
77             if path.ends_with("Cargo.toml") || path.ends_with("Cargo.lock") {
78                 return true;
79             }
80             if change_kind == ChangeKind::Modify {
81                 return false;
82             }
83             if path.extension().unwrap_or_default() != "rs" {
84                 return false;
85             }
86             if IMPLICIT_TARGET_FILES.iter().any(|it| path.ends_with(it)) {
87                 return true;
88             }
89             let parent = match path.parent() {
90                 Some(it) => it,
91                 None => return false,
92             };
93             if IMPLICIT_TARGET_DIRS.iter().any(|it| parent.ends_with(it)) {
94                 return true;
95             }
96             if path.ends_with("main.rs") {
97                 let grand_parent = match parent.parent() {
98                     Some(it) => it,
99                     None => return false,
100                 };
101                 if IMPLICIT_TARGET_DIRS.iter().any(|it| grand_parent.ends_with(it)) {
102                     return true;
103                 }
104             }
105             false
106         }
107     }
108     pub(crate) fn report_new_status_if_needed(&mut self) {
109         let mut status = lsp_ext::ServerStatusParams {
110             health: lsp_ext::Health::Ok,
111             quiescent: self.is_quiescent(),
112             message: None,
113         };
114
115         if let Some(error) = self.build_data_error() {
116             status.health = lsp_ext::Health::Warning;
117             status.message = Some(error)
118         }
119         if !self.config.cargo_autoreload()
120             && self.is_quiescent()
121             && self.fetch_workspaces_queue.op_requested()
122         {
123             status.health = lsp_ext::Health::Warning;
124             status.message = Some("Workspace reload required".to_string())
125         }
126
127         if let Some(error) = self.fetch_workspace_error() {
128             status.health = lsp_ext::Health::Error;
129             status.message = Some(error)
130         }
131
132         if self.last_reported_status.as_ref() != Some(&status) {
133             self.last_reported_status = Some(status.clone());
134
135             if let (lsp_ext::Health::Error, Some(message)) = (status.health, &status.message) {
136                 self.show_message(lsp_types::MessageType::Error, message.clone());
137             }
138
139             if self.config.server_status_notification() {
140                 self.send_notification::<lsp_ext::ServerStatusNotification>(status);
141             }
142         }
143     }
144
145     pub(crate) fn fetch_workspaces_request(&mut self) {
146         self.fetch_workspaces_queue.request_op(())
147     }
148     pub(crate) fn fetch_workspaces_if_needed(&mut self) {
149         if self.fetch_workspaces_queue.should_start_op().is_none() {
150             return;
151         }
152         log::info!("will fetch workspaces");
153
154         self.task_pool.handle.spawn_with_sender({
155             let linked_projects = self.config.linked_projects();
156             let detached_files = self.config.detached_files().to_vec();
157             let cargo_config = self.config.cargo();
158
159             move |sender| {
160                 let progress = {
161                     let sender = sender.clone();
162                     move |msg| {
163                         sender
164                             .send(Task::FetchWorkspace(ProjectWorkspaceProgress::Report(msg)))
165                             .unwrap()
166                     }
167                 };
168
169                 sender.send(Task::FetchWorkspace(ProjectWorkspaceProgress::Begin)).unwrap();
170
171                 let mut workspaces = linked_projects
172                     .iter()
173                     .map(|project| match project {
174                         LinkedProject::ProjectManifest(manifest) => {
175                             project_model::ProjectWorkspace::load(
176                                 manifest.clone(),
177                                 &cargo_config,
178                                 &progress,
179                             )
180                         }
181                         LinkedProject::InlineJsonProject(it) => {
182                             project_model::ProjectWorkspace::load_inline(
183                                 it.clone(),
184                                 cargo_config.target.as_deref(),
185                             )
186                         }
187                     })
188                     .collect::<Vec<_>>();
189
190                 if !detached_files.is_empty() {
191                     workspaces
192                         .push(project_model::ProjectWorkspace::load_detached_files(detached_files));
193                 }
194
195                 log::info!("did fetch workspaces {:?}", workspaces);
196                 sender
197                     .send(Task::FetchWorkspace(ProjectWorkspaceProgress::End(workspaces)))
198                     .unwrap();
199             }
200         });
201     }
202     pub(crate) fn fetch_workspaces_completed(
203         &mut self,
204         workspaces: Vec<anyhow::Result<ProjectWorkspace>>,
205     ) {
206         self.fetch_workspaces_queue.op_completed(workspaces)
207     }
208
209     pub(crate) fn fetch_build_data_request(&mut self, build_data_collector: BuildDataCollector) {
210         self.fetch_build_data_queue.request_op(build_data_collector);
211     }
212     pub(crate) fn fetch_build_data_if_needed(&mut self) {
213         let mut build_data_collector = match self.fetch_build_data_queue.should_start_op() {
214             Some(it) => it,
215             None => return,
216         };
217         self.task_pool.handle.spawn_with_sender(move |sender| {
218             sender.send(Task::FetchBuildData(BuildDataProgress::Begin)).unwrap();
219
220             let progress = {
221                 let sender = sender.clone();
222                 move |msg| {
223                     sender.send(Task::FetchBuildData(BuildDataProgress::Report(msg))).unwrap()
224                 }
225             };
226             let res = build_data_collector.collect(&progress);
227             sender.send(Task::FetchBuildData(BuildDataProgress::End(res))).unwrap();
228         });
229     }
230     pub(crate) fn fetch_build_data_completed(
231         &mut self,
232         build_data: anyhow::Result<BuildDataResult>,
233     ) {
234         self.fetch_build_data_queue.op_completed(Some(build_data))
235     }
236
237     pub(crate) fn switch_workspaces(&mut self) {
238         let _p = profile::span("GlobalState::switch_workspaces");
239         log::info!("will switch workspaces");
240
241         if let Some(error_message) = self.fetch_workspace_error() {
242             log::error!("failed to switch workspaces: {}", error_message);
243             if !self.workspaces.is_empty() {
244                 return;
245             }
246         }
247
248         if let Some(error_message) = self.build_data_error() {
249             log::error!("failed to switch build data: {}", error_message);
250         }
251
252         let workspaces = self
253             .fetch_workspaces_queue
254             .last_op_result()
255             .iter()
256             .filter_map(|res| res.as_ref().ok().cloned())
257             .collect::<Vec<_>>();
258
259         let workspace_build_data = match self.fetch_build_data_queue.last_op_result() {
260             Some(Ok(it)) => Some(it.clone()),
261             None | Some(Err(_)) => None,
262         };
263
264         if *self.workspaces == workspaces && self.workspace_build_data == workspace_build_data {
265             return;
266         }
267
268         if let FilesWatcher::Client = self.config.files().watcher {
269             if self.config.did_change_watched_files_dynamic_registration() {
270                 let registration_options = lsp_types::DidChangeWatchedFilesRegistrationOptions {
271                     watchers: workspaces
272                         .iter()
273                         .flat_map(|it| it.to_roots(workspace_build_data.as_ref()))
274                         .filter(|it| it.is_member)
275                         .flat_map(|root| {
276                             root.include.into_iter().map(|it| format!("{}/**/*.rs", it.display()))
277                         })
278                         .map(|glob_pattern| lsp_types::FileSystemWatcher {
279                             glob_pattern,
280                             kind: None,
281                         })
282                         .collect(),
283                 };
284                 let registration = lsp_types::Registration {
285                     id: "workspace/didChangeWatchedFiles".to_string(),
286                     method: "workspace/didChangeWatchedFiles".to_string(),
287                     register_options: Some(serde_json::to_value(registration_options).unwrap()),
288                 };
289                 self.send_request::<lsp_types::request::RegisterCapability>(
290                     lsp_types::RegistrationParams { registrations: vec![registration] },
291                     |_, _| (),
292                 );
293             }
294         }
295
296         let mut change = Change::new();
297
298         let files_config = self.config.files();
299         let project_folders =
300             ProjectFolders::new(&workspaces, &files_config.exclude, workspace_build_data.as_ref());
301
302         if self.proc_macro_client.is_none() {
303             self.proc_macro_client = match self.config.proc_macro_srv() {
304                 None => None,
305                 Some((path, args)) => match ProcMacroClient::extern_process(path.clone(), args) {
306                     Ok(it) => Some(it),
307                     Err(err) => {
308                         log::error!(
309                             "Failed to run proc_macro_srv from path {}, error: {:?}",
310                             path.display(),
311                             err
312                         );
313                         None
314                     }
315                 },
316             };
317         }
318
319         let watch = match files_config.watcher {
320             FilesWatcher::Client => vec![],
321             FilesWatcher::Notify => project_folders.watch,
322         };
323         self.vfs_config_version += 1;
324         self.loader.handle.set_config(vfs::loader::Config {
325             load: project_folders.load,
326             watch,
327             version: self.vfs_config_version,
328         });
329
330         // Create crate graph from all the workspaces
331         let crate_graph = {
332             let mut crate_graph = CrateGraph::default();
333             let vfs = &mut self.vfs.write().0;
334             let loader = &mut self.loader;
335             let mem_docs = &self.mem_docs;
336             let mut load = |path: &AbsPath| {
337                 let _p = profile::span("GlobalState::load");
338                 let vfs_path = vfs::VfsPath::from(path.to_path_buf());
339                 if !mem_docs.contains_key(&vfs_path) {
340                     let contents = loader.handle.load_sync(path);
341                     vfs.set_file_contents(vfs_path.clone(), contents);
342                 }
343                 let res = vfs.file_id(&vfs_path);
344                 if res.is_none() {
345                     log::warn!("failed to load {}", path.display())
346                 }
347                 res
348             };
349             for ws in workspaces.iter() {
350                 crate_graph.extend(ws.to_crate_graph(
351                     workspace_build_data.as_ref(),
352                     self.proc_macro_client.as_ref(),
353                     &mut load,
354                 ));
355             }
356
357             crate_graph
358         };
359         change.set_crate_graph(crate_graph);
360
361         self.source_root_config = project_folders.source_root_config;
362         self.workspaces = Arc::new(workspaces);
363         self.workspace_build_data = workspace_build_data;
364
365         self.analysis_host.apply_change(change);
366         self.process_changes();
367         self.reload_flycheck();
368         log::info!("did switch workspaces");
369     }
370
371     fn fetch_workspace_error(&self) -> Option<String> {
372         let mut buf = String::new();
373
374         for ws in self.fetch_workspaces_queue.last_op_result() {
375             if let Err(err) = ws {
376                 stdx::format_to!(buf, "rust-analyzer failed to load workspace: {:#}\n", err);
377             }
378         }
379
380         if buf.is_empty() {
381             return None;
382         }
383
384         Some(buf)
385     }
386
387     fn build_data_error(&self) -> Option<String> {
388         match self.fetch_build_data_queue.last_op_result() {
389             Some(Err(err)) => {
390                 Some(format!("rust-analyzer failed to fetch build data: {:#}\n", err))
391             }
392             Some(Ok(data)) => data.error(),
393             None => None,
394         }
395     }
396
397     fn reload_flycheck(&mut self) {
398         let _p = profile::span("GlobalState::reload_flycheck");
399         let config = match self.config.flycheck() {
400             Some(it) => it,
401             None => {
402                 self.flycheck = Vec::new();
403                 return;
404             }
405         };
406
407         let sender = self.flycheck_sender.clone();
408         self.flycheck = self
409             .workspaces
410             .iter()
411             .enumerate()
412             .filter_map(|(id, w)| match w {
413                 ProjectWorkspace::Cargo { cargo, .. } => Some((id, cargo.workspace_root())),
414                 ProjectWorkspace::Json { project, .. } => {
415                     // Enable flychecks for json projects if a custom flycheck command was supplied
416                     // in the workspace configuration.
417                     match config {
418                         FlycheckConfig::CustomCommand { .. } => Some((id, project.path())),
419                         _ => None,
420                     }
421                 }
422                 ProjectWorkspace::DetachedFiles { .. } => None,
423             })
424             .map(|(id, root)| {
425                 let sender = sender.clone();
426                 FlycheckHandle::spawn(
427                     id,
428                     Box::new(move |msg| sender.send(msg).unwrap()),
429                     config.clone(),
430                     root.to_path_buf().into(),
431                 )
432             })
433             .collect();
434     }
435 }
436
437 #[derive(Default)]
438 pub(crate) struct ProjectFolders {
439     pub(crate) load: Vec<vfs::loader::Entry>,
440     pub(crate) watch: Vec<usize>,
441     pub(crate) source_root_config: SourceRootConfig,
442 }
443
444 impl ProjectFolders {
445     pub(crate) fn new(
446         workspaces: &[ProjectWorkspace],
447         global_excludes: &[AbsPathBuf],
448         build_data: Option<&BuildDataResult>,
449     ) -> ProjectFolders {
450         let mut res = ProjectFolders::default();
451         let mut fsc = FileSetConfig::builder();
452         let mut local_filesets = vec![];
453
454         for root in workspaces.iter().flat_map(|it| it.to_roots(build_data)) {
455             let file_set_roots: Vec<VfsPath> =
456                 root.include.iter().cloned().map(VfsPath::from).collect();
457
458             let entry = {
459                 let mut dirs = vfs::loader::Directories::default();
460                 dirs.extensions.push("rs".into());
461                 dirs.include.extend(root.include);
462                 dirs.exclude.extend(root.exclude);
463                 for excl in global_excludes {
464                     if dirs
465                         .include
466                         .iter()
467                         .any(|incl| incl.starts_with(excl) || excl.starts_with(incl))
468                     {
469                         dirs.exclude.push(excl.clone());
470                     }
471                 }
472
473                 vfs::loader::Entry::Directories(dirs)
474             };
475
476             if root.is_member {
477                 res.watch.push(res.load.len());
478             }
479             res.load.push(entry);
480
481             if root.is_member {
482                 local_filesets.push(fsc.len());
483             }
484             fsc.add_file_set(file_set_roots)
485         }
486
487         let fsc = fsc.build();
488         res.source_root_config = SourceRootConfig { fsc, local_filesets };
489
490         res
491     }
492 }
493
494 #[derive(Default, Debug)]
495 pub(crate) struct SourceRootConfig {
496     pub(crate) fsc: FileSetConfig,
497     pub(crate) local_filesets: Vec<usize>,
498 }
499
500 impl SourceRootConfig {
501     pub(crate) fn partition(&self, vfs: &vfs::Vfs) -> Vec<SourceRoot> {
502         let _p = profile::span("SourceRootConfig::partition");
503         self.fsc
504             .partition(vfs)
505             .into_iter()
506             .enumerate()
507             .map(|(idx, file_set)| {
508                 let is_local = self.local_filesets.contains(&idx);
509                 if is_local {
510                     SourceRoot::new_local(file_set)
511                 } else {
512                     SourceRoot::new_library(file_set)
513                 }
514             })
515             .collect()
516     }
517 }