]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/reload.rs
Merge #7483
[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         self.proc_macro_client = match self.config.proc_macro_srv() {
273             None => None,
274             Some((path, args)) => match ProcMacroClient::extern_process(path.clone(), args) {
275                 Ok(it) => Some(it),
276                 Err(err) => {
277                     log::error!(
278                         "Failed to run proc_macro_srv from path {}, error: {:?}",
279                         path.display(),
280                         err
281                     );
282                     None
283                 }
284             },
285         };
286
287         let watch = match files_config.watcher {
288             FilesWatcher::Client => vec![],
289             FilesWatcher::Notify => project_folders.watch,
290         };
291         self.loader.handle.set_config(vfs::loader::Config { load: project_folders.load, watch });
292
293         // Create crate graph from all the workspaces
294         let crate_graph = {
295             let mut crate_graph = CrateGraph::default();
296             let vfs = &mut self.vfs.write().0;
297             let loader = &mut self.loader;
298             let mem_docs = &self.mem_docs;
299             let mut load = |path: &AbsPath| {
300                 let vfs_path = vfs::VfsPath::from(path.to_path_buf());
301                 if !mem_docs.contains_key(&vfs_path) {
302                     let contents = loader.handle.load_sync(path);
303                     vfs.set_file_contents(vfs_path.clone(), contents);
304                 }
305                 let res = vfs.file_id(&vfs_path);
306                 if res.is_none() {
307                     log::warn!("failed to load {}", path.display())
308                 }
309                 res
310             };
311             for ws in workspaces.iter() {
312                 crate_graph.extend(ws.to_crate_graph(
313                     workspace_build_data.as_ref(),
314                     self.proc_macro_client.as_ref(),
315                     &mut load,
316                 ));
317             }
318
319             crate_graph
320         };
321         change.set_crate_graph(crate_graph);
322
323         if self.config.load_out_dirs_from_check() && workspace_build_data.is_none() {
324             let mut collector = BuildDataCollector::default();
325             for ws in &workspaces {
326                 ws.collect_build_data_configs(&mut collector);
327             }
328             self.fetch_build_data_request(collector)
329         }
330
331         self.source_root_config = project_folders.source_root_config;
332         self.workspaces = Arc::new(workspaces);
333         self.workspace_build_data = workspace_build_data;
334
335         self.analysis_host.apply_change(change);
336         self.process_changes();
337         self.reload_flycheck();
338         log::info!("did switch workspaces");
339     }
340
341     fn reload_flycheck(&mut self) {
342         let _p = profile::span("GlobalState::reload_flycheck");
343         let config = match self.config.flycheck() {
344             Some(it) => it,
345             None => {
346                 self.flycheck = Vec::new();
347                 return;
348             }
349         };
350
351         let sender = self.flycheck_sender.clone();
352         self.flycheck = self
353             .workspaces
354             .iter()
355             .enumerate()
356             .filter_map(|(id, w)| match w {
357                 ProjectWorkspace::Cargo { cargo, .. } => Some((id, cargo.workspace_root())),
358                 ProjectWorkspace::Json { project, .. } => {
359                     // Enable flychecks for json projects if a custom flycheck command was supplied
360                     // in the workspace configuration.
361                     match config {
362                         FlycheckConfig::CustomCommand { .. } => Some((id, project.path())),
363                         _ => None,
364                     }
365                 }
366             })
367             .map(|(id, root)| {
368                 let sender = sender.clone();
369                 FlycheckHandle::spawn(
370                     id,
371                     Box::new(move |msg| sender.send(msg).unwrap()),
372                     config.clone(),
373                     root.to_path_buf().into(),
374                 )
375             })
376             .collect();
377     }
378 }
379
380 #[derive(Default)]
381 pub(crate) struct ProjectFolders {
382     pub(crate) load: Vec<vfs::loader::Entry>,
383     pub(crate) watch: Vec<usize>,
384     pub(crate) source_root_config: SourceRootConfig,
385 }
386
387 impl ProjectFolders {
388     pub(crate) fn new(
389         workspaces: &[ProjectWorkspace],
390         global_excludes: &[AbsPathBuf],
391         build_data: Option<&BuildDataResult>,
392     ) -> ProjectFolders {
393         let mut res = ProjectFolders::default();
394         let mut fsc = FileSetConfig::builder();
395         let mut local_filesets = vec![];
396
397         for root in workspaces.iter().flat_map(|it| it.to_roots(build_data)) {
398             let file_set_roots: Vec<VfsPath> =
399                 root.include.iter().cloned().map(VfsPath::from).collect();
400
401             let entry = {
402                 let mut dirs = vfs::loader::Directories::default();
403                 dirs.extensions.push("rs".into());
404                 dirs.include.extend(root.include);
405                 dirs.exclude.extend(root.exclude);
406                 for excl in global_excludes {
407                     if dirs.include.iter().any(|incl| incl.starts_with(excl)) {
408                         dirs.exclude.push(excl.clone());
409                     }
410                 }
411
412                 vfs::loader::Entry::Directories(dirs)
413             };
414
415             if root.is_member {
416                 res.watch.push(res.load.len());
417             }
418             res.load.push(entry);
419
420             if root.is_member {
421                 local_filesets.push(fsc.len());
422             }
423             fsc.add_file_set(file_set_roots)
424         }
425
426         let fsc = fsc.build();
427         res.source_root_config = SourceRootConfig { fsc, local_filesets };
428
429         res
430     }
431 }
432
433 #[derive(Default, Debug)]
434 pub(crate) struct SourceRootConfig {
435     pub(crate) fsc: FileSetConfig,
436     pub(crate) local_filesets: Vec<usize>,
437 }
438
439 impl SourceRootConfig {
440     pub(crate) fn partition(&self, vfs: &vfs::Vfs) -> Vec<SourceRoot> {
441         let _p = profile::span("SourceRootConfig::partition");
442         self.fsc
443             .partition(vfs)
444             .into_iter()
445             .enumerate()
446             .map(|(idx, file_set)| {
447                 let is_local = self.local_filesets.contains(&idx);
448                 if is_local {
449                     SourceRoot::new_local(file_set)
450                 } else {
451                     SourceRoot::new_library(file_set)
452                 }
453             })
454             .collect()
455     }
456 }