]> git.lizzy.rs Git - rust.git/blob - crates/ra_db/src/lib.rs
Remove unwanted dependency
[rust.git] / crates / ra_db / src / lib.rs
1 //! ra_db defines basic database traits. The concrete DB is defined by ra_ide.
2 mod cancellation;
3 mod input;
4 pub mod fixture;
5
6 use std::{panic, sync::Arc};
7
8 use ra_prof::profile;
9 use ra_syntax::{ast, Parse, SourceFile, TextRange, TextSize};
10 use rustc_hash::FxHashSet;
11
12 pub use crate::{
13     cancellation::Canceled,
14     input::{
15         CrateData, CrateGraph, CrateId, CrateName, Dependency, Edition, Env, FileId, ProcMacroId,
16         SourceRoot, SourceRootId,
17     },
18 };
19 pub use relative_path::{RelativePath, RelativePathBuf};
20 pub use salsa;
21 pub use vfs::{file_set::FileSet, VfsPath};
22
23 #[macro_export]
24 macro_rules! impl_intern_key {
25     ($name:ident) => {
26         impl $crate::salsa::InternKey for $name {
27             fn from_intern_id(v: $crate::salsa::InternId) -> Self {
28                 $name(v)
29             }
30             fn as_intern_id(&self) -> $crate::salsa::InternId {
31                 self.0
32             }
33         }
34     };
35 }
36
37 pub trait Upcast<T: ?Sized> {
38     fn upcast(&self) -> &T;
39 }
40
41 pub trait CheckCanceled {
42     /// Aborts current query if there are pending changes.
43     ///
44     /// rust-analyzer needs to be able to answer semantic questions about the
45     /// code while the code is being modified. A common problem is that a
46     /// long-running query is being calculated when a new change arrives.
47     ///
48     /// We can't just apply the change immediately: this will cause the pending
49     /// query to see inconsistent state (it will observe an absence of
50     /// repeatable read). So what we do is we **cancel** all pending queries
51     /// before applying the change.
52     ///
53     /// We implement cancellation by panicking with a special value and catching
54     /// it on the API boundary. Salsa explicitly supports this use-case.
55     fn check_canceled(&self);
56
57     fn catch_canceled<F, T>(&self, f: F) -> Result<T, Canceled>
58     where
59         Self: Sized + panic::RefUnwindSafe,
60         F: FnOnce(&Self) -> T + panic::UnwindSafe,
61     {
62         panic::catch_unwind(|| f(self)).map_err(|err| match err.downcast::<Canceled>() {
63             Ok(canceled) => *canceled,
64             Err(payload) => panic::resume_unwind(payload),
65         })
66     }
67 }
68
69 impl<T: salsa::Database> CheckCanceled for T {
70     fn check_canceled(&self) {
71         if self.salsa_runtime().is_current_revision_canceled() {
72             Canceled::throw()
73         }
74     }
75 }
76
77 #[derive(Clone, Copy, Debug)]
78 pub struct FilePosition {
79     pub file_id: FileId,
80     pub offset: TextSize,
81 }
82
83 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
84 pub struct FileRange {
85     pub file_id: FileId,
86     pub range: TextRange,
87 }
88
89 pub const DEFAULT_LRU_CAP: usize = 128;
90
91 pub trait FileLoader {
92     /// Text of the file.
93     fn file_text(&self, file_id: FileId) -> Arc<String>;
94     /// Note that we intentionally accept a `&str` and not a `&Path` here. This
95     /// method exists to handle `#[path = "/some/path.rs"] mod foo;` and such,
96     /// so the input is guaranteed to be utf-8 string. One might be tempted to
97     /// introduce some kind of "utf-8 path with / separators", but that's a bad idea. Behold
98     /// `#[path = "C://no/way"]`
99     fn resolve_path(&self, anchor: FileId, path: &str) -> Option<FileId>;
100     fn relevant_crates(&self, file_id: FileId) -> Arc<FxHashSet<CrateId>>;
101 }
102
103 /// Database which stores all significant input facts: source code and project
104 /// model. Everything else in rust-analyzer is derived from these queries.
105 #[salsa::query_group(SourceDatabaseStorage)]
106 pub trait SourceDatabase: CheckCanceled + FileLoader + std::fmt::Debug {
107     // Parses the file into the syntax tree.
108     #[salsa::invoke(parse_query)]
109     fn parse(&self, file_id: FileId) -> Parse<ast::SourceFile>;
110
111     /// The crate graph.
112     #[salsa::input]
113     fn crate_graph(&self) -> Arc<CrateGraph>;
114 }
115
116 fn parse_query(db: &dyn SourceDatabase, file_id: FileId) -> Parse<ast::SourceFile> {
117     let _p = profile("parse_query").detail(|| format!("{:?}", file_id));
118     let text = db.file_text(file_id);
119     SourceFile::parse(&*text)
120 }
121
122 /// We don't want to give HIR knowledge of source roots, hence we extract these
123 /// methods into a separate DB.
124 #[salsa::query_group(SourceDatabaseExtStorage)]
125 pub trait SourceDatabaseExt: SourceDatabase {
126     #[salsa::input]
127     fn file_text(&self, file_id: FileId) -> Arc<String>;
128     /// Path to a file, relative to the root of its source root.
129     /// Source root of the file.
130     #[salsa::input]
131     fn file_source_root(&self, file_id: FileId) -> SourceRootId;
132     /// Contents of the source root.
133     #[salsa::input]
134     fn source_root(&self, id: SourceRootId) -> Arc<SourceRoot>;
135
136     fn source_root_crates(&self, id: SourceRootId) -> Arc<FxHashSet<CrateId>>;
137 }
138
139 fn source_root_crates(db: &dyn SourceDatabaseExt, id: SourceRootId) -> Arc<FxHashSet<CrateId>> {
140     let graph = db.crate_graph();
141     let res = graph
142         .iter()
143         .filter(|&krate| {
144             let root_file = graph[krate].root_file_id;
145             db.file_source_root(root_file) == id
146         })
147         .collect::<FxHashSet<_>>();
148     Arc::new(res)
149 }
150
151 /// Silly workaround for cyclic deps between the traits
152 pub struct FileLoaderDelegate<T>(pub T);
153
154 impl<T: SourceDatabaseExt> FileLoader for FileLoaderDelegate<&'_ T> {
155     fn file_text(&self, file_id: FileId) -> Arc<String> {
156         SourceDatabaseExt::file_text(self.0, file_id)
157     }
158     fn resolve_path(&self, anchor: FileId, path: &str) -> Option<FileId> {
159         // FIXME: this *somehow* should be platform agnostic...
160         let source_root = self.0.file_source_root(anchor);
161         let source_root = self.0.source_root(source_root);
162         source_root.file_set.resolve_path(anchor, path)
163     }
164
165     fn relevant_crates(&self, file_id: FileId) -> Arc<FxHashSet<CrateId>> {
166         let source_root = self.0.file_source_root(file_id);
167         self.0.source_root_crates(source_root)
168     }
169 }