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())
106 panic!("unexpected annotation: {}", expected);
108 had_annotations = true;
111 assert!(had_annotations || allow_none, "no `//^` annotations found");
113 let mut defs: Vec<DefWithBodyId> = Vec::new();
114 for file_id in files {
115 let module = db.module_for_file_opt(file_id);
116 let module = match module {
120 let def_map = module.def_map(&db);
121 visit_module(&db, &def_map, module.local_id, &mut |it| defs.push(it));
123 defs.sort_by_key(|def| match def {
124 DefWithBodyId::FunctionId(it) => {
125 let loc = it.lookup(&db);
126 loc.source(&db).value.syntax().text_range().start()
128 DefWithBodyId::ConstId(it) => {
129 let loc = it.lookup(&db);
130 loc.source(&db).value.syntax().text_range().start()
132 DefWithBodyId::StaticId(it) => {
133 let loc = it.lookup(&db);
134 loc.source(&db).value.syntax().text_range().start()
137 let mut unexpected_type_mismatches = String::new();
139 let (_body, body_source_map) = db.body_with_source_map(def);
140 let inference_result = db.infer(def);
142 for (pat, ty) in inference_result.type_of_pat.iter() {
143 let node = match pat_node(&body_source_map, pat, &db) {
144 Some(value) => value,
147 let range = node.as_ref().original_file_range(&db);
148 if let Some(expected) = types.remove(&range) {
149 let actual = if display_source {
150 ty.display_source_code(&db, def.module(&db)).unwrap()
152 ty.display_test(&db).to_string()
154 assert_eq!(actual, expected);
158 for (expr, ty) in inference_result.type_of_expr.iter() {
159 let node = match expr_node(&body_source_map, expr, &db) {
160 Some(value) => value,
163 let range = node.as_ref().original_file_range(&db);
164 if let Some(expected) = types.remove(&range) {
165 let actual = if display_source {
166 ty.display_source_code(&db, def.module(&db)).unwrap()
168 ty.display_test(&db).to_string()
170 assert_eq!(actual, expected);
172 if let Some(expected) = adjustments.remove(&range) {
173 if let Some(adjustments) = inference_result.expr_adjustments.get(&expr) {
178 .map(|Adjustment { kind, .. }| format!("{:?}", kind))
182 panic!("expected {:?} adjustments, found none", expected);
187 for (pat, mismatch) in inference_result.pat_type_mismatches() {
188 let node = match pat_node(&body_source_map, pat, &db) {
189 Some(value) => value,
192 let range = node.as_ref().original_file_range(&db);
193 let actual = format!(
194 "expected {}, got {}",
195 mismatch.expected.display_test(&db),
196 mismatch.actual.display_test(&db)
198 if let Some(annotation) = mismatches.remove(&range) {
199 assert_eq!(actual, annotation);
201 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 if let Some(annotation) = mismatches.remove(&range) {
219 assert_eq!(actual, annotation);
221 format_to!(unexpected_type_mismatches, "{:?}: {}\n", range.range, actual);
226 let mut buf = String::new();
227 if !unexpected_type_mismatches.is_empty() {
228 format_to!(buf, "Unexpected type mismatches:\n{}", unexpected_type_mismatches);
230 if !mismatches.is_empty() {
231 format_to!(buf, "Unchecked mismatch annotations:\n");
232 for m in mismatches {
233 format_to!(buf, "{:?}: {}\n", m.0.range, m.1);
236 if !types.is_empty() {
237 format_to!(buf, "Unchecked type annotations:\n");
239 format_to!(buf, "{:?}: type {}\n", t.0.range, t.1);
242 if !adjustments.is_empty() {
243 format_to!(buf, "Unchecked adjustments annotations:\n");
244 for t in adjustments {
245 format_to!(buf, "{:?}: type {:?}\n", t.0.range, t.1);
248 assert!(buf.is_empty(), "{}", buf);
252 body_source_map: &BodySourceMap,
255 ) -> Option<InFile<SyntaxNode>> {
256 Some(match body_source_map.expr_syntax(expr) {
258 let root = db.parse_or_expand(sp.file_id).unwrap();
259 sp.map(|ptr| ptr.to_node(&root).syntax().clone())
261 Err(SyntheticSyntax) => return None,
266 body_source_map: &BodySourceMap,
269 ) -> Option<InFile<SyntaxNode>> {
270 Some(match body_source_map.pat_syntax(pat) {
272 let root = db.parse_or_expand(sp.file_id).unwrap();
275 |it| it.to_node(&root).syntax().clone(),
276 |it| it.to_node(&root).syntax().clone(),
280 Err(SyntheticSyntax) => return None,
284 fn infer(ra_fixture: &str) -> String {
285 infer_with_mismatches(ra_fixture, false)
288 fn infer_with_mismatches(content: &str, include_mismatches: bool) -> String {
289 let _tracing = setup_tracing();
290 let (db, file_id) = TestDB::with_single_file(content);
292 let mut buf = String::new();
294 let mut infer_def = |inference_result: Arc<InferenceResult>,
295 body_source_map: Arc<BodySourceMap>| {
296 let mut types: Vec<(InFile<SyntaxNode>, &Ty)> = Vec::new();
297 let mut mismatches: Vec<(InFile<SyntaxNode>, &TypeMismatch)> = Vec::new();
299 for (pat, ty) in inference_result.type_of_pat.iter() {
300 let syntax_ptr = match body_source_map.pat_syntax(pat) {
302 let root = db.parse_or_expand(sp.file_id).unwrap();
305 |it| it.to_node(&root).syntax().clone(),
306 |it| it.to_node(&root).syntax().clone(),
310 Err(SyntheticSyntax) => continue,
312 types.push((syntax_ptr.clone(), ty));
313 if let Some(mismatch) = inference_result.type_mismatch_for_pat(pat) {
314 mismatches.push((syntax_ptr, mismatch));
318 for (expr, ty) in inference_result.type_of_expr.iter() {
319 let node = match body_source_map.expr_syntax(expr) {
321 let root = db.parse_or_expand(sp.file_id).unwrap();
322 sp.map(|ptr| ptr.to_node(&root).syntax().clone())
324 Err(SyntheticSyntax) => continue,
326 types.push((node.clone(), ty));
327 if let Some(mismatch) = inference_result.type_mismatch_for_expr(expr) {
328 mismatches.push((node, mismatch));
332 // sort ranges for consistency
333 types.sort_by_key(|(node, _)| {
334 let range = node.value.text_range();
335 (range.start(), range.end())
337 for (node, ty) in &types {
338 let (range, text) = if let Some(self_param) = ast::SelfParam::cast(node.value.clone()) {
339 (self_param.name().unwrap().syntax().text_range(), "self".to_string())
341 (node.value.text_range(), node.value.text().to_string().replace("\n", " "))
343 let macro_prefix = if node.file_id != file_id.into() { "!" } else { "" };
353 if include_mismatches {
354 mismatches.sort_by_key(|(node, _)| {
355 let range = node.value.text_range();
356 (range.start(), range.end())
358 for (src_ptr, mismatch) in &mismatches {
359 let range = src_ptr.value.text_range();
360 let macro_prefix = if src_ptr.file_id != file_id.into() { "!" } else { "" };
363 "{}{:?}: expected {}, got {}\n",
366 mismatch.expected.display_test(&db),
367 mismatch.actual.display_test(&db),
373 let module = db.module_for_file(file_id);
374 let def_map = module.def_map(&db);
376 let mut defs: Vec<DefWithBodyId> = Vec::new();
377 visit_module(&db, &def_map, module.local_id, &mut |it| defs.push(it));
378 defs.sort_by_key(|def| match def {
379 DefWithBodyId::FunctionId(it) => {
380 let loc = it.lookup(&db);
381 loc.source(&db).value.syntax().text_range().start()
383 DefWithBodyId::ConstId(it) => {
384 let loc = it.lookup(&db);
385 loc.source(&db).value.syntax().text_range().start()
387 DefWithBodyId::StaticId(it) => {
388 let loc = it.lookup(&db);
389 loc.source(&db).value.syntax().text_range().start()
393 let (_body, source_map) = db.body_with_source_map(def);
394 let infer = db.infer(def);
395 infer_def(infer, source_map);
398 buf.truncate(buf.trim_end().len());
404 crate_def_map: &DefMap,
405 module_id: LocalModuleId,
406 cb: &mut dyn FnMut(DefWithBodyId),
408 visit_scope(db, crate_def_map, &crate_def_map[module_id].scope, cb);
409 for impl_id in crate_def_map[module_id].scope.impls() {
410 let impl_data = db.impl_data(impl_id);
411 for &item in impl_data.items.iter() {
413 AssocItemId::FunctionId(it) => {
416 let body = db.body(def);
417 visit_body(db, &body, cb);
419 AssocItemId::ConstId(it) => {
422 let body = db.body(def);
423 visit_body(db, &body, cb);
425 AssocItemId::TypeAliasId(_) => (),
432 crate_def_map: &DefMap,
434 cb: &mut dyn FnMut(DefWithBodyId),
436 for decl in scope.declarations() {
438 ModuleDefId::FunctionId(it) => {
441 let body = db.body(def);
442 visit_body(db, &body, cb);
444 ModuleDefId::ConstId(it) => {
447 let body = db.body(def);
448 visit_body(db, &body, cb);
450 ModuleDefId::StaticId(it) => {
453 let body = db.body(def);
454 visit_body(db, &body, cb);
456 ModuleDefId::TraitId(it) => {
457 let trait_data = db.trait_data(it);
458 for &(_, item) in trait_data.items.iter() {
460 AssocItemId::FunctionId(it) => cb(it.into()),
461 AssocItemId::ConstId(it) => cb(it.into()),
462 AssocItemId::TypeAliasId(_) => (),
466 ModuleDefId::ModuleId(it) => visit_module(db, crate_def_map, it.local_id, cb),
472 fn visit_body(db: &TestDB, body: &Body, cb: &mut dyn FnMut(DefWithBodyId)) {
473 for (_, def_map) in body.blocks(db) {
474 for (mod_id, _) in def_map.modules() {
475 visit_module(db, &def_map, mod_id, cb);
481 fn ellipsize(mut text: String, max_len: usize) -> String {
482 if text.len() <= max_len {
485 let ellipsis = "...";
486 let e_len = ellipsis.len();
487 let mut prefix_len = (max_len - e_len) / 2;
488 while !text.is_char_boundary(prefix_len) {
491 let mut suffix_len = max_len - e_len - prefix_len;
492 while !text.is_char_boundary(text.len() - suffix_len) {
495 text.replace_range(prefix_len..text.len() - suffix_len, ellipsis);
499 fn check_infer(ra_fixture: &str, expect: Expect) {
500 let mut actual = infer(ra_fixture);
502 expect.assert_eq(&actual);
505 fn check_infer_with_mismatches(ra_fixture: &str, expect: Expect) {
506 let mut actual = infer_with_mismatches(ra_fixture, true);
508 expect.assert_eq(&actual);
513 let (mut db, pos) = TestDB::with_position(
520 type Key<S: UnificationStoreBase> = <S as UnificationStoreBase>::Key;
522 pub trait UnificationStoreBase: Index<Output = Key<Self>> {
525 fn len(&self) -> usize;
528 pub trait UnificationStoreMut: UnificationStoreBase {
529 fn push(&mut self, value: Self::Key);
539 let module = db.module_for_file(pos.file_id);
540 let crate_def_map = module.def_map(&db);
541 visit_module(&db, &crate_def_map, module.local_id, &mut |def| {
551 type Key<S: UnificationStoreBase> = <S as UnificationStoreBase>::Key;
553 pub trait UnificationStoreBase: Index<Output = Key<Self>> {
556 fn len(&self) -> usize;
559 pub trait UnificationStoreMut: UnificationStoreBase {
560 fn push(&mut self, value: Self::Key);
571 db.set_file_text(pos.file_id, Arc::new(new_text));
573 let module = db.module_for_file(pos.file_id);
574 let crate_def_map = module.def_map(&db);
575 visit_module(&db, &crate_def_map, module.local_id, &mut |def| {