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