]> git.lizzy.rs Git - rust.git/blob - crates/hir_ty/src/tests.rs
Access a body's block def maps via a method
[rust.git] / crates / hir_ty / src / tests.rs
1 mod never_type;
2 mod coercion;
3 mod regression;
4 mod simple;
5 mod patterns;
6 mod traits;
7 mod method_resolution;
8 mod macros;
9 mod display_source_code;
10
11 use std::{env, sync::Arc};
12
13 use base_db::{fixture::WithFixture, FileRange, SourceDatabase, SourceDatabaseExt};
14 use expect_test::Expect;
15 use hir_def::{
16     body::{Body, BodySourceMap, SyntheticSyntax},
17     child_by_source::ChildBySource,
18     db::DefDatabase,
19     item_scope::ItemScope,
20     keys,
21     nameres::DefMap,
22     src::HasSource,
23     AssocItemId, DefWithBodyId, LocalModuleId, Lookup, ModuleDefId,
24 };
25 use hir_expand::{db::AstDatabase, InFile};
26 use once_cell::race::OnceBool;
27 use stdx::format_to;
28 use syntax::{
29     algo,
30     ast::{self, AstNode, NameOwner},
31     SyntaxNode,
32 };
33 use tracing_subscriber::{layer::SubscriberExt, EnvFilter, Registry};
34 use tracing_tree::HierarchicalLayer;
35
36 use crate::{
37     db::HirDatabase, display::HirDisplay, infer::TypeMismatch, test_db::TestDB, InferenceResult, Ty,
38 };
39
40 // These tests compare the inference results for all expressions in a file
41 // against snapshots of the expected results using expect. Use
42 // `env UPDATE_EXPECT=1 cargo test -p hir_ty` to update the snapshots.
43
44 fn setup_tracing() -> Option<tracing::subscriber::DefaultGuard> {
45     static ENABLE: OnceBool = OnceBool::new();
46     if !ENABLE.get_or_init(|| env::var("CHALK_DEBUG").is_ok()) {
47         return None;
48     }
49
50     let filter = EnvFilter::from_env("CHALK_DEBUG");
51     let layer = HierarchicalLayer::default()
52         .with_indent_lines(true)
53         .with_ansi(false)
54         .with_indent_amount(2)
55         .with_writer(std::io::stderr);
56     let subscriber = Registry::default().with(filter).with(layer);
57     Some(tracing::subscriber::set_default(subscriber))
58 }
59
60 fn check_types(ra_fixture: &str) {
61     check_types_impl(ra_fixture, false)
62 }
63
64 fn check_types_source_code(ra_fixture: &str) {
65     check_types_impl(ra_fixture, true)
66 }
67
68 fn check_types_impl(ra_fixture: &str, display_source: bool) {
69     let _tracing = setup_tracing();
70     let db = TestDB::with_files(ra_fixture);
71     let mut checked_one = false;
72     for (file_id, annotations) in db.extract_annotations() {
73         for (range, expected) in annotations {
74             let ty = type_at_range(&db, FileRange { file_id, range });
75             let actual = if display_source {
76                 let module = db.module_for_file(file_id);
77                 ty.display_source_code(&db, module).unwrap()
78             } else {
79                 ty.display_test(&db).to_string()
80             };
81             assert_eq!(expected, actual);
82             checked_one = true;
83         }
84     }
85     assert!(checked_one, "no `//^` annotations found");
86 }
87
88 fn type_at_range(db: &TestDB, pos: FileRange) -> Ty {
89     let file = db.parse(pos.file_id).ok().unwrap();
90     let expr = algo::find_node_at_range::<ast::Expr>(file.syntax(), pos.range).unwrap();
91     let fn_def = expr.syntax().ancestors().find_map(ast::Fn::cast).unwrap();
92     let module = db.module_for_file(pos.file_id);
93     let func = *module.child_by_source(db)[keys::FUNCTION]
94         .get(&InFile::new(pos.file_id.into(), fn_def))
95         .unwrap();
96
97     let (_body, source_map) = db.body_with_source_map(func.into());
98     if let Some(expr_id) = source_map.node_expr(InFile::new(pos.file_id.into(), &expr)) {
99         let infer = db.infer(func.into());
100         return infer[expr_id].clone();
101     }
102     panic!("Can't find expression")
103 }
104
105 fn infer(ra_fixture: &str) -> String {
106     infer_with_mismatches(ra_fixture, false)
107 }
108
109 fn infer_with_mismatches(content: &str, include_mismatches: bool) -> String {
110     let _tracing = setup_tracing();
111     let (db, file_id) = TestDB::with_single_file(content);
112
113     let mut buf = String::new();
114
115     let mut infer_def = |inference_result: Arc<InferenceResult>,
116                          body_source_map: Arc<BodySourceMap>| {
117         let mut types: Vec<(InFile<SyntaxNode>, &Ty)> = Vec::new();
118         let mut mismatches: Vec<(InFile<SyntaxNode>, &TypeMismatch)> = Vec::new();
119
120         for (pat, ty) in inference_result.type_of_pat.iter() {
121             let syntax_ptr = match body_source_map.pat_syntax(pat) {
122                 Ok(sp) => {
123                     let root = db.parse_or_expand(sp.file_id).unwrap();
124                     sp.map(|ptr| {
125                         ptr.either(
126                             |it| it.to_node(&root).syntax().clone(),
127                             |it| it.to_node(&root).syntax().clone(),
128                         )
129                     })
130                 }
131                 Err(SyntheticSyntax) => continue,
132             };
133             types.push((syntax_ptr, ty));
134         }
135
136         for (expr, ty) in inference_result.type_of_expr.iter() {
137             let node = match body_source_map.expr_syntax(expr) {
138                 Ok(sp) => {
139                     let root = db.parse_or_expand(sp.file_id).unwrap();
140                     sp.map(|ptr| ptr.to_node(&root).syntax().clone())
141                 }
142                 Err(SyntheticSyntax) => continue,
143             };
144             types.push((node.clone(), ty));
145             if let Some(mismatch) = inference_result.type_mismatch_for_expr(expr) {
146                 mismatches.push((node, mismatch));
147             }
148         }
149
150         // sort ranges for consistency
151         types.sort_by_key(|(node, _)| {
152             let range = node.value.text_range();
153             (range.start(), range.end())
154         });
155         for (node, ty) in &types {
156             let (range, text) = if let Some(self_param) = ast::SelfParam::cast(node.value.clone()) {
157                 (self_param.name().unwrap().syntax().text_range(), "self".to_string())
158             } else {
159                 (node.value.text_range(), node.value.text().to_string().replace("\n", " "))
160             };
161             let macro_prefix = if node.file_id != file_id.into() { "!" } else { "" };
162             format_to!(
163                 buf,
164                 "{}{:?} '{}': {}\n",
165                 macro_prefix,
166                 range,
167                 ellipsize(text, 15),
168                 ty.display_test(&db)
169             );
170         }
171         if include_mismatches {
172             mismatches.sort_by_key(|(node, _)| {
173                 let range = node.value.text_range();
174                 (range.start(), range.end())
175             });
176             for (src_ptr, mismatch) in &mismatches {
177                 let range = src_ptr.value.text_range();
178                 let macro_prefix = if src_ptr.file_id != file_id.into() { "!" } else { "" };
179                 format_to!(
180                     buf,
181                     "{}{:?}: expected {}, got {}\n",
182                     macro_prefix,
183                     range,
184                     mismatch.expected.display_test(&db),
185                     mismatch.actual.display_test(&db),
186                 );
187             }
188         }
189     };
190
191     let module = db.module_for_file(file_id);
192     let def_map = module.def_map(&db);
193
194     let mut defs: Vec<DefWithBodyId> = Vec::new();
195     visit_module(&db, &def_map, module.local_id, &mut |it| defs.push(it));
196     defs.sort_by_key(|def| match def {
197         DefWithBodyId::FunctionId(it) => {
198             let loc = it.lookup(&db);
199             loc.source(&db).value.syntax().text_range().start()
200         }
201         DefWithBodyId::ConstId(it) => {
202             let loc = it.lookup(&db);
203             loc.source(&db).value.syntax().text_range().start()
204         }
205         DefWithBodyId::StaticId(it) => {
206             let loc = it.lookup(&db);
207             loc.source(&db).value.syntax().text_range().start()
208         }
209     });
210     for def in defs {
211         let (_body, source_map) = db.body_with_source_map(def);
212         let infer = db.infer(def);
213         infer_def(infer, source_map);
214     }
215
216     buf.truncate(buf.trim_end().len());
217     buf
218 }
219
220 fn visit_module(
221     db: &TestDB,
222     crate_def_map: &DefMap,
223     module_id: LocalModuleId,
224     cb: &mut dyn FnMut(DefWithBodyId),
225 ) {
226     visit_scope(db, crate_def_map, &crate_def_map[module_id].scope, cb);
227     for impl_id in crate_def_map[module_id].scope.impls() {
228         let impl_data = db.impl_data(impl_id);
229         for &item in impl_data.items.iter() {
230             match item {
231                 AssocItemId::FunctionId(it) => {
232                     let def = it.into();
233                     cb(def);
234                     let body = db.body(def);
235                     visit_body(db, &body, cb);
236                 }
237                 AssocItemId::ConstId(it) => {
238                     let def = it.into();
239                     cb(def);
240                     let body = db.body(def);
241                     visit_body(db, &body, cb);
242                 }
243                 AssocItemId::TypeAliasId(_) => (),
244             }
245         }
246     }
247
248     fn visit_scope(
249         db: &TestDB,
250         crate_def_map: &DefMap,
251         scope: &ItemScope,
252         cb: &mut dyn FnMut(DefWithBodyId),
253     ) {
254         for decl in scope.declarations() {
255             match decl {
256                 ModuleDefId::FunctionId(it) => {
257                     let def = it.into();
258                     cb(def);
259                     let body = db.body(def);
260                     visit_body(db, &body, cb);
261                 }
262                 ModuleDefId::ConstId(it) => {
263                     let def = it.into();
264                     cb(def);
265                     let body = db.body(def);
266                     visit_body(db, &body, cb);
267                 }
268                 ModuleDefId::StaticId(it) => {
269                     let def = it.into();
270                     cb(def);
271                     let body = db.body(def);
272                     visit_body(db, &body, cb);
273                 }
274                 ModuleDefId::TraitId(it) => {
275                     let trait_data = db.trait_data(it);
276                     for &(_, item) in trait_data.items.iter() {
277                         match item {
278                             AssocItemId::FunctionId(it) => cb(it.into()),
279                             AssocItemId::ConstId(it) => cb(it.into()),
280                             AssocItemId::TypeAliasId(_) => (),
281                         }
282                     }
283                 }
284                 ModuleDefId::ModuleId(it) => visit_module(db, crate_def_map, it.local_id, cb),
285                 _ => (),
286             }
287         }
288     }
289
290     fn visit_body(db: &TestDB, body: &Body, cb: &mut dyn FnMut(DefWithBodyId)) {
291         for (_, def_map) in body.blocks(db) {
292             for (mod_id, _) in def_map.modules() {
293                 visit_module(db, &def_map, mod_id, cb);
294             }
295         }
296     }
297 }
298
299 fn ellipsize(mut text: String, max_len: usize) -> String {
300     if text.len() <= max_len {
301         return text;
302     }
303     let ellipsis = "...";
304     let e_len = ellipsis.len();
305     let mut prefix_len = (max_len - e_len) / 2;
306     while !text.is_char_boundary(prefix_len) {
307         prefix_len += 1;
308     }
309     let mut suffix_len = max_len - e_len - prefix_len;
310     while !text.is_char_boundary(text.len() - suffix_len) {
311         suffix_len += 1;
312     }
313     text.replace_range(prefix_len..text.len() - suffix_len, ellipsis);
314     text
315 }
316
317 #[test]
318 fn typing_whitespace_inside_a_function_should_not_invalidate_types() {
319     let (mut db, pos) = TestDB::with_position(
320         "
321         //- /lib.rs
322         fn foo() -> i32 {
323             $01 + 1
324         }
325     ",
326     );
327     {
328         let events = db.log_executed(|| {
329             let module = db.module_for_file(pos.file_id);
330             let crate_def_map = module.def_map(&db);
331             visit_module(&db, &crate_def_map, module.local_id, &mut |def| {
332                 db.infer(def);
333             });
334         });
335         assert!(format!("{:?}", events).contains("infer"))
336     }
337
338     let new_text = "
339         fn foo() -> i32 {
340             1
341             +
342             1
343         }
344     "
345     .to_string();
346
347     db.set_file_text(pos.file_id, Arc::new(new_text));
348
349     {
350         let events = db.log_executed(|| {
351             let module = db.module_for_file(pos.file_id);
352             let crate_def_map = module.def_map(&db);
353             visit_module(&db, &crate_def_map, module.local_id, &mut |def| {
354                 db.infer(def);
355             });
356         });
357         assert!(!format!("{:?}", events).contains("infer"), "{:#?}", events)
358     }
359 }
360
361 fn check_infer(ra_fixture: &str, expect: Expect) {
362     let mut actual = infer(ra_fixture);
363     actual.push('\n');
364     expect.assert_eq(&actual);
365 }
366
367 fn check_infer_with_mismatches(ra_fixture: &str, expect: Expect) {
368     let mut actual = infer_with_mismatches(ra_fixture, true);
369     actual.push('\n');
370     expect.assert_eq(&actual);
371 }
372
373 #[test]
374 fn salsa_bug() {
375     let (mut db, pos) = TestDB::with_position(
376         "
377         //- /lib.rs
378         trait Index {
379             type Output;
380         }
381
382         type Key<S: UnificationStoreBase> = <S as UnificationStoreBase>::Key;
383
384         pub trait UnificationStoreBase: Index<Output = Key<Self>> {
385             type Key;
386
387             fn len(&self) -> usize;
388         }
389
390         pub trait UnificationStoreMut: UnificationStoreBase {
391             fn push(&mut self, value: Self::Key);
392         }
393
394         fn main() {
395             let x = 1;
396             x.push(1);$0
397         }
398     ",
399     );
400
401     let module = db.module_for_file(pos.file_id);
402     let crate_def_map = module.def_map(&db);
403     visit_module(&db, &crate_def_map, module.local_id, &mut |def| {
404         db.infer(def);
405     });
406
407     let new_text = "
408         //- /lib.rs
409         trait Index {
410             type Output;
411         }
412
413         type Key<S: UnificationStoreBase> = <S as UnificationStoreBase>::Key;
414
415         pub trait UnificationStoreBase: Index<Output = Key<Self>> {
416             type Key;
417
418             fn len(&self) -> usize;
419         }
420
421         pub trait UnificationStoreMut: UnificationStoreBase {
422             fn push(&mut self, value: Self::Key);
423         }
424
425         fn main() {
426
427             let x = 1;
428             x.push(1);
429         }
430     "
431     .to_string();
432
433     db.set_file_text(pos.file_id, Arc::new(new_text));
434
435     let module = db.module_for_file(pos.file_id);
436     let crate_def_map = module.def_map(&db);
437     visit_module(&db, &crate_def_map, module.local_id, &mut |def| {
438         db.infer(def);
439     });
440 }