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,
89 watcher: Option<Watcher>,
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 = match Watcher::start(worker.inp.clone()) {
103 Ok(watcher) => Some(watcher),
105 log::error!("could not start watcher: {}", e);
111 roots: Arena::default(),
112 files: Arena::default(),
113 root2files: FxHashMap::default(),
117 pending_changes: Vec::new(),
120 // A hack to make nesting work.
121 roots.sort_by_key(|it| Reverse(it.as_os_str().len()));
122 for (i, path) in roots.iter().enumerate() {
123 let root = res.roots.alloc(RootFilter::new(path.clone()));
124 res.root2files.insert(root, Default::default());
125 let nested = roots[..i]
127 .filter(|it| it.starts_with(path))
128 .map(|it| it.clone())
129 .collect::<Vec<_>>();
130 let filter = move |entry: &DirEntry| {
131 if entry.file_type().is_file() {
132 has_rs_extension(entry.path())
134 nested.iter().all(|it| it != entry.path())
137 let task = io::Task::AddRoot {
140 filter: Box::new(filter),
142 res.worker.inp.send(task).unwrap();
143 if let Some(ref mut watcher) = res.watcher {
147 let roots = res.roots.iter().map(|(id, _)| id).collect();
151 pub fn root2path(&self, root: VfsRoot) -> PathBuf {
152 self.roots[root].root.clone()
155 pub fn path2file(&self, path: &Path) -> Option<VfsFile> {
156 if let Some((_root, _path, Some(file))) = self.find_root(path) {
162 pub fn file2path(&self, file: VfsFile) -> PathBuf {
163 let rel_path = &self.files[file].path;
164 let root_path = &self.roots[self.files[file].root].root;
165 rel_path.to_path(root_path)
168 pub fn file_for_path(&self, path: &Path) -> Option<VfsFile> {
169 if let Some((_root, _path, Some(file))) = self.find_root(path) {
175 pub fn load(&mut self, path: &Path) -> Option<VfsFile> {
176 if let Some((root, rel_path, file)) = self.find_root(path) {
177 return if let Some(file) = file {
180 let text = fs::read_to_string(path).unwrap_or_default();
181 let text = Arc::new(text);
182 let file = self.add_file(root, rel_path.clone(), Arc::clone(&text), false);
183 let change = VfsChange::AddFile {
189 self.pending_changes.push(change);
196 pub fn task_receiver(&self) -> &Receiver<io::TaskResult> {
200 pub fn handle_task(&mut self, task: io::TaskResult) {
202 io::TaskResult::AddRoot(task) => {
203 let mut files = Vec::new();
204 // While we were scanning the root in the backgound, a file might have
205 // been open in the editor, so we need to account for that.
206 let exising = self.root2files[&task.root]
208 .map(|&file| (self.files[file].path.clone(), file))
209 .collect::<FxHashMap<_, _>>();
210 for (path, text) in task.files {
211 if let Some(&file) = exising.get(&path) {
212 let text = Arc::clone(&self.files[file].text);
213 files.push((file, path, text));
216 let text = Arc::new(text);
217 let file = self.add_file(task.root, path.clone(), Arc::clone(&text), false);
218 files.push((file, path, text));
221 let change = VfsChange::AddRoot {
225 self.pending_changes.push(change);
227 io::TaskResult::HandleChange(change) => match &change {
228 watcher::WatcherChange::Create(path)
229 | watcher::WatcherChange::Remove(path)
230 | watcher::WatcherChange::Write(path) => {
231 if self.should_handle_change(&path) {
232 self.worker.inp.send(io::Task::LoadChange(change)).unwrap()
235 watcher::WatcherChange::Rescan => {
236 // TODO we should reload all files
239 io::TaskResult::LoadChange(None) => {}
240 io::TaskResult::LoadChange(Some(change)) => match change {
241 io::WatcherChangeData::Create { path, text }
242 | io::WatcherChangeData::Write { path, text } => {
243 if let Some((root, path, file)) = self.find_root(&path) {
244 if let Some(file) = file {
245 self.do_change_file(file, text, false);
247 self.do_add_file(root, path, text, false);
251 io::WatcherChangeData::Remove { path } => {
252 if let Some((root, path, file)) = self.find_root(&path) {
253 if let Some(file) = file {
254 self.do_remove_file(root, path, file, false);
262 fn should_handle_change(&self, path: &Path) -> bool {
263 if let Some((_root, _rel_path, file)) = self.find_root(&path) {
264 if let Some(file) = file {
265 if self.files[file].is_overlayed {
267 log::debug!("skipping overlayed \"{}\"", path.display());
273 // file doesn't belong to any root
281 path: RelativePathBuf,
284 ) -> Option<VfsFile> {
285 let text = Arc::new(text);
286 let file = self.add_file(root, path.clone(), text.clone(), is_overlay);
287 self.pending_changes.push(VfsChange::AddFile {
296 fn do_change_file(&mut self, file: VfsFile, text: String, is_overlay: bool) {
297 if !is_overlay && self.files[file].is_overlayed {
300 let text = Arc::new(text);
301 self.change_file(file, text.clone(), is_overlay);
303 .push(VfsChange::ChangeFile { file, text });
309 path: RelativePathBuf,
313 if !is_overlay && self.files[file].is_overlayed {
316 self.remove_file(file);
318 .push(VfsChange::RemoveFile { root, path, file });
321 pub fn add_file_overlay(&mut self, path: &Path, text: String) -> Option<VfsFile> {
322 if let Some((root, rel_path, file)) = self.find_root(path) {
323 if let Some(file) = file {
324 self.do_change_file(file, text, true);
327 self.do_add_file(root, rel_path, text, true)
334 pub fn change_file_overlay(&mut self, path: &Path, new_text: String) {
335 if let Some((_root, _path, file)) = self.find_root(path) {
336 let file = file.expect("can't change a file which wasn't added");
337 self.do_change_file(file, new_text, true);
341 pub fn remove_file_overlay(&mut self, path: &Path) -> Option<VfsFile> {
342 if let Some((root, path, file)) = self.find_root(path) {
343 let file = file.expect("can't remove a file which wasn't added");
344 let full_path = path.to_path(&self.roots[root].root);
345 if let Ok(text) = fs::read_to_string(&full_path) {
346 self.do_change_file(file, text, true);
348 self.do_remove_file(root, path, file, true);
356 pub fn commit_changes(&mut self) -> Vec<VfsChange> {
357 mem::replace(&mut self.pending_changes, Vec::new())
360 /// Sutdown the VFS and terminate the background watching thread.
361 pub fn shutdown(self) -> thread::Result<()> {
362 if let Some(watcher) = self.watcher {
363 let _ = watcher.shutdown();
365 let _ = self.worker.shutdown();
366 self.worker_handle.shutdown()
372 path: RelativePathBuf,
376 let data = VfsFileData {
382 let file = self.files.alloc(data);
383 self.root2files.get_mut(&root).unwrap().insert(file);
387 fn change_file(&mut self, file: VfsFile, new_text: Arc<String>, is_overlayed: bool) {
388 let mut file_data = &mut self.files[file];
389 file_data.text = new_text;
390 file_data.is_overlayed = is_overlayed;
393 fn remove_file(&mut self, file: VfsFile) {
394 //FIXME: use arena with removal
395 self.files[file].text = Default::default();
396 self.files[file].path = Default::default();
397 let root = self.files[file].root;
398 let removed = self.root2files.get_mut(&root).unwrap().remove(&file);
402 fn find_root(&self, path: &Path) -> Option<(VfsRoot, RelativePathBuf, Option<VfsFile>)> {
403 let (root, path) = self
406 .find_map(|(root, data)| data.can_contain(path).map(|it| (root, it)))?;
407 let file = self.root2files[&root]
410 .find(|&file| self.files[file].path == path);
411 Some((root, path, file))
415 #[derive(Debug, Clone)]
419 files: Vec<(VfsFile, RelativePathBuf, Arc<String>)>,
424 path: RelativePathBuf,
430 path: RelativePathBuf,