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