]> git.lizzy.rs Git - rust.git/blob - crates/rust-analyzer/src/global_state.rs
Flatten Task enum ¯\_(ツ)_/¯
[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::{
7     path::{Path, PathBuf},
8     sync::Arc,
9 };
10
11 use crossbeam_channel::{unbounded, Receiver};
12 use lsp_types::Url;
13 use parking_lot::RwLock;
14 use ra_flycheck::{Flycheck, FlycheckConfig};
15 use ra_ide::{Analysis, AnalysisChange, AnalysisHost, CrateGraph, FileId, SourceRootId};
16 use ra_project_model::{CargoWorkspace, ProcMacroClient, ProjectWorkspace, Target};
17 use ra_vfs::{LineEndings, RootEntry, Vfs, VfsChange, VfsFile, VfsTask, Watch};
18 use stdx::format_to;
19
20 use crate::{
21     config::{Config, FilesWatcher},
22     diagnostics::{CheckFixes, DiagnosticCollection},
23     main_loop::pending_requests::{CompletedRequest, LatestRequests},
24     to_proto::url_from_abs_path,
25     vfs_glob::{Glob, RustPackageFilterBuilder},
26     LspError, Result,
27 };
28 use ra_db::{CrateId, ExternSourceId};
29 use ra_progress::{ProgressSource, ProgressStatus};
30 use rustc_hash::{FxHashMap, FxHashSet};
31
32 fn create_flycheck(
33     workspaces: &[ProjectWorkspace],
34     config: &FlycheckConfig,
35     progress_src: &ProgressSource<(), String>,
36 ) -> Option<Flycheck> {
37     // FIXME: Figure out the multi-workspace situation
38     workspaces.iter().find_map(move |w| match w {
39         ProjectWorkspace::Cargo { cargo, .. } => {
40             let cargo_project_root = cargo.workspace_root().to_path_buf();
41             Some(Flycheck::new(config.clone(), cargo_project_root, progress_src.clone()))
42         }
43         ProjectWorkspace::Json { .. } => {
44             log::warn!("Cargo check watching only supported for cargo workspaces, disabling");
45             None
46         }
47     })
48 }
49
50 /// `GlobalState` is the primary mutable state of the language server
51 ///
52 /// The most interesting components are `vfs`, which stores a consistent
53 /// snapshot of the file systems, and `analysis_host`, which stores our
54 /// incremental salsa database.
55 #[derive(Debug)]
56 pub struct GlobalState {
57     pub config: Config,
58     pub local_roots: Vec<PathBuf>,
59     pub workspaces: Arc<Vec<ProjectWorkspace>>,
60     pub analysis_host: AnalysisHost,
61     pub vfs: Arc<RwLock<Vfs>>,
62     pub task_receiver: Receiver<VfsTask>,
63     pub latest_requests: Arc<RwLock<LatestRequests>>,
64     pub flycheck: Option<Flycheck>,
65     pub diagnostics: DiagnosticCollection,
66     pub proc_macro_client: ProcMacroClient,
67     pub flycheck_progress_src: ProgressSource<(), String>,
68     pub flycheck_progress_receiver: Receiver<ProgressStatus<(), String>>,
69 }
70
71 /// An immutable snapshot of the world's state at a point in time.
72 pub struct GlobalStateSnapshot {
73     pub config: Config,
74     pub workspaces: Arc<Vec<ProjectWorkspace>>,
75     pub analysis: Analysis,
76     pub latest_requests: Arc<RwLock<LatestRequests>>,
77     pub check_fixes: CheckFixes,
78     vfs: Arc<RwLock<Vfs>>,
79 }
80
81 impl GlobalState {
82     pub fn new(
83         workspaces: Vec<ProjectWorkspace>,
84         lru_capacity: Option<usize>,
85         exclude_globs: &[Glob],
86         config: Config,
87     ) -> GlobalState {
88         let mut change = AnalysisChange::new();
89
90         let mut extern_dirs: FxHashSet<PathBuf> = FxHashSet::default();
91
92         let mut local_roots = Vec::new();
93         let roots: Vec<_> = {
94             let create_filter = |is_member| {
95                 RustPackageFilterBuilder::default()
96                     .set_member(is_member)
97                     .exclude(exclude_globs.iter().cloned())
98                     .into_vfs_filter()
99             };
100             let mut roots = Vec::new();
101             for root in workspaces.iter().flat_map(ProjectWorkspace::to_roots) {
102                 let path = root.path().to_owned();
103                 if root.is_member() {
104                     local_roots.push(path.clone());
105                 }
106                 roots.push(RootEntry::new(path, create_filter(root.is_member())));
107                 if let Some(out_dir) = root.out_dir() {
108                     extern_dirs.insert(out_dir.to_path_buf());
109                     roots.push(RootEntry::new(
110                         out_dir.to_path_buf(),
111                         create_filter(root.is_member()),
112                     ))
113                 }
114             }
115             roots
116         };
117
118         let (task_sender, task_receiver) = unbounded();
119         let task_sender = Box::new(move |t| task_sender.send(t).unwrap());
120         let watch = Watch(matches!(config.files.watcher, FilesWatcher::Notify));
121         let (mut vfs, vfs_roots) = Vfs::new(roots, task_sender, watch);
122
123         let mut extern_source_roots = FxHashMap::default();
124         for r in vfs_roots {
125             let vfs_root_path = vfs.root2path(r);
126             let is_local = local_roots.iter().any(|it| vfs_root_path.starts_with(it));
127             change.add_root(SourceRootId(r.0), is_local);
128
129             // FIXME: add path2root in vfs to simpily this logic
130             if extern_dirs.contains(&vfs_root_path) {
131                 extern_source_roots.insert(vfs_root_path, ExternSourceId(r.0));
132             }
133         }
134
135         let proc_macro_client = match &config.proc_macro_srv {
136             None => ProcMacroClient::dummy(),
137             Some((path, args)) => match ProcMacroClient::extern_process(path.into(), args) {
138                 Ok(it) => it,
139                 Err(err) => {
140                     log::error!(
141                         "Failed to run ra_proc_macro_srv from path {}, error: {:?}",
142                         path.display(),
143                         err
144                     );
145                     ProcMacroClient::dummy()
146                 }
147             },
148         };
149
150         // Create crate graph from all the workspaces
151         let mut crate_graph = CrateGraph::default();
152         let mut load = |path: &Path| {
153             // Some path from metadata will be non canonicalized, e.g. /foo/../bar/lib.rs
154             let path = path.canonicalize().ok()?;
155             let vfs_file = vfs.load(&path);
156             vfs_file.map(|f| FileId(f.0))
157         };
158         for ws in workspaces.iter() {
159             crate_graph.extend(ws.to_crate_graph(
160                 config.cargo.target.as_deref(),
161                 &extern_source_roots,
162                 &proc_macro_client,
163                 &mut load,
164             ));
165         }
166         change.set_crate_graph(crate_graph);
167
168         let (flycheck_progress_receiver, flycheck_progress_src) =
169             ProgressSource::real_if(config.client_caps.work_done_progress);
170         let flycheck = config
171             .check
172             .as_ref()
173             .and_then(|c| create_flycheck(&workspaces, c, &flycheck_progress_src));
174
175         let mut analysis_host = AnalysisHost::new(lru_capacity);
176         analysis_host.apply_change(change);
177         GlobalState {
178             config,
179             local_roots,
180             workspaces: Arc::new(workspaces),
181             analysis_host,
182             vfs: Arc::new(RwLock::new(vfs)),
183             task_receiver,
184             latest_requests: Default::default(),
185             flycheck,
186             flycheck_progress_src,
187             flycheck_progress_receiver,
188             diagnostics: Default::default(),
189             proc_macro_client,
190         }
191     }
192
193     pub fn update_configuration(&mut self, config: Config) {
194         self.analysis_host.update_lru_capacity(config.lru_capacity);
195         if config.check != self.config.check {
196             self.flycheck = config
197                 .check
198                 .as_ref()
199                 .and_then(|it| create_flycheck(&self.workspaces, it, &self.flycheck_progress_src));
200         }
201
202         self.config = config;
203     }
204
205     /// Returns a vec of libraries
206     /// FIXME: better API here
207     pub fn process_changes(&mut self, roots_scanned: &mut u32) -> bool {
208         let changes = self.vfs.write().commit_changes();
209         if changes.is_empty() {
210             return false;
211         }
212         let mut change = AnalysisChange::new();
213         for c in changes {
214             match c {
215                 VfsChange::AddRoot { root, files } => {
216                     *roots_scanned += 1;
217                     for (file, path, text) in files {
218                         change.add_file(SourceRootId(root.0), FileId(file.0), path, text);
219                     }
220                 }
221                 VfsChange::AddFile { root, file, path, text } => {
222                     change.add_file(SourceRootId(root.0), FileId(file.0), path, text);
223                 }
224                 VfsChange::RemoveFile { root, file, path } => {
225                     change.remove_file(SourceRootId(root.0), FileId(file.0), path)
226                 }
227                 VfsChange::ChangeFile { file, text } => {
228                     change.change_file(FileId(file.0), text);
229                 }
230             }
231         }
232         self.analysis_host.apply_change(change);
233         true
234     }
235
236     pub fn snapshot(&self) -> GlobalStateSnapshot {
237         GlobalStateSnapshot {
238             config: self.config.clone(),
239             workspaces: Arc::clone(&self.workspaces),
240             analysis: self.analysis_host.analysis(),
241             vfs: Arc::clone(&self.vfs),
242             latest_requests: Arc::clone(&self.latest_requests),
243             check_fixes: Arc::clone(&self.diagnostics.check_fixes),
244         }
245     }
246
247     pub fn maybe_collect_garbage(&mut self) {
248         self.analysis_host.maybe_collect_garbage()
249     }
250
251     pub fn collect_garbage(&mut self) {
252         self.analysis_host.collect_garbage()
253     }
254
255     pub fn complete_request(&mut self, request: CompletedRequest) {
256         self.latest_requests.write().record(request)
257     }
258 }
259
260 impl GlobalStateSnapshot {
261     pub fn analysis(&self) -> &Analysis {
262         &self.analysis
263     }
264
265     pub fn url_to_file_id(&self, url: &Url) -> Result<FileId> {
266         let path = url.to_file_path().map_err(|()| format!("invalid uri: {}", url))?;
267         let file = self.vfs.read().path2file(&path).ok_or_else(|| {
268             // Show warning as this file is outside current workspace
269             // FIXME: just handle such files, and remove `LspError::UNKNOWN_FILE`.
270             LspError {
271                 code: LspError::UNKNOWN_FILE,
272                 message: "Rust file outside current workspace is not supported yet.".to_string(),
273             }
274         })?;
275         Ok(FileId(file.0))
276     }
277
278     pub fn file_id_to_url(&self, id: FileId) -> Url {
279         file_id_to_url(&self.vfs.read(), id)
280     }
281
282     pub fn file_line_endings(&self, id: FileId) -> LineEndings {
283         self.vfs.read().file_line_endings(VfsFile(id.0))
284     }
285
286     pub fn anchored_path(&self, file_id: FileId, path: &str) -> Url {
287         let mut base = self.vfs.read().file2path(VfsFile(file_id.0));
288         base.pop();
289         let path = base.join(path);
290         url_from_abs_path(&path)
291     }
292
293     pub(crate) fn cargo_target_for_crate_root(
294         &self,
295         crate_id: CrateId,
296     ) -> Option<(&CargoWorkspace, Target)> {
297         let file_id = self.analysis().crate_root(crate_id).ok()?;
298         let path = self.vfs.read().file2path(VfsFile(file_id.0));
299         self.workspaces.iter().find_map(|ws| match ws {
300             ProjectWorkspace::Cargo { cargo, .. } => {
301                 cargo.target_by_root(&path).map(|it| (cargo, it))
302             }
303             ProjectWorkspace::Json { .. } => None,
304         })
305     }
306
307     pub fn status(&self) -> String {
308         let mut buf = String::new();
309         if self.workspaces.is_empty() {
310             buf.push_str("no workspaces\n")
311         } else {
312             buf.push_str("workspaces:\n");
313             for w in self.workspaces.iter() {
314                 format_to!(buf, "{} packages loaded\n", w.n_packages());
315             }
316         }
317         buf.push_str("\nanalysis:\n");
318         buf.push_str(
319             &self
320                 .analysis
321                 .status()
322                 .unwrap_or_else(|_| "Analysis retrieval was cancelled".to_owned()),
323         );
324         buf
325     }
326
327     pub fn workspace_root_for(&self, file_id: FileId) -> Option<&Path> {
328         let path = self.vfs.read().file2path(VfsFile(file_id.0));
329         self.workspaces.iter().find_map(|ws| ws.workspace_root_for(&path))
330     }
331 }
332
333 pub(crate) fn file_id_to_url(vfs: &Vfs, id: FileId) -> Url {
334     let path = vfs.file2path(VfsFile(id.0));
335     url_from_abs_path(&path)
336 }