]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/test_db.rs
Merge #7617
[rust.git] / crates / hir_def / src / test_db.rs
1 //! Database used for testing `hir_def`.
2
3 use std::{
4     fmt, panic,
5     sync::{Arc, Mutex},
6 };
7
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;
17
18 use crate::{db::DefDatabase, nameres::DefMap, Lookup, ModuleDefId, ModuleId};
19
20 #[salsa::database(
21     base_db::SourceDatabaseExtStorage,
22     base_db::SourceDatabaseStorage,
23     hir_expand::db::AstDatabaseStorage,
24     crate::db::InternDatabaseStorage,
25     crate::db::DefDatabaseStorage
26 )]
27 #[derive(Default)]
28 pub(crate) struct TestDB {
29     storage: salsa::Storage<TestDB>,
30     events: Mutex<Option<Vec<salsa::Event>>>,
31 }
32
33 impl Upcast<dyn AstDatabase> for TestDB {
34     fn upcast(&self) -> &(dyn AstDatabase + 'static) {
35         &*self
36     }
37 }
38
39 impl Upcast<dyn DefDatabase> for TestDB {
40     fn upcast(&self) -> &(dyn DefDatabase + 'static) {
41         &*self
42     }
43 }
44
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 {
49             events.push(event);
50         }
51     }
52 }
53
54 impl fmt::Debug for TestDB {
55     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56         f.debug_struct("TestDB").finish()
57     }
58 }
59
60 impl panic::RefUnwindSafe for TestDB {}
61
62 impl FileLoader for TestDB {
63     fn file_text(&self, file_id: FileId) -> Arc<String> {
64         FileLoaderDelegate(self).file_text(file_id)
65     }
66     fn resolve_path(&self, path: AnchoredPath) -> Option<FileId> {
67         FileLoaderDelegate(self).resolve_path(path)
68     }
69     fn relevant_crates(&self, file_id: FileId) -> Arc<FxHashSet<CrateId>> {
70         FileLoaderDelegate(self).relevant_crates(file_id)
71     }
72 }
73
74 impl TestDB {
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);
81                 }
82             }
83         }
84         panic!("Can't find module for file")
85     }
86
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);
90
91         def_map = match self.block_at_position(&def_map, position) {
92             Some(it) => it,
93             None => return file_module,
94         };
95         loop {
96             let new_map = self.block_at_position(&def_map, position);
97             match new_map {
98                 Some(new_block) if !Arc::ptr_eq(&new_block, &def_map) => {
99                     def_map = new_block;
100                 }
101                 _ => {
102                     // FIXME: handle `mod` inside block expression
103                     return def_map.module_id(def_map.root());
104                 }
105             }
106         }
107     }
108
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.
111         let mut size = None;
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() {
116                 continue;
117             }
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 {
123                     let ast =
124                         ast_map.get(item_tree[it.lookup(self).id.value].ast_id).to_node(&root);
125                     let range = ast.syntax().text_range();
126
127                     if !range.contains(position.offset) {
128                         continue;
129                     }
130
131                     let new_size = match size {
132                         None => range.len(),
133                         Some(size) => {
134                             if range.len() < size {
135                                 range.len()
136                             } else {
137                                 size
138                             }
139                         }
140                     };
141                     if size != Some(new_size) {
142                         size = Some(new_size);
143                         fn_def = Some(it);
144                     }
145                 }
146             }
147         }
148
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);
154
155         let scope_iter = algo::ancestors_at_offset(&root.syntax_node(), position.offset)
156             .filter_map(|node| {
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();
161                 Some(scope)
162             });
163
164         for scope in scope_iter {
165             let containing_blocks =
166                 scopes.scope_chain(Some(scope)).filter_map(|scope| scopes.block(scope));
167
168             for block in containing_blocks {
169                 if let Some(def_map) = self.block_def_map(block) {
170                     return Some(def_map);
171                 }
172             }
173         }
174
175         None
176     }
177
178     pub(crate) fn log(&self, f: impl FnOnce()) -> Vec<salsa::Event> {
179         *self.events.lock().unwrap() = Some(Vec::new());
180         f();
181         self.events.lock().unwrap().take().unwrap()
182     }
183
184     pub(crate) fn log_executed(&self, f: impl FnOnce()) -> Vec<String> {
185         let events = self.log(f);
186         events
187             .into_iter()
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)))
193                 }
194                 _ => None,
195             })
196             .collect()
197     }
198
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)
207             }
208         }
209         assert!(!files.is_empty());
210         files
211             .into_iter()
212             .filter_map(|file_id| {
213                 let text = self.file_text(file_id);
214                 let annotations = extract_annotations(&text);
215                 if annotations.is_empty() {
216                     return None;
217                 }
218                 Some((file_id, annotations))
219             })
220             .collect()
221     }
222
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);
227
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);
231
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);
236                     }
237                 }
238             }
239         }
240     }
241
242     pub(crate) fn check_diagnostics(&self) {
243         let db: &TestDB = self;
244         let annotations = db.extract_annotations();
245         assert!(!annotations.is_empty());
246
247         let mut actual: FxHashMap<FileId, Vec<(TextRange, String)>> = FxHashMap::default();
248         db.diagnostics(|d| {
249             let src = d.display_source();
250             let root = db.parse_or_expand(src.file_id).unwrap();
251
252             let node = src.map(|ptr| ptr.to_node(&root));
253             let frange = node.as_ref().original_file_range(db);
254
255             let message = d.message();
256             actual.entry(frange.file_id).or_default().push((frange.range, message));
257         });
258
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);
267                 }
268             }
269         }
270
271         assert_eq!(annotations, actual);
272     }
273 }