1 //! Database used for testing `hir_def`.
8 use base_db::{salsa, CrateId, FileId, FileLoader, FileLoaderDelegate, FilePosition, Upcast};
9 use base_db::{AnchoredPath, SourceDatabase};
10 use hir_expand::diagnostics::Diagnostic;
11 use hir_expand::diagnostics::DiagnosticSinkBuilder;
12 use hir_expand::{db::AstDatabase, InFile};
13 use rustc_hash::FxHashMap;
14 use rustc_hash::FxHashSet;
15 use syntax::{algo, ast, AstNode, TextRange, TextSize};
16 use test_utils::extract_annotations;
18 use crate::{db::DefDatabase, nameres::DefMap, Lookup, ModuleDefId, ModuleId};
21 base_db::SourceDatabaseExtStorage,
22 base_db::SourceDatabaseStorage,
23 hir_expand::db::AstDatabaseStorage,
24 crate::db::InternDatabaseStorage,
25 crate::db::DefDatabaseStorage
28 pub(crate) struct TestDB {
29 storage: salsa::Storage<TestDB>,
30 events: Mutex<Option<Vec<salsa::Event>>>,
33 impl Upcast<dyn AstDatabase> for TestDB {
34 fn upcast(&self) -> &(dyn AstDatabase + 'static) {
39 impl Upcast<dyn DefDatabase> for TestDB {
40 fn upcast(&self) -> &(dyn DefDatabase + 'static) {
45 impl salsa::Database for TestDB {
46 fn salsa_event(&self, event: salsa::Event) {
47 let mut events = self.events.lock().unwrap();
48 if let Some(events) = &mut *events {
54 impl fmt::Debug for TestDB {
55 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56 f.debug_struct("TestDB").finish()
60 impl panic::RefUnwindSafe for TestDB {}
62 impl FileLoader for TestDB {
63 fn file_text(&self, file_id: FileId) -> Arc<String> {
64 FileLoaderDelegate(self).file_text(file_id)
66 fn resolve_path(&self, path: AnchoredPath) -> Option<FileId> {
67 FileLoaderDelegate(self).resolve_path(path)
69 fn relevant_crates(&self, file_id: FileId) -> Arc<FxHashSet<CrateId>> {
70 FileLoaderDelegate(self).relevant_crates(file_id)
75 pub(crate) fn module_for_file(&self, file_id: FileId) -> ModuleId {
76 for &krate in self.relevant_crates(file_id).iter() {
77 let crate_def_map = self.crate_def_map(krate);
78 for (local_id, data) in crate_def_map.modules() {
79 if data.origin.file_id() == Some(file_id) {
80 return crate_def_map.module_id(local_id);
84 panic!("Can't find module for file")
87 pub(crate) fn module_at_position(&self, position: FilePosition) -> ModuleId {
88 let file_module = self.module_for_file(position.file_id);
89 let mut def_map = file_module.def_map(self);
91 def_map = match self.block_at_position(&def_map, position) {
93 None => return file_module,
96 let new_map = self.block_at_position(&def_map, position);
98 Some(new_block) if !Arc::ptr_eq(&new_block, &def_map) => {
102 // FIXME: handle `mod` inside block expression
103 return def_map.module_id(def_map.root());
109 fn block_at_position(&self, def_map: &DefMap, position: FilePosition) -> Option<Arc<DefMap>> {
110 // Find the smallest (innermost) function in `def_map` containing the cursor.
112 let mut fn_def = None;
113 for (_, module) in def_map.modules() {
114 let file_id = module.definition_source(self).file_id;
115 if file_id != position.file_id.into() {
118 let root = self.parse_or_expand(file_id).unwrap();
119 let ast_map = self.ast_id_map(file_id);
120 let item_tree = self.item_tree(file_id);
121 for decl in module.scope.declarations() {
122 if let ModuleDefId::FunctionId(it) = decl {
124 ast_map.get(item_tree[it.lookup(self).id.value].ast_id).to_node(&root);
125 let range = ast.syntax().text_range();
127 if !range.contains(position.offset) {
131 let new_size = match size {
134 if range.len() < size {
141 if size != Some(new_size) {
142 size = Some(new_size);
149 // Find the innermost block expression that has a `DefMap`.
150 let def_with_body = fn_def?.into();
151 let (_, source_map) = self.body_with_source_map(def_with_body);
152 let scopes = self.expr_scopes(def_with_body);
153 let root = self.parse(position.file_id);
155 let scope_iter = algo::ancestors_at_offset(&root.syntax_node(), position.offset)
157 let block = ast::BlockExpr::cast(node)?;
158 let expr = ast::Expr::from(block);
159 let expr_id = source_map.node_expr(InFile::new(position.file_id.into(), &expr))?;
160 let scope = scopes.scope_for(expr_id).unwrap();
164 for scope in scope_iter {
165 let containing_blocks =
166 scopes.scope_chain(Some(scope)).filter_map(|scope| scopes.block(scope));
168 for block in containing_blocks {
169 if let Some(def_map) = self.block_def_map(block) {
170 return Some(def_map);
178 pub(crate) fn log(&self, f: impl FnOnce()) -> Vec<salsa::Event> {
179 *self.events.lock().unwrap() = Some(Vec::new());
181 self.events.lock().unwrap().take().unwrap()
184 pub(crate) fn log_executed(&self, f: impl FnOnce()) -> Vec<String> {
185 let events = self.log(f);
188 .filter_map(|e| match e.kind {
189 // This pretty horrible, but `Debug` is the only way to inspect
190 // QueryDescriptor at the moment.
191 salsa::EventKind::WillExecute { database_key } => {
192 Some(format!("{:?}", database_key.debug(self)))
199 pub(crate) fn extract_annotations(&self) -> FxHashMap<FileId, Vec<(TextRange, String)>> {
200 let mut files = Vec::new();
201 let crate_graph = self.crate_graph();
202 for krate in crate_graph.iter() {
203 let crate_def_map = self.crate_def_map(krate);
204 for (module_id, _) in crate_def_map.modules() {
205 let file_id = crate_def_map[module_id].origin.file_id();
206 files.extend(file_id)
209 assert!(!files.is_empty());
212 .filter_map(|file_id| {
213 let text = self.file_text(file_id);
214 let annotations = extract_annotations(&text);
215 if annotations.is_empty() {
218 Some((file_id, annotations))
223 pub(crate) fn diagnostics<F: FnMut(&dyn Diagnostic)>(&self, mut cb: F) {
224 let crate_graph = self.crate_graph();
225 for krate in crate_graph.iter() {
226 let crate_def_map = self.crate_def_map(krate);
228 let mut sink = DiagnosticSinkBuilder::new().build(&mut cb);
229 for (module_id, module) in crate_def_map.modules() {
230 crate_def_map.add_diagnostics(self, module_id, &mut sink);
232 for decl in module.scope.declarations() {
233 if let ModuleDefId::FunctionId(it) = decl {
234 let source_map = self.body_with_source_map(it.into()).1;
235 source_map.add_diagnostics(self, &mut sink);
242 pub(crate) fn check_diagnostics(&self) {
243 let db: &TestDB = self;
244 let annotations = db.extract_annotations();
245 assert!(!annotations.is_empty());
247 let mut actual: FxHashMap<FileId, Vec<(TextRange, String)>> = FxHashMap::default();
249 let src = d.display_source();
250 let root = db.parse_or_expand(src.file_id).unwrap();
252 let node = src.map(|ptr| ptr.to_node(&root));
253 let frange = node.as_ref().original_file_range(db);
255 let message = d.message();
256 actual.entry(frange.file_id).or_default().push((frange.range, message));
259 for (file_id, diags) in actual.iter_mut() {
260 diags.sort_by_key(|it| it.0.start());
261 let text = db.file_text(*file_id);
262 // For multiline spans, place them on line start
263 for (range, content) in diags {
264 if text[*range].contains('\n') {
265 *range = TextRange::new(range.start(), range.start() + TextSize::from(1));
266 *content = format!("... {}", content);
271 assert_eq!(annotations, actual);