]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/global_state.rs
Merge #5015 #5027 #5028
[rust.git] / crates / rust-analyzer / src / global_state.rs
1 //! The context or environment in which the language server functions. In our
2 //! server implementation this is know as the `WorldState`.
3 //!
4 //! Each tick provides an immutable snapshot of the state as `WorldSnapshot`.
5
6 use std::{convert::TryFrom, path::Path, sync::Arc};
7
8 use crossbeam_channel::{unbounded, Receiver};
9 use lsp_types::Url;
10 use parking_lot::RwLock;
11 use ra_db::{CrateId, SourceRoot, VfsPath};
12 use ra_flycheck::{Flycheck, FlycheckConfig};
13 use ra_ide::{Analysis, AnalysisChange, AnalysisHost, CrateGraph, FileId};
14 use ra_project_model::{CargoWorkspace, ProcMacroClient, ProjectWorkspace, Target};
15 use stdx::format_to;
16 use vfs::{file_set::FileSetConfig, loader::Handle, AbsPathBuf};
17
18 use crate::{
19     config::{Config, FilesWatcher},
20     diagnostics::{CheckFixes, DiagnosticCollection},
21     from_proto,
22     line_endings::LineEndings,
23     main_loop::request_metrics::{LatestRequests, RequestMetrics},
24     to_proto::url_from_abs_path,
25     Result,
26 };
27 use rustc_hash::FxHashMap;
28
29 fn create_flycheck(workspaces: &[ProjectWorkspace], config: &FlycheckConfig) -> Option<Flycheck> {
30     // FIXME: Figure out the multi-workspace situation
31     workspaces.iter().find_map(|w| match w {
32         ProjectWorkspace::Cargo { cargo, .. } => {
33             let cargo_project_root = cargo.workspace_root().to_path_buf();
34             Some(Flycheck::new(config.clone(), cargo_project_root))
35         }
36         ProjectWorkspace::Json { .. } => {
37             log::warn!("Cargo check watching only supported for cargo workspaces, disabling");
38             None
39         }
40     })
41 }
42
43 /// `GlobalState` is the primary mutable state of the language server
44 ///
45 /// The most interesting components are `vfs`, which stores a consistent
46 /// snapshot of the file systems, and `analysis_host`, which stores our
47 /// incremental salsa database.
48 #[derive(Debug)]
49 pub struct GlobalState {
50     pub config: Config,
51     pub workspaces: Arc<Vec<ProjectWorkspace>>,
52     pub analysis_host: AnalysisHost,
53     pub loader: Box<dyn vfs::loader::Handle>,
54     pub task_receiver: Receiver<vfs::loader::Message>,
55     pub flycheck: Option<Flycheck>,
56     pub diagnostics: DiagnosticCollection,
57     pub proc_macro_client: ProcMacroClient,
58     pub(crate) vfs: Arc<RwLock<(vfs::Vfs, FxHashMap<FileId, LineEndings>)>>,
59     pub(crate) latest_requests: Arc<RwLock<LatestRequests>>,
60     source_root_config: SourceRootConfig,
61 }
62
63 /// An immutable snapshot of the world's state at a point in time.
64 pub struct GlobalStateSnapshot {
65     pub config: Config,
66     pub workspaces: Arc<Vec<ProjectWorkspace>>,
67     pub analysis: Analysis,
68     pub check_fixes: CheckFixes,
69     pub(crate) latest_requests: Arc<RwLock<LatestRequests>>,
70     vfs: Arc<RwLock<(vfs::Vfs, FxHashMap<FileId, LineEndings>)>>,
71 }
72
73 impl GlobalState {
74     pub fn new(
75         workspaces: Vec<ProjectWorkspace>,
76         lru_capacity: Option<usize>,
77         config: Config,
78     ) -> GlobalState {
79         let mut change = AnalysisChange::new();
80
81         let project_folders = ProjectFolders::new(&workspaces);
82
83         let (task_sender, task_receiver) = unbounded::<vfs::loader::Message>();
84         let mut vfs = vfs::Vfs::default();
85
86         let proc_macro_client = match &config.proc_macro_srv {
87             None => ProcMacroClient::dummy(),
88             Some((path, args)) => match ProcMacroClient::extern_process(path.into(), args) {
89                 Ok(it) => it,
90                 Err(err) => {
91                     log::error!(
92                         "Failed to run ra_proc_macro_srv from path {}, error: {:?}",
93                         path.display(),
94                         err
95                     );
96                     ProcMacroClient::dummy()
97                 }
98             },
99         };
100
101         let mut loader = {
102             let loader = vfs_notify::LoaderHandle::spawn(Box::new(move |msg| {
103                 task_sender.send(msg).unwrap()
104             }));
105             Box::new(loader)
106         };
107         let watch = match config.files.watcher {
108             FilesWatcher::Client => vec![],
109             FilesWatcher::Notify => project_folders.watch,
110         };
111         loader.set_config(vfs::loader::Config { load: project_folders.load, watch });
112
113         // Create crate graph from all the workspaces
114         let mut crate_graph = CrateGraph::default();
115         let mut load = |path: &Path| {
116             let path = AbsPathBuf::try_from(path.to_path_buf()).ok()?;
117             let contents = loader.load_sync(&path);
118             let path = vfs::VfsPath::from(path);
119             vfs.set_file_contents(path.clone(), contents);
120             vfs.file_id(&path)
121         };
122         for ws in workspaces.iter() {
123             crate_graph.extend(ws.to_crate_graph(
124                 config.cargo.target.as_deref(),
125                 &proc_macro_client,
126                 &mut load,
127             ));
128         }
129         change.set_crate_graph(crate_graph);
130
131         let flycheck = config.check.as_ref().and_then(|c| create_flycheck(&workspaces, c));
132
133         let mut analysis_host = AnalysisHost::new(lru_capacity);
134         analysis_host.apply_change(change);
135         let mut res = GlobalState {
136             config,
137             workspaces: Arc::new(workspaces),
138             analysis_host,
139             loader,
140             vfs: Arc::new(RwLock::new((vfs, FxHashMap::default()))),
141             task_receiver,
142             latest_requests: Default::default(),
143             flycheck,
144             diagnostics: Default::default(),
145             proc_macro_client,
146             source_root_config: project_folders.source_root_config,
147         };
148         res.process_changes();
149         res
150     }
151
152     pub fn update_configuration(&mut self, config: Config) {
153         self.analysis_host.update_lru_capacity(config.lru_capacity);
154         if config.check != self.config.check {
155             self.flycheck =
156                 config.check.as_ref().and_then(|it| create_flycheck(&self.workspaces, it));
157         }
158
159         self.config = config;
160     }
161
162     pub fn process_changes(&mut self) -> bool {
163         let change = {
164             let mut change = AnalysisChange::new();
165             let (vfs, line_endings_map) = &mut *self.vfs.write();
166             let changed_files = vfs.take_changes();
167             if changed_files.is_empty() {
168                 return false;
169             }
170
171             let fs_op = changed_files.iter().any(|it| it.is_created_or_deleted());
172             if fs_op {
173                 let roots = self.source_root_config.partition(&vfs);
174                 change.set_roots(roots)
175             }
176
177             for file in changed_files {
178                 let text = if file.exists() {
179                     let bytes = vfs.file_contents(file.file_id).to_vec();
180                     match String::from_utf8(bytes).ok() {
181                         Some(text) => {
182                             let (text, line_endings) = LineEndings::normalize(text);
183                             line_endings_map.insert(file.file_id, line_endings);
184                             Some(Arc::new(text))
185                         }
186                         None => None,
187                     }
188                 } else {
189                     None
190                 };
191                 change.change_file(file.file_id, text);
192             }
193             change
194         };
195
196         self.analysis_host.apply_change(change);
197         true
198     }
199
200     pub fn snapshot(&self) -> GlobalStateSnapshot {
201         GlobalStateSnapshot {
202             config: self.config.clone(),
203             workspaces: Arc::clone(&self.workspaces),
204             analysis: self.analysis_host.analysis(),
205             vfs: Arc::clone(&self.vfs),
206             latest_requests: Arc::clone(&self.latest_requests),
207             check_fixes: Arc::clone(&self.diagnostics.check_fixes),
208         }
209     }
210
211     pub fn maybe_collect_garbage(&mut self) {
212         self.analysis_host.maybe_collect_garbage()
213     }
214
215     pub fn collect_garbage(&mut self) {
216         self.analysis_host.collect_garbage()
217     }
218
219     pub(crate) fn complete_request(&mut self, request: RequestMetrics) {
220         self.latest_requests.write().record(request)
221     }
222 }
223
224 impl GlobalStateSnapshot {
225     pub(crate) fn analysis(&self) -> &Analysis {
226         &self.analysis
227     }
228
229     pub(crate) fn url_to_file_id(&self, url: &Url) -> Result<FileId> {
230         let path = from_proto::abs_path(url)?;
231         let path = path.into();
232         let res =
233             self.vfs.read().0.file_id(&path).ok_or_else(|| format!("file not found: {}", path))?;
234         Ok(res)
235     }
236
237     pub(crate) fn file_id_to_url(&self, id: FileId) -> Url {
238         file_id_to_url(&self.vfs.read().0, id)
239     }
240
241     pub(crate) fn file_line_endings(&self, id: FileId) -> LineEndings {
242         self.vfs.read().1[&id]
243     }
244
245     pub fn anchored_path(&self, file_id: FileId, path: &str) -> Url {
246         let mut base = self.vfs.read().0.file_path(file_id);
247         base.pop();
248         let path = base.join(path);
249         let path = path.as_path().unwrap();
250         url_from_abs_path(&path)
251     }
252
253     pub(crate) fn cargo_target_for_crate_root(
254         &self,
255         crate_id: CrateId,
256     ) -> Option<(&CargoWorkspace, Target)> {
257         let file_id = self.analysis().crate_root(crate_id).ok()?;
258         let path = self.vfs.read().0.file_path(file_id);
259         let path = path.as_path()?;
260         self.workspaces.iter().find_map(|ws| match ws {
261             ProjectWorkspace::Cargo { cargo, .. } => {
262                 cargo.target_by_root(&path).map(|it| (cargo, it))
263             }
264             ProjectWorkspace::Json { .. } => None,
265         })
266     }
267
268     pub fn status(&self) -> String {
269         let mut buf = String::new();
270         if self.workspaces.is_empty() {
271             buf.push_str("no workspaces\n")
272         } else {
273             buf.push_str("workspaces:\n");
274             for w in self.workspaces.iter() {
275                 format_to!(buf, "{} packages loaded\n", w.n_packages());
276             }
277         }
278         buf.push_str("\nanalysis:\n");
279         buf.push_str(
280             &self
281                 .analysis
282                 .status()
283                 .unwrap_or_else(|_| "Analysis retrieval was cancelled".to_owned()),
284         );
285         buf
286     }
287 }
288
289 pub(crate) fn file_id_to_url(vfs: &vfs::Vfs, id: FileId) -> Url {
290     let path = vfs.file_path(id);
291     let path = path.as_path().unwrap();
292     url_from_abs_path(&path)
293 }
294
295 #[derive(Default)]
296 pub(crate) struct ProjectFolders {
297     pub(crate) load: Vec<vfs::loader::Entry>,
298     pub(crate) watch: Vec<usize>,
299     pub(crate) source_root_config: SourceRootConfig,
300 }
301
302 impl ProjectFolders {
303     pub(crate) fn new(workspaces: &[ProjectWorkspace]) -> ProjectFolders {
304         let mut res = ProjectFolders::default();
305         let mut fsc = FileSetConfig::builder();
306         let mut local_filesets = vec![];
307
308         for root in workspaces.iter().flat_map(|it| it.to_roots()) {
309             let path = root.path().to_owned();
310
311             let mut file_set_roots: Vec<VfsPath> = vec![];
312
313             let entry = if root.is_member() {
314                 vfs::loader::Entry::local_cargo_package(path.to_path_buf())
315             } else {
316                 vfs::loader::Entry::cargo_package_dependency(path.to_path_buf())
317             };
318             res.load.push(entry);
319             if root.is_member() {
320                 res.watch.push(res.load.len() - 1);
321             }
322
323             if let Some(out_dir) = root.out_dir() {
324                 let out_dir = AbsPathBuf::try_from(out_dir.to_path_buf()).unwrap();
325                 res.load.push(vfs::loader::Entry::rs_files_recursively(out_dir.clone()));
326                 if root.is_member() {
327                     res.watch.push(res.load.len() - 1);
328                 }
329                 file_set_roots.push(out_dir.into());
330             }
331             file_set_roots.push(path.to_path_buf().into());
332
333             if root.is_member() {
334                 local_filesets.push(fsc.len());
335             }
336             fsc.add_file_set(file_set_roots)
337         }
338
339         let fsc = fsc.build();
340         res.source_root_config = SourceRootConfig { fsc, local_filesets };
341
342         res
343     }
344 }
345
346 #[derive(Default, Debug)]
347 pub(crate) struct SourceRootConfig {
348     pub(crate) fsc: FileSetConfig,
349     pub(crate) local_filesets: Vec<usize>,
350 }
351
352 impl SourceRootConfig {
353     pub fn partition(&self, vfs: &vfs::Vfs) -> Vec<SourceRoot> {
354         self.fsc
355             .partition(vfs)
356             .into_iter()
357             .enumerate()
358             .map(|(idx, file_set)| {
359                 let is_local = self.local_filesets.contains(&idx);
360                 if is_local {
361                     SourceRoot::new_local(file_set)
362                 } else {
363                     SourceRoot::new_library(file_set)
364                 }
365             })
366             .collect()
367     }
368 }