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