9 mod display_source_code;
13 use std::{collections::HashMap, env, sync::Arc};
15 use base_db::{fixture::WithFixture, FileRange, SourceDatabaseExt};
16 use expect_test::Expect;
18 body::{Body, BodySourceMap, SyntheticSyntax},
19 db::{DefDatabase, InternDatabase},
20 expr::{ExprId, PatId},
21 item_scope::ItemScope,
24 AssocItemId, DefWithBodyId, HasModule, LocalModuleId, Lookup, ModuleDefId,
26 use hir_expand::{db::AstDatabase, InFile};
27 use once_cell::race::OnceBool;
30 ast::{self, AstNode, HasName},
33 use tracing_subscriber::{layer::SubscriberExt, EnvFilter, Registry};
34 use tracing_tree::HierarchicalLayer;
39 infer::{Adjustment, TypeMismatch},
44 // These tests compare the inference results for all expressions in a file
45 // against snapshots of the expected results using expect. Use
46 // `env UPDATE_EXPECT=1 cargo test -p hir_ty` to update the snapshots.
48 fn setup_tracing() -> Option<tracing::subscriber::DefaultGuard> {
49 static ENABLE: OnceBool = OnceBool::new();
50 if !ENABLE.get_or_init(|| env::var("CHALK_DEBUG").is_ok()) {
54 let filter = EnvFilter::from_env("CHALK_DEBUG");
55 let layer = HierarchicalLayer::default()
56 .with_indent_lines(true)
58 .with_indent_amount(2)
59 .with_writer(std::io::stderr);
60 let subscriber = Registry::default().with(filter).with(layer);
61 Some(tracing::subscriber::set_default(subscriber))
64 fn check_types(ra_fixture: &str) {
65 check_impl(ra_fixture, false, true, false)
68 fn check_types_source_code(ra_fixture: &str) {
69 check_impl(ra_fixture, false, true, true)
72 fn check_no_mismatches(ra_fixture: &str) {
73 check_impl(ra_fixture, true, false, false)
76 fn check(ra_fixture: &str) {
77 check_impl(ra_fixture, false, false, false)
80 fn check_impl(ra_fixture: &str, allow_none: bool, only_types: bool, display_source: bool) {
81 let _tracing = setup_tracing();
82 let (db, files) = TestDB::with_many_files(ra_fixture);
84 let mut had_annotations = false;
85 let mut mismatches = HashMap::new();
86 let mut types = HashMap::new();
87 let mut adjustments = HashMap::<_, Vec<_>>::new();
88 for (file_id, annotations) in db.extract_annotations() {
89 for (range, expected) in annotations {
90 let file_range = FileRange { file_id, range };
92 types.insert(file_range, expected);
93 } else if expected.starts_with("type: ") {
94 types.insert(file_range, expected.trim_start_matches("type: ").to_string());
95 } else if expected.starts_with("expected") {
96 mismatches.insert(file_range, expected);
97 } else if expected.starts_with("adjustments:") {
101 .trim_start_matches("adjustments:")
104 .map(|it| it.trim().to_string())
105 .filter(|it| !it.is_empty())
109 panic!("unexpected annotation: {expected}");
111 had_annotations = true;
114 assert!(had_annotations || allow_none, "no `//^` annotations found");
116 let mut defs: Vec<DefWithBodyId> = Vec::new();
117 for file_id in files {
118 let module = db.module_for_file_opt(file_id);
119 let module = match module {
123 let def_map = module.def_map(&db);
124 visit_module(&db, &def_map, module.local_id, &mut |it| defs.push(it));
126 defs.sort_by_key(|def| match def {
127 DefWithBodyId::FunctionId(it) => {
128 let loc = it.lookup(&db);
129 loc.source(&db).value.syntax().text_range().start()
131 DefWithBodyId::ConstId(it) => {
132 let loc = it.lookup(&db);
133 loc.source(&db).value.syntax().text_range().start()
135 DefWithBodyId::StaticId(it) => {
136 let loc = it.lookup(&db);
137 loc.source(&db).value.syntax().text_range().start()
139 DefWithBodyId::VariantId(it) => {
140 let loc = db.lookup_intern_enum(it.parent);
141 loc.source(&db).value.syntax().text_range().start()
144 let mut unexpected_type_mismatches = String::new();
146 let (_body, body_source_map) = db.body_with_source_map(def);
147 let inference_result = db.infer(def);
149 for (pat, ty) in inference_result.type_of_pat.iter() {
150 let node = match pat_node(&body_source_map, pat, &db) {
151 Some(value) => value,
154 let range = node.as_ref().original_file_range(&db);
155 if let Some(expected) = types.remove(&range) {
156 let actual = if display_source {
157 ty.display_source_code(&db, def.module(&db)).unwrap()
159 ty.display_test(&db).to_string()
161 assert_eq!(actual, expected);
165 for (expr, ty) in inference_result.type_of_expr.iter() {
166 let node = match expr_node(&body_source_map, expr, &db) {
167 Some(value) => value,
170 let range = node.as_ref().original_file_range(&db);
171 if let Some(expected) = types.remove(&range) {
172 let actual = if display_source {
173 ty.display_source_code(&db, def.module(&db)).unwrap()
175 ty.display_test(&db).to_string()
177 assert_eq!(actual, expected);
179 if let Some(expected) = adjustments.remove(&range) {
180 let adjustments = inference_result
183 .map_or_else(Default::default, |it| &**it);
188 .map(|Adjustment { kind, .. }| format!("{kind:?}"))
194 for (pat, mismatch) in inference_result.pat_type_mismatches() {
195 let node = match pat_node(&body_source_map, pat, &db) {
196 Some(value) => value,
199 let range = node.as_ref().original_file_range(&db);
200 let actual = format!(
201 "expected {}, got {}",
202 mismatch.expected.display_test(&db),
203 mismatch.actual.display_test(&db)
205 match mismatches.remove(&range) {
206 Some(annotation) => assert_eq!(actual, annotation),
207 None => format_to!(unexpected_type_mismatches, "{:?}: {}\n", range.range, actual),
210 for (expr, mismatch) in inference_result.expr_type_mismatches() {
211 let node = match body_source_map.expr_syntax(expr) {
213 let root = db.parse_or_expand(sp.file_id).unwrap();
214 sp.map(|ptr| ptr.to_node(&root).syntax().clone())
216 Err(SyntheticSyntax) => continue,
218 let range = node.as_ref().original_file_range(&db);
219 let actual = format!(
220 "expected {}, got {}",
221 mismatch.expected.display_test(&db),
222 mismatch.actual.display_test(&db)
224 match mismatches.remove(&range) {
225 Some(annotation) => assert_eq!(actual, annotation),
226 None => format_to!(unexpected_type_mismatches, "{:?}: {}\n", range.range, actual),
231 let mut buf = String::new();
232 if !unexpected_type_mismatches.is_empty() {
233 format_to!(buf, "Unexpected type mismatches:\n{}", unexpected_type_mismatches);
235 if !mismatches.is_empty() {
236 format_to!(buf, "Unchecked mismatch annotations:\n");
237 for m in mismatches {
238 format_to!(buf, "{:?}: {}\n", m.0.range, m.1);
241 if !types.is_empty() {
242 format_to!(buf, "Unchecked type annotations:\n");
244 format_to!(buf, "{:?}: type {}\n", t.0.range, t.1);
247 if !adjustments.is_empty() {
248 format_to!(buf, "Unchecked adjustments annotations:\n");
249 for t in adjustments {
250 format_to!(buf, "{:?}: type {:?}\n", t.0.range, t.1);
253 assert!(buf.is_empty(), "{}", buf);
257 body_source_map: &BodySourceMap,
260 ) -> Option<InFile<SyntaxNode>> {
261 Some(match body_source_map.expr_syntax(expr) {
263 let root = db.parse_or_expand(sp.file_id).unwrap();
264 sp.map(|ptr| ptr.to_node(&root).syntax().clone())
266 Err(SyntheticSyntax) => return None,
271 body_source_map: &BodySourceMap,
274 ) -> Option<InFile<SyntaxNode>> {
275 Some(match body_source_map.pat_syntax(pat) {
277 let root = db.parse_or_expand(sp.file_id).unwrap();
280 |it| it.to_node(&root).syntax().clone(),
281 |it| it.to_node(&root).syntax().clone(),
285 Err(SyntheticSyntax) => return None,
289 fn infer(ra_fixture: &str) -> String {
290 infer_with_mismatches(ra_fixture, false)
293 fn infer_with_mismatches(content: &str, include_mismatches: bool) -> String {
294 let _tracing = setup_tracing();
295 let (db, file_id) = TestDB::with_single_file(content);
297 let mut buf = String::new();
299 let mut infer_def = |inference_result: Arc<InferenceResult>,
300 body_source_map: Arc<BodySourceMap>| {
301 let mut types: Vec<(InFile<SyntaxNode>, &Ty)> = Vec::new();
302 let mut mismatches: Vec<(InFile<SyntaxNode>, &TypeMismatch)> = Vec::new();
304 for (pat, ty) in inference_result.type_of_pat.iter() {
305 let syntax_ptr = match body_source_map.pat_syntax(pat) {
307 let root = db.parse_or_expand(sp.file_id).unwrap();
310 |it| it.to_node(&root).syntax().clone(),
311 |it| it.to_node(&root).syntax().clone(),
315 Err(SyntheticSyntax) => continue,
317 types.push((syntax_ptr.clone(), ty));
318 if let Some(mismatch) = inference_result.type_mismatch_for_pat(pat) {
319 mismatches.push((syntax_ptr, mismatch));
323 for (expr, ty) in inference_result.type_of_expr.iter() {
324 let node = match body_source_map.expr_syntax(expr) {
326 let root = db.parse_or_expand(sp.file_id).unwrap();
327 sp.map(|ptr| ptr.to_node(&root).syntax().clone())
329 Err(SyntheticSyntax) => continue,
331 types.push((node.clone(), ty));
332 if let Some(mismatch) = inference_result.type_mismatch_for_expr(expr) {
333 mismatches.push((node, mismatch));
337 // sort ranges for consistency
338 types.sort_by_key(|(node, _)| {
339 let range = node.value.text_range();
340 (range.start(), range.end())
342 for (node, ty) in &types {
343 let (range, text) = if let Some(self_param) = ast::SelfParam::cast(node.value.clone()) {
344 (self_param.name().unwrap().syntax().text_range(), "self".to_string())
346 (node.value.text_range(), node.value.text().to_string().replace('\n', " "))
348 let macro_prefix = if node.file_id != file_id.into() { "!" } else { "" };
358 if include_mismatches {
359 mismatches.sort_by_key(|(node, _)| {
360 let range = node.value.text_range();
361 (range.start(), range.end())
363 for (src_ptr, mismatch) in &mismatches {
364 let range = src_ptr.value.text_range();
365 let macro_prefix = if src_ptr.file_id != file_id.into() { "!" } else { "" };
368 "{}{:?}: expected {}, got {}\n",
371 mismatch.expected.display_test(&db),
372 mismatch.actual.display_test(&db),
378 let module = db.module_for_file(file_id);
379 let def_map = module.def_map(&db);
381 let mut defs: Vec<DefWithBodyId> = Vec::new();
382 visit_module(&db, &def_map, module.local_id, &mut |it| defs.push(it));
383 defs.sort_by_key(|def| match def {
384 DefWithBodyId::FunctionId(it) => {
385 let loc = it.lookup(&db);
386 loc.source(&db).value.syntax().text_range().start()
388 DefWithBodyId::ConstId(it) => {
389 let loc = it.lookup(&db);
390 loc.source(&db).value.syntax().text_range().start()
392 DefWithBodyId::StaticId(it) => {
393 let loc = it.lookup(&db);
394 loc.source(&db).value.syntax().text_range().start()
396 DefWithBodyId::VariantId(it) => {
397 let loc = db.lookup_intern_enum(it.parent);
398 loc.source(&db).value.syntax().text_range().start()
402 let (_body, source_map) = db.body_with_source_map(def);
403 let infer = db.infer(def);
404 infer_def(infer, source_map);
407 buf.truncate(buf.trim_end().len());
413 crate_def_map: &DefMap,
414 module_id: LocalModuleId,
415 cb: &mut dyn FnMut(DefWithBodyId),
417 visit_scope(db, crate_def_map, &crate_def_map[module_id].scope, cb);
418 for impl_id in crate_def_map[module_id].scope.impls() {
419 let impl_data = db.impl_data(impl_id);
420 for &item in impl_data.items.iter() {
422 AssocItemId::FunctionId(it) => {
425 let body = db.body(def);
426 visit_body(db, &body, cb);
428 AssocItemId::ConstId(it) => {
431 let body = db.body(def);
432 visit_body(db, &body, cb);
434 AssocItemId::TypeAliasId(_) => (),
441 crate_def_map: &DefMap,
443 cb: &mut dyn FnMut(DefWithBodyId),
445 for decl in scope.declarations() {
447 ModuleDefId::FunctionId(it) => {
450 let body = db.body(def);
451 visit_body(db, &body, cb);
453 ModuleDefId::ConstId(it) => {
456 let body = db.body(def);
457 visit_body(db, &body, cb);
459 ModuleDefId::StaticId(it) => {
462 let body = db.body(def);
463 visit_body(db, &body, cb);
465 ModuleDefId::AdtId(hir_def::AdtId::EnumId(it)) => {
469 .map(|(id, _)| hir_def::EnumVariantId { parent: it, local_id: id })
473 let body = db.body(def);
474 visit_body(db, &body, cb);
477 ModuleDefId::TraitId(it) => {
478 let trait_data = db.trait_data(it);
479 for &(_, item) in trait_data.items.iter() {
481 AssocItemId::FunctionId(it) => cb(it.into()),
482 AssocItemId::ConstId(it) => cb(it.into()),
483 AssocItemId::TypeAliasId(_) => (),
487 ModuleDefId::ModuleId(it) => visit_module(db, crate_def_map, it.local_id, cb),
493 fn visit_body(db: &TestDB, body: &Body, cb: &mut dyn FnMut(DefWithBodyId)) {
494 for (_, def_map) in body.blocks(db) {
495 for (mod_id, _) in def_map.modules() {
496 visit_module(db, &def_map, mod_id, cb);
502 fn ellipsize(mut text: String, max_len: usize) -> String {
503 if text.len() <= max_len {
506 let ellipsis = "...";
507 let e_len = ellipsis.len();
508 let mut prefix_len = (max_len - e_len) / 2;
509 while !text.is_char_boundary(prefix_len) {
512 let mut suffix_len = max_len - e_len - prefix_len;
513 while !text.is_char_boundary(text.len() - suffix_len) {
516 text.replace_range(prefix_len..text.len() - suffix_len, ellipsis);
520 fn check_infer(ra_fixture: &str, expect: Expect) {
521 let mut actual = infer(ra_fixture);
523 expect.assert_eq(&actual);
526 fn check_infer_with_mismatches(ra_fixture: &str, expect: Expect) {
527 let mut actual = infer_with_mismatches(ra_fixture, true);
529 expect.assert_eq(&actual);
534 let (mut db, pos) = TestDB::with_position(
541 type Key<S: UnificationStoreBase> = <S as UnificationStoreBase>::Key;
543 pub trait UnificationStoreBase: Index<Output = Key<Self>> {
546 fn len(&self) -> usize;
549 pub trait UnificationStoreMut: UnificationStoreBase {
550 fn push(&mut self, value: Self::Key);
560 let module = db.module_for_file(pos.file_id);
561 let crate_def_map = module.def_map(&db);
562 visit_module(&db, &crate_def_map, module.local_id, &mut |def| {
572 type Key<S: UnificationStoreBase> = <S as UnificationStoreBase>::Key;
574 pub trait UnificationStoreBase: Index<Output = Key<Self>> {
577 fn len(&self) -> usize;
580 pub trait UnificationStoreMut: UnificationStoreBase {
581 fn push(&mut self, value: Self::Key);
592 db.set_file_text(pos.file_id, Arc::new(new_text));
594 let module = db.module_for_file(pos.file_id);
595 let crate_def_map = module.def_map(&db);
596 visit_module(&db, &crate_def_map, module.local_id, &mut |def| {