]> git.lizzy.rs Git - rust.git/blob - crates/ra_lsp_server/src/server_world.rs
automatically collect garbage
[rust.git] / crates / ra_lsp_server / src / server_world.rs
1 use std::{
2     path::PathBuf,
3     sync::Arc,
4 };
5
6 use lsp_types::Url;
7 use ra_ide_api::{
8     Analysis, AnalysisChange, AnalysisHost, CrateGraph, FileId, LibraryData,
9     SourceRootId
10 };
11 use ra_vfs::{Vfs, VfsChange, VfsFile, VfsRoot};
12 use rustc_hash::FxHashMap;
13 use relative_path::RelativePathBuf;
14 use parking_lot::RwLock;
15 use failure::format_err;
16
17 use crate::{
18     project_model::{ProjectWorkspace, TargetKind},
19     Result,
20 };
21
22 #[derive(Debug)]
23 pub struct ServerWorldState {
24     pub roots_to_scan: usize,
25     pub root: PathBuf,
26     pub workspaces: Arc<Vec<ProjectWorkspace>>,
27     pub analysis_host: AnalysisHost,
28     pub vfs: Arc<RwLock<Vfs>>,
29 }
30
31 pub struct ServerWorld {
32     pub workspaces: Arc<Vec<ProjectWorkspace>>,
33     pub analysis: Analysis,
34     pub vfs: Arc<RwLock<Vfs>>,
35 }
36
37 impl ServerWorldState {
38     pub fn new(root: PathBuf, workspaces: Vec<ProjectWorkspace>) -> ServerWorldState {
39         let mut change = AnalysisChange::new();
40
41         let mut roots = Vec::new();
42         roots.push(root.clone());
43         for ws in workspaces.iter() {
44             for pkg in ws.cargo.packages() {
45                 roots.push(pkg.root(&ws.cargo).to_path_buf());
46             }
47             for krate in ws.sysroot.crates() {
48                 roots.push(krate.root_dir(&ws.sysroot).to_path_buf())
49             }
50         }
51         roots.sort();
52         roots.dedup();
53         let roots_to_scan = roots.len();
54         let (mut vfs, roots) = Vfs::new(roots);
55         for r in roots {
56             let is_local = vfs.root2path(r).starts_with(&root);
57             change.add_root(SourceRootId(r.0.into()), is_local);
58         }
59
60         let mut crate_graph = CrateGraph::default();
61         for ws in workspaces.iter() {
62             // First, load std
63             let mut sysroot_crates = FxHashMap::default();
64             for krate in ws.sysroot.crates() {
65                 if let Some(file_id) = vfs.load(krate.root(&ws.sysroot)) {
66                     let file_id = FileId(file_id.0.into());
67                     sysroot_crates.insert(krate, crate_graph.add_crate_root(file_id));
68                 }
69             }
70             for from in ws.sysroot.crates() {
71                 for to in from.deps(&ws.sysroot) {
72                     let name = to.name(&ws.sysroot);
73                     if let (Some(&from), Some(&to)) =
74                         (sysroot_crates.get(&from), sysroot_crates.get(&to))
75                     {
76                         if let Err(_) = crate_graph.add_dep(from, name.clone(), to) {
77                             log::error!("cyclic dependency between sysroot crates")
78                         }
79                     }
80                 }
81             }
82
83             let libstd = ws
84                 .sysroot
85                 .std()
86                 .and_then(|it| sysroot_crates.get(&it).map(|&it| it));
87
88             let mut pkg_to_lib_crate = FxHashMap::default();
89             let mut pkg_crates = FxHashMap::default();
90             // Next, create crates for each package, target pair
91             for pkg in ws.cargo.packages() {
92                 let mut lib_tgt = None;
93                 for tgt in pkg.targets(&ws.cargo) {
94                     let root = tgt.root(&ws.cargo);
95                     if let Some(file_id) = vfs.load(root) {
96                         let file_id = FileId(file_id.0.into());
97                         let crate_id = crate_graph.add_crate_root(file_id);
98                         if tgt.kind(&ws.cargo) == TargetKind::Lib {
99                             lib_tgt = Some(crate_id);
100                             pkg_to_lib_crate.insert(pkg, crate_id);
101                         }
102                         pkg_crates
103                             .entry(pkg)
104                             .or_insert_with(Vec::new)
105                             .push(crate_id);
106                     }
107                 }
108
109                 // Set deps to the std and to the lib target of the current package
110                 for &from in pkg_crates.get(&pkg).into_iter().flatten() {
111                     if let Some(to) = lib_tgt {
112                         if to != from {
113                             if let Err(_) =
114                                 crate_graph.add_dep(from, pkg.name(&ws.cargo).into(), to)
115                             {
116                                 log::error!(
117                                     "cyclic dependency between targets of {}",
118                                     pkg.name(&ws.cargo)
119                                 )
120                             }
121                         }
122                     }
123                     if let Some(std) = libstd {
124                         if let Err(_) = crate_graph.add_dep(from, "std".into(), std) {
125                             log::error!("cyclic dependency on std for {}", pkg.name(&ws.cargo))
126                         }
127                     }
128                 }
129             }
130
131             // Now add a dep ednge from all targets of upstream to the lib
132             // target of downstream.
133             for pkg in ws.cargo.packages() {
134                 for dep in pkg.dependencies(&ws.cargo) {
135                     if let Some(&to) = pkg_to_lib_crate.get(&dep.pkg) {
136                         for &from in pkg_crates.get(&pkg).into_iter().flatten() {
137                             if let Err(_) = crate_graph.add_dep(from, dep.name.clone(), to) {
138                                 log::error!(
139                                     "cyclic dependency {} -> {}",
140                                     pkg.name(&ws.cargo),
141                                     dep.pkg.name(&ws.cargo)
142                                 )
143                             }
144                         }
145                     }
146                 }
147             }
148         }
149         change.set_crate_graph(crate_graph);
150
151         let mut analysis_host = AnalysisHost::default();
152         analysis_host.apply_change(change);
153         ServerWorldState {
154             roots_to_scan,
155             root,
156             workspaces: Arc::new(workspaces),
157             analysis_host,
158             vfs: Arc::new(RwLock::new(vfs)),
159         }
160     }
161
162     /// Returns a vec of libraries
163     /// FIXME: better API here
164     pub fn process_changes(
165         &mut self,
166     ) -> Vec<(SourceRootId, Vec<(FileId, RelativePathBuf, Arc<String>)>)> {
167         let changes = self.vfs.write().commit_changes();
168         if changes.is_empty() {
169             return Vec::new();
170         }
171         let mut libs = Vec::new();
172         let mut change = AnalysisChange::new();
173         for c in changes {
174             match c {
175                 VfsChange::AddRoot { root, files } => {
176                     let root_path = self.vfs.read().root2path(root);
177                     if root_path.starts_with(&self.root) {
178                         self.roots_to_scan -= 1;
179                         for (file, path, text) in files {
180                             change.add_file(
181                                 SourceRootId(root.0.into()),
182                                 FileId(file.0.into()),
183                                 path,
184                                 text,
185                             );
186                         }
187                     } else {
188                         let files = files
189                             .into_iter()
190                             .map(|(vfsfile, path, text)| (FileId(vfsfile.0.into()), path, text))
191                             .collect();
192                         libs.push((SourceRootId(root.0.into()), files));
193                     }
194                 }
195                 VfsChange::AddFile {
196                     root,
197                     file,
198                     path,
199                     text,
200                 } => {
201                     change.add_file(
202                         SourceRootId(root.0.into()),
203                         FileId(file.0.into()),
204                         path,
205                         text,
206                     );
207                 }
208                 VfsChange::RemoveFile { root, file, path } => {
209                     change.remove_file(SourceRootId(root.0.into()), FileId(file.0.into()), path)
210                 }
211                 VfsChange::ChangeFile { file, text } => {
212                     change.change_file(FileId(file.0.into()), text);
213                 }
214             }
215         }
216         self.analysis_host.apply_change(change);
217         libs
218     }
219
220     pub fn add_lib(&mut self, data: LibraryData) {
221         self.roots_to_scan -= 1;
222         let mut change = AnalysisChange::new();
223         change.add_library(data);
224         self.analysis_host.apply_change(change);
225     }
226
227     pub fn snapshot(&self) -> ServerWorld {
228         ServerWorld {
229             workspaces: Arc::clone(&self.workspaces),
230             analysis: self.analysis_host.analysis(),
231             vfs: Arc::clone(&self.vfs),
232         }
233     }
234
235     pub fn maybe_collect_garbage(&mut self) {
236         self.analysis_host.maybe_collect_garbage()
237     }
238
239     pub fn collect_garbage(&mut self) {
240         self.analysis_host.collect_garbage()
241     }
242 }
243
244 impl ServerWorld {
245     pub fn analysis(&self) -> &Analysis {
246         &self.analysis
247     }
248
249     pub fn uri_to_file_id(&self, uri: &Url) -> Result<FileId> {
250         let path = uri
251             .to_file_path()
252             .map_err(|()| format_err!("invalid uri: {}", uri))?;
253         let file = self
254             .vfs
255             .read()
256             .path2file(&path)
257             .ok_or_else(|| format_err!("unknown file: {}", path.display()))?;
258         Ok(FileId(file.0.into()))
259     }
260
261     pub fn file_id_to_uri(&self, id: FileId) -> Result<Url> {
262         let path = self.vfs.read().file2path(VfsFile(id.0.into()));
263         let url = Url::from_file_path(&path)
264             .map_err(|_| format_err!("can't convert path to url: {}", path.display()))?;
265         Ok(url)
266     }
267
268     pub fn path_to_uri(&self, root: SourceRootId, path: &RelativePathBuf) -> Result<Url> {
269         let base = self.vfs.read().root2path(VfsRoot(root.0.into()));
270         let path = path.to_path(base);
271         let url = Url::from_file_path(&path)
272             .map_err(|_| format_err!("can't convert path to url: {}", path.display()))?;
273         Ok(url)
274     }
275
276     pub fn status(&self) -> String {
277         let mut res = String::new();
278         if self.workspaces.is_empty() {
279             res.push_str("no workspaces\n")
280         } else {
281             res.push_str("workspaces:\n");
282             for w in self.workspaces.iter() {
283                 res += &format!("{} packages loaded\n", w.cargo.packages().count());
284             }
285         }
286         res.push_str("\nanalysis:\n");
287         res.push_str(&self.analysis.status());
288         res
289     }
290 }