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