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 path::{Path, PathBuf},
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};
31 pub use crate::io::TaskResult as VfsTask;
32 use io::{TaskResult, Worker};
34 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
35 pub struct VfsRoot(pub RawId);
36 impl_arena_id!(VfsRoot);
38 /// Describes the contents of a single source root.
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 {
45 excluded_dirs: Vec<PathBuf>,
48 pub(crate) struct Roots {
49 roots: Arena<VfsRoot, Arc<RootConfig>>,
52 impl std::ops::Deref for Roots {
53 type Target = Arena<VfsRoot, Arc<RootConfig>>;
54 fn deref(&self) -> &Self::Target {
60 fn new(root: PathBuf, excluded_dirs: Vec<PathBuf>) -> RootConfig {
61 RootConfig { root, excluded_dirs }
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)) {
69 let rel_path = path.strip_prefix(&self.root).ok()?;
70 let rel_path = RelativePathBuf::from_path(rel_path).ok()?;
72 // Ignore some common directories.
74 // FIXME: don't hard-code, specify at source-root creation time using
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" {
84 if path.is_file() && rel_path.extension() != Some("rs") {
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()));
98 for (i, path) in paths.iter().enumerate() {
99 let nested_roots = paths[..i]
101 .filter(|it| it.starts_with(path))
102 .map(|it| it.clone())
103 .collect::<Vec<_>>();
105 let config = Arc::new(RootConfig::new(path.clone(), nested_roots));
107 roots.alloc(config.clone());
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)))
116 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
117 pub struct VfsFile(pub RawId);
118 impl_arena_id!(VfsFile);
122 path: RelativePathBuf,
129 files: Arena<VfsFile, VfsFileData>,
130 root2files: ArenaMap<VfsRoot, FxHashSet<VfsFile>>,
131 pending_changes: Vec<VfsChange>,
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())
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();
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();
156 Vfs { roots, files: Arena::default(), root2files, worker, pending_changes: Vec::new() };
157 let vfs_roots = res.roots.iter().map(|(id, _)| id).collect();
161 pub fn root2path(&self, root: VfsRoot) -> PathBuf {
162 self.roots[root].root.clone()
165 pub fn path2root(&self, path: &Path) -> Option<VfsRoot> {
166 match self.find_root(path) {
167 Some((root, _path, _file)) => Some(root),
172 pub fn path2file(&self, path: &Path) -> Option<VfsFile> {
173 if let Some((_root, _path, Some(file))) = self.find_root(path) {
179 pub fn file2path(&self, file: VfsFile) -> PathBuf {
180 let rel_path = &self.files[file].path;
181 let root_path = &self.roots[self.files[file].root].root;
182 rel_path.to_path(root_path)
185 pub fn file_for_path(&self, path: &Path) -> Option<VfsFile> {
186 if let Some((_root, _path, Some(file))) = self.find_root(path) {
192 pub fn num_roots(&self) -> usize {
196 pub fn load(&mut self, path: &Path) -> Option<VfsFile> {
197 if let Some((root, rel_path, file)) = self.find_root(path) {
198 return if let Some(file) = file {
201 let text = fs::read_to_string(path).unwrap_or_default();
202 let text = Arc::new(text);
203 let file = self.add_file(root, rel_path.clone(), Arc::clone(&text), false);
204 let change = VfsChange::AddFile { file, text, root, path: rel_path };
205 self.pending_changes.push(change);
212 pub fn task_receiver(&self) -> &Receiver<io::TaskResult> {
213 self.worker.receiver()
216 pub fn handle_task(&mut self, task: io::TaskResult) {
218 TaskResult::BulkLoadRoot { root, files } => {
219 let mut cur_files = Vec::new();
220 // While we were scanning the root in the backgound, a file might have
221 // been open in the editor, so we need to account for that.
222 let exising = self.root2files[root]
224 .map(|&file| (self.files[file].path.clone(), file))
225 .collect::<FxHashMap<_, _>>();
226 for (path, text) in files {
227 if let Some(&file) = exising.get(&path) {
228 let text = Arc::clone(&self.files[file].text);
229 cur_files.push((file, path, text));
232 let text = Arc::new(text);
233 let file = self.add_file(root, path.clone(), Arc::clone(&text), false);
234 cur_files.push((file, path, text));
237 let change = VfsChange::AddRoot { root, files: cur_files };
238 self.pending_changes.push(change);
240 TaskResult::AddSingleFile { root, path, text } => {
241 if self.find_file(root, &path).is_none() {
242 self.do_add_file(root, path, text, false);
245 TaskResult::ChangeSingleFile { root, path, text } => {
246 if let Some(file) = self.find_file(root, &path) {
247 self.do_change_file(file, text, false);
249 self.do_add_file(root, path, text, false);
252 TaskResult::RemoveSingleFile { root, path } => {
253 if let Some(file) = self.find_file(root, &path) {
254 self.do_remove_file(root, path, file, false);
263 path: RelativePathBuf,
266 ) -> Option<VfsFile> {
267 let text = Arc::new(text);
268 let file = self.add_file(root, path.clone(), text.clone(), is_overlay);
269 self.pending_changes.push(VfsChange::AddFile { file, root, path, text });
273 fn do_change_file(&mut self, file: VfsFile, text: String, is_overlay: bool) {
274 if !is_overlay && self.files[file].is_overlayed {
277 let text = Arc::new(text);
278 self.change_file(file, text.clone(), is_overlay);
279 self.pending_changes.push(VfsChange::ChangeFile { file, text });
285 path: RelativePathBuf,
289 if !is_overlay && self.files[file].is_overlayed {
292 self.remove_file(file);
293 self.pending_changes.push(VfsChange::RemoveFile { root, path, file });
296 pub fn add_file_overlay(&mut self, path: &Path, text: String) -> Option<VfsFile> {
297 if let Some((root, rel_path, file)) = self.find_root(path) {
298 if let Some(file) = file {
299 self.do_change_file(file, text, true);
302 self.do_add_file(root, rel_path, text, true)
309 pub fn change_file_overlay(&mut self, path: &Path, new_text: String) {
310 if let Some((_root, _path, file)) = self.find_root(path) {
311 let file = file.expect("can't change a file which wasn't added");
312 self.do_change_file(file, new_text, true);
316 pub fn remove_file_overlay(&mut self, path: &Path) -> Option<VfsFile> {
317 if let Some((root, path, file)) = self.find_root(path) {
318 let file = file.expect("can't remove a file which wasn't added");
319 let full_path = path.to_path(&self.roots[root].root);
320 if let Ok(text) = fs::read_to_string(&full_path) {
321 self.do_change_file(file, text, true);
323 self.do_remove_file(root, path, file, true);
331 pub fn commit_changes(&mut self) -> Vec<VfsChange> {
332 mem::replace(&mut self.pending_changes, Vec::new())
335 /// Sutdown the VFS and terminate the background watching thread.
336 pub fn shutdown(self) -> thread::Result<()> {
337 self.worker.shutdown()
343 path: RelativePathBuf,
347 let data = VfsFileData { root, path, text, is_overlayed };
348 let file = self.files.alloc(data);
349 self.root2files.get_mut(root).unwrap().insert(file);
353 fn change_file(&mut self, file: VfsFile, new_text: Arc<String>, is_overlayed: bool) {
354 let mut file_data = &mut self.files[file];
355 file_data.text = new_text;
356 file_data.is_overlayed = is_overlayed;
359 fn remove_file(&mut self, file: VfsFile) {
360 //FIXME: use arena with removal
361 self.files[file].text = Default::default();
362 self.files[file].path = Default::default();
363 let root = self.files[file].root;
364 let removed = self.root2files.get_mut(root).unwrap().remove(&file);
368 fn find_root(&self, path: &Path) -> Option<(VfsRoot, RelativePathBuf, Option<VfsFile>)> {
369 let (root, path) = self.roots.find(&path)?;
370 let file = self.find_file(root, &path);
371 Some((root, path, file))
374 fn find_file(&self, root: VfsRoot, path: &RelativePath) -> Option<VfsFile> {
375 self.root2files[root].iter().map(|&it| it).find(|&file| self.files[file].path == path)
379 #[derive(Debug, Clone)]
381 AddRoot { root: VfsRoot, files: Vec<(VfsFile, RelativePathBuf, Arc<String>)> },
382 AddFile { root: VfsRoot, file: VfsFile, path: RelativePathBuf, text: Arc<String> },
383 RemoveFile { root: VfsRoot, file: VfsFile, path: RelativePathBuf },
384 ChangeFile { file: VfsFile, text: Arc<String> },