1 //! VFS stands for Virtual File System.
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.
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)
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
23 path::{Path, PathBuf},
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;
35 pub use crate::io::TaskResult as VfsTask;
36 pub use crate::watcher::{Watcher, WatcherChange};
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.
42 file_filter: fn(&Path) -> bool,
46 fn new(root: PathBuf) -> RootFilter {
49 file_filter: has_rs_extension,
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) {
58 let path = path.strip_prefix(&self.root).ok()?;
59 RelativePathBuf::from_path(path).ok()
63 pub(crate) fn has_rs_extension(p: &Path) -> bool {
64 p.extension() == Some(OsStr::new("rs"))
67 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
68 pub struct VfsRoot(pub RawId);
69 impl_arena_id!(VfsRoot);
71 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
72 pub struct VfsFile(pub RawId);
73 impl_arena_id!(VfsFile);
77 path: RelativePathBuf,
83 roots: Arena<VfsRoot, RootFilter>,
84 files: Arena<VfsFile, VfsFileData>,
85 root2files: FxHashMap<VfsRoot, FxHashSet<VfsFile>>,
86 pending_changes: Vec<VfsChange>,
88 worker_handle: WorkerHandle,
92 impl fmt::Debug for Vfs {
93 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
94 f.write_str("Vfs { ... }")
99 pub fn new(mut roots: Vec<PathBuf>) -> (Vfs, Vec<VfsRoot>) {
100 let (worker, worker_handle) = io::start();
102 let watcher = Watcher::start(worker.inp.clone()).unwrap(); // TODO return Result?
105 roots: Arena::default(),
106 files: Arena::default(),
107 root2files: FxHashMap::default(),
111 pending_changes: Vec::new(),
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]
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())
128 nested.iter().all(|it| it != entry.path())
131 let task = io::Task::AddRoot {
134 filter: Box::new(filter),
136 res.worker.inp.send(task).unwrap();
137 res.watcher.watch(path).unwrap();
139 let roots = res.roots.iter().map(|(id, _)| id).collect();
143 pub fn root2path(&self, root: VfsRoot) -> PathBuf {
144 self.roots[root].root.clone()
147 pub fn path2file(&self, path: &Path) -> Option<VfsFile> {
148 if let Some((_root, _path, Some(file))) = self.find_root(path) {
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)
160 pub fn file_for_path(&self, path: &Path) -> Option<VfsFile> {
161 if let Some((_root, _path, Some(file))) = self.find_root(path) {
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 {
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 {
181 self.pending_changes.push(change);
188 pub fn task_receiver(&self) -> &Receiver<io::TaskResult> {
192 pub fn handle_task(&mut self, task: io::TaskResult) {
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]
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));
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));
213 let change = VfsChange::AddRoot {
217 self.pending_changes.push(change);
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()
227 watcher::WatcherChange::Rescan => {
228 // TODO we should reload all files
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);
239 self.do_add_file(root, path, text, false);
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);
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 {
264 // file doesn't belong to any root
272 path: RelativePathBuf,
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 {
287 fn do_change_file(&mut self, file: VfsFile, text: String, is_overlay: bool) {
288 if !is_overlay && self.files[file].is_overlayed {
291 let text = Arc::new(text);
292 self.change_file(file, text.clone(), is_overlay);
294 .push(VfsChange::ChangeFile { file, text });
300 path: RelativePathBuf,
304 if !is_overlay && self.files[file].is_overlayed {
307 self.remove_file(file);
309 .push(VfsChange::RemoveFile { root, path, file });
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);
318 self.do_add_file(root, rel_path, text, true)
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);
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);
339 self.do_remove_file(root, path, file, true);
347 pub fn commit_changes(&mut self) -> Vec<VfsChange> {
348 mem::replace(&mut self.pending_changes, Vec::new())
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()
361 path: RelativePathBuf,
365 let data = VfsFileData {
371 let file = self.files.alloc(data);
372 self.root2files.get_mut(&root).unwrap().insert(file);
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;
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);
391 fn find_root(&self, path: &Path) -> Option<(VfsRoot, RelativePathBuf, Option<VfsFile>)> {
392 let (root, path) = self
395 .find_map(|(root, data)| data.can_contain(path).map(|it| (root, it)))?;
396 let file = self.root2files[&root]
399 .find(|&file| self.files[file].path == path);
400 Some((root, path, file))
404 #[derive(Debug, Clone)]
408 files: Vec<(VfsFile, RelativePathBuf, Arc<String>)>,
413 path: RelativePathBuf,
419 path: RelativePathBuf,