]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/reload.rs
Merge #10558
[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 let Some(error) = self.fetch_build_data_error() {
70             status.health = lsp_ext::Health::Warning;
71             status.message = Some(error)
72         }
73         if !self.config.cargo_autoreload()
74             && self.is_quiescent()
75             && self.fetch_workspaces_queue.op_requested()
76         {
77             status.health = lsp_ext::Health::Warning;
78             status.message = Some("Workspace reload required".to_string())
79         }
80
81         if let Some(error) = self.fetch_workspace_error() {
82             status.health = lsp_ext::Health::Error;
83             status.message = Some(error)
84         }
85         status
86     }
87
88     pub(crate) fn fetch_workspaces(&mut self) {
89         tracing::info!("will fetch workspaces");
90
91         self.task_pool.handle.spawn_with_sender({
92             let linked_projects = self.config.linked_projects();
93             let detached_files = self.config.detached_files().to_vec();
94             let cargo_config = self.config.cargo();
95
96             move |sender| {
97                 let progress = {
98                     let sender = sender.clone();
99                     move |msg| {
100                         sender
101                             .send(Task::FetchWorkspace(ProjectWorkspaceProgress::Report(msg)))
102                             .unwrap()
103                     }
104                 };
105
106                 sender.send(Task::FetchWorkspace(ProjectWorkspaceProgress::Begin)).unwrap();
107
108                 let mut workspaces = linked_projects
109                     .iter()
110                     .map(|project| match project {
111                         LinkedProject::ProjectManifest(manifest) => {
112                             project_model::ProjectWorkspace::load(
113                                 manifest.clone(),
114                                 &cargo_config,
115                                 &progress,
116                             )
117                         }
118                         LinkedProject::InlineJsonProject(it) => {
119                             project_model::ProjectWorkspace::load_inline(
120                                 it.clone(),
121                                 cargo_config.target.as_deref(),
122                             )
123                         }
124                     })
125                     .collect::<Vec<_>>();
126
127                 if !detached_files.is_empty() {
128                     workspaces
129                         .push(project_model::ProjectWorkspace::load_detached_files(detached_files));
130                 }
131
132                 tracing::info!("did fetch workspaces {:?}", workspaces);
133                 sender
134                     .send(Task::FetchWorkspace(ProjectWorkspaceProgress::End(workspaces)))
135                     .unwrap();
136             }
137         });
138     }
139
140     pub(crate) fn fetch_build_data(&mut self) {
141         let workspaces = Arc::clone(&self.workspaces);
142         let config = self.config.cargo();
143         self.task_pool.handle.spawn_with_sender(move |sender| {
144             sender.send(Task::FetchBuildData(BuildDataProgress::Begin)).unwrap();
145
146             let progress = {
147                 let sender = sender.clone();
148                 move |msg| {
149                     sender.send(Task::FetchBuildData(BuildDataProgress::Report(msg))).unwrap()
150                 }
151             };
152             let mut res = Vec::new();
153             for ws in workspaces.iter() {
154                 res.push(ws.run_build_scripts(&config, &progress));
155             }
156             sender.send(Task::FetchBuildData(BuildDataProgress::End((workspaces, res)))).unwrap();
157         });
158     }
159
160     pub(crate) fn switch_workspaces(&mut self) {
161         let _p = profile::span("GlobalState::switch_workspaces");
162         tracing::info!("will switch workspaces");
163
164         if let Some(error_message) = self.fetch_workspace_error() {
165             tracing::error!("failed to switch workspaces: {}", error_message);
166             if !self.workspaces.is_empty() {
167                 // It only makes sense to switch to a partially broken workspace
168                 // if we don't have any workspace at all yet.
169                 return;
170             }
171         }
172
173         if let Some(error_message) = self.fetch_build_data_error() {
174             tracing::error!("failed to switch build data: {}", error_message);
175         }
176
177         let workspaces = self
178             .fetch_workspaces_queue
179             .last_op_result()
180             .iter()
181             .filter_map(|res| res.as_ref().ok().cloned())
182             .collect::<Vec<_>>();
183
184         fn eq_ignore_build_data<'a>(
185             left: &'a ProjectWorkspace,
186             right: &'a ProjectWorkspace,
187         ) -> bool {
188             let key = |p: &'a ProjectWorkspace| match p {
189                 ProjectWorkspace::Cargo {
190                     cargo,
191                     sysroot,
192                     rustc,
193                     rustc_cfg,
194                     cfg_overrides,
195
196                     build_scripts: _,
197                 } => Some((cargo, sysroot, rustc, rustc_cfg, cfg_overrides)),
198                 _ => None,
199             };
200             match (key(left), key(right)) {
201                 (Some(lk), Some(rk)) => lk == rk,
202                 _ => left == right,
203             }
204         }
205
206         let same_workspaces = workspaces.len() == self.workspaces.len()
207             && workspaces
208                 .iter()
209                 .zip(self.workspaces.iter())
210                 .all(|(l, r)| eq_ignore_build_data(l, r));
211
212         if same_workspaces {
213             let (workspaces, build_scripts) = self.fetch_build_data_queue.last_op_result();
214             if Arc::ptr_eq(workspaces, &self.workspaces) {
215                 let workspaces = workspaces
216                     .iter()
217                     .cloned()
218                     .zip(build_scripts)
219                     .map(|(mut ws, bs)| {
220                         ws.set_build_scripts(bs.as_ref().ok().cloned().unwrap_or_default());
221                         ws
222                     })
223                     .collect::<Vec<_>>();
224
225                 // Workspaces are the same, but we've updated build data.
226                 self.workspaces = Arc::new(workspaces);
227             } else {
228                 // Current build scripts do not match the version of the active
229                 // workspace, so there's nothing for us to update.
230                 return;
231             }
232         } else {
233             // Here, we completely changed the workspace (Cargo.toml edit), so
234             // we don't care about build-script results, they are stale.
235             self.workspaces = Arc::new(workspaces)
236         }
237
238         if let FilesWatcher::Client = self.config.files().watcher {
239             if self.config.did_change_watched_files_dynamic_registration() {
240                 let registration_options = lsp_types::DidChangeWatchedFilesRegistrationOptions {
241                     watchers: self
242                         .workspaces
243                         .iter()
244                         .flat_map(|ws| ws.to_roots())
245                         .filter(|it| it.is_local)
246                         .flat_map(|root| {
247                             root.include.into_iter().flat_map(|it| {
248                                 [
249                                     format!("{}/**/*.rs", it.display()),
250                                     format!("{}/**/Cargo.toml", it.display()),
251                                     format!("{}/**/Cargo.lock", it.display()),
252                                 ]
253                             })
254                         })
255                         .map(|glob_pattern| lsp_types::FileSystemWatcher {
256                             glob_pattern,
257                             kind: None,
258                         })
259                         .collect(),
260                 };
261                 let registration = lsp_types::Registration {
262                     id: "workspace/didChangeWatchedFiles".to_string(),
263                     method: "workspace/didChangeWatchedFiles".to_string(),
264                     register_options: Some(serde_json::to_value(registration_options).unwrap()),
265                 };
266                 self.send_request::<lsp_types::request::RegisterCapability>(
267                     lsp_types::RegistrationParams { registrations: vec![registration] },
268                     |_, _| (),
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 }