]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/test_db.rs
Merge #7799
[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, src::HasSource, 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             for decl in module.scope.declarations() {
119                 if let ModuleDefId::FunctionId(it) = decl {
120                     let range = it.lookup(self).source(self).value.syntax().text_range();
121
122                     if !range.contains(position.offset) {
123                         continue;
124                     }
125
126                     let new_size = match size {
127                         None => range.len(),
128                         Some(size) => {
129                             if range.len() < size {
130                                 range.len()
131                             } else {
132                                 size
133                             }
134                         }
135                     };
136                     if size != Some(new_size) {
137                         size = Some(new_size);
138                         fn_def = Some(it);
139                     }
140                 }
141             }
142         }
143
144         // Find the innermost block expression that has a `DefMap`.
145         let def_with_body = fn_def?.into();
146         let (_, source_map) = self.body_with_source_map(def_with_body);
147         let scopes = self.expr_scopes(def_with_body);
148         let root = self.parse(position.file_id);
149
150         let scope_iter = algo::ancestors_at_offset(&root.syntax_node(), position.offset)
151             .filter_map(|node| {
152                 let block = ast::BlockExpr::cast(node)?;
153                 let expr = ast::Expr::from(block);
154                 let expr_id = source_map.node_expr(InFile::new(position.file_id.into(), &expr))?;
155                 let scope = scopes.scope_for(expr_id).unwrap();
156                 Some(scope)
157             });
158
159         for scope in scope_iter {
160             let containing_blocks =
161                 scopes.scope_chain(Some(scope)).filter_map(|scope| scopes.block(scope));
162
163             for block in containing_blocks {
164                 if let Some(def_map) = self.block_def_map(block) {
165                     return Some(def_map);
166                 }
167             }
168         }
169
170         None
171     }
172
173     pub(crate) fn log(&self, f: impl FnOnce()) -> Vec<salsa::Event> {
174         *self.events.lock().unwrap() = Some(Vec::new());
175         f();
176         self.events.lock().unwrap().take().unwrap()
177     }
178
179     pub(crate) fn log_executed(&self, f: impl FnOnce()) -> Vec<String> {
180         let events = self.log(f);
181         events
182             .into_iter()
183             .filter_map(|e| match e.kind {
184                 // This pretty horrible, but `Debug` is the only way to inspect
185                 // QueryDescriptor at the moment.
186                 salsa::EventKind::WillExecute { database_key } => {
187                     Some(format!("{:?}", database_key.debug(self)))
188                 }
189                 _ => None,
190             })
191             .collect()
192     }
193
194     pub(crate) fn extract_annotations(&self) -> FxHashMap<FileId, Vec<(TextRange, String)>> {
195         let mut files = Vec::new();
196         let crate_graph = self.crate_graph();
197         for krate in crate_graph.iter() {
198             let crate_def_map = self.crate_def_map(krate);
199             for (module_id, _) in crate_def_map.modules() {
200                 let file_id = crate_def_map[module_id].origin.file_id();
201                 files.extend(file_id)
202             }
203         }
204         assert!(!files.is_empty());
205         files
206             .into_iter()
207             .filter_map(|file_id| {
208                 let text = self.file_text(file_id);
209                 let annotations = extract_annotations(&text);
210                 if annotations.is_empty() {
211                     return None;
212                 }
213                 Some((file_id, annotations))
214             })
215             .collect()
216     }
217
218     pub(crate) fn diagnostics<F: FnMut(&dyn Diagnostic)>(&self, mut cb: F) {
219         let crate_graph = self.crate_graph();
220         for krate in crate_graph.iter() {
221             let crate_def_map = self.crate_def_map(krate);
222
223             let mut sink = DiagnosticSinkBuilder::new().build(&mut cb);
224             for (module_id, module) in crate_def_map.modules() {
225                 crate_def_map.add_diagnostics(self, module_id, &mut sink);
226
227                 for decl in module.scope.declarations() {
228                     if let ModuleDefId::FunctionId(it) = decl {
229                         let source_map = self.body_with_source_map(it.into()).1;
230                         source_map.add_diagnostics(self, &mut sink);
231                     }
232                 }
233             }
234         }
235     }
236
237     pub(crate) fn check_diagnostics(&self) {
238         let db: &TestDB = self;
239         let annotations = db.extract_annotations();
240         assert!(!annotations.is_empty());
241
242         let mut actual: FxHashMap<FileId, Vec<(TextRange, String)>> = FxHashMap::default();
243         db.diagnostics(|d| {
244             let src = d.display_source();
245             let root = db.parse_or_expand(src.file_id).unwrap();
246
247             let node = src.map(|ptr| ptr.to_node(&root));
248             let frange = node.as_ref().original_file_range(db);
249
250             let message = d.message();
251             actual.entry(frange.file_id).or_default().push((frange.range, message));
252         });
253
254         for (file_id, diags) in actual.iter_mut() {
255             diags.sort_by_key(|it| it.0.start());
256             let text = db.file_text(*file_id);
257             // For multiline spans, place them on line start
258             for (range, content) in diags {
259                 if text[*range].contains('\n') {
260                     *range = TextRange::new(range.start(), range.start() + TextSize::from(1));
261                     *content = format!("... {}", content);
262                 }
263             }
264         }
265
266         assert_eq!(annotations, actual);
267     }
268 }