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 path2file(&self, path: &Path) -> Option<VfsFile> {
166 if let Some((_root, _path, Some(file))) = self.find_root(path) {
172 pub fn file2path(&self, file: VfsFile) -> PathBuf {
173 let rel_path = &self.files[file].path;
174 let root_path = &self.roots[self.files[file].root].root;
175 rel_path.to_path(root_path)
178 pub fn file_for_path(&self, path: &Path) -> Option<VfsFile> {
179 if let Some((_root, _path, Some(file))) = self.find_root(path) {
185 pub fn num_roots(&self) -> usize {
189 pub fn load(&mut self, path: &Path) -> Option<VfsFile> {
190 if let Some((root, rel_path, file)) = self.find_root(path) {
191 return if let Some(file) = file {
194 let text = fs::read_to_string(path).unwrap_or_default();
195 let text = Arc::new(text);
196 let file = self.add_file(root, rel_path.clone(), Arc::clone(&text), false);
197 let change = VfsChange::AddFile { file, text, root, path: rel_path };
198 self.pending_changes.push(change);
205 pub fn task_receiver(&self) -> &Receiver<io::TaskResult> {
206 self.worker.receiver()
209 pub fn handle_task(&mut self, task: io::TaskResult) {
211 TaskResult::BulkLoadRoot { root, files } => {
212 let mut cur_files = Vec::new();
213 // While we were scanning the root in the backgound, a file might have
214 // been open in the editor, so we need to account for that.
215 let exising = self.root2files[root]
217 .map(|&file| (self.files[file].path.clone(), file))
218 .collect::<FxHashMap<_, _>>();
219 for (path, text) in files {
220 if let Some(&file) = exising.get(&path) {
221 let text = Arc::clone(&self.files[file].text);
222 cur_files.push((file, path, text));
225 let text = Arc::new(text);
226 let file = self.add_file(root, path.clone(), Arc::clone(&text), false);
227 cur_files.push((file, path, text));
230 let change = VfsChange::AddRoot { root, files: cur_files };
231 self.pending_changes.push(change);
233 TaskResult::AddSingleFile { root, path, text } => {
234 if self.find_file(root, &path).is_none() {
235 self.do_add_file(root, path, text, false);
238 TaskResult::ChangeSingleFile { root, path, text } => {
239 if let Some(file) = self.find_file(root, &path) {
240 self.do_change_file(file, text, false);
242 self.do_add_file(root, path, text, false);
245 TaskResult::RemoveSingleFile { root, path } => {
246 if let Some(file) = self.find_file(root, &path) {
247 self.do_remove_file(root, path, file, false);
256 path: RelativePathBuf,
259 ) -> Option<VfsFile> {
260 let text = Arc::new(text);
261 let file = self.add_file(root, path.clone(), text.clone(), is_overlay);
262 self.pending_changes.push(VfsChange::AddFile { file, root, path, text });
266 fn do_change_file(&mut self, file: VfsFile, text: String, is_overlay: bool) {
267 if !is_overlay && self.files[file].is_overlayed {
270 let text = Arc::new(text);
271 self.change_file(file, text.clone(), is_overlay);
272 self.pending_changes.push(VfsChange::ChangeFile { file, text });
278 path: RelativePathBuf,
282 if !is_overlay && self.files[file].is_overlayed {
285 self.remove_file(file);
286 self.pending_changes.push(VfsChange::RemoveFile { root, path, file });
289 pub fn add_file_overlay(&mut self, path: &Path, text: String) -> Option<VfsFile> {
290 if let Some((root, rel_path, file)) = self.find_root(path) {
291 if let Some(file) = file {
292 self.do_change_file(file, text, true);
295 self.do_add_file(root, rel_path, text, true)
302 pub fn change_file_overlay(&mut self, path: &Path, new_text: String) {
303 if let Some((_root, _path, file)) = self.find_root(path) {
304 let file = file.expect("can't change a file which wasn't added");
305 self.do_change_file(file, new_text, true);
309 pub fn remove_file_overlay(&mut self, path: &Path) -> Option<VfsFile> {
310 if let Some((root, path, file)) = self.find_root(path) {
311 let file = file.expect("can't remove a file which wasn't added");
312 let full_path = path.to_path(&self.roots[root].root);
313 if let Ok(text) = fs::read_to_string(&full_path) {
314 self.do_change_file(file, text, true);
316 self.do_remove_file(root, path, file, true);
324 pub fn commit_changes(&mut self) -> Vec<VfsChange> {
325 mem::replace(&mut self.pending_changes, Vec::new())
328 /// Sutdown the VFS and terminate the background watching thread.
329 pub fn shutdown(self) -> thread::Result<()> {
330 self.worker.shutdown()
336 path: RelativePathBuf,
340 let data = VfsFileData { root, path, text, is_overlayed };
341 let file = self.files.alloc(data);
342 self.root2files.get_mut(root).unwrap().insert(file);
346 fn change_file(&mut self, file: VfsFile, new_text: Arc<String>, is_overlayed: bool) {
347 let mut file_data = &mut self.files[file];
348 file_data.text = new_text;
349 file_data.is_overlayed = is_overlayed;
352 fn remove_file(&mut self, file: VfsFile) {
353 //FIXME: use arena with removal
354 self.files[file].text = Default::default();
355 self.files[file].path = Default::default();
356 let root = self.files[file].root;
357 let removed = self.root2files.get_mut(root).unwrap().remove(&file);
361 fn find_root(&self, path: &Path) -> Option<(VfsRoot, RelativePathBuf, Option<VfsFile>)> {
362 let (root, path) = self.roots.find(&path)?;
363 let file = self.find_file(root, &path);
364 Some((root, path, file))
367 fn find_file(&self, root: VfsRoot, path: &RelativePath) -> Option<VfsFile> {
368 self.root2files[root].iter().map(|&it| it).find(|&file| self.files[file].path == path)
372 #[derive(Debug, Clone)]
374 AddRoot { root: VfsRoot, files: Vec<(VfsFile, RelativePathBuf, Arc<String>)> },
375 AddFile { root: VfsRoot, file: VfsFile, path: RelativePathBuf, text: Arc<String> },
376 RemoveFile { root: VfsRoot, file: VfsFile, path: RelativePathBuf },
377 ChangeFile { file: VfsFile, text: Arc<String> },