]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/reload.rs
Honor client's dynamic registration caps
[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 ide::Change;
6 use ide_db::base_db::{CrateGraph, SourceRoot, VfsPath};
7 use project_model::{ProcMacroClient, ProjectWorkspace};
8 use vfs::{file_set::FileSetConfig, AbsPath, AbsPathBuf, ChangeKind};
9
10 use crate::{
11     config::{Config, FilesWatcher, LinkedProject},
12     global_state::{GlobalState, Status},
13     lsp_ext,
14     main_loop::Task,
15 };
16 use lsp_ext::StatusParams;
17
18 #[derive(Debug)]
19 pub(crate) enum ProjectWorkspaceProgress {
20     Begin,
21     Report(String),
22     End(Vec<anyhow::Result<ProjectWorkspace>>),
23 }
24
25 impl GlobalState {
26     pub(crate) fn update_configuration(&mut self, config: Config) {
27         let _p = profile::span("GlobalState::update_configuration");
28         let old_config = mem::replace(&mut self.config, Arc::new(config));
29         if self.config.lru_capacity() != old_config.lru_capacity() {
30             self.analysis_host.update_lru_capacity(self.config.lru_capacity());
31         }
32         if self.config.linked_projects() != old_config.linked_projects() {
33             self.fetch_workspaces_request()
34         } else if self.config.flycheck() != old_config.flycheck() {
35             self.reload_flycheck();
36         }
37     }
38     pub(crate) fn maybe_refresh(&mut self, changes: &[(AbsPathBuf, ChangeKind)]) {
39         if !changes.iter().any(|(path, kind)| is_interesting(path, *kind)) {
40             return;
41         }
42         match self.status {
43             Status::Loading | Status::NeedsReload => return,
44             Status::Ready | Status::Invalid => (),
45         }
46         if self.config.cargo_autoreload() {
47             self.fetch_workspaces_request();
48         } else {
49             self.transition(Status::NeedsReload);
50         }
51
52         fn is_interesting(path: &AbsPath, change_kind: ChangeKind) -> bool {
53             const IMPLICIT_TARGET_FILES: &[&str] = &["build.rs", "src/main.rs", "src/lib.rs"];
54             const IMPLICIT_TARGET_DIRS: &[&str] = &["src/bin", "examples", "tests", "benches"];
55
56             if path.ends_with("Cargo.toml") || path.ends_with("Cargo.lock") {
57                 return true;
58             }
59             if change_kind == ChangeKind::Modify {
60                 return false;
61             }
62             if path.extension().unwrap_or_default() != "rs" {
63                 return false;
64             }
65             if IMPLICIT_TARGET_FILES.iter().any(|it| path.ends_with(it)) {
66                 return true;
67             }
68             let parent = match path.parent() {
69                 Some(it) => it,
70                 None => return false,
71             };
72             if IMPLICIT_TARGET_DIRS.iter().any(|it| parent.ends_with(it)) {
73                 return true;
74             }
75             if path.ends_with("main.rs") {
76                 let grand_parent = match parent.parent() {
77                     Some(it) => it,
78                     None => return false,
79                 };
80                 if IMPLICIT_TARGET_DIRS.iter().any(|it| grand_parent.ends_with(it)) {
81                     return true;
82                 }
83             }
84             false
85         }
86     }
87     pub(crate) fn transition(&mut self, new_status: Status) {
88         self.status = new_status;
89         if self.config.status_notification() {
90             let lsp_status = match new_status {
91                 Status::Loading => lsp_ext::Status::Loading,
92                 Status::Ready => lsp_ext::Status::Ready,
93                 Status::Invalid => lsp_ext::Status::Invalid,
94                 Status::NeedsReload => lsp_ext::Status::NeedsReload,
95             };
96             self.send_notification::<lsp_ext::StatusNotification>(StatusParams {
97                 status: lsp_status,
98             });
99         }
100     }
101
102     pub(crate) fn fetch_workspaces_request(&mut self) {
103         self.fetch_workspaces_queue.request_op()
104     }
105     pub(crate) fn fetch_workspaces_if_needed(&mut self) {
106         log::info!("will fetch workspaces");
107         if !self.fetch_workspaces_queue.should_start_op() {
108             return;
109         }
110
111         self.task_pool.handle.spawn_with_sender({
112             let linked_projects = self.config.linked_projects();
113             let cargo_config = self.config.cargo();
114
115             move |sender| {
116                 let progress = {
117                     let sender = sender.clone();
118                     move |msg| {
119                         sender
120                             .send(Task::FetchWorkspace(ProjectWorkspaceProgress::Report(msg)))
121                             .unwrap()
122                     }
123                 };
124
125                 sender.send(Task::FetchWorkspace(ProjectWorkspaceProgress::Begin)).unwrap();
126
127                 let workspaces = linked_projects
128                     .iter()
129                     .map(|project| match project {
130                         LinkedProject::ProjectManifest(manifest) => {
131                             project_model::ProjectWorkspace::load(
132                                 manifest.clone(),
133                                 &cargo_config,
134                                 &progress,
135                             )
136                         }
137                         LinkedProject::InlineJsonProject(it) => {
138                             project_model::ProjectWorkspace::load_inline(it.clone())
139                         }
140                     })
141                     .collect::<Vec<_>>();
142
143                 log::info!("did fetch workspaces {:?}", workspaces);
144                 sender
145                     .send(Task::FetchWorkspace(ProjectWorkspaceProgress::End(workspaces)))
146                     .unwrap();
147             }
148         });
149     }
150     pub(crate) fn fetch_workspaces_completed(&mut self) {
151         self.fetch_workspaces_queue.op_completed()
152     }
153
154     pub(crate) fn switch_workspaces(&mut self, workspaces: Vec<anyhow::Result<ProjectWorkspace>>) {
155         let _p = profile::span("GlobalState::switch_workspaces");
156         log::info!("will switch workspaces: {:?}", workspaces);
157
158         let mut has_errors = false;
159         let workspaces = workspaces
160             .into_iter()
161             .filter_map(|res| {
162                 res.map_err(|err| {
163                     has_errors = true;
164                     log::error!("failed to load workspace: {:#}", err);
165                     if self.workspaces.is_empty() {
166                         self.show_message(
167                             lsp_types::MessageType::Error,
168                             format!("rust-analyzer failed to load workspace: {:#}", err),
169                         );
170                     }
171                 })
172                 .ok()
173             })
174             .collect::<Vec<_>>();
175
176         if &*self.workspaces == &workspaces {
177             return;
178         }
179
180         if !self.workspaces.is_empty() && has_errors {
181             return;
182         }
183
184         if let FilesWatcher::Client = self.config.files().watcher {
185             if self.config.did_change_watched_files_dynamic_registration() {
186                 let registration_options = lsp_types::DidChangeWatchedFilesRegistrationOptions {
187                     watchers: workspaces
188                         .iter()
189                         .flat_map(ProjectWorkspace::to_roots)
190                         .filter(|it| it.is_member)
191                         .flat_map(|root| {
192                             root.include.into_iter().map(|it| format!("{}/**/*.rs", it.display()))
193                         })
194                         .map(|glob_pattern| lsp_types::FileSystemWatcher {
195                             glob_pattern,
196                             kind: None,
197                         })
198                         .collect(),
199                 };
200                 let registration = lsp_types::Registration {
201                     id: "workspace/didChangeWatchedFiles".to_string(),
202                     method: "workspace/didChangeWatchedFiles".to_string(),
203                     register_options: Some(serde_json::to_value(registration_options).unwrap()),
204                 };
205                 self.send_request::<lsp_types::request::RegisterCapability>(
206                     lsp_types::RegistrationParams { registrations: vec![registration] },
207                     |_, _| (),
208                 );
209             }
210         }
211
212         let mut change = Change::new();
213
214         let project_folders = ProjectFolders::new(&workspaces);
215
216         self.proc_macro_client = match self.config.proc_macro_srv() {
217             None => None,
218             Some((path, args)) => match ProcMacroClient::extern_process(path.clone(), args) {
219                 Ok(it) => Some(it),
220                 Err(err) => {
221                     log::error!(
222                         "Failed to run proc_macro_srv from path {}, error: {:?}",
223                         path.display(),
224                         err
225                     );
226                     None
227                 }
228             },
229         };
230
231         let watch = match self.config.files().watcher {
232             FilesWatcher::Client => vec![],
233             FilesWatcher::Notify => project_folders.watch,
234         };
235         self.loader.handle.set_config(vfs::loader::Config { load: project_folders.load, watch });
236
237         // Create crate graph from all the workspaces
238         let crate_graph = {
239             let mut crate_graph = CrateGraph::default();
240             let vfs = &mut self.vfs.write().0;
241             let loader = &mut self.loader;
242             let mem_docs = &self.mem_docs;
243             let mut load = |path: &AbsPath| {
244                 let vfs_path = vfs::VfsPath::from(path.to_path_buf());
245                 if !mem_docs.contains_key(&vfs_path) {
246                     let contents = loader.handle.load_sync(path);
247                     vfs.set_file_contents(vfs_path.clone(), contents);
248                 }
249                 let res = vfs.file_id(&vfs_path);
250                 if res.is_none() {
251                     log::warn!("failed to load {}", path.display())
252                 }
253                 res
254             };
255             for ws in workspaces.iter() {
256                 crate_graph.extend(ws.to_crate_graph(
257                     self.config.cargo().target.as_deref(),
258                     self.proc_macro_client.as_ref(),
259                     &mut load,
260                 ));
261             }
262
263             crate_graph
264         };
265         change.set_crate_graph(crate_graph);
266
267         self.source_root_config = project_folders.source_root_config;
268         self.workspaces = Arc::new(workspaces);
269
270         self.analysis_host.apply_change(change);
271         self.process_changes();
272         self.reload_flycheck();
273         log::info!("did switch workspaces");
274     }
275
276     fn reload_flycheck(&mut self) {
277         let config = match self.config.flycheck() {
278             Some(it) => it,
279             None => {
280                 self.flycheck = Vec::new();
281                 return;
282             }
283         };
284
285         let sender = self.flycheck_sender.clone();
286         self.flycheck = self
287             .workspaces
288             .iter()
289             .enumerate()
290             .filter_map(|(id, w)| match w {
291                 ProjectWorkspace::Cargo { cargo, sysroot: _, rustc: _ } => {
292                     Some((id, cargo.workspace_root()))
293                 }
294                 ProjectWorkspace::Json { project, .. } => {
295                     // Enable flychecks for json projects if a custom flycheck command was supplied
296                     // in the workspace configuration.
297                     match config {
298                         FlycheckConfig::CustomCommand { .. } => Some((id, project.path())),
299                         _ => None,
300                     }
301                 }
302             })
303             .map(|(id, root)| {
304                 let sender = sender.clone();
305                 FlycheckHandle::spawn(
306                     id,
307                     Box::new(move |msg| sender.send(msg).unwrap()),
308                     config.clone(),
309                     root.to_path_buf().into(),
310                 )
311             })
312             .collect();
313     }
314 }
315
316 #[derive(Default)]
317 pub(crate) struct ProjectFolders {
318     pub(crate) load: Vec<vfs::loader::Entry>,
319     pub(crate) watch: Vec<usize>,
320     pub(crate) source_root_config: SourceRootConfig,
321 }
322
323 impl ProjectFolders {
324     pub(crate) fn new(workspaces: &[ProjectWorkspace]) -> ProjectFolders {
325         let mut res = ProjectFolders::default();
326         let mut fsc = FileSetConfig::builder();
327         let mut local_filesets = vec![];
328
329         for root in workspaces.iter().flat_map(|it| it.to_roots()) {
330             let file_set_roots: Vec<VfsPath> =
331                 root.include.iter().cloned().map(VfsPath::from).collect();
332
333             let entry = {
334                 let mut dirs = vfs::loader::Directories::default();
335                 dirs.extensions.push("rs".into());
336                 dirs.include.extend(root.include);
337                 dirs.exclude.extend(root.exclude);
338                 vfs::loader::Entry::Directories(dirs)
339             };
340
341             if root.is_member {
342                 res.watch.push(res.load.len());
343             }
344             res.load.push(entry);
345
346             if root.is_member {
347                 local_filesets.push(fsc.len());
348             }
349             fsc.add_file_set(file_set_roots)
350         }
351
352         let fsc = fsc.build();
353         res.source_root_config = SourceRootConfig { fsc, local_filesets };
354
355         res
356     }
357 }
358
359 #[derive(Default, Debug)]
360 pub(crate) struct SourceRootConfig {
361     pub(crate) fsc: FileSetConfig,
362     pub(crate) local_filesets: Vec<usize>,
363 }
364
365 impl SourceRootConfig {
366     pub(crate) fn partition(&self, vfs: &vfs::Vfs) -> Vec<SourceRoot> {
367         let _p = profile::span("SourceRootConfig::partition");
368         self.fsc
369             .partition(vfs)
370             .into_iter()
371             .enumerate()
372             .map(|(idx, file_set)| {
373                 let is_local = self.local_filesets.contains(&idx);
374                 if is_local {
375                     SourceRoot::new_local(file_set)
376                 } else {
377                     SourceRoot::new_library(file_set)
378                 }
379             })
380             .collect()
381     }
382 }