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