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