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