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