]> git.lizzy.rs Git - rust.git/blob - crates/ra_vfs/src/lib.rs
reference `notify` issue
[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 mod watcher;
18
19 use std::{
20     cmp::Reverse,
21     ffi::OsStr,
22     fmt, fs, mem,
23     path::{Path, PathBuf},
24     sync::Arc,
25     thread,
26 };
27
28 use crossbeam_channel::Receiver;
29 use ra_arena::{impl_arena_id, Arena, RawId};
30 use relative_path::RelativePathBuf;
31 use rustc_hash::{FxHashMap, FxHashSet};
32 use thread_worker::WorkerHandle;
33 use walkdir::DirEntry;
34
35 pub use crate::io::TaskResult as VfsTask;
36 pub use crate::watcher::{Watcher, WatcherChange};
37
38 /// `RootFilter` is a predicate that checks if a file can belong to a root. If
39 /// several filters match a file (nested dirs), the most nested one wins.
40 struct RootFilter {
41     root: PathBuf,
42     file_filter: fn(&Path) -> bool,
43 }
44
45 impl RootFilter {
46     fn new(root: PathBuf) -> RootFilter {
47         RootFilter {
48             root,
49             file_filter: has_rs_extension,
50         }
51     }
52     /// Check if this root can contain `path`. NB: even if this returns
53     /// true, the `path` might actually be conained in some nested root.
54     fn can_contain(&self, path: &Path) -> Option<RelativePathBuf> {
55         if !(self.file_filter)(path) {
56             return None;
57         }
58         let path = path.strip_prefix(&self.root).ok()?;
59         RelativePathBuf::from_path(path).ok()
60     }
61 }
62
63 pub(crate) fn has_rs_extension(p: &Path) -> bool {
64     p.extension() == Some(OsStr::new("rs"))
65 }
66
67 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
68 pub struct VfsRoot(pub RawId);
69 impl_arena_id!(VfsRoot);
70
71 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
72 pub struct VfsFile(pub RawId);
73 impl_arena_id!(VfsFile);
74
75 struct VfsFileData {
76     root: VfsRoot,
77     path: RelativePathBuf,
78     is_overlayed: bool,
79     text: Arc<String>,
80 }
81
82 pub struct Vfs {
83     roots: Arena<VfsRoot, RootFilter>,
84     files: Arena<VfsFile, VfsFileData>,
85     root2files: FxHashMap<VfsRoot, FxHashSet<VfsFile>>,
86     pending_changes: Vec<VfsChange>,
87     worker: io::Worker,
88     worker_handle: WorkerHandle,
89     watcher: Watcher,
90 }
91
92 impl fmt::Debug for Vfs {
93     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
94         f.write_str("Vfs { ... }")
95     }
96 }
97
98 impl Vfs {
99     pub fn new(mut roots: Vec<PathBuf>) -> (Vfs, Vec<VfsRoot>) {
100         let (worker, worker_handle) = io::start();
101
102         let watcher = Watcher::start(worker.inp.clone()).unwrap(); // TODO return Result?
103
104         let mut res = Vfs {
105             roots: Arena::default(),
106             files: Arena::default(),
107             root2files: FxHashMap::default(),
108             worker,
109             worker_handle,
110             watcher,
111             pending_changes: Vec::new(),
112         };
113
114         // A hack to make nesting work.
115         roots.sort_by_key(|it| Reverse(it.as_os_str().len()));
116         for (i, path) in roots.iter().enumerate() {
117             let root = res.roots.alloc(RootFilter::new(path.clone()));
118             res.root2files.insert(root, Default::default());
119             let nested = roots[..i]
120                 .iter()
121                 .filter(|it| it.starts_with(path))
122                 .map(|it| it.clone())
123                 .collect::<Vec<_>>();
124             let filter = move |entry: &DirEntry| {
125                 if entry.file_type().is_file() {
126                     has_rs_extension(entry.path())
127                 } else {
128                     nested.iter().all(|it| it != entry.path())
129                 }
130             };
131             let task = io::Task::AddRoot {
132                 root,
133                 path: path.clone(),
134                 filter: Box::new(filter),
135             };
136             res.worker.inp.send(task).unwrap();
137             res.watcher.watch(path).unwrap();
138         }
139         let roots = res.roots.iter().map(|(id, _)| id).collect();
140         (res, roots)
141     }
142
143     pub fn root2path(&self, root: VfsRoot) -> PathBuf {
144         self.roots[root].root.clone()
145     }
146
147     pub fn path2file(&self, path: &Path) -> Option<VfsFile> {
148         if let Some((_root, _path, Some(file))) = self.find_root(path) {
149             return Some(file);
150         }
151         None
152     }
153
154     pub fn file2path(&self, file: VfsFile) -> PathBuf {
155         let rel_path = &self.files[file].path;
156         let root_path = &self.roots[self.files[file].root].root;
157         rel_path.to_path(root_path)
158     }
159
160     pub fn file_for_path(&self, path: &Path) -> Option<VfsFile> {
161         if let Some((_root, _path, Some(file))) = self.find_root(path) {
162             return Some(file);
163         }
164         None
165     }
166
167     pub fn load(&mut self, path: &Path) -> Option<VfsFile> {
168         if let Some((root, rel_path, file)) = self.find_root(path) {
169             return if let Some(file) = file {
170                 Some(file)
171             } else {
172                 let text = fs::read_to_string(path).unwrap_or_default();
173                 let text = Arc::new(text);
174                 let file = self.add_file(root, rel_path.clone(), Arc::clone(&text), false);
175                 let change = VfsChange::AddFile {
176                     file,
177                     text,
178                     root,
179                     path: rel_path,
180                 };
181                 self.pending_changes.push(change);
182                 Some(file)
183             };
184         }
185         None
186     }
187
188     pub fn task_receiver(&self) -> &Receiver<io::TaskResult> {
189         &self.worker.out
190     }
191
192     pub fn handle_task(&mut self, task: io::TaskResult) {
193         match task {
194             io::TaskResult::AddRoot(task) => {
195                 let mut files = Vec::new();
196                 // While we were scanning the root in the backgound, a file might have
197                 // been open in the editor, so we need to account for that.
198                 let exising = self.root2files[&task.root]
199                     .iter()
200                     .map(|&file| (self.files[file].path.clone(), file))
201                     .collect::<FxHashMap<_, _>>();
202                 for (path, text) in task.files {
203                     if let Some(&file) = exising.get(&path) {
204                         let text = Arc::clone(&self.files[file].text);
205                         files.push((file, path, text));
206                         continue;
207                     }
208                     let text = Arc::new(text);
209                     let file = self.add_file(task.root, path.clone(), Arc::clone(&text), false);
210                     files.push((file, path, text));
211                 }
212
213                 let change = VfsChange::AddRoot {
214                     root: task.root,
215                     files,
216                 };
217                 self.pending_changes.push(change);
218             }
219             io::TaskResult::HandleChange(change) => match &change {
220                 watcher::WatcherChange::Create(path)
221                 | watcher::WatcherChange::Remove(path)
222                 | watcher::WatcherChange::Write(path) => {
223                     if self.should_handle_change(&path) {
224                         self.worker.inp.send(io::Task::LoadChange(change)).unwrap()
225                     }
226                 }
227                 watcher::WatcherChange::Rescan => {
228                     // TODO we should reload all files
229                 }
230             },
231             io::TaskResult::LoadChange(None) => {}
232             io::TaskResult::LoadChange(Some(change)) => match change {
233                 io::WatcherChangeData::Create { path, text }
234                 | io::WatcherChangeData::Write { path, text } => {
235                     if let Some((root, path, file)) = self.find_root(&path) {
236                         if let Some(file) = file {
237                             self.do_change_file(file, text, false);
238                         } else {
239                             self.do_add_file(root, path, text, false);
240                         }
241                     }
242                 }
243                 io::WatcherChangeData::Remove { path } => {
244                     if let Some((root, path, file)) = self.find_root(&path) {
245                         if let Some(file) = file {
246                             self.do_remove_file(root, path, file, false);
247                         }
248                     }
249                 }
250             },
251         }
252     }
253
254     fn should_handle_change(&self, path: &Path) -> bool {
255         if let Some((_root, _rel_path, file)) = self.find_root(&path) {
256             if let Some(file) = file {
257                 if self.files[file].is_overlayed {
258                     // file is overlayed
259                     return false;
260                 }
261             }
262             true
263         } else {
264             // file doesn't belong to any root
265             false
266         }
267     }
268
269     fn do_add_file(
270         &mut self,
271         root: VfsRoot,
272         path: RelativePathBuf,
273         text: String,
274         is_overlay: bool,
275     ) -> Option<VfsFile> {
276         let text = Arc::new(text);
277         let file = self.add_file(root, path.clone(), text.clone(), is_overlay);
278         self.pending_changes.push(VfsChange::AddFile {
279             file,
280             root,
281             path,
282             text,
283         });
284         Some(file)
285     }
286
287     fn do_change_file(&mut self, file: VfsFile, text: String, is_overlay: bool) {
288         if !is_overlay && self.files[file].is_overlayed {
289             return;
290         }
291         let text = Arc::new(text);
292         self.change_file(file, text.clone(), is_overlay);
293         self.pending_changes
294             .push(VfsChange::ChangeFile { file, text });
295     }
296
297     fn do_remove_file(
298         &mut self,
299         root: VfsRoot,
300         path: RelativePathBuf,
301         file: VfsFile,
302         is_overlay: bool,
303     ) {
304         if !is_overlay && self.files[file].is_overlayed {
305             return;
306         }
307         self.remove_file(file);
308         self.pending_changes
309             .push(VfsChange::RemoveFile { root, path, file });
310     }
311
312     pub fn add_file_overlay(&mut self, path: &Path, text: String) -> Option<VfsFile> {
313         if let Some((root, rel_path, file)) = self.find_root(path) {
314             if let Some(file) = file {
315                 self.do_change_file(file, text, true);
316                 Some(file)
317             } else {
318                 self.do_add_file(root, rel_path, text, true)
319             }
320         } else {
321             None
322         }
323     }
324
325     pub fn change_file_overlay(&mut self, path: &Path, new_text: String) {
326         if let Some((_root, _path, file)) = self.find_root(path) {
327             let file = file.expect("can't change a file which wasn't added");
328             self.do_change_file(file, new_text, true);
329         }
330     }
331
332     pub fn remove_file_overlay(&mut self, path: &Path) -> Option<VfsFile> {
333         if let Some((root, path, file)) = self.find_root(path) {
334             let file = file.expect("can't remove a file which wasn't added");
335             let full_path = path.to_path(&self.roots[root].root);
336             if let Ok(text) = fs::read_to_string(&full_path) {
337                 self.do_change_file(file, text, true);
338             } else {
339                 self.do_remove_file(root, path, file, true);
340             }
341             Some(file)
342         } else {
343             None
344         }
345     }
346
347     pub fn commit_changes(&mut self) -> Vec<VfsChange> {
348         mem::replace(&mut self.pending_changes, Vec::new())
349     }
350
351     /// Sutdown the VFS and terminate the background watching thread.
352     pub fn shutdown(self) -> thread::Result<()> {
353         let _ = self.watcher.shutdown();
354         let _ = self.worker.shutdown();
355         self.worker_handle.shutdown()
356     }
357
358     fn add_file(
359         &mut self,
360         root: VfsRoot,
361         path: RelativePathBuf,
362         text: Arc<String>,
363         is_overlayed: bool,
364     ) -> VfsFile {
365         let data = VfsFileData {
366             root,
367             path,
368             text,
369             is_overlayed,
370         };
371         let file = self.files.alloc(data);
372         self.root2files.get_mut(&root).unwrap().insert(file);
373         file
374     }
375
376     fn change_file(&mut self, file: VfsFile, new_text: Arc<String>, is_overlayed: bool) {
377         let mut file_data = &mut self.files[file];
378         file_data.text = new_text;
379         file_data.is_overlayed = is_overlayed;
380     }
381
382     fn remove_file(&mut self, file: VfsFile) {
383         //FIXME: use arena with removal
384         self.files[file].text = Default::default();
385         self.files[file].path = Default::default();
386         let root = self.files[file].root;
387         let removed = self.root2files.get_mut(&root).unwrap().remove(&file);
388         assert!(removed);
389     }
390
391     fn find_root(&self, path: &Path) -> Option<(VfsRoot, RelativePathBuf, Option<VfsFile>)> {
392         let (root, path) = self
393             .roots
394             .iter()
395             .find_map(|(root, data)| data.can_contain(path).map(|it| (root, it)))?;
396         let file = self.root2files[&root]
397             .iter()
398             .map(|&it| it)
399             .find(|&file| self.files[file].path == path);
400         Some((root, path, file))
401     }
402 }
403
404 #[derive(Debug, Clone)]
405 pub enum VfsChange {
406     AddRoot {
407         root: VfsRoot,
408         files: Vec<(VfsFile, RelativePathBuf, Arc<String>)>,
409     },
410     AddFile {
411         root: VfsRoot,
412         file: VfsFile,
413         path: RelativePathBuf,
414         text: Arc<String>,
415     },
416     RemoveFile {
417         root: VfsRoot,
418         file: VfsFile,
419         path: RelativePathBuf,
420     },
421     ChangeFile {
422         file: VfsFile,
423         text: Arc<String>,
424     },
425 }