]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/reload.rs
Report progress for cargo metadata and output-dir
[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::{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,
23 }
24
25 impl GlobalState {
26     pub(crate) fn update_configuration(&mut self, config: Config) {
27         let _p = profile::span("GlobalState::update_configuration");
28         let old_config = mem::replace(&mut self.config, Arc::new(config));
29         if self.config.lru_capacity() != old_config.lru_capacity() {
30             self.analysis_host.update_lru_capacity(self.config.lru_capacity());
31         }
32         if self.config.linked_projects() != old_config.linked_projects() {
33             self.fetch_workspaces()
34         } else if self.config.flycheck() != old_config.flycheck() {
35             self.reload_flycheck();
36         }
37     }
38     pub(crate) fn maybe_refresh(&mut self, changes: &[(AbsPathBuf, ChangeKind)]) {
39         if !changes.iter().any(|(path, kind)| is_interesting(path, *kind)) {
40             return;
41         }
42         match self.status {
43             Status::Loading | Status::NeedsReload => return,
44             Status::Ready | Status::Invalid => (),
45         }
46         if self.config.cargo_autoreload() {
47             self.fetch_workspaces();
48         } else {
49             self.transition(Status::NeedsReload);
50         }
51
52         fn is_interesting(path: &AbsPath, change_kind: ChangeKind) -> bool {
53             const IMPLICIT_TARGET_FILES: &[&str] = &["build.rs", "src/main.rs", "src/lib.rs"];
54             const IMPLICIT_TARGET_DIRS: &[&str] = &["src/bin", "examples", "tests", "benches"];
55
56             if path.ends_with("Cargo.toml") || path.ends_with("Cargo.lock") {
57                 return true;
58             }
59             if change_kind == ChangeKind::Modify {
60                 return false;
61             }
62             if path.extension().unwrap_or_default() != "rs" {
63                 return false;
64             }
65             if IMPLICIT_TARGET_FILES.iter().any(|it| path.ends_with(it)) {
66                 return true;
67             }
68             let parent = match path.parent() {
69                 Some(it) => it,
70                 None => return false,
71             };
72             if IMPLICIT_TARGET_DIRS.iter().any(|it| parent.ends_with(it)) {
73                 return true;
74             }
75             if path.ends_with("main.rs") {
76                 let grand_parent = match parent.parent() {
77                     Some(it) => it,
78                     None => return false,
79                 };
80                 if IMPLICIT_TARGET_DIRS.iter().any(|it| grand_parent.ends_with(it)) {
81                     return true;
82                 }
83             }
84             false
85         }
86     }
87     pub(crate) fn transition(&mut self, new_status: Status) {
88         self.status = new_status;
89         if self.config.status_notification() {
90             let lsp_status = match new_status {
91                 Status::Loading => lsp_ext::Status::Loading,
92                 Status::Ready => lsp_ext::Status::Ready,
93                 Status::Invalid => lsp_ext::Status::Invalid,
94                 Status::NeedsReload => lsp_ext::Status::NeedsReload,
95             };
96             self.send_notification::<lsp_ext::StatusNotification>(StatusParams {
97                 status: lsp_status,
98             });
99         }
100     }
101     pub(crate) fn fetch_workspaces(&mut self) {
102         log::info!("will fetch workspaces");
103
104         self.task_pool.handle.spawn_with_sender({
105             let linked_projects = self.config.linked_projects();
106             let cargo_config = self.config.cargo();
107
108             move |sender| {
109                 let progress = {
110                     let sender = sender.clone();
111                     move |msg| {
112                         sender
113                             .send(Task::FetchWorkspace(ProjectWorkspaceProgress::Report(msg)))
114                             .unwrap()
115                     }
116                 };
117
118                 sender.send(Task::FetchWorkspace(ProjectWorkspaceProgress::Begin)).unwrap();
119
120                 let workspaces = linked_projects
121                     .iter()
122                     .map(|project| match project {
123                         LinkedProject::ProjectManifest(manifest) => {
124                             project_model::ProjectWorkspace::load(
125                                 manifest.clone(),
126                                 &cargo_config,
127                                 &progress,
128                             )
129                         }
130                         LinkedProject::InlineJsonProject(it) => {
131                             project_model::ProjectWorkspace::load_inline(it.clone())
132                         }
133                     })
134                     .collect::<Vec<_>>();
135
136                 sender.send(Task::FetchWorkspace(ProjectWorkspaceProgress::End)).unwrap();
137                 log::info!("did fetch workspaces {:?}", workspaces);
138                 sender.send(Task::Workspaces(workspaces)).unwrap()
139             }
140         });
141     }
142     pub(crate) fn switch_workspaces(&mut self, workspaces: Vec<anyhow::Result<ProjectWorkspace>>) {
143         let _p = profile::span("GlobalState::switch_workspaces");
144         log::info!("will switch workspaces: {:?}", workspaces);
145
146         let mut has_errors = false;
147         let workspaces = workspaces
148             .into_iter()
149             .filter_map(|res| {
150                 res.map_err(|err| {
151                     has_errors = true;
152                     log::error!("failed to load workspace: {:#}", err);
153                     if self.workspaces.is_empty() {
154                         self.show_message(
155                             lsp_types::MessageType::Error,
156                             format!("rust-analyzer failed to load workspace: {:#}", err),
157                         );
158                     }
159                 })
160                 .ok()
161             })
162             .collect::<Vec<_>>();
163
164         if &*self.workspaces == &workspaces {
165             return;
166         }
167
168         if !self.workspaces.is_empty() && has_errors {
169             return;
170         }
171
172         if let FilesWatcher::Client = self.config.files().watcher {
173             let registration_options = lsp_types::DidChangeWatchedFilesRegistrationOptions {
174                 watchers: workspaces
175                     .iter()
176                     .flat_map(ProjectWorkspace::to_roots)
177                     .filter(|it| it.is_member)
178                     .flat_map(|root| {
179                         root.include.into_iter().map(|it| format!("{}/**/*.rs", it.display()))
180                     })
181                     .map(|glob_pattern| lsp_types::FileSystemWatcher { glob_pattern, kind: None })
182                     .collect(),
183             };
184             let registration = lsp_types::Registration {
185                 id: "workspace/didChangeWatchedFiles".to_string(),
186                 method: "workspace/didChangeWatchedFiles".to_string(),
187                 register_options: Some(serde_json::to_value(registration_options).unwrap()),
188             };
189             self.send_request::<lsp_types::request::RegisterCapability>(
190                 lsp_types::RegistrationParams { registrations: vec![registration] },
191                 |_, _| (),
192             );
193         }
194
195         let mut change = Change::new();
196
197         let project_folders = ProjectFolders::new(&workspaces);
198
199         self.proc_macro_client = match self.config.proc_macro_srv() {
200             None => None,
201             Some((path, args)) => match ProcMacroClient::extern_process(path.clone(), args) {
202                 Ok(it) => Some(it),
203                 Err(err) => {
204                     log::error!(
205                         "Failed to run proc_macro_srv from path {}, error: {:?}",
206                         path.display(),
207                         err
208                     );
209                     None
210                 }
211             },
212         };
213
214         let watch = match self.config.files().watcher {
215             FilesWatcher::Client => vec![],
216             FilesWatcher::Notify => project_folders.watch,
217         };
218         self.loader.handle.set_config(vfs::loader::Config { load: project_folders.load, watch });
219
220         // Create crate graph from all the workspaces
221         let crate_graph = {
222             let mut crate_graph = CrateGraph::default();
223             let vfs = &mut self.vfs.write().0;
224             let loader = &mut self.loader;
225             let mem_docs = &self.mem_docs;
226             let mut load = |path: &AbsPath| {
227                 let vfs_path = vfs::VfsPath::from(path.to_path_buf());
228                 if !mem_docs.contains_key(&vfs_path) {
229                     let contents = loader.handle.load_sync(path);
230                     vfs.set_file_contents(vfs_path.clone(), contents);
231                 }
232                 let res = vfs.file_id(&vfs_path);
233                 if res.is_none() {
234                     log::warn!("failed to load {}", path.display())
235                 }
236                 res
237             };
238             for ws in workspaces.iter() {
239                 crate_graph.extend(ws.to_crate_graph(
240                     self.config.cargo().target.as_deref(),
241                     self.proc_macro_client.as_ref(),
242                     &mut load,
243                 ));
244             }
245
246             crate_graph
247         };
248         change.set_crate_graph(crate_graph);
249
250         self.source_root_config = project_folders.source_root_config;
251         self.workspaces = Arc::new(workspaces);
252
253         self.analysis_host.apply_change(change);
254         self.process_changes();
255         self.reload_flycheck();
256         log::info!("did switch workspaces");
257     }
258
259     fn reload_flycheck(&mut self) {
260         let config = match self.config.flycheck() {
261             Some(it) => it,
262             None => {
263                 self.flycheck = Vec::new();
264                 return;
265             }
266         };
267
268         let sender = self.flycheck_sender.clone();
269         self.flycheck = self
270             .workspaces
271             .iter()
272             .enumerate()
273             .filter_map(|(id, w)| match w {
274                 ProjectWorkspace::Cargo { cargo, sysroot: _, rustc: _ } => {
275                     Some((id, cargo.workspace_root()))
276                 }
277                 ProjectWorkspace::Json { project, .. } => {
278                     // Enable flychecks for json projects if a custom flycheck command was supplied
279                     // in the workspace configuration.
280                     match config {
281                         FlycheckConfig::CustomCommand { .. } => Some((id, project.path())),
282                         _ => None,
283                     }
284                 }
285             })
286             .map(|(id, root)| {
287                 let sender = sender.clone();
288                 FlycheckHandle::spawn(
289                     id,
290                     Box::new(move |msg| sender.send(msg).unwrap()),
291                     config.clone(),
292                     root.to_path_buf().into(),
293                 )
294             })
295             .collect();
296     }
297 }
298
299 #[derive(Default)]
300 pub(crate) struct ProjectFolders {
301     pub(crate) load: Vec<vfs::loader::Entry>,
302     pub(crate) watch: Vec<usize>,
303     pub(crate) source_root_config: SourceRootConfig,
304 }
305
306 impl ProjectFolders {
307     pub(crate) fn new(workspaces: &[ProjectWorkspace]) -> ProjectFolders {
308         let mut res = ProjectFolders::default();
309         let mut fsc = FileSetConfig::builder();
310         let mut local_filesets = vec![];
311
312         for root in workspaces.iter().flat_map(|it| it.to_roots()) {
313             let file_set_roots: Vec<VfsPath> =
314                 root.include.iter().cloned().map(VfsPath::from).collect();
315
316             let entry = {
317                 let mut dirs = vfs::loader::Directories::default();
318                 dirs.extensions.push("rs".into());
319                 dirs.include.extend(root.include);
320                 dirs.exclude.extend(root.exclude);
321                 vfs::loader::Entry::Directories(dirs)
322             };
323
324             if root.is_member {
325                 res.watch.push(res.load.len());
326             }
327             res.load.push(entry);
328
329             if root.is_member {
330                 local_filesets.push(fsc.len());
331             }
332             fsc.add_file_set(file_set_roots)
333         }
334
335         let fsc = fsc.build();
336         res.source_root_config = SourceRootConfig { fsc, local_filesets };
337
338         res
339     }
340 }
341
342 #[derive(Default, Debug)]
343 pub(crate) struct SourceRootConfig {
344     pub(crate) fsc: FileSetConfig,
345     pub(crate) local_filesets: Vec<usize>,
346 }
347
348 impl SourceRootConfig {
349     pub(crate) fn partition(&self, vfs: &vfs::Vfs) -> Vec<SourceRoot> {
350         let _p = profile::span("SourceRootConfig::partition");
351         self.fsc
352             .partition(vfs)
353             .into_iter()
354             .enumerate()
355             .map(|(idx, file_set)| {
356                 let is_local = self.local_filesets.contains(&idx);
357                 if is_local {
358                     SourceRoot::new_local(file_set)
359                 } else {
360                     SourceRoot::new_library(file_set)
361                 }
362             })
363             .collect()
364     }
365 }