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