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
21 ops::{Deref, DerefMut},
22 path::{Path, PathBuf},
27 use crossbeam_channel::Receiver;
28 use ra_arena::{impl_arena_id, Arena, RawId};
29 use relative_path::{Component, RelativePath, RelativePathBuf};
30 use rustc_hash::{FxHashMap, FxHashSet};
32 pub use crate::io::TaskResult as VfsTask;
33 use io::{Task, TaskResult, WatcherChange, WatcherChangeData, Worker};
35 /// `RootFilter` is a predicate that checks if a file can belong to a root. If
36 /// several filters match a file (nested dirs), the most nested one wins.
37 pub(crate) struct RootFilter {
39 filter: fn(&Path, &RelativePath) -> bool,
43 fn new(root: PathBuf) -> RootFilter {
46 filter: default_filter,
49 /// Check if this root can contain `path`. NB: even if this returns
50 /// true, the `path` might actually be conained in some nested root.
51 pub(crate) fn can_contain(&self, path: &Path) -> Option<RelativePathBuf> {
52 let rel_path = path.strip_prefix(&self.root).ok()?;
53 let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
54 if !(self.filter)(path, rel_path.as_relative_path()) {
61 pub(crate) fn default_filter(path: &Path, rel_path: &RelativePath) -> bool {
63 for (i, c) in rel_path.components().enumerate() {
64 if let Component::Normal(c) = c {
65 // TODO hardcoded for now
66 if (i == 0 && c == "target") || c == ".git" || c == "node_modules" {
73 rel_path.extension() == Some("rs")
77 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
78 pub struct VfsRoot(pub RawId);
79 impl_arena_id!(VfsRoot);
81 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
82 pub struct VfsFile(pub RawId);
83 impl_arena_id!(VfsFile);
87 path: RelativePathBuf,
92 pub(crate) struct Roots {
93 roots: Arena<VfsRoot, Arc<RootFilter>>,
97 pub(crate) fn new() -> Roots {
99 roots: Arena::default(),
102 pub(crate) fn find(&self, path: &Path) -> Option<(VfsRoot, RelativePathBuf)> {
105 .find_map(|(root, data)| data.can_contain(path).map(|it| (root, it)))
109 impl Deref for Roots {
110 type Target = Arena<VfsRoot, Arc<RootFilter>>;
111 fn deref(&self) -> &Self::Target {
116 impl DerefMut for Roots {
117 fn deref_mut(&mut self) -> &mut Self::Target {
124 files: Arena<VfsFile, VfsFileData>,
125 root2files: FxHashMap<VfsRoot, FxHashSet<VfsFile>>,
126 pending_changes: Vec<VfsChange>,
130 impl fmt::Debug for Vfs {
131 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
132 f.write_str("Vfs { ... }")
137 pub fn new(roots: Vec<PathBuf>) -> (Vfs, Vec<VfsRoot>) {
138 let mut root_paths = roots;
139 let worker = io::Worker::start();
141 let mut roots = Roots::new();
142 let mut root2files = FxHashMap::default();
144 // A hack to make nesting work.
145 root_paths.sort_by_key(|it| Reverse(it.as_os_str().len()));
146 for (i, path) in root_paths.iter().enumerate() {
147 let root_filter = Arc::new(RootFilter::new(path.clone()));
149 let root = roots.alloc(root_filter.clone());
150 root2files.insert(root, Default::default());
152 let nested_roots = root_paths[..i]
154 .filter(|it| it.starts_with(path))
155 .map(|it| it.clone())
156 .collect::<Vec<_>>();
158 let task = io::Task::AddRoot {
164 worker.sender().send(task).unwrap();
167 roots: Arc::new(roots),
168 files: Arena::default(),
171 pending_changes: Vec::new(),
173 let vfs_roots = res.roots.iter().map(|(id, _)| id).collect();
177 pub fn root2path(&self, root: VfsRoot) -> PathBuf {
178 self.roots[root].root.clone()
181 pub fn path2file(&self, path: &Path) -> Option<VfsFile> {
182 if let Some((_root, _path, Some(file))) = self.find_root(path) {
188 pub fn file2path(&self, file: VfsFile) -> PathBuf {
189 let rel_path = &self.files[file].path;
190 let root_path = &self.roots[self.files[file].root].root;
191 rel_path.to_path(root_path)
194 pub fn file_for_path(&self, path: &Path) -> Option<VfsFile> {
195 if let Some((_root, _path, Some(file))) = self.find_root(path) {
201 pub fn load(&mut self, path: &Path) -> Option<VfsFile> {
202 if let Some((root, rel_path, file)) = self.find_root(path) {
203 return if let Some(file) = file {
206 let text = fs::read_to_string(path).unwrap_or_default();
207 let text = Arc::new(text);
208 let file = self.add_file(root, rel_path.clone(), Arc::clone(&text), false);
209 let change = VfsChange::AddFile {
215 self.pending_changes.push(change);
222 pub fn task_receiver(&self) -> &Receiver<io::TaskResult> {
223 self.worker.receiver()
226 pub fn handle_task(&mut self, task: io::TaskResult) {
228 TaskResult::AddRoot(task) => {
229 let mut files = Vec::new();
230 // While we were scanning the root in the backgound, a file might have
231 // been open in the editor, so we need to account for that.
232 let exising = self.root2files[&task.root]
234 .map(|&file| (self.files[file].path.clone(), file))
235 .collect::<FxHashMap<_, _>>();
236 for (path, text) in task.files {
237 if let Some(&file) = exising.get(&path) {
238 let text = Arc::clone(&self.files[file].text);
239 files.push((file, path, text));
242 let text = Arc::new(text);
243 let file = self.add_file(task.root, path.clone(), Arc::clone(&text), false);
244 files.push((file, path, text));
247 let change = VfsChange::AddRoot {
251 self.pending_changes.push(change);
253 TaskResult::HandleChange(change) => match &change {
254 WatcherChange::Create(path) if path.is_dir() => {
255 if let Some((root, _path, _file)) = self.find_root(&path) {
256 let root_filter = self.roots[root].clone();
260 dir: path.to_path_buf(),
266 WatcherChange::Create(path)
267 | WatcherChange::Remove(path)
268 | WatcherChange::Write(path) => {
269 if self.should_handle_change(&path) {
270 self.worker.sender().send(Task::LoadChange(change)).unwrap()
273 WatcherChange::Rescan => {
274 // TODO we should reload all files
277 TaskResult::LoadChange(change) => match change {
278 WatcherChangeData::Create { path, text }
279 | WatcherChangeData::Write { path, text } => {
280 if let Some((root, path, file)) = self.find_root(&path) {
281 if let Some(file) = file {
282 self.do_change_file(file, text, false);
284 self.do_add_file(root, path, text, false);
288 WatcherChangeData::Remove { path } => {
289 if let Some((root, path, file)) = self.find_root(&path) {
290 if let Some(file) = file {
291 self.do_remove_file(root, path, file, false);
299 fn should_handle_change(&self, path: &Path) -> bool {
300 if let Some((_root, _rel_path, file)) = self.find_root(&path) {
301 if let Some(file) = file {
302 if self.files[file].is_overlayed {
304 log::debug!("skipping overlayed \"{}\"", path.display());
310 // file doesn't belong to any root
318 path: RelativePathBuf,
321 ) -> Option<VfsFile> {
322 let text = Arc::new(text);
323 let file = self.add_file(root, path.clone(), text.clone(), is_overlay);
324 self.pending_changes.push(VfsChange::AddFile {
333 fn do_change_file(&mut self, file: VfsFile, text: String, is_overlay: bool) {
334 if !is_overlay && self.files[file].is_overlayed {
337 let text = Arc::new(text);
338 self.change_file(file, text.clone(), is_overlay);
340 .push(VfsChange::ChangeFile { file, text });
346 path: RelativePathBuf,
350 if !is_overlay && self.files[file].is_overlayed {
353 self.remove_file(file);
355 .push(VfsChange::RemoveFile { root, path, file });
358 pub fn add_file_overlay(&mut self, path: &Path, text: String) -> Option<VfsFile> {
359 if let Some((root, rel_path, file)) = self.find_root(path) {
360 if let Some(file) = file {
361 self.do_change_file(file, text, true);
364 self.do_add_file(root, rel_path, text, true)
371 pub fn change_file_overlay(&mut self, path: &Path, new_text: String) {
372 if let Some((_root, _path, file)) = self.find_root(path) {
373 let file = file.expect("can't change a file which wasn't added");
374 self.do_change_file(file, new_text, true);
378 pub fn remove_file_overlay(&mut self, path: &Path) -> Option<VfsFile> {
379 if let Some((root, path, file)) = self.find_root(path) {
380 let file = file.expect("can't remove a file which wasn't added");
381 let full_path = path.to_path(&self.roots[root].root);
382 if let Ok(text) = fs::read_to_string(&full_path) {
383 self.do_change_file(file, text, true);
385 self.do_remove_file(root, path, file, true);
393 pub fn commit_changes(&mut self) -> Vec<VfsChange> {
394 mem::replace(&mut self.pending_changes, Vec::new())
397 /// Sutdown the VFS and terminate the background watching thread.
398 pub fn shutdown(self) -> thread::Result<()> {
399 self.worker.shutdown()
405 path: RelativePathBuf,
409 let data = VfsFileData {
415 let file = self.files.alloc(data);
416 self.root2files.get_mut(&root).unwrap().insert(file);
420 fn change_file(&mut self, file: VfsFile, new_text: Arc<String>, is_overlayed: bool) {
421 let mut file_data = &mut self.files[file];
422 file_data.text = new_text;
423 file_data.is_overlayed = is_overlayed;
426 fn remove_file(&mut self, file: VfsFile) {
427 //FIXME: use arena with removal
428 self.files[file].text = Default::default();
429 self.files[file].path = Default::default();
430 let root = self.files[file].root;
431 let removed = self.root2files.get_mut(&root).unwrap().remove(&file);
435 fn find_root(&self, path: &Path) -> Option<(VfsRoot, RelativePathBuf, Option<VfsFile>)> {
436 let (root, path) = self.roots.find(&path)?;
437 let file = self.root2files[&root]
440 .find(|&file| self.files[file].path == path);
441 Some((root, path, file))
445 #[derive(Debug, Clone)]
449 files: Vec<(VfsFile, RelativePathBuf, Arc<String>)>,
454 path: RelativePathBuf,
460 path: RelativePathBuf,