]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/reload.rs
Merge #7514
[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 ide::Change;
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};
9
10 use crate::{
11     config::{Config, FilesWatcher, LinkedProject},
12     global_state::{GlobalState, Status},
13     lsp_ext,
14     main_loop::Task,
15 };
16 use lsp_ext::StatusParams;
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 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());
38         }
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();
43         }
44     }
45     pub(crate) fn maybe_refresh(&mut self, changes: &[(AbsPathBuf, ChangeKind)]) {
46         if !changes.iter().any(|(path, kind)| is_interesting(path, *kind)) {
47             return;
48         }
49         match self.status {
50             Status::Loading | Status::NeedsReload => return,
51             Status::Ready { .. } | Status::Invalid => (),
52         }
53         if self.config.cargo_autoreload() {
54             self.fetch_workspaces_request();
55         } else {
56             self.transition(Status::NeedsReload);
57         }
58
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"];
62
63             if path.ends_with("Cargo.toml") || path.ends_with("Cargo.lock") {
64                 return true;
65             }
66             if change_kind == ChangeKind::Modify {
67                 return false;
68             }
69             if path.extension().unwrap_or_default() != "rs" {
70                 return false;
71             }
72             if IMPLICIT_TARGET_FILES.iter().any(|it| path.ends_with(it)) {
73                 return true;
74             }
75             let parent = match path.parent() {
76                 Some(it) => it,
77                 None => return false,
78             };
79             if IMPLICIT_TARGET_DIRS.iter().any(|it| parent.ends_with(it)) {
80                 return true;
81             }
82             if path.ends_with("main.rs") {
83                 let grand_parent = match parent.parent() {
84                     Some(it) => it,
85                     None => return false,
86                 };
87                 if IMPLICIT_TARGET_DIRS.iter().any(|it| grand_parent.ends_with(it)) {
88                     return true;
89                 }
90             }
91             false
92         }
93     }
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,
103             };
104             self.send_notification::<lsp_ext::StatusNotification>(StatusParams {
105                 status: lsp_status,
106             });
107         }
108     }
109
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);
112     }
113
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() {
116             Some(it) => it,
117             None => return,
118         };
119         self.task_pool.handle.spawn_with_sender(move |sender| {
120             sender.send(Task::FetchBuildData(BuildDataProgress::Begin)).unwrap();
121
122             let progress = {
123                 let sender = sender.clone();
124                 move |msg| {
125                     sender.send(Task::FetchBuildData(BuildDataProgress::Report(msg))).unwrap()
126                 }
127             };
128             let res = build_data_collector.collect(&progress);
129             sender.send(Task::FetchBuildData(BuildDataProgress::End(res))).unwrap();
130         });
131     }
132     pub(crate) fn fetch_build_data_completed(&mut self) {
133         self.fetch_build_data_queue.op_completed()
134     }
135
136     pub(crate) fn fetch_workspaces_request(&mut self) {
137         self.fetch_workspaces_queue.request_op(())
138     }
139     pub(crate) fn fetch_workspaces_if_needed(&mut self) {
140         if self.fetch_workspaces_queue.should_start_op().is_none() {
141             return;
142         }
143         log::info!("will fetch workspaces");
144
145         self.task_pool.handle.spawn_with_sender({
146             let linked_projects = self.config.linked_projects();
147             let cargo_config = self.config.cargo();
148
149             move |sender| {
150                 let progress = {
151                     let sender = sender.clone();
152                     move |msg| {
153                         sender
154                             .send(Task::FetchWorkspace(ProjectWorkspaceProgress::Report(msg)))
155                             .unwrap()
156                     }
157                 };
158
159                 sender.send(Task::FetchWorkspace(ProjectWorkspaceProgress::Begin)).unwrap();
160
161                 let workspaces = linked_projects
162                     .iter()
163                     .map(|project| match project {
164                         LinkedProject::ProjectManifest(manifest) => {
165                             project_model::ProjectWorkspace::load(
166                                 manifest.clone(),
167                                 &cargo_config,
168                                 &progress,
169                             )
170                         }
171                         LinkedProject::InlineJsonProject(it) => {
172                             project_model::ProjectWorkspace::load_inline(
173                                 it.clone(),
174                                 cargo_config.target.as_deref(),
175                             )
176                         }
177                     })
178                     .collect::<Vec<_>>();
179
180                 log::info!("did fetch workspaces {:?}", workspaces);
181                 sender
182                     .send(Task::FetchWorkspace(ProjectWorkspaceProgress::End(workspaces)))
183                     .unwrap();
184             }
185         });
186     }
187     pub(crate) fn fetch_workspaces_completed(&mut self) {
188         self.fetch_workspaces_queue.op_completed()
189     }
190
191     pub(crate) fn switch_workspaces(
192         &mut self,
193         workspaces: Vec<anyhow::Result<ProjectWorkspace>>,
194         workspace_build_data: Option<anyhow::Result<BuildDataResult>>,
195     ) {
196         let _p = profile::span("GlobalState::switch_workspaces");
197         log::info!("will switch workspaces: {:?}", workspaces);
198
199         let mut has_errors = false;
200         let workspaces = workspaces
201             .into_iter()
202             .filter_map(|res| {
203                 res.map_err(|err| {
204                     has_errors = true;
205                     log::error!("failed to load workspace: {:#}", err);
206                     if self.workspaces.is_empty() {
207                         self.show_message(
208                             lsp_types::MessageType::Error,
209                             format!("rust-analyzer failed to load workspace: {:#}", err),
210                         );
211                     }
212                 })
213                 .ok()
214             })
215             .collect::<Vec<_>>();
216
217         let workspace_build_data = match workspace_build_data {
218             Some(Ok(it)) => Some(it),
219             Some(Err(err)) => {
220                 log::error!("failed to fetch build data: {:#}", err);
221                 self.show_message(
222                     lsp_types::MessageType::Error,
223                     format!("rust-analyzer failed to fetch build data: {:#}", err),
224                 );
225                 return;
226             }
227             None => None,
228         };
229
230         if &*self.workspaces == &workspaces && self.workspace_build_data == workspace_build_data {
231             return;
232         }
233
234         if !self.workspaces.is_empty() && has_errors {
235             return;
236         }
237
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 {
241                     watchers: workspaces
242                         .iter()
243                         .flat_map(|it| it.to_roots(workspace_build_data.as_ref()))
244                         .filter(|it| it.is_member)
245                         .flat_map(|root| {
246                             root.include.into_iter().map(|it| format!("{}/**/*.rs", it.display()))
247                         })
248                         .map(|glob_pattern| lsp_types::FileSystemWatcher {
249                             glob_pattern,
250                             kind: None,
251                         })
252                         .collect(),
253                 };
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()),
258                 };
259                 self.send_request::<lsp_types::request::RegisterCapability>(
260                     lsp_types::RegistrationParams { registrations: vec![registration] },
261                     |_, _| (),
262                 );
263             }
264         }
265
266         let mut change = Change::new();
267
268         let files_config = self.config.files();
269         let project_folders =
270             ProjectFolders::new(&workspaces, &files_config.exclude, workspace_build_data.as_ref());
271
272         if self.proc_macro_client.is_none() {
273             self.proc_macro_client = match self.config.proc_macro_srv() {
274                 None => None,
275                 Some((path, args)) => match ProcMacroClient::extern_process(path.clone(), args) {
276                     Ok(it) => Some(it),
277                     Err(err) => {
278                         log::error!(
279                             "Failed to run proc_macro_srv from path {}, error: {:?}",
280                             path.display(),
281                             err
282                         );
283                         None
284                     }
285                 },
286             };
287         }
288
289         let watch = match files_config.watcher {
290             FilesWatcher::Client => vec![],
291             FilesWatcher::Notify => project_folders.watch,
292         };
293         self.loader.handle.set_config(vfs::loader::Config { load: project_folders.load, watch });
294
295         // Create crate graph from all the workspaces
296         let crate_graph = {
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);
306                 }
307                 let res = vfs.file_id(&vfs_path);
308                 if res.is_none() {
309                     log::warn!("failed to load {}", path.display())
310                 }
311                 res
312             };
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(),
317                     &mut load,
318                 ));
319             }
320
321             crate_graph
322         };
323         change.set_crate_graph(crate_graph);
324
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);
329             }
330             self.fetch_build_data_request(collector)
331         }
332
333         self.source_root_config = project_folders.source_root_config;
334         self.workspaces = Arc::new(workspaces);
335         self.workspace_build_data = workspace_build_data;
336
337         self.analysis_host.apply_change(change);
338         self.process_changes();
339         self.reload_flycheck();
340         log::info!("did switch workspaces");
341     }
342
343     fn reload_flycheck(&mut self) {
344         let _p = profile::span("GlobalState::reload_flycheck");
345         let config = match self.config.flycheck() {
346             Some(it) => it,
347             None => {
348                 self.flycheck = Vec::new();
349                 return;
350             }
351         };
352
353         let sender = self.flycheck_sender.clone();
354         self.flycheck = self
355             .workspaces
356             .iter()
357             .enumerate()
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.
363                     match config {
364                         FlycheckConfig::CustomCommand { .. } => Some((id, project.path())),
365                         _ => None,
366                     }
367                 }
368             })
369             .map(|(id, root)| {
370                 let sender = sender.clone();
371                 FlycheckHandle::spawn(
372                     id,
373                     Box::new(move |msg| sender.send(msg).unwrap()),
374                     config.clone(),
375                     root.to_path_buf().into(),
376                 )
377             })
378             .collect();
379     }
380 }
381
382 #[derive(Default)]
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,
387 }
388
389 impl ProjectFolders {
390     pub(crate) fn new(
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![];
398
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();
402
403             let entry = {
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());
411                     }
412                 }
413
414                 vfs::loader::Entry::Directories(dirs)
415             };
416
417             if root.is_member {
418                 res.watch.push(res.load.len());
419             }
420             res.load.push(entry);
421
422             if root.is_member {
423                 local_filesets.push(fsc.len());
424             }
425             fsc.add_file_set(file_set_roots)
426         }
427
428         let fsc = fsc.build();
429         res.source_root_config = SourceRootConfig { fsc, local_filesets };
430
431         res
432     }
433 }
434
435 #[derive(Default, Debug)]
436 pub(crate) struct SourceRootConfig {
437     pub(crate) fsc: FileSetConfig,
438     pub(crate) local_filesets: Vec<usize>,
439 }
440
441 impl SourceRootConfig {
442     pub(crate) fn partition(&self, vfs: &vfs::Vfs) -> Vec<SourceRoot> {
443         let _p = profile::span("SourceRootConfig::partition");
444         self.fsc
445             .partition(vfs)
446             .into_iter()
447             .enumerate()
448             .map(|(idx, file_set)| {
449                 let is_local = self.local_filesets.contains(&idx);
450                 if is_local {
451                     SourceRoot::new_local(file_set)
452                 } else {
453                     SourceRoot::new_library(file_set)
454                 }
455             })
456             .collect()
457     }
458 }