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, src::HasSource, 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 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();
122 if !range.contains(position.offset) {
126 let new_size = match size {
129 if range.len() < size {
136 if size != Some(new_size) {
137 size = Some(new_size);
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);
150 let scope_iter = algo::ancestors_at_offset(&root.syntax_node(), position.offset)
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();
159 for scope in scope_iter {
160 let containing_blocks =
161 scopes.scope_chain(Some(scope)).filter_map(|scope| scopes.block(scope));
163 for block in containing_blocks {
164 if let Some(def_map) = self.block_def_map(block) {
165 return Some(def_map);
173 pub(crate) fn log(&self, f: impl FnOnce()) -> Vec<salsa::Event> {
174 *self.events.lock().unwrap() = Some(Vec::new());
176 self.events.lock().unwrap().take().unwrap()
179 pub(crate) fn log_executed(&self, f: impl FnOnce()) -> Vec<String> {
180 let events = self.log(f);
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)))
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)
204 assert!(!files.is_empty());
207 .filter_map(|file_id| {
208 let text = self.file_text(file_id);
209 let annotations = extract_annotations(&text);
210 if annotations.is_empty() {
213 Some((file_id, annotations))
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);
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);
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);
237 pub(crate) fn check_diagnostics(&self) {
238 let db: &TestDB = self;
239 let annotations = db.extract_annotations();
240 assert!(!annotations.is_empty());
242 let mut actual: FxHashMap<FileId, Vec<(TextRange, String)>> = FxHashMap::default();
244 let src = d.display_source();
245 let root = db.parse_or_expand(src.file_id).unwrap();
247 let node = src.map(|ptr| ptr.to_node(&root));
248 let frange = node.as_ref().original_file_range(db);
250 let message = d.message();
251 actual.entry(frange.file_id).or_default().push((frange.range, message));
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);
266 assert_eq!(annotations, actual);
269 pub(crate) fn check_no_diagnostics(&self) {
270 let db: &TestDB = self;
271 let annotations = db.extract_annotations();
272 assert!(annotations.is_empty());
274 let mut has_diagnostics = false;
276 has_diagnostics = true;
279 assert!(!has_diagnostics);