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