9 mod display_source_code;
12 use std::{collections::HashMap, env, sync::Arc};
14 use base_db::{fixture::WithFixture, FileRange, SourceDatabaseExt};
15 use expect_test::Expect;
17 body::{Body, BodySourceMap, SyntheticSyntax},
19 expr::{ExprId, PatId},
20 item_scope::ItemScope,
23 AssocItemId, DefWithBodyId, HasModule, LocalModuleId, Lookup, ModuleDefId,
25 use hir_expand::{db::AstDatabase, InFile};
26 use once_cell::race::OnceBool;
29 ast::{self, AstNode, HasName},
32 use tracing_subscriber::{layer::SubscriberExt, EnvFilter, Registry};
33 use tracing_tree::HierarchicalLayer;
38 infer::{Adjustment, TypeMismatch},
43 // These tests compare the inference results for all expressions in a file
44 // against snapshots of the expected results using expect. Use
45 // `env UPDATE_EXPECT=1 cargo test -p hir_ty` to update the snapshots.
47 fn setup_tracing() -> Option<tracing::subscriber::DefaultGuard> {
48 static ENABLE: OnceBool = OnceBool::new();
49 if !ENABLE.get_or_init(|| env::var("CHALK_DEBUG").is_ok()) {
53 let filter = EnvFilter::from_env("CHALK_DEBUG");
54 let layer = HierarchicalLayer::default()
55 .with_indent_lines(true)
57 .with_indent_amount(2)
58 .with_writer(std::io::stderr);
59 let subscriber = Registry::default().with(filter).with(layer);
60 Some(tracing::subscriber::set_default(subscriber))
63 fn check_types(ra_fixture: &str) {
64 check_impl(ra_fixture, false, true, false)
67 fn check_types_source_code(ra_fixture: &str) {
68 check_impl(ra_fixture, false, true, true)
71 fn check_no_mismatches(ra_fixture: &str) {
72 check_impl(ra_fixture, true, false, false)
75 fn check(ra_fixture: &str) {
76 check_impl(ra_fixture, false, false, false)
79 fn check_impl(ra_fixture: &str, allow_none: bool, only_types: bool, display_source: bool) {
80 let _tracing = setup_tracing();
81 let (db, files) = TestDB::with_many_files(ra_fixture);
83 let mut had_annotations = false;
84 let mut mismatches = HashMap::new();
85 let mut types = HashMap::new();
86 let mut adjustments = HashMap::<_, Vec<_>>::new();
87 for (file_id, annotations) in db.extract_annotations() {
88 for (range, expected) in annotations {
89 let file_range = FileRange { file_id, range };
91 types.insert(file_range, expected);
92 } else if expected.starts_with("type: ") {
93 types.insert(file_range, expected.trim_start_matches("type: ").to_string());
94 } else if expected.starts_with("expected") {
95 mismatches.insert(file_range, expected);
96 } else if expected.starts_with("adjustments: ") {
100 .trim_start_matches("adjustments: ")
102 .map(|it| it.trim().to_string())
103 .filter(|it| !it.is_empty())
107 panic!("unexpected annotation: {}", expected);
109 had_annotations = true;
112 assert!(had_annotations || allow_none, "no `//^` annotations found");
114 let mut defs: Vec<DefWithBodyId> = Vec::new();
115 for file_id in files {
116 let module = db.module_for_file_opt(file_id);
117 let module = match module {
121 let def_map = module.def_map(&db);
122 visit_module(&db, &def_map, module.local_id, &mut |it| defs.push(it));
124 defs.sort_by_key(|def| match def {
125 DefWithBodyId::FunctionId(it) => {
126 let loc = it.lookup(&db);
127 loc.source(&db).value.syntax().text_range().start()
129 DefWithBodyId::ConstId(it) => {
130 let loc = it.lookup(&db);
131 loc.source(&db).value.syntax().text_range().start()
133 DefWithBodyId::StaticId(it) => {
134 let loc = it.lookup(&db);
135 loc.source(&db).value.syntax().text_range().start()
138 let mut unexpected_type_mismatches = String::new();
140 let (_body, body_source_map) = db.body_with_source_map(def);
141 let inference_result = db.infer(def);
143 for (pat, ty) in inference_result.type_of_pat.iter() {
144 let node = match pat_node(&body_source_map, pat, &db) {
145 Some(value) => value,
148 let range = node.as_ref().original_file_range(&db);
149 if let Some(expected) = types.remove(&range) {
150 let actual = if display_source {
151 ty.display_source_code(&db, def.module(&db)).unwrap()
153 ty.display_test(&db).to_string()
155 assert_eq!(actual, expected);
159 for (expr, ty) in inference_result.type_of_expr.iter() {
160 let node = match expr_node(&body_source_map, expr, &db) {
161 Some(value) => value,
164 let range = node.as_ref().original_file_range(&db);
165 if let Some(expected) = types.remove(&range) {
166 let actual = if display_source {
167 ty.display_source_code(&db, def.module(&db)).unwrap()
169 ty.display_test(&db).to_string()
171 assert_eq!(actual, expected);
173 if let Some(expected) = adjustments.remove(&range) {
174 if let Some(adjustments) = inference_result.expr_adjustments.get(&expr) {
179 .map(|Adjustment { kind, .. }| format!("{:?}", kind))
183 panic!("expected {:?} adjustments, found none", expected);
188 for (pat, mismatch) in inference_result.pat_type_mismatches() {
189 let node = match pat_node(&body_source_map, pat, &db) {
190 Some(value) => value,
193 let range = node.as_ref().original_file_range(&db);
194 let actual = format!(
195 "expected {}, got {}",
196 mismatch.expected.display_test(&db),
197 mismatch.actual.display_test(&db)
199 match mismatches.remove(&range) {
200 Some(annotation) => assert_eq!(actual, annotation),
201 None => format_to!(unexpected_type_mismatches, "{:?}: {}\n", range.range, actual),
204 for (expr, mismatch) in inference_result.expr_type_mismatches() {
205 let node = match body_source_map.expr_syntax(expr) {
207 let root = db.parse_or_expand(sp.file_id).unwrap();
208 sp.map(|ptr| ptr.to_node(&root).syntax().clone())
210 Err(SyntheticSyntax) => continue,
212 let range = node.as_ref().original_file_range(&db);
213 let actual = format!(
214 "expected {}, got {}",
215 mismatch.expected.display_test(&db),
216 mismatch.actual.display_test(&db)
218 match mismatches.remove(&range) {
219 Some(annotation) => assert_eq!(actual, annotation),
220 None => format_to!(unexpected_type_mismatches, "{:?}: {}\n", range.range, actual),
225 let mut buf = String::new();
226 if !unexpected_type_mismatches.is_empty() {
227 format_to!(buf, "Unexpected type mismatches:\n{}", unexpected_type_mismatches);
229 if !mismatches.is_empty() {
230 format_to!(buf, "Unchecked mismatch annotations:\n");
231 for m in mismatches {
232 format_to!(buf, "{:?}: {}\n", m.0.range, m.1);
235 if !types.is_empty() {
236 format_to!(buf, "Unchecked type annotations:\n");
238 format_to!(buf, "{:?}: type {}\n", t.0.range, t.1);
241 if !adjustments.is_empty() {
242 format_to!(buf, "Unchecked adjustments annotations:\n");
243 for t in adjustments {
244 format_to!(buf, "{:?}: type {:?}\n", t.0.range, t.1);
247 assert!(buf.is_empty(), "{}", buf);
251 body_source_map: &BodySourceMap,
254 ) -> Option<InFile<SyntaxNode>> {
255 Some(match body_source_map.expr_syntax(expr) {
257 let root = db.parse_or_expand(sp.file_id).unwrap();
258 sp.map(|ptr| ptr.to_node(&root).syntax().clone())
260 Err(SyntheticSyntax) => return None,
265 body_source_map: &BodySourceMap,
268 ) -> Option<InFile<SyntaxNode>> {
269 Some(match body_source_map.pat_syntax(pat) {
271 let root = db.parse_or_expand(sp.file_id).unwrap();
274 |it| it.to_node(&root).syntax().clone(),
275 |it| it.to_node(&root).syntax().clone(),
279 Err(SyntheticSyntax) => return None,
283 fn infer(ra_fixture: &str) -> String {
284 infer_with_mismatches(ra_fixture, false)
287 fn infer_with_mismatches(content: &str, include_mismatches: bool) -> String {
288 let _tracing = setup_tracing();
289 let (db, file_id) = TestDB::with_single_file(content);
291 let mut buf = String::new();
293 let mut infer_def = |inference_result: Arc<InferenceResult>,
294 body_source_map: Arc<BodySourceMap>| {
295 let mut types: Vec<(InFile<SyntaxNode>, &Ty)> = Vec::new();
296 let mut mismatches: Vec<(InFile<SyntaxNode>, &TypeMismatch)> = Vec::new();
298 for (pat, ty) in inference_result.type_of_pat.iter() {
299 let syntax_ptr = match body_source_map.pat_syntax(pat) {
301 let root = db.parse_or_expand(sp.file_id).unwrap();
304 |it| it.to_node(&root).syntax().clone(),
305 |it| it.to_node(&root).syntax().clone(),
309 Err(SyntheticSyntax) => continue,
311 types.push((syntax_ptr.clone(), ty));
312 if let Some(mismatch) = inference_result.type_mismatch_for_pat(pat) {
313 mismatches.push((syntax_ptr, mismatch));
317 for (expr, ty) in inference_result.type_of_expr.iter() {
318 let node = match body_source_map.expr_syntax(expr) {
320 let root = db.parse_or_expand(sp.file_id).unwrap();
321 sp.map(|ptr| ptr.to_node(&root).syntax().clone())
323 Err(SyntheticSyntax) => continue,
325 types.push((node.clone(), ty));
326 if let Some(mismatch) = inference_result.type_mismatch_for_expr(expr) {
327 mismatches.push((node, mismatch));
331 // sort ranges for consistency
332 types.sort_by_key(|(node, _)| {
333 let range = node.value.text_range();
334 (range.start(), range.end())
336 for (node, ty) in &types {
337 let (range, text) = if let Some(self_param) = ast::SelfParam::cast(node.value.clone()) {
338 (self_param.name().unwrap().syntax().text_range(), "self".to_string())
340 (node.value.text_range(), node.value.text().to_string().replace("\n", " "))
342 let macro_prefix = if node.file_id != file_id.into() { "!" } else { "" };
352 if include_mismatches {
353 mismatches.sort_by_key(|(node, _)| {
354 let range = node.value.text_range();
355 (range.start(), range.end())
357 for (src_ptr, mismatch) in &mismatches {
358 let range = src_ptr.value.text_range();
359 let macro_prefix = if src_ptr.file_id != file_id.into() { "!" } else { "" };
362 "{}{:?}: expected {}, got {}\n",
365 mismatch.expected.display_test(&db),
366 mismatch.actual.display_test(&db),
372 let module = db.module_for_file(file_id);
373 let def_map = module.def_map(&db);
375 let mut defs: Vec<DefWithBodyId> = Vec::new();
376 visit_module(&db, &def_map, module.local_id, &mut |it| defs.push(it));
377 defs.sort_by_key(|def| match def {
378 DefWithBodyId::FunctionId(it) => {
379 let loc = it.lookup(&db);
380 loc.source(&db).value.syntax().text_range().start()
382 DefWithBodyId::ConstId(it) => {
383 let loc = it.lookup(&db);
384 loc.source(&db).value.syntax().text_range().start()
386 DefWithBodyId::StaticId(it) => {
387 let loc = it.lookup(&db);
388 loc.source(&db).value.syntax().text_range().start()
392 let (_body, source_map) = db.body_with_source_map(def);
393 let infer = db.infer(def);
394 infer_def(infer, source_map);
397 buf.truncate(buf.trim_end().len());
403 crate_def_map: &DefMap,
404 module_id: LocalModuleId,
405 cb: &mut dyn FnMut(DefWithBodyId),
407 visit_scope(db, crate_def_map, &crate_def_map[module_id].scope, cb);
408 for impl_id in crate_def_map[module_id].scope.impls() {
409 let impl_data = db.impl_data(impl_id);
410 for &item in impl_data.items.iter() {
412 AssocItemId::FunctionId(it) => {
415 let body = db.body(def);
416 visit_body(db, &body, cb);
418 AssocItemId::ConstId(it) => {
421 let body = db.body(def);
422 visit_body(db, &body, cb);
424 AssocItemId::TypeAliasId(_) => (),
431 crate_def_map: &DefMap,
433 cb: &mut dyn FnMut(DefWithBodyId),
435 for decl in scope.declarations() {
437 ModuleDefId::FunctionId(it) => {
440 let body = db.body(def);
441 visit_body(db, &body, cb);
443 ModuleDefId::ConstId(it) => {
446 let body = db.body(def);
447 visit_body(db, &body, cb);
449 ModuleDefId::StaticId(it) => {
452 let body = db.body(def);
453 visit_body(db, &body, cb);
455 ModuleDefId::TraitId(it) => {
456 let trait_data = db.trait_data(it);
457 for &(_, item) in trait_data.items.iter() {
459 AssocItemId::FunctionId(it) => cb(it.into()),
460 AssocItemId::ConstId(it) => cb(it.into()),
461 AssocItemId::TypeAliasId(_) => (),
465 ModuleDefId::ModuleId(it) => visit_module(db, crate_def_map, it.local_id, cb),
471 fn visit_body(db: &TestDB, body: &Body, cb: &mut dyn FnMut(DefWithBodyId)) {
472 for (_, def_map) in body.blocks(db) {
473 for (mod_id, _) in def_map.modules() {
474 visit_module(db, &def_map, mod_id, cb);
480 fn ellipsize(mut text: String, max_len: usize) -> String {
481 if text.len() <= max_len {
484 let ellipsis = "...";
485 let e_len = ellipsis.len();
486 let mut prefix_len = (max_len - e_len) / 2;
487 while !text.is_char_boundary(prefix_len) {
490 let mut suffix_len = max_len - e_len - prefix_len;
491 while !text.is_char_boundary(text.len() - suffix_len) {
494 text.replace_range(prefix_len..text.len() - suffix_len, ellipsis);
498 fn check_infer(ra_fixture: &str, expect: Expect) {
499 let mut actual = infer(ra_fixture);
501 expect.assert_eq(&actual);
504 fn check_infer_with_mismatches(ra_fixture: &str, expect: Expect) {
505 let mut actual = infer_with_mismatches(ra_fixture, true);
507 expect.assert_eq(&actual);
512 let (mut db, pos) = TestDB::with_position(
519 type Key<S: UnificationStoreBase> = <S as UnificationStoreBase>::Key;
521 pub trait UnificationStoreBase: Index<Output = Key<Self>> {
524 fn len(&self) -> usize;
527 pub trait UnificationStoreMut: UnificationStoreBase {
528 fn push(&mut self, value: Self::Key);
538 let module = db.module_for_file(pos.file_id);
539 let crate_def_map = module.def_map(&db);
540 visit_module(&db, &crate_def_map, module.local_id, &mut |def| {
550 type Key<S: UnificationStoreBase> = <S as UnificationStoreBase>::Key;
552 pub trait UnificationStoreBase: Index<Output = Key<Self>> {
555 fn len(&self) -> usize;
558 pub trait UnificationStoreMut: UnificationStoreBase {
559 fn push(&mut self, value: Self::Key);
570 db.set_file_text(pos.file_id, Arc::new(new_text));
572 let module = db.module_for_file(pos.file_id);
573 let crate_def_map = module.def_map(&db);
574 visit_module(&db, &crate_def_map, module.local_id, &mut |def| {