1 //! ra_db defines basic database traits. The concrete DB is defined by ra_ide.
6 use std::{panic, sync::Arc};
9 use ra_syntax::{ast, Parse, SourceFile, TextRange, TextSize};
10 use rustc_hash::FxHashSet;
13 cancellation::Canceled,
15 CrateData, CrateGraph, CrateId, CrateName, Dependency, Edition, Env, FileId, ProcMacroId,
16 SourceRoot, SourceRootId,
19 pub use relative_path::{RelativePath, RelativePathBuf};
21 pub use vfs::{file_set::FileSet, VfsPath};
24 macro_rules! impl_intern_key {
26 impl $crate::salsa::InternKey for $name {
27 fn from_intern_id(v: $crate::salsa::InternId) -> Self {
30 fn as_intern_id(&self) -> $crate::salsa::InternId {
37 pub trait Upcast<T: ?Sized> {
38 fn upcast(&self) -> &T;
41 pub trait CheckCanceled {
42 /// Aborts current query if there are pending changes.
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.
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.
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);
57 fn catch_canceled<F, T>(&self, f: F) -> Result<T, Canceled>
59 Self: Sized + panic::RefUnwindSafe,
60 F: FnOnce(&Self) -> T + panic::UnwindSafe,
62 panic::catch_unwind(|| f(self)).map_err(|err| match err.downcast::<Canceled>() {
63 Ok(canceled) => *canceled,
64 Err(payload) => panic::resume_unwind(payload),
69 impl<T: salsa::Database> CheckCanceled for T {
70 fn check_canceled(&self) {
71 if self.salsa_runtime().is_current_revision_canceled() {
77 #[derive(Clone, Copy, Debug)]
78 pub struct FilePosition {
83 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
84 pub struct FileRange {
89 pub const DEFAULT_LRU_CAP: usize = 128;
91 pub trait FileLoader {
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>>;
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>;
113 fn crate_graph(&self) -> Arc<CrateGraph>;
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)
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 {
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.
131 fn file_source_root(&self, file_id: FileId) -> SourceRootId;
132 /// Contents of the source root.
134 fn source_root(&self, id: SourceRootId) -> Arc<SourceRoot>;
136 fn source_root_crates(&self, id: SourceRootId) -> Arc<FxHashSet<CrateId>>;
139 fn source_root_crates(db: &dyn SourceDatabaseExt, id: SourceRootId) -> Arc<FxHashSet<CrateId>> {
140 let graph = db.crate_graph();
144 let root_file = graph[krate].root_file_id;
145 db.file_source_root(root_file) == id
147 .collect::<FxHashSet<_>>();
151 /// Silly workaround for cyclic deps between the traits
152 pub struct FileLoaderDelegate<T>(pub T);
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)
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)
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)