]> git.lizzy.rs Git - rust.git/blob - crates/ra_vfs/src/lib.rs
Merge #762
[rust.git] / crates / ra_vfs / src / lib.rs
1 //! VFS stands for Virtual File System.
2 //!
3 //! When doing analysis, we don't want to do any IO, we want to keep all source
4 //! code in memory. However, the actual source code is stored on disk, so you
5 //! need to get it into the memory in the first place somehow. VFS is the
6 //! component which does this.
7 //!
8 //! It is also responsible for watching the disk for changes, and for merging
9 //! editor state (modified, unsaved files) with disk state.
10 //! TODO: Some LSP clients support watching the disk, so this crate should
11 //! to support custom watcher events (related to https://github.com/rust-analyzer/rust-analyzer/issues/131)
12 //!
13 //! VFS is based on a concept of roots: a set of directories on the file system
14 //! which are watched for changes. Typically, there will be a root for each
15 //! Cargo package.
16 mod io;
17
18 use std::{
19     cmp::Reverse,
20     fmt, fs, mem,
21     path::{Path, PathBuf},
22     sync::Arc,
23     thread,
24 };
25
26 use crossbeam_channel::Receiver;
27 use ra_arena::{impl_arena_id, Arena, RawId, map::ArenaMap};
28 use relative_path::{Component, RelativePath, RelativePathBuf};
29 use rustc_hash::{FxHashMap, FxHashSet};
30
31 pub use crate::io::TaskResult as VfsTask;
32 use io::{TaskResult, Worker};
33
34 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
35 pub struct VfsRoot(pub RawId);
36 impl_arena_id!(VfsRoot);
37
38 /// Describes the contents of a single source root.
39 ///
40 /// `RootConfig` can be thought of as a glob pattern like `src/**.rs` whihc
41 /// specifes the source root or as a function whihc takes a `PathBuf` and
42 /// returns `true` iff path belongs to the source root
43 pub(crate) struct RootConfig {
44     root: PathBuf,
45     excluded_dirs: Vec<PathBuf>,
46 }
47
48 pub(crate) struct Roots {
49     roots: Arena<VfsRoot, Arc<RootConfig>>,
50 }
51
52 impl std::ops::Deref for Roots {
53     type Target = Arena<VfsRoot, Arc<RootConfig>>;
54     fn deref(&self) -> &Self::Target {
55         &self.roots
56     }
57 }
58
59 impl RootConfig {
60     fn new(root: PathBuf, excluded_dirs: Vec<PathBuf>) -> RootConfig {
61         RootConfig { root, excluded_dirs }
62     }
63     /// Cheks if root contains a path and returns a root-relative path.
64     pub(crate) fn contains(&self, path: &Path) -> Option<RelativePathBuf> {
65         // First, check excluded dirs
66         if self.excluded_dirs.iter().any(|it| path.starts_with(it)) {
67             return None;
68         }
69         let rel_path = path.strip_prefix(&self.root).ok()?;
70         let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
71
72         // Ignore some common directories.
73         //
74         // FIXME: don't hard-code, specify at source-root creation time using
75         // gitignore
76         for (i, c) in rel_path.components().enumerate() {
77             if let Component::Normal(c) = c {
78                 if (i == 0 && c == "target") || c == ".git" || c == "node_modules" {
79                     return None;
80                 }
81             }
82         }
83
84         if path.is_file() && rel_path.extension() != Some("rs") {
85             return None;
86         }
87
88         Some(rel_path)
89     }
90 }
91
92 impl Roots {
93     pub(crate) fn new(mut paths: Vec<PathBuf>) -> Roots {
94         let mut roots = Arena::default();
95         // A hack to make nesting work.
96         paths.sort_by_key(|it| Reverse(it.as_os_str().len()));
97         paths.dedup();
98         for (i, path) in paths.iter().enumerate() {
99             let nested_roots = paths[..i]
100                 .iter()
101                 .filter(|it| it.starts_with(path))
102                 .map(|it| it.clone())
103                 .collect::<Vec<_>>();
104
105             let config = Arc::new(RootConfig::new(path.clone(), nested_roots));
106
107             roots.alloc(config.clone());
108         }
109         Roots { roots }
110     }
111     pub(crate) fn find(&self, path: &Path) -> Option<(VfsRoot, RelativePathBuf)> {
112         self.roots.iter().find_map(|(root, data)| data.contains(path).map(|it| (root, it)))
113     }
114 }
115
116 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
117 pub struct VfsFile(pub RawId);
118 impl_arena_id!(VfsFile);
119
120 struct VfsFileData {
121     root: VfsRoot,
122     path: RelativePathBuf,
123     is_overlayed: bool,
124     text: Arc<String>,
125 }
126
127 pub struct Vfs {
128     roots: Arc<Roots>,
129     files: Arena<VfsFile, VfsFileData>,
130     root2files: ArenaMap<VfsRoot, FxHashSet<VfsFile>>,
131     pending_changes: Vec<VfsChange>,
132     worker: Worker,
133 }
134
135 impl fmt::Debug for Vfs {
136     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
137         f.debug_struct("Vfs")
138             .field("n_roots", &self.roots.len())
139             .field("n_files", &self.files.len())
140             .field("n_pending_changes", &self.pending_changes.len())
141             .finish()
142     }
143 }
144
145 impl Vfs {
146     pub fn new(roots: Vec<PathBuf>) -> (Vfs, Vec<VfsRoot>) {
147         let roots = Arc::new(Roots::new(roots));
148         let worker = io::Worker::start(Arc::clone(&roots));
149         let mut root2files = ArenaMap::default();
150
151         for (root, config) in roots.iter() {
152             root2files.insert(root, Default::default());
153             worker.sender().send(io::Task::AddRoot { root, config: Arc::clone(config) }).unwrap();
154         }
155         let res =
156             Vfs { roots, files: Arena::default(), root2files, worker, pending_changes: Vec::new() };
157         let vfs_roots = res.roots.iter().map(|(id, _)| id).collect();
158         (res, vfs_roots)
159     }
160
161     pub fn root2path(&self, root: VfsRoot) -> PathBuf {
162         self.roots[root].root.clone()
163     }
164
165     pub fn path2file(&self, path: &Path) -> Option<VfsFile> {
166         if let Some((_root, _path, Some(file))) = self.find_root(path) {
167             return Some(file);
168         }
169         None
170     }
171
172     pub fn file2path(&self, file: VfsFile) -> PathBuf {
173         let rel_path = &self.files[file].path;
174         let root_path = &self.roots[self.files[file].root].root;
175         rel_path.to_path(root_path)
176     }
177
178     pub fn file_for_path(&self, path: &Path) -> Option<VfsFile> {
179         if let Some((_root, _path, Some(file))) = self.find_root(path) {
180             return Some(file);
181         }
182         None
183     }
184
185     pub fn num_roots(&self) -> usize {
186         self.roots.len()
187     }
188
189     pub fn load(&mut self, path: &Path) -> Option<VfsFile> {
190         if let Some((root, rel_path, file)) = self.find_root(path) {
191             return if let Some(file) = file {
192                 Some(file)
193             } else {
194                 let text = fs::read_to_string(path).unwrap_or_default();
195                 let text = Arc::new(text);
196                 let file = self.add_file(root, rel_path.clone(), Arc::clone(&text), false);
197                 let change = VfsChange::AddFile { file, text, root, path: rel_path };
198                 self.pending_changes.push(change);
199                 Some(file)
200             };
201         }
202         None
203     }
204
205     pub fn task_receiver(&self) -> &Receiver<io::TaskResult> {
206         self.worker.receiver()
207     }
208
209     pub fn handle_task(&mut self, task: io::TaskResult) {
210         match task {
211             TaskResult::BulkLoadRoot { root, files } => {
212                 let mut cur_files = Vec::new();
213                 // While we were scanning the root in the backgound, a file might have
214                 // been open in the editor, so we need to account for that.
215                 let exising = self.root2files[root]
216                     .iter()
217                     .map(|&file| (self.files[file].path.clone(), file))
218                     .collect::<FxHashMap<_, _>>();
219                 for (path, text) in files {
220                     if let Some(&file) = exising.get(&path) {
221                         let text = Arc::clone(&self.files[file].text);
222                         cur_files.push((file, path, text));
223                         continue;
224                     }
225                     let text = Arc::new(text);
226                     let file = self.add_file(root, path.clone(), Arc::clone(&text), false);
227                     cur_files.push((file, path, text));
228                 }
229
230                 let change = VfsChange::AddRoot { root, files: cur_files };
231                 self.pending_changes.push(change);
232             }
233             TaskResult::AddSingleFile { root, path, text } => {
234                 if self.find_file(root, &path).is_none() {
235                     self.do_add_file(root, path, text, false);
236                 }
237             }
238             TaskResult::ChangeSingleFile { root, path, text } => {
239                 if let Some(file) = self.find_file(root, &path) {
240                     self.do_change_file(file, text, false);
241                 } else {
242                     self.do_add_file(root, path, text, false);
243                 }
244             }
245             TaskResult::RemoveSingleFile { root, path } => {
246                 if let Some(file) = self.find_file(root, &path) {
247                     self.do_remove_file(root, path, file, false);
248                 }
249             }
250         }
251     }
252
253     fn do_add_file(
254         &mut self,
255         root: VfsRoot,
256         path: RelativePathBuf,
257         text: String,
258         is_overlay: bool,
259     ) -> Option<VfsFile> {
260         let text = Arc::new(text);
261         let file = self.add_file(root, path.clone(), text.clone(), is_overlay);
262         self.pending_changes.push(VfsChange::AddFile { file, root, path, text });
263         Some(file)
264     }
265
266     fn do_change_file(&mut self, file: VfsFile, text: String, is_overlay: bool) {
267         if !is_overlay && self.files[file].is_overlayed {
268             return;
269         }
270         let text = Arc::new(text);
271         self.change_file(file, text.clone(), is_overlay);
272         self.pending_changes.push(VfsChange::ChangeFile { file, text });
273     }
274
275     fn do_remove_file(
276         &mut self,
277         root: VfsRoot,
278         path: RelativePathBuf,
279         file: VfsFile,
280         is_overlay: bool,
281     ) {
282         if !is_overlay && self.files[file].is_overlayed {
283             return;
284         }
285         self.remove_file(file);
286         self.pending_changes.push(VfsChange::RemoveFile { root, path, file });
287     }
288
289     pub fn add_file_overlay(&mut self, path: &Path, text: String) -> Option<VfsFile> {
290         if let Some((root, rel_path, file)) = self.find_root(path) {
291             if let Some(file) = file {
292                 self.do_change_file(file, text, true);
293                 Some(file)
294             } else {
295                 self.do_add_file(root, rel_path, text, true)
296             }
297         } else {
298             None
299         }
300     }
301
302     pub fn change_file_overlay(&mut self, path: &Path, new_text: String) {
303         if let Some((_root, _path, file)) = self.find_root(path) {
304             let file = file.expect("can't change a file which wasn't added");
305             self.do_change_file(file, new_text, true);
306         }
307     }
308
309     pub fn remove_file_overlay(&mut self, path: &Path) -> Option<VfsFile> {
310         if let Some((root, path, file)) = self.find_root(path) {
311             let file = file.expect("can't remove a file which wasn't added");
312             let full_path = path.to_path(&self.roots[root].root);
313             if let Ok(text) = fs::read_to_string(&full_path) {
314                 self.do_change_file(file, text, true);
315             } else {
316                 self.do_remove_file(root, path, file, true);
317             }
318             Some(file)
319         } else {
320             None
321         }
322     }
323
324     pub fn commit_changes(&mut self) -> Vec<VfsChange> {
325         mem::replace(&mut self.pending_changes, Vec::new())
326     }
327
328     /// Sutdown the VFS and terminate the background watching thread.
329     pub fn shutdown(self) -> thread::Result<()> {
330         self.worker.shutdown()
331     }
332
333     fn add_file(
334         &mut self,
335         root: VfsRoot,
336         path: RelativePathBuf,
337         text: Arc<String>,
338         is_overlayed: bool,
339     ) -> VfsFile {
340         let data = VfsFileData { root, path, text, is_overlayed };
341         let file = self.files.alloc(data);
342         self.root2files.get_mut(root).unwrap().insert(file);
343         file
344     }
345
346     fn change_file(&mut self, file: VfsFile, new_text: Arc<String>, is_overlayed: bool) {
347         let mut file_data = &mut self.files[file];
348         file_data.text = new_text;
349         file_data.is_overlayed = is_overlayed;
350     }
351
352     fn remove_file(&mut self, file: VfsFile) {
353         //FIXME: use arena with removal
354         self.files[file].text = Default::default();
355         self.files[file].path = Default::default();
356         let root = self.files[file].root;
357         let removed = self.root2files.get_mut(root).unwrap().remove(&file);
358         assert!(removed);
359     }
360
361     fn find_root(&self, path: &Path) -> Option<(VfsRoot, RelativePathBuf, Option<VfsFile>)> {
362         let (root, path) = self.roots.find(&path)?;
363         let file = self.find_file(root, &path);
364         Some((root, path, file))
365     }
366
367     fn find_file(&self, root: VfsRoot, path: &RelativePath) -> Option<VfsFile> {
368         self.root2files[root].iter().map(|&it| it).find(|&file| self.files[file].path == path)
369     }
370 }
371
372 #[derive(Debug, Clone)]
373 pub enum VfsChange {
374     AddRoot { root: VfsRoot, files: Vec<(VfsFile, RelativePathBuf, Arc<String>)> },
375     AddFile { root: VfsRoot, file: VfsFile, path: RelativePathBuf, text: Arc<String> },
376     RemoveFile { root: VfsRoot, file: VfsFile, path: RelativePathBuf },
377     ChangeFile { file: VfsFile, text: Arc<String> },
378 }