1 //! Database used for testing `hir_def`.
9 salsa, CrateId, FileId, FileLoader, FileLoaderDelegate, FilePosition, FileRange, Upcast,
11 use base_db::{AnchoredPath, SourceDatabase};
12 use hir_expand::{db::AstDatabase, InFile};
13 use rustc_hash::FxHashMap;
14 use rustc_hash::FxHashSet;
15 use syntax::{algo, ast, AstNode, SyntaxNode, SyntaxNodePtr, TextRange, TextSize};
16 use test_utils::extract_annotations;
21 nameres::{diagnostics::DefDiagnosticKind, DefMap, ModuleSource},
23 LocalModuleId, Lookup, ModuleDefId, ModuleId,
27 base_db::SourceDatabaseExtStorage,
28 base_db::SourceDatabaseStorage,
29 hir_expand::db::AstDatabaseStorage,
30 crate::db::InternDatabaseStorage,
31 crate::db::DefDatabaseStorage
34 pub(crate) struct TestDB {
35 storage: salsa::Storage<TestDB>,
36 events: Mutex<Option<Vec<salsa::Event>>>,
39 impl Upcast<dyn AstDatabase> for TestDB {
40 fn upcast(&self) -> &(dyn AstDatabase + 'static) {
45 impl Upcast<dyn DefDatabase> for TestDB {
46 fn upcast(&self) -> &(dyn DefDatabase + 'static) {
51 impl salsa::Database for TestDB {
52 fn salsa_event(&self, event: salsa::Event) {
53 let mut events = self.events.lock().unwrap();
54 if let Some(events) = &mut *events {
60 impl fmt::Debug for TestDB {
61 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62 f.debug_struct("TestDB").finish()
66 impl panic::RefUnwindSafe for TestDB {}
68 impl FileLoader for TestDB {
69 fn file_text(&self, file_id: FileId) -> Arc<String> {
70 FileLoaderDelegate(self).file_text(file_id)
72 fn resolve_path(&self, path: AnchoredPath) -> Option<FileId> {
73 FileLoaderDelegate(self).resolve_path(path)
75 fn relevant_crates(&self, file_id: FileId) -> Arc<FxHashSet<CrateId>> {
76 FileLoaderDelegate(self).relevant_crates(file_id)
81 pub(crate) fn module_for_file(&self, file_id: FileId) -> ModuleId {
82 for &krate in self.relevant_crates(file_id).iter() {
83 let crate_def_map = self.crate_def_map(krate);
84 for (local_id, data) in crate_def_map.modules() {
85 if data.origin.file_id() == Some(file_id) {
86 return crate_def_map.module_id(local_id);
90 panic!("Can't find module for file")
93 pub(crate) fn module_at_position(&self, position: FilePosition) -> ModuleId {
94 let file_module = self.module_for_file(position.file_id);
95 let mut def_map = file_module.def_map(self);
96 let module = self.mod_at_position(&def_map, position);
98 def_map = match self.block_at_position(&def_map, position) {
100 None => return def_map.module_id(module),
103 let new_map = self.block_at_position(&def_map, position);
105 Some(new_block) if !Arc::ptr_eq(&new_block, &def_map) => {
109 // FIXME: handle `mod` inside block expression
110 return def_map.module_id(def_map.root());
116 /// Finds the smallest/innermost module in `def_map` containing `position`.
117 fn mod_at_position(&self, def_map: &DefMap, position: FilePosition) -> LocalModuleId {
119 let mut res = def_map.root();
120 for (module, data) in def_map.modules() {
121 let src = data.definition_source(self);
122 if src.file_id != position.file_id.into() {
126 let range = match src.value {
127 ModuleSource::SourceFile(it) => it.syntax().text_range(),
128 ModuleSource::Module(it) => it.syntax().text_range(),
129 ModuleSource::BlockExpr(it) => it.syntax().text_range(),
132 if !range.contains(position.offset) {
136 let new_size = match size {
139 if range.len() < size {
147 if size != Some(new_size) {
148 cov_mark::hit!(submodule_in_testdb);
149 size = Some(new_size);
157 fn block_at_position(&self, def_map: &DefMap, position: FilePosition) -> Option<Arc<DefMap>> {
158 // Find the smallest (innermost) function in `def_map` containing the cursor.
160 let mut fn_def = None;
161 for (_, module) in def_map.modules() {
162 let file_id = module.definition_source(self).file_id;
163 if file_id != position.file_id.into() {
166 for decl in module.scope.declarations() {
167 if let ModuleDefId::FunctionId(it) = decl {
168 let range = it.lookup(self).source(self).value.syntax().text_range();
170 if !range.contains(position.offset) {
174 let new_size = match size {
177 if range.len() < size {
184 if size != Some(new_size) {
185 size = Some(new_size);
192 // Find the innermost block expression that has a `DefMap`.
193 let def_with_body = fn_def?.into();
194 let (_, source_map) = self.body_with_source_map(def_with_body);
195 let scopes = self.expr_scopes(def_with_body);
196 let root = self.parse(position.file_id);
198 let scope_iter = algo::ancestors_at_offset(&root.syntax_node(), position.offset)
200 let block = ast::BlockExpr::cast(node)?;
201 let expr = ast::Expr::from(block);
202 let expr_id = source_map.node_expr(InFile::new(position.file_id.into(), &expr))?;
203 let scope = scopes.scope_for(expr_id).unwrap();
207 for scope in scope_iter {
208 let containing_blocks =
209 scopes.scope_chain(Some(scope)).filter_map(|scope| scopes.block(scope));
211 for block in containing_blocks {
212 if let Some(def_map) = self.block_def_map(block) {
213 return Some(def_map);
221 pub(crate) fn log(&self, f: impl FnOnce()) -> Vec<salsa::Event> {
222 *self.events.lock().unwrap() = Some(Vec::new());
224 self.events.lock().unwrap().take().unwrap()
227 pub(crate) fn log_executed(&self, f: impl FnOnce()) -> Vec<String> {
228 let events = self.log(f);
231 .filter_map(|e| match e.kind {
232 // This pretty horrible, but `Debug` is the only way to inspect
233 // QueryDescriptor at the moment.
234 salsa::EventKind::WillExecute { database_key } => {
235 Some(format!("{:?}", database_key.debug(self)))
242 pub(crate) fn extract_annotations(&self) -> FxHashMap<FileId, Vec<(TextRange, String)>> {
243 let mut files = Vec::new();
244 let crate_graph = self.crate_graph();
245 for krate in crate_graph.iter() {
246 let crate_def_map = self.crate_def_map(krate);
247 for (module_id, _) in crate_def_map.modules() {
248 let file_id = crate_def_map[module_id].origin.file_id();
249 files.extend(file_id)
252 assert!(!files.is_empty());
255 .filter_map(|file_id| {
256 let text = self.file_text(file_id);
257 let annotations = extract_annotations(&text);
258 if annotations.is_empty() {
261 Some((file_id, annotations))
266 pub(crate) fn diagnostics(&self, cb: &mut dyn FnMut(FileRange, String)) {
267 let crate_graph = self.crate_graph();
268 for krate in crate_graph.iter() {
269 let crate_def_map = self.crate_def_map(krate);
271 for diag in crate_def_map.diagnostics() {
272 let (node, message): (InFile<SyntaxNode>, &str) = match &diag.kind {
273 DefDiagnosticKind::UnresolvedModule { ast, .. } => {
274 let node = ast.to_node(self.upcast());
275 (InFile::new(ast.file_id, node.syntax().clone()), "UnresolvedModule")
277 DefDiagnosticKind::UnresolvedExternCrate { ast, .. } => {
278 let node = ast.to_node(self.upcast());
279 (InFile::new(ast.file_id, node.syntax().clone()), "UnresolvedExternCrate")
281 DefDiagnosticKind::UnresolvedImport { ast, .. } => {
282 let node = ast.to_node(self.upcast());
283 (InFile::new(ast.file_id, node.syntax().clone()), "UnresolvedImport")
285 DefDiagnosticKind::UnconfiguredCode { ast, .. } => {
286 let node = ast.to_node(self.upcast());
287 (InFile::new(ast.file_id, node.syntax().clone()), "UnconfiguredCode")
289 DefDiagnosticKind::UnresolvedProcMacro { ast, .. } => {
290 (ast.to_node(self.upcast()), "UnresolvedProcMacro")
292 DefDiagnosticKind::UnresolvedMacroCall { ast, .. } => {
293 let node = ast.to_node(self.upcast());
294 (InFile::new(ast.file_id, node.syntax().clone()), "UnresolvedMacroCall")
296 DefDiagnosticKind::MacroError { ast, message } => {
297 (ast.to_node(self.upcast()), message.as_str())
301 let frange = node.as_ref().original_file_range(self);
302 cb(frange, message.to_string())
305 for (_module_id, module) in crate_def_map.modules() {
306 for decl in module.scope.declarations() {
307 if let ModuleDefId::FunctionId(it) = decl {
308 let source_map = self.body_with_source_map(it.into()).1;
309 for diag in source_map.diagnostics() {
310 let (ptr, message): (InFile<SyntaxNodePtr>, &str) = match diag {
311 BodyDiagnostic::InactiveCode { node, .. } => {
312 (node.clone().map(|it| it.into()), "InactiveCode")
314 BodyDiagnostic::MacroError { node, message } => {
315 (node.clone().map(|it| it.into()), message.as_str())
317 BodyDiagnostic::UnresolvedProcMacro { node } => {
318 (node.clone().map(|it| it.into()), "UnresolvedProcMacro")
320 BodyDiagnostic::UnresolvedMacroCall { node, .. } => {
321 (node.clone().map(|it| it.into()), "UnresolvedMacroCall")
325 let root = self.parse_or_expand(ptr.file_id).unwrap();
326 let node = ptr.map(|ptr| ptr.to_node(&root));
327 let frange = node.as_ref().original_file_range(self);
328 cb(frange, message.to_string())
336 pub(crate) fn check_diagnostics(&self) {
337 let db: &TestDB = self;
338 let annotations = db.extract_annotations();
339 assert!(!annotations.is_empty());
341 let mut actual: FxHashMap<FileId, Vec<(TextRange, String)>> = FxHashMap::default();
342 db.diagnostics(&mut |frange, message| {
343 actual.entry(frange.file_id).or_default().push((frange.range, message));
346 for (file_id, diags) in actual.iter_mut() {
347 diags.sort_by_key(|it| it.0.start());
348 let text = db.file_text(*file_id);
349 // For multiline spans, place them on line start
350 for (range, content) in diags {
351 if text[*range].contains('\n') {
352 *range = TextRange::new(range.start(), range.start() + TextSize::from(1));
353 *content = format!("... {}", content);
358 assert_eq!(annotations, actual);
361 pub(crate) fn check_no_diagnostics(&self) {
362 let db: &TestDB = self;
363 let annotations = db.extract_annotations();
364 assert!(annotations.is_empty());
366 let mut has_diagnostics = false;
367 db.diagnostics(&mut |_, _| {
368 has_diagnostics = true;
371 assert!(!has_diagnostics);