]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/reload.rs
Merge #7386
[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(Vec<anyhow::Result<ProjectWorkspace>>),
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_request()
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_request();
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
102     pub(crate) fn fetch_workspaces_request(&mut self) {
103         self.fetch_workspaces_queue.request_op()
104     }
105     pub(crate) fn fetch_workspaces_if_needed(&mut self) {
106         log::info!("will fetch workspaces");
107         if !self.fetch_workspaces_queue.should_start_op() {
108             return;
109         }
110
111         self.task_pool.handle.spawn_with_sender({
112             let linked_projects = self.config.linked_projects();
113             let cargo_config = self.config.cargo();
114
115             move |sender| {
116                 let progress = {
117                     let sender = sender.clone();
118                     move |msg| {
119                         sender
120                             .send(Task::FetchWorkspace(ProjectWorkspaceProgress::Report(msg)))
121                             .unwrap()
122                     }
123                 };
124
125                 sender.send(Task::FetchWorkspace(ProjectWorkspaceProgress::Begin)).unwrap();
126
127                 let workspaces = linked_projects
128                     .iter()
129                     .map(|project| match project {
130                         LinkedProject::ProjectManifest(manifest) => {
131                             project_model::ProjectWorkspace::load(
132                                 manifest.clone(),
133                                 &cargo_config,
134                                 &progress,
135                             )
136                         }
137                         LinkedProject::InlineJsonProject(it) => {
138                             project_model::ProjectWorkspace::load_inline(
139                                 it.clone(),
140                                 cargo_config.target.as_deref(),
141                             )
142                         }
143                     })
144                     .collect::<Vec<_>>();
145
146                 log::info!("did fetch workspaces {:?}", workspaces);
147                 sender
148                     .send(Task::FetchWorkspace(ProjectWorkspaceProgress::End(workspaces)))
149                     .unwrap();
150             }
151         });
152     }
153     pub(crate) fn fetch_workspaces_completed(&mut self) {
154         self.fetch_workspaces_queue.op_completed()
155     }
156
157     pub(crate) fn switch_workspaces(&mut self, workspaces: Vec<anyhow::Result<ProjectWorkspace>>) {
158         let _p = profile::span("GlobalState::switch_workspaces");
159         log::info!("will switch workspaces: {:?}", workspaces);
160
161         let mut has_errors = false;
162         let workspaces = workspaces
163             .into_iter()
164             .filter_map(|res| {
165                 res.map_err(|err| {
166                     has_errors = true;
167                     log::error!("failed to load workspace: {:#}", err);
168                     if self.workspaces.is_empty() {
169                         self.show_message(
170                             lsp_types::MessageType::Error,
171                             format!("rust-analyzer failed to load workspace: {:#}", err),
172                         );
173                     }
174                 })
175                 .ok()
176             })
177             .collect::<Vec<_>>();
178
179         if &*self.workspaces == &workspaces {
180             return;
181         }
182
183         if !self.workspaces.is_empty() && has_errors {
184             return;
185         }
186
187         if let FilesWatcher::Client = self.config.files().watcher {
188             if self.config.did_change_watched_files_dynamic_registration() {
189                 let registration_options = lsp_types::DidChangeWatchedFilesRegistrationOptions {
190                     watchers: workspaces
191                         .iter()
192                         .flat_map(ProjectWorkspace::to_roots)
193                         .filter(|it| it.is_member)
194                         .flat_map(|root| {
195                             root.include.into_iter().map(|it| format!("{}/**/*.rs", it.display()))
196                         })
197                         .map(|glob_pattern| lsp_types::FileSystemWatcher {
198                             glob_pattern,
199                             kind: None,
200                         })
201                         .collect(),
202                 };
203                 let registration = lsp_types::Registration {
204                     id: "workspace/didChangeWatchedFiles".to_string(),
205                     method: "workspace/didChangeWatchedFiles".to_string(),
206                     register_options: Some(serde_json::to_value(registration_options).unwrap()),
207                 };
208                 self.send_request::<lsp_types::request::RegisterCapability>(
209                     lsp_types::RegistrationParams { registrations: vec![registration] },
210                     |_, _| (),
211                 );
212             }
213         }
214
215         let mut change = Change::new();
216
217         let project_folders = ProjectFolders::new(&workspaces);
218
219         self.proc_macro_client = match self.config.proc_macro_srv() {
220             None => None,
221             Some((path, args)) => match ProcMacroClient::extern_process(path.clone(), args) {
222                 Ok(it) => Some(it),
223                 Err(err) => {
224                     log::error!(
225                         "Failed to run proc_macro_srv from path {}, error: {:?}",
226                         path.display(),
227                         err
228                     );
229                     None
230                 }
231             },
232         };
233
234         let watch = match self.config.files().watcher {
235             FilesWatcher::Client => vec![],
236             FilesWatcher::Notify => project_folders.watch,
237         };
238         self.loader.handle.set_config(vfs::loader::Config { load: project_folders.load, watch });
239
240         // Create crate graph from all the workspaces
241         let crate_graph = {
242             let mut crate_graph = CrateGraph::default();
243             let vfs = &mut self.vfs.write().0;
244             let loader = &mut self.loader;
245             let mem_docs = &self.mem_docs;
246             let mut load = |path: &AbsPath| {
247                 let vfs_path = vfs::VfsPath::from(path.to_path_buf());
248                 if !mem_docs.contains_key(&vfs_path) {
249                     let contents = loader.handle.load_sync(path);
250                     vfs.set_file_contents(vfs_path.clone(), contents);
251                 }
252                 let res = vfs.file_id(&vfs_path);
253                 if res.is_none() {
254                     log::warn!("failed to load {}", path.display())
255                 }
256                 res
257             };
258             for ws in workspaces.iter() {
259                 crate_graph.extend(ws.to_crate_graph(self.proc_macro_client.as_ref(), &mut load));
260             }
261
262             crate_graph
263         };
264         change.set_crate_graph(crate_graph);
265
266         self.source_root_config = project_folders.source_root_config;
267         self.workspaces = Arc::new(workspaces);
268
269         self.analysis_host.apply_change(change);
270         self.process_changes();
271         self.reload_flycheck();
272         log::info!("did switch workspaces");
273     }
274
275     fn reload_flycheck(&mut self) {
276         let _p = profile::span("GlobalState::reload_flycheck");
277         let config = match self.config.flycheck() {
278             Some(it) => it,
279             None => {
280                 self.flycheck = Vec::new();
281                 return;
282             }
283         };
284
285         let sender = self.flycheck_sender.clone();
286         self.flycheck = self
287             .workspaces
288             .iter()
289             .enumerate()
290             .filter_map(|(id, w)| match w {
291                 ProjectWorkspace::Cargo { cargo, .. } => Some((id, cargo.workspace_root())),
292                 ProjectWorkspace::Json { project, .. } => {
293                     // Enable flychecks for json projects if a custom flycheck command was supplied
294                     // in the workspace configuration.
295                     match config {
296                         FlycheckConfig::CustomCommand { .. } => Some((id, project.path())),
297                         _ => None,
298                     }
299                 }
300             })
301             .map(|(id, root)| {
302                 let sender = sender.clone();
303                 FlycheckHandle::spawn(
304                     id,
305                     Box::new(move |msg| sender.send(msg).unwrap()),
306                     config.clone(),
307                     root.to_path_buf().into(),
308                 )
309             })
310             .collect();
311     }
312 }
313
314 #[derive(Default)]
315 pub(crate) struct ProjectFolders {
316     pub(crate) load: Vec<vfs::loader::Entry>,
317     pub(crate) watch: Vec<usize>,
318     pub(crate) source_root_config: SourceRootConfig,
319 }
320
321 impl ProjectFolders {
322     pub(crate) fn new(workspaces: &[ProjectWorkspace]) -> ProjectFolders {
323         let mut res = ProjectFolders::default();
324         let mut fsc = FileSetConfig::builder();
325         let mut local_filesets = vec![];
326
327         for root in workspaces.iter().flat_map(|it| it.to_roots()) {
328             let file_set_roots: Vec<VfsPath> =
329                 root.include.iter().cloned().map(VfsPath::from).collect();
330
331             let entry = {
332                 let mut dirs = vfs::loader::Directories::default();
333                 dirs.extensions.push("rs".into());
334                 dirs.include.extend(root.include);
335                 dirs.exclude.extend(root.exclude);
336                 vfs::loader::Entry::Directories(dirs)
337             };
338
339             if root.is_member {
340                 res.watch.push(res.load.len());
341             }
342             res.load.push(entry);
343
344             if root.is_member {
345                 local_filesets.push(fsc.len());
346             }
347             fsc.add_file_set(file_set_roots)
348         }
349
350         let fsc = fsc.build();
351         res.source_root_config = SourceRootConfig { fsc, local_filesets };
352
353         res
354     }
355 }
356
357 #[derive(Default, Debug)]
358 pub(crate) struct SourceRootConfig {
359     pub(crate) fsc: FileSetConfig,
360     pub(crate) local_filesets: Vec<usize>,
361 }
362
363 impl SourceRootConfig {
364     pub(crate) fn partition(&self, vfs: &vfs::Vfs) -> Vec<SourceRoot> {
365         let _p = profile::span("SourceRootConfig::partition");
366         self.fsc
367             .partition(vfs)
368             .into_iter()
369             .enumerate()
370             .map(|(idx, file_set)| {
371                 let is_local = self.local_filesets.contains(&idx);
372                 if is_local {
373                     SourceRoot::new_local(file_set)
374                 } else {
375                     SourceRoot::new_library(file_set)
376                 }
377             })
378             .collect()
379     }
380 }