]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/reload.rs
Merge #7799
[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         log::info!(
54             "Reloading workspace because of the following changes: {}",
55             itertools::join(
56                 changes
57                     .iter()
58                     .filter(|(path, kind)| is_interesting(path, *kind))
59                     .map(|(path, kind)| format!("{}/{:?}", path.display(), kind)),
60                 ", "
61             )
62         );
63         if self.config.cargo_autoreload() {
64             self.fetch_workspaces_request();
65         } else {
66             self.transition(Status::NeedsReload);
67         }
68
69         fn is_interesting(path: &AbsPath, change_kind: ChangeKind) -> bool {
70             const IMPLICIT_TARGET_FILES: &[&str] = &["build.rs", "src/main.rs", "src/lib.rs"];
71             const IMPLICIT_TARGET_DIRS: &[&str] = &["src/bin", "examples", "tests", "benches"];
72
73             if path.ends_with("Cargo.toml") || path.ends_with("Cargo.lock") {
74                 return true;
75             }
76             if change_kind == ChangeKind::Modify {
77                 return false;
78             }
79             if path.extension().unwrap_or_default() != "rs" {
80                 return false;
81             }
82             if IMPLICIT_TARGET_FILES.iter().any(|it| path.ends_with(it)) {
83                 return true;
84             }
85             let parent = match path.parent() {
86                 Some(it) => it,
87                 None => return false,
88             };
89             if IMPLICIT_TARGET_DIRS.iter().any(|it| parent.ends_with(it)) {
90                 return true;
91             }
92             if path.ends_with("main.rs") {
93                 let grand_parent = match parent.parent() {
94                     Some(it) => it,
95                     None => return false,
96                 };
97                 if IMPLICIT_TARGET_DIRS.iter().any(|it| grand_parent.ends_with(it)) {
98                     return true;
99                 }
100             }
101             false
102         }
103     }
104     pub(crate) fn transition(&mut self, new_status: Status) {
105         self.status = new_status;
106         if self.config.status_notification() {
107             let lsp_status = match new_status {
108                 Status::Loading => lsp_ext::Status::Loading,
109                 Status::Ready { partial: true } => lsp_ext::Status::ReadyPartial,
110                 Status::Ready { partial: false } => lsp_ext::Status::Ready,
111                 Status::Invalid => lsp_ext::Status::Invalid,
112                 Status::NeedsReload => lsp_ext::Status::NeedsReload,
113             };
114             self.send_notification::<lsp_ext::StatusNotification>(StatusParams {
115                 status: lsp_status,
116             });
117         }
118     }
119
120     pub(crate) fn fetch_build_data_request(&mut self, build_data_collector: BuildDataCollector) {
121         self.fetch_build_data_queue.request_op(build_data_collector);
122     }
123
124     pub(crate) fn fetch_build_data_if_needed(&mut self) {
125         let mut build_data_collector = match self.fetch_build_data_queue.should_start_op() {
126             Some(it) => it,
127             None => return,
128         };
129         self.task_pool.handle.spawn_with_sender(move |sender| {
130             sender.send(Task::FetchBuildData(BuildDataProgress::Begin)).unwrap();
131
132             let progress = {
133                 let sender = sender.clone();
134                 move |msg| {
135                     sender.send(Task::FetchBuildData(BuildDataProgress::Report(msg))).unwrap()
136                 }
137             };
138             let res = build_data_collector.collect(&progress);
139             sender.send(Task::FetchBuildData(BuildDataProgress::End(res))).unwrap();
140         });
141     }
142     pub(crate) fn fetch_build_data_completed(&mut self) {
143         self.fetch_build_data_queue.op_completed()
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 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 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                 log::info!("did fetch workspaces {:?}", workspaces);
191                 sender
192                     .send(Task::FetchWorkspace(ProjectWorkspaceProgress::End(workspaces)))
193                     .unwrap();
194             }
195         });
196     }
197     pub(crate) fn fetch_workspaces_completed(&mut self) {
198         self.fetch_workspaces_queue.op_completed()
199     }
200
201     pub(crate) fn switch_workspaces(
202         &mut self,
203         workspaces: Vec<anyhow::Result<ProjectWorkspace>>,
204         workspace_build_data: Option<anyhow::Result<BuildDataResult>>,
205     ) {
206         let _p = profile::span("GlobalState::switch_workspaces");
207         log::info!("will switch workspaces: {:?}", workspaces);
208
209         let mut has_errors = false;
210         let workspaces = workspaces
211             .into_iter()
212             .filter_map(|res| {
213                 res.map_err(|err| {
214                     has_errors = true;
215                     log::error!("failed to load workspace: {:#}", err);
216                     if self.workspaces.is_empty() {
217                         self.show_message(
218                             lsp_types::MessageType::Error,
219                             format!("rust-analyzer failed to load workspace: {:#}", err),
220                         );
221                     }
222                 })
223                 .ok()
224             })
225             .collect::<Vec<_>>();
226
227         let workspace_build_data = match workspace_build_data {
228             Some(Ok(it)) => Some(it),
229             Some(Err(err)) => {
230                 log::error!("failed to fetch build data: {:#}", err);
231                 self.show_message(
232                     lsp_types::MessageType::Error,
233                     format!("rust-analyzer failed to fetch build data: {:#}", err),
234                 );
235                 return;
236             }
237             None => None,
238         };
239
240         if &*self.workspaces == &workspaces && self.workspace_build_data == workspace_build_data {
241             return;
242         }
243
244         if !self.workspaces.is_empty() && has_errors {
245             return;
246         }
247
248         if let FilesWatcher::Client = self.config.files().watcher {
249             if self.config.did_change_watched_files_dynamic_registration() {
250                 let registration_options = lsp_types::DidChangeWatchedFilesRegistrationOptions {
251                     watchers: workspaces
252                         .iter()
253                         .flat_map(|it| it.to_roots(workspace_build_data.as_ref()))
254                         .filter(|it| it.is_member)
255                         .flat_map(|root| {
256                             root.include.into_iter().map(|it| format!("{}/**/*.rs", it.display()))
257                         })
258                         .map(|glob_pattern| lsp_types::FileSystemWatcher {
259                             glob_pattern,
260                             kind: None,
261                         })
262                         .collect(),
263                 };
264                 let registration = lsp_types::Registration {
265                     id: "workspace/didChangeWatchedFiles".to_string(),
266                     method: "workspace/didChangeWatchedFiles".to_string(),
267                     register_options: Some(serde_json::to_value(registration_options).unwrap()),
268                 };
269                 self.send_request::<lsp_types::request::RegisterCapability>(
270                     lsp_types::RegistrationParams { registrations: vec![registration] },
271                     |_, _| (),
272                 );
273             }
274         }
275
276         let mut change = Change::new();
277
278         let files_config = self.config.files();
279         let project_folders =
280             ProjectFolders::new(&workspaces, &files_config.exclude, workspace_build_data.as_ref());
281
282         if self.proc_macro_client.is_none() {
283             self.proc_macro_client = match self.config.proc_macro_srv() {
284                 None => None,
285                 Some((path, args)) => match ProcMacroClient::extern_process(path.clone(), args) {
286                     Ok(it) => Some(it),
287                     Err(err) => {
288                         log::error!(
289                             "Failed to run proc_macro_srv from path {}, error: {:?}",
290                             path.display(),
291                             err
292                         );
293                         None
294                     }
295                 },
296             };
297         }
298
299         let watch = match files_config.watcher {
300             FilesWatcher::Client => vec![],
301             FilesWatcher::Notify => project_folders.watch,
302         };
303         self.vfs_config_version += 1;
304         self.loader.handle.set_config(vfs::loader::Config {
305             load: project_folders.load,
306             watch,
307             version: self.vfs_config_version,
308         });
309
310         // Create crate graph from all the workspaces
311         let crate_graph = {
312             let mut crate_graph = CrateGraph::default();
313             let vfs = &mut self.vfs.write().0;
314             let loader = &mut self.loader;
315             let mem_docs = &self.mem_docs;
316             let mut load = |path: &AbsPath| {
317                 let vfs_path = vfs::VfsPath::from(path.to_path_buf());
318                 if !mem_docs.contains_key(&vfs_path) {
319                     let contents = loader.handle.load_sync(path);
320                     vfs.set_file_contents(vfs_path.clone(), contents);
321                 }
322                 let res = vfs.file_id(&vfs_path);
323                 if res.is_none() {
324                     log::warn!("failed to load {}", path.display())
325                 }
326                 res
327             };
328             for ws in workspaces.iter() {
329                 crate_graph.extend(ws.to_crate_graph(
330                     workspace_build_data.as_ref(),
331                     self.proc_macro_client.as_ref(),
332                     &mut load,
333                 ));
334             }
335
336             crate_graph
337         };
338         change.set_crate_graph(crate_graph);
339
340         if self.config.run_build_scripts() && workspace_build_data.is_none() {
341             let mut collector = BuildDataCollector::default();
342             for ws in &workspaces {
343                 ws.collect_build_data_configs(&mut collector);
344             }
345             self.fetch_build_data_request(collector)
346         }
347
348         self.source_root_config = project_folders.source_root_config;
349         self.workspaces = Arc::new(workspaces);
350         self.workspace_build_data = workspace_build_data;
351
352         self.analysis_host.apply_change(change);
353         self.process_changes();
354         self.reload_flycheck();
355         log::info!("did switch workspaces");
356     }
357
358     fn reload_flycheck(&mut self) {
359         let _p = profile::span("GlobalState::reload_flycheck");
360         let config = match self.config.flycheck() {
361             Some(it) => it,
362             None => {
363                 self.flycheck = Vec::new();
364                 return;
365             }
366         };
367
368         let sender = self.flycheck_sender.clone();
369         self.flycheck = self
370             .workspaces
371             .iter()
372             .enumerate()
373             .filter_map(|(id, w)| match w {
374                 ProjectWorkspace::Cargo { cargo, .. } => Some((id, cargo.workspace_root())),
375                 ProjectWorkspace::Json { project, .. } => {
376                     // Enable flychecks for json projects if a custom flycheck command was supplied
377                     // in the workspace configuration.
378                     match config {
379                         FlycheckConfig::CustomCommand { .. } => Some((id, project.path())),
380                         _ => None,
381                     }
382                 }
383             })
384             .map(|(id, root)| {
385                 let sender = sender.clone();
386                 FlycheckHandle::spawn(
387                     id,
388                     Box::new(move |msg| sender.send(msg).unwrap()),
389                     config.clone(),
390                     root.to_path_buf().into(),
391                 )
392             })
393             .collect();
394     }
395 }
396
397 #[derive(Default)]
398 pub(crate) struct ProjectFolders {
399     pub(crate) load: Vec<vfs::loader::Entry>,
400     pub(crate) watch: Vec<usize>,
401     pub(crate) source_root_config: SourceRootConfig,
402 }
403
404 impl ProjectFolders {
405     pub(crate) fn new(
406         workspaces: &[ProjectWorkspace],
407         global_excludes: &[AbsPathBuf],
408         build_data: Option<&BuildDataResult>,
409     ) -> ProjectFolders {
410         let mut res = ProjectFolders::default();
411         let mut fsc = FileSetConfig::builder();
412         let mut local_filesets = vec![];
413
414         for root in workspaces.iter().flat_map(|it| it.to_roots(build_data)) {
415             let file_set_roots: Vec<VfsPath> =
416                 root.include.iter().cloned().map(VfsPath::from).collect();
417
418             let entry = {
419                 let mut dirs = vfs::loader::Directories::default();
420                 dirs.extensions.push("rs".into());
421                 dirs.include.extend(root.include);
422                 dirs.exclude.extend(root.exclude);
423                 for excl in global_excludes {
424                     if dirs.include.iter().any(|incl| incl.starts_with(excl)) {
425                         dirs.exclude.push(excl.clone());
426                     }
427                 }
428
429                 vfs::loader::Entry::Directories(dirs)
430             };
431
432             if root.is_member {
433                 res.watch.push(res.load.len());
434             }
435             res.load.push(entry);
436
437             if root.is_member {
438                 local_filesets.push(fsc.len());
439             }
440             fsc.add_file_set(file_set_roots)
441         }
442
443         let fsc = fsc.build();
444         res.source_root_config = SourceRootConfig { fsc, local_filesets };
445
446         res
447     }
448 }
449
450 #[derive(Default, Debug)]
451 pub(crate) struct SourceRootConfig {
452     pub(crate) fsc: FileSetConfig,
453     pub(crate) local_filesets: Vec<usize>,
454 }
455
456 impl SourceRootConfig {
457     pub(crate) fn partition(&self, vfs: &vfs::Vfs) -> Vec<SourceRoot> {
458         let _p = profile::span("SourceRootConfig::partition");
459         self.fsc
460             .partition(vfs)
461             .into_iter()
462             .enumerate()
463             .map(|(idx, file_set)| {
464                 let is_local = self.local_filesets.contains(&idx);
465                 if is_local {
466                     SourceRoot::new_local(file_set)
467                 } else {
468                     SourceRoot::new_library(file_set)
469                 }
470             })
471             .collect()
472     }
473 }