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