]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/reload.rs
Merge #10076
[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 hir::db::DefDatabase;
6 use ide::Change;
7 use ide_db::base_db::{
8     CrateGraph, Env, ProcMacro, ProcMacroExpander, ProcMacroKind, SourceRoot, VfsPath,
9 };
10 use proc_macro_api::ProcMacroClient;
11 use project_model::{ProjectWorkspace, WorkspaceBuildScripts};
12 use vfs::{file_set::FileSetConfig, AbsPath, AbsPathBuf, ChangeKind};
13
14 use crate::{
15     config::{Config, FilesWatcher, LinkedProject},
16     global_state::GlobalState,
17     lsp_ext,
18     main_loop::Task,
19 };
20
21 #[derive(Debug)]
22 pub(crate) enum ProjectWorkspaceProgress {
23     Begin,
24     Report(String),
25     End(Vec<anyhow::Result<ProjectWorkspace>>),
26 }
27
28 #[derive(Debug)]
29 pub(crate) enum BuildDataProgress {
30     Begin,
31     Report(String),
32     End((Arc<Vec<ProjectWorkspace>>, Vec<anyhow::Result<WorkspaceBuildScripts>>)),
33 }
34
35 impl GlobalState {
36     pub(crate) fn is_quiescent(&self) -> bool {
37         !(self.fetch_workspaces_queue.op_in_progress()
38             || self.fetch_build_data_queue.op_in_progress()
39             || self.vfs_progress_config_version < self.vfs_config_version
40             || self.vfs_progress_n_done < self.vfs_progress_n_total)
41     }
42
43     pub(crate) fn update_configuration(&mut self, config: Config) {
44         let _p = profile::span("GlobalState::update_configuration");
45         let old_config = mem::replace(&mut self.config, Arc::new(config));
46         if self.config.lru_capacity() != old_config.lru_capacity() {
47             self.analysis_host.update_lru_capacity(self.config.lru_capacity());
48         }
49         if self.config.linked_projects() != old_config.linked_projects() {
50             self.fetch_workspaces_queue.request_op()
51         } else if self.config.flycheck() != old_config.flycheck() {
52             self.reload_flycheck();
53         }
54
55         // Apply experimental feature flags.
56         self.analysis_host
57             .raw_database_mut()
58             .set_enable_proc_attr_macros(self.config.expand_proc_attr_macros());
59     }
60     pub(crate) fn maybe_refresh(&mut self, changes: &[(AbsPathBuf, ChangeKind)]) {
61         if !changes.iter().any(|(path, kind)| is_interesting(path, *kind)) {
62             return;
63         }
64         tracing::info!(
65             "Requesting workspace reload because of the following changes: {}",
66             itertools::join(
67                 changes
68                     .iter()
69                     .filter(|(path, kind)| is_interesting(path, *kind))
70                     .map(|(path, kind)| format!("{}: {:?}", path.display(), kind)),
71                 ", "
72             )
73         );
74         self.fetch_workspaces_queue.request_op();
75
76         fn is_interesting(path: &AbsPath, change_kind: ChangeKind) -> bool {
77             const IMPLICIT_TARGET_FILES: &[&str] = &["build.rs", "src/main.rs", "src/lib.rs"];
78             const IMPLICIT_TARGET_DIRS: &[&str] = &["src/bin", "examples", "tests", "benches"];
79             let file_name = path.file_name().unwrap_or_default();
80
81             if file_name == "Cargo.toml" || file_name == "Cargo.lock" {
82                 return true;
83             }
84             if change_kind == ChangeKind::Modify {
85                 return false;
86             }
87             if path.extension().unwrap_or_default() != "rs" {
88                 return false;
89             }
90             if IMPLICIT_TARGET_FILES.iter().any(|it| path.as_ref().ends_with(it)) {
91                 return true;
92             }
93             let parent = match path.parent() {
94                 Some(it) => it,
95                 None => return false,
96             };
97             if IMPLICIT_TARGET_DIRS.iter().any(|it| parent.as_ref().ends_with(it)) {
98                 return true;
99             }
100             if file_name == "main.rs" {
101                 let grand_parent = match parent.parent() {
102                     Some(it) => it,
103                     None => return false,
104                 };
105                 if IMPLICIT_TARGET_DIRS.iter().any(|it| grand_parent.as_ref().ends_with(it)) {
106                     return true;
107                 }
108             }
109             false
110         }
111     }
112
113     pub(crate) fn current_status(&self) -> lsp_ext::ServerStatusParams {
114         let mut status = lsp_ext::ServerStatusParams {
115             health: lsp_ext::Health::Ok,
116             quiescent: self.is_quiescent(),
117             message: None,
118         };
119
120         if let Some(error) = self.fetch_build_data_error() {
121             status.health = lsp_ext::Health::Warning;
122             status.message = Some(error)
123         }
124         if !self.config.cargo_autoreload()
125             && self.is_quiescent()
126             && self.fetch_workspaces_queue.op_requested()
127         {
128             status.health = lsp_ext::Health::Warning;
129             status.message = Some("Workspace reload required".to_string())
130         }
131
132         if let Some(error) = self.fetch_workspace_error() {
133             status.health = lsp_ext::Health::Error;
134             status.message = Some(error)
135         }
136         status
137     }
138
139     pub(crate) fn fetch_workspaces(&mut self) {
140         tracing::info!("will fetch workspaces");
141
142         self.task_pool.handle.spawn_with_sender({
143             let linked_projects = self.config.linked_projects();
144             let detached_files = self.config.detached_files().to_vec();
145             let cargo_config = self.config.cargo();
146
147             move |sender| {
148                 let progress = {
149                     let sender = sender.clone();
150                     move |msg| {
151                         sender
152                             .send(Task::FetchWorkspace(ProjectWorkspaceProgress::Report(msg)))
153                             .unwrap()
154                     }
155                 };
156
157                 sender.send(Task::FetchWorkspace(ProjectWorkspaceProgress::Begin)).unwrap();
158
159                 let mut workspaces = linked_projects
160                     .iter()
161                     .map(|project| match project {
162                         LinkedProject::ProjectManifest(manifest) => {
163                             project_model::ProjectWorkspace::load(
164                                 manifest.clone(),
165                                 &cargo_config,
166                                 &progress,
167                             )
168                         }
169                         LinkedProject::InlineJsonProject(it) => {
170                             project_model::ProjectWorkspace::load_inline(
171                                 it.clone(),
172                                 cargo_config.target.as_deref(),
173                             )
174                         }
175                     })
176                     .collect::<Vec<_>>();
177
178                 if !detached_files.is_empty() {
179                     workspaces
180                         .push(project_model::ProjectWorkspace::load_detached_files(detached_files));
181                 }
182
183                 tracing::info!("did fetch workspaces {:?}", workspaces);
184                 sender
185                     .send(Task::FetchWorkspace(ProjectWorkspaceProgress::End(workspaces)))
186                     .unwrap();
187             }
188         });
189     }
190
191     pub(crate) fn fetch_build_data(&mut self) {
192         let workspaces = Arc::clone(&self.workspaces);
193         let config = self.config.cargo();
194         self.task_pool.handle.spawn_with_sender(move |sender| {
195             sender.send(Task::FetchBuildData(BuildDataProgress::Begin)).unwrap();
196
197             let progress = {
198                 let sender = sender.clone();
199                 move |msg| {
200                     sender.send(Task::FetchBuildData(BuildDataProgress::Report(msg))).unwrap()
201                 }
202             };
203             let mut res = Vec::new();
204             for ws in workspaces.iter() {
205                 res.push(ws.run_build_scripts(&config, &progress));
206             }
207             sender.send(Task::FetchBuildData(BuildDataProgress::End((workspaces, res)))).unwrap();
208         });
209     }
210
211     pub(crate) fn switch_workspaces(&mut self) {
212         let _p = profile::span("GlobalState::switch_workspaces");
213         tracing::info!("will switch workspaces");
214
215         if let Some(error_message) = self.fetch_workspace_error() {
216             tracing::error!("failed to switch workspaces: {}", error_message);
217             if !self.workspaces.is_empty() {
218                 // It only makes sense to switch to a partially broken workspace
219                 // if we don't have any workspace at all yet.
220                 return;
221             }
222         }
223
224         if let Some(error_message) = self.fetch_build_data_error() {
225             tracing::error!("failed to switch build data: {}", error_message);
226         }
227
228         let workspaces = self
229             .fetch_workspaces_queue
230             .last_op_result()
231             .iter()
232             .filter_map(|res| res.as_ref().ok().cloned())
233             .collect::<Vec<_>>();
234
235         fn eq_ignore_build_data<'a>(
236             left: &'a ProjectWorkspace,
237             right: &'a ProjectWorkspace,
238         ) -> bool {
239             let key = |p: &'a ProjectWorkspace| match p {
240                 ProjectWorkspace::Cargo {
241                     cargo,
242                     sysroot,
243                     rustc,
244                     rustc_cfg,
245                     cfg_overrides,
246
247                     build_scripts: _,
248                 } => Some((cargo, sysroot, rustc, rustc_cfg, cfg_overrides)),
249                 _ => None,
250             };
251             match (key(left), key(right)) {
252                 (Some(lk), Some(rk)) => lk == rk,
253                 _ => left == right,
254             }
255         }
256
257         let same_workspaces = workspaces.len() == self.workspaces.len()
258             && workspaces
259                 .iter()
260                 .zip(self.workspaces.iter())
261                 .all(|(l, r)| eq_ignore_build_data(l, r));
262
263         if same_workspaces {
264             let (workspaces, build_scripts) = self.fetch_build_data_queue.last_op_result();
265             if Arc::ptr_eq(&workspaces, &self.workspaces) {
266                 let workspaces = workspaces
267                     .iter()
268                     .cloned()
269                     .zip(build_scripts)
270                     .map(|(mut ws, bs)| {
271                         ws.set_build_scripts(bs.as_ref().ok().cloned().unwrap_or_default());
272                         ws
273                     })
274                     .collect::<Vec<_>>();
275
276                 // Workspaces are the same, but we've updated build data.
277                 self.workspaces = Arc::new(workspaces);
278             } else {
279                 // Current build scripts do not match the version of the active
280                 // workspace, so there's nothing for us to update.
281                 return;
282             }
283         } else {
284             // Here, we completely changed the workspace (Cargo.toml edit), so
285             // we don't care about build-script results, they are stale.
286             self.workspaces = Arc::new(workspaces)
287         }
288
289         if let FilesWatcher::Client = self.config.files().watcher {
290             if self.config.did_change_watched_files_dynamic_registration() {
291                 let registration_options = lsp_types::DidChangeWatchedFilesRegistrationOptions {
292                     watchers: self
293                         .workspaces
294                         .iter()
295                         .flat_map(|ws| ws.to_roots())
296                         .filter(|it| it.is_member)
297                         .flat_map(|root| {
298                             root.include.into_iter().flat_map(|it| {
299                                 [
300                                     format!("{}/**/*.rs", it.display()),
301                                     format!("{}/**/Cargo.toml", it.display()),
302                                     format!("{}/**/Cargo.lock", it.display()),
303                                 ]
304                             })
305                         })
306                         .map(|glob_pattern| lsp_types::FileSystemWatcher {
307                             glob_pattern,
308                             kind: None,
309                         })
310                         .collect(),
311                 };
312                 let registration = lsp_types::Registration {
313                     id: "workspace/didChangeWatchedFiles".to_string(),
314                     method: "workspace/didChangeWatchedFiles".to_string(),
315                     register_options: Some(serde_json::to_value(registration_options).unwrap()),
316                 };
317                 self.send_request::<lsp_types::request::RegisterCapability>(
318                     lsp_types::RegistrationParams { registrations: vec![registration] },
319                     |_, _| (),
320                 );
321             }
322         }
323
324         let mut change = Change::new();
325
326         let files_config = self.config.files();
327         let project_folders = ProjectFolders::new(&self.workspaces, &files_config.exclude);
328
329         if self.proc_macro_client.is_none() {
330             self.proc_macro_client = match self.config.proc_macro_srv() {
331                 None => None,
332                 Some((path, args)) => match ProcMacroClient::extern_process(path.clone(), args) {
333                     Ok(it) => Some(it),
334                     Err(err) => {
335                         tracing::error!(
336                             "Failed to run proc_macro_srv from path {}, error: {:?}",
337                             path.display(),
338                             err
339                         );
340                         None
341                     }
342                 },
343             };
344         }
345
346         let watch = match files_config.watcher {
347             FilesWatcher::Client => vec![],
348             FilesWatcher::Notify => project_folders.watch,
349         };
350         self.vfs_config_version += 1;
351         self.loader.handle.set_config(vfs::loader::Config {
352             load: project_folders.load,
353             watch,
354             version: self.vfs_config_version,
355         });
356
357         // Create crate graph from all the workspaces
358         let crate_graph = {
359             let proc_macro_client = self.proc_macro_client.as_ref();
360             let mut load_proc_macro =
361                 move |path: &AbsPath| load_proc_macro(proc_macro_client, path);
362
363             let vfs = &mut self.vfs.write().0;
364             let loader = &mut self.loader;
365             let mem_docs = &self.mem_docs;
366             let mut load = move |path: &AbsPath| {
367                 let _p = profile::span("GlobalState::load");
368                 let vfs_path = vfs::VfsPath::from(path.to_path_buf());
369                 if !mem_docs.contains(&vfs_path) {
370                     let contents = loader.handle.load_sync(path);
371                     vfs.set_file_contents(vfs_path.clone(), contents);
372                 }
373                 let res = vfs.file_id(&vfs_path);
374                 if res.is_none() {
375                     tracing::warn!("failed to load {}", path.display())
376                 }
377                 res
378             };
379
380             let mut crate_graph = CrateGraph::default();
381             for ws in self.workspaces.iter() {
382                 crate_graph.extend(ws.to_crate_graph(&mut load_proc_macro, &mut load));
383             }
384             crate_graph
385         };
386         change.set_crate_graph(crate_graph);
387
388         self.source_root_config = project_folders.source_root_config;
389
390         self.analysis_host.apply_change(change);
391         self.process_changes();
392         self.reload_flycheck();
393         tracing::info!("did switch workspaces");
394     }
395
396     fn fetch_workspace_error(&self) -> Option<String> {
397         let mut buf = String::new();
398
399         for ws in self.fetch_workspaces_queue.last_op_result() {
400             if let Err(err) = ws {
401                 stdx::format_to!(buf, "rust-analyzer failed to load workspace: {:#}\n", err);
402             }
403         }
404
405         if buf.is_empty() {
406             return None;
407         }
408
409         Some(buf)
410     }
411
412     fn fetch_build_data_error(&self) -> Option<String> {
413         let mut buf = "rust-analyzer failed to run build scripts:\n".to_string();
414         let mut has_errors = false;
415
416         for ws in &self.fetch_build_data_queue.last_op_result().1 {
417             match ws {
418                 Ok(data) => {
419                     if let Some(err) = data.error() {
420                         has_errors = true;
421                         stdx::format_to!(buf, "{:#}\n", err);
422                     }
423                 }
424                 Err(err) => {
425                     has_errors = true;
426                     stdx::format_to!(buf, "{:#}\n", err);
427                 }
428             }
429         }
430
431         if has_errors {
432             Some(buf)
433         } else {
434             None
435         }
436     }
437
438     fn reload_flycheck(&mut self) {
439         let _p = profile::span("GlobalState::reload_flycheck");
440         let config = match self.config.flycheck() {
441             Some(it) => it,
442             None => {
443                 self.flycheck = Vec::new();
444                 return;
445             }
446         };
447
448         let sender = self.flycheck_sender.clone();
449         self.flycheck = self
450             .workspaces
451             .iter()
452             .enumerate()
453             .filter_map(|(id, w)| match w {
454                 ProjectWorkspace::Cargo { cargo, .. } => Some((id, cargo.workspace_root())),
455                 ProjectWorkspace::Json { project, .. } => {
456                     // Enable flychecks for json projects if a custom flycheck command was supplied
457                     // in the workspace configuration.
458                     match config {
459                         FlycheckConfig::CustomCommand { .. } => Some((id, project.path())),
460                         _ => None,
461                     }
462                 }
463                 ProjectWorkspace::DetachedFiles { .. } => None,
464             })
465             .map(|(id, root)| {
466                 let sender = sender.clone();
467                 FlycheckHandle::spawn(
468                     id,
469                     Box::new(move |msg| sender.send(msg).unwrap()),
470                     config.clone(),
471                     root.to_path_buf().into(),
472                 )
473             })
474             .collect();
475     }
476 }
477
478 #[derive(Default)]
479 pub(crate) struct ProjectFolders {
480     pub(crate) load: Vec<vfs::loader::Entry>,
481     pub(crate) watch: Vec<usize>,
482     pub(crate) source_root_config: SourceRootConfig,
483 }
484
485 impl ProjectFolders {
486     pub(crate) fn new(
487         workspaces: &[ProjectWorkspace],
488         global_excludes: &[AbsPathBuf],
489     ) -> ProjectFolders {
490         let mut res = ProjectFolders::default();
491         let mut fsc = FileSetConfig::builder();
492         let mut local_filesets = vec![];
493
494         for root in workspaces.iter().flat_map(|ws| ws.to_roots()) {
495             let file_set_roots: Vec<VfsPath> =
496                 root.include.iter().cloned().map(VfsPath::from).collect();
497
498             let entry = {
499                 let mut dirs = vfs::loader::Directories::default();
500                 dirs.extensions.push("rs".into());
501                 dirs.include.extend(root.include);
502                 dirs.exclude.extend(root.exclude);
503                 for excl in global_excludes {
504                     if dirs
505                         .include
506                         .iter()
507                         .any(|incl| incl.starts_with(excl) || excl.starts_with(incl))
508                     {
509                         dirs.exclude.push(excl.clone());
510                     }
511                 }
512
513                 vfs::loader::Entry::Directories(dirs)
514             };
515
516             if root.is_member {
517                 res.watch.push(res.load.len());
518             }
519             res.load.push(entry);
520
521             if root.is_member {
522                 local_filesets.push(fsc.len());
523             }
524             fsc.add_file_set(file_set_roots)
525         }
526
527         let fsc = fsc.build();
528         res.source_root_config = SourceRootConfig { fsc, local_filesets };
529
530         res
531     }
532 }
533
534 #[derive(Default, Debug)]
535 pub(crate) struct SourceRootConfig {
536     pub(crate) fsc: FileSetConfig,
537     pub(crate) local_filesets: Vec<usize>,
538 }
539
540 impl SourceRootConfig {
541     pub(crate) fn partition(&self, vfs: &vfs::Vfs) -> Vec<SourceRoot> {
542         let _p = profile::span("SourceRootConfig::partition");
543         self.fsc
544             .partition(vfs)
545             .into_iter()
546             .enumerate()
547             .map(|(idx, file_set)| {
548                 let is_local = self.local_filesets.contains(&idx);
549                 if is_local {
550                     SourceRoot::new_local(file_set)
551                 } else {
552                     SourceRoot::new_library(file_set)
553                 }
554             })
555             .collect()
556     }
557 }
558
559 pub(crate) fn load_proc_macro(client: Option<&ProcMacroClient>, path: &AbsPath) -> Vec<ProcMacro> {
560     return client
561         .map(|it| it.by_dylib_path(path))
562         .unwrap_or_default()
563         .into_iter()
564         .map(expander_to_proc_macro)
565         .collect();
566
567     fn expander_to_proc_macro(expander: proc_macro_api::ProcMacroProcessExpander) -> ProcMacro {
568         let name = expander.name().into();
569         let kind = match expander.kind() {
570             proc_macro_api::ProcMacroKind::CustomDerive => ProcMacroKind::CustomDerive,
571             proc_macro_api::ProcMacroKind::FuncLike => ProcMacroKind::FuncLike,
572             proc_macro_api::ProcMacroKind::Attr => ProcMacroKind::Attr,
573         };
574         let expander = Arc::new(Expander(expander));
575         ProcMacro { name, kind, expander }
576     }
577
578     #[derive(Debug)]
579     struct Expander(proc_macro_api::ProcMacroProcessExpander);
580
581     impl ProcMacroExpander for Expander {
582         fn expand(
583             &self,
584             subtree: &tt::Subtree,
585             attrs: Option<&tt::Subtree>,
586             env: &Env,
587         ) -> Result<tt::Subtree, tt::ExpansionError> {
588             let env = env.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
589             self.0.expand(subtree, attrs, env)
590         }
591     }
592 }