]> git.lizzy.rs Git - rust.git/blob - crates/ra_lsp_server/src/server_world.rs
Merge #489
[rust.git] / crates / ra_lsp_server / src / server_world.rs
1 use std::{
2     path::PathBuf,
3     sync::Arc,
4 };
5
6 use languageserver_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                         crate_graph.add_dep(from, name.clone(), to);
77                     }
78                 }
79             }
80
81             let libstd = ws
82                 .sysroot
83                 .std()
84                 .and_then(|it| sysroot_crates.get(&it).map(|&it| it));
85
86             let mut pkg_to_lib_crate = FxHashMap::default();
87             let mut pkg_crates = FxHashMap::default();
88             // Next, create crates for each package, target pair
89             for pkg in ws.cargo.packages() {
90                 let mut lib_tgt = None;
91                 for tgt in pkg.targets(&ws.cargo) {
92                     let root = tgt.root(&ws.cargo);
93                     if let Some(file_id) = vfs.load(root) {
94                         let file_id = FileId(file_id.0.into());
95                         let crate_id = crate_graph.add_crate_root(file_id);
96                         if tgt.kind(&ws.cargo) == TargetKind::Lib {
97                             lib_tgt = Some(crate_id);
98                             pkg_to_lib_crate.insert(pkg, crate_id);
99                         }
100                         pkg_crates
101                             .entry(pkg)
102                             .or_insert_with(Vec::new)
103                             .push(crate_id);
104                     }
105                 }
106
107                 // Set deps to the std and to the lib target of the current package
108                 for &from in pkg_crates.get(&pkg).into_iter().flatten() {
109                     if let Some(to) = lib_tgt {
110                         if to != from {
111                             crate_graph.add_dep(from, pkg.name(&ws.cargo).into(), to);
112                         }
113                     }
114                     if let Some(std) = libstd {
115                         crate_graph.add_dep(from, "std".into(), std);
116                     }
117                 }
118             }
119
120             // Now add a dep ednge from all targets of upstream to the lib
121             // target of downstream.
122             for pkg in ws.cargo.packages() {
123                 for dep in pkg.dependencies(&ws.cargo) {
124                     if let Some(&to) = pkg_to_lib_crate.get(&dep.pkg) {
125                         for &from in pkg_crates.get(&pkg).into_iter().flatten() {
126                             crate_graph.add_dep(from, dep.name.clone(), to);
127                         }
128                     }
129                 }
130             }
131         }
132         change.set_crate_graph(crate_graph);
133
134         let mut analysis_host = AnalysisHost::default();
135         analysis_host.apply_change(change);
136         ServerWorldState {
137             roots_to_scan,
138             root,
139             workspaces: Arc::new(workspaces),
140             analysis_host,
141             vfs: Arc::new(RwLock::new(vfs)),
142         }
143     }
144
145     /// Returns a vec of libraries
146     /// FIXME: better API here
147     pub fn process_changes(
148         &mut self,
149     ) -> Vec<(SourceRootId, Vec<(FileId, RelativePathBuf, Arc<String>)>)> {
150         let changes = self.vfs.write().commit_changes();
151         if changes.is_empty() {
152             return Vec::new();
153         }
154         let mut libs = Vec::new();
155         let mut change = AnalysisChange::new();
156         for c in changes {
157             match c {
158                 VfsChange::AddRoot { root, files } => {
159                     let root_path = self.vfs.read().root2path(root);
160                     if root_path.starts_with(&self.root) {
161                         self.roots_to_scan -= 1;
162                         for (file, path, text) in files {
163                             change.add_file(
164                                 SourceRootId(root.0.into()),
165                                 FileId(file.0.into()),
166                                 path,
167                                 text,
168                             );
169                         }
170                     } else {
171                         let files = files
172                             .into_iter()
173                             .map(|(vfsfile, path, text)| (FileId(vfsfile.0.into()), path, text))
174                             .collect();
175                         libs.push((SourceRootId(root.0.into()), files));
176                     }
177                 }
178                 VfsChange::AddFile {
179                     root,
180                     file,
181                     path,
182                     text,
183                 } => {
184                     change.add_file(
185                         SourceRootId(root.0.into()),
186                         FileId(file.0.into()),
187                         path,
188                         text,
189                     );
190                 }
191                 VfsChange::RemoveFile { root, file, path } => {
192                     change.remove_file(SourceRootId(root.0.into()), FileId(file.0.into()), path)
193                 }
194                 VfsChange::ChangeFile { file, text } => {
195                     change.change_file(FileId(file.0.into()), text);
196                 }
197             }
198         }
199         self.analysis_host.apply_change(change);
200         libs
201     }
202
203     pub fn add_lib(&mut self, data: LibraryData) {
204         self.roots_to_scan -= 1;
205         let mut change = AnalysisChange::new();
206         change.add_library(data);
207         self.analysis_host.apply_change(change);
208     }
209
210     pub fn snapshot(&self) -> ServerWorld {
211         ServerWorld {
212             workspaces: Arc::clone(&self.workspaces),
213             analysis: self.analysis_host.analysis(),
214             vfs: Arc::clone(&self.vfs),
215         }
216     }
217 }
218
219 impl ServerWorld {
220     pub fn analysis(&self) -> &Analysis {
221         &self.analysis
222     }
223
224     pub fn uri_to_file_id(&self, uri: &Url) -> Result<FileId> {
225         let path = uri
226             .to_file_path()
227             .map_err(|()| format_err!("invalid uri: {}", uri))?;
228         let file = self
229             .vfs
230             .read()
231             .path2file(&path)
232             .ok_or_else(|| format_err!("unknown file: {}", path.display()))?;
233         Ok(FileId(file.0.into()))
234     }
235
236     pub fn file_id_to_uri(&self, id: FileId) -> Result<Url> {
237         let path = self.vfs.read().file2path(VfsFile(id.0.into()));
238         let url = Url::from_file_path(&path)
239             .map_err(|_| format_err!("can't convert path to url: {}", path.display()))?;
240         Ok(url)
241     }
242
243     pub fn path_to_uri(&self, root: SourceRootId, path: &RelativePathBuf) -> Result<Url> {
244         let base = self.vfs.read().root2path(VfsRoot(root.0.into()));
245         let path = path.to_path(base);
246         let url = Url::from_file_path(&path)
247             .map_err(|_| format_err!("can't convert path to url: {}", path.display()))?;
248         Ok(url)
249     }
250 }