9 mod display_source_code;
12 use std::{collections::HashMap, env, sync::Arc};
14 use base_db::{fixture::WithFixture, FileRange, SourceDatabase, SourceDatabaseExt};
15 use expect_test::Expect;
17 body::{Body, BodySourceMap, SyntheticSyntax},
18 child_by_source::ChildBySource,
20 item_scope::ItemScope,
24 AssocItemId, DefWithBodyId, LocalModuleId, Lookup, ModuleDefId,
26 use hir_expand::{db::AstDatabase, InFile};
27 use once_cell::race::OnceBool;
31 ast::{self, AstNode, NameOwner},
34 use tracing_subscriber::{layer::SubscriberExt, EnvFilter, Registry};
35 use tracing_tree::HierarchicalLayer;
38 db::HirDatabase, display::HirDisplay, infer::TypeMismatch, test_db::TestDB, InferenceResult, Ty,
41 // These tests compare the inference results for all expressions in a file
42 // against snapshots of the expected results using expect. Use
43 // `env UPDATE_EXPECT=1 cargo test -p hir_ty` to update the snapshots.
45 fn setup_tracing() -> Option<tracing::subscriber::DefaultGuard> {
46 static ENABLE: OnceBool = OnceBool::new();
47 if !ENABLE.get_or_init(|| env::var("CHALK_DEBUG").is_ok()) {
51 let filter = EnvFilter::from_env("CHALK_DEBUG");
52 let layer = HierarchicalLayer::default()
53 .with_indent_lines(true)
55 .with_indent_amount(2)
56 .with_writer(std::io::stderr);
57 let subscriber = Registry::default().with(filter).with(layer);
58 Some(tracing::subscriber::set_default(subscriber))
61 fn check_types(ra_fixture: &str) {
62 check_types_impl(ra_fixture, false)
65 fn check_types_source_code(ra_fixture: &str) {
66 check_types_impl(ra_fixture, true)
69 fn check_types_impl(ra_fixture: &str, display_source: bool) {
70 let _tracing = setup_tracing();
71 let db = TestDB::with_files(ra_fixture);
72 let mut checked_one = false;
73 for (file_id, annotations) in db.extract_annotations() {
74 for (range, expected) in annotations {
75 let ty = type_at_range(&db, FileRange { file_id, range });
76 let actual = if display_source {
77 let module = db.module_for_file(file_id);
78 ty.display_source_code(&db, module).unwrap()
80 ty.display_test(&db).to_string()
82 assert_eq!(expected, actual);
87 assert!(checked_one, "no `//^` annotations found");
90 fn check_no_mismatches(ra_fixture: &str) {
91 check_mismatches_impl(ra_fixture, true)
95 fn check_mismatches(ra_fixture: &str) {
96 check_mismatches_impl(ra_fixture, false)
99 fn check_mismatches_impl(ra_fixture: &str, allow_none: bool) {
100 let _tracing = setup_tracing();
101 let (db, file_id) = TestDB::with_single_file(ra_fixture);
102 let module = db.module_for_file(file_id);
103 let def_map = module.def_map(&db);
105 let mut defs: Vec<DefWithBodyId> = Vec::new();
106 visit_module(&db, &def_map, module.local_id, &mut |it| defs.push(it));
107 defs.sort_by_key(|def| match def {
108 DefWithBodyId::FunctionId(it) => {
109 let loc = it.lookup(&db);
110 loc.source(&db).value.syntax().text_range().start()
112 DefWithBodyId::ConstId(it) => {
113 let loc = it.lookup(&db);
114 loc.source(&db).value.syntax().text_range().start()
116 DefWithBodyId::StaticId(it) => {
117 let loc = it.lookup(&db);
118 loc.source(&db).value.syntax().text_range().start()
121 let mut mismatches = HashMap::new();
122 let mut push_mismatch = |src_ptr: InFile<SyntaxNode>, mismatch: TypeMismatch| {
123 let range = src_ptr.value.text_range();
124 if src_ptr.file_id.call_node(&db).is_some() {
125 panic!("type mismatch in macro expansion");
127 let file_range = FileRange { file_id: src_ptr.file_id.original_file(&db), range };
128 let actual = format!(
129 "expected {}, got {}",
130 mismatch.expected.display_test(&db),
131 mismatch.actual.display_test(&db)
133 mismatches.insert(file_range, actual);
136 let (_body, body_source_map) = db.body_with_source_map(def);
137 let inference_result = db.infer(def);
138 for (pat, mismatch) in inference_result.pat_type_mismatches() {
139 let syntax_ptr = match body_source_map.pat_syntax(pat) {
141 let root = db.parse_or_expand(sp.file_id).unwrap();
144 |it| it.to_node(&root).syntax().clone(),
145 |it| it.to_node(&root).syntax().clone(),
149 Err(SyntheticSyntax) => continue,
151 push_mismatch(syntax_ptr, mismatch.clone());
153 for (expr, mismatch) in inference_result.expr_type_mismatches() {
154 let node = match body_source_map.expr_syntax(expr) {
156 let root = db.parse_or_expand(sp.file_id).unwrap();
157 sp.map(|ptr| ptr.to_node(&root).syntax().clone())
159 Err(SyntheticSyntax) => continue,
161 push_mismatch(node, mismatch.clone());
164 let mut checked_one = false;
165 for (file_id, annotations) in db.extract_annotations() {
166 for (range, expected) in annotations {
167 let file_range = FileRange { file_id, range };
168 if let Some(mismatch) = mismatches.remove(&file_range) {
169 assert_eq!(mismatch, expected);
171 assert!(false, "Expected mismatch not encountered: {}\n", expected);
176 let mut buf = String::new();
177 for (range, mismatch) in mismatches {
178 format_to!(buf, "{:?}: {}\n", range.range, mismatch,);
180 assert!(buf.is_empty(), "Unexpected type mismatches:\n{}", buf);
182 assert!(checked_one || allow_none, "no `//^` annotations found");
185 fn type_at_range(db: &TestDB, pos: FileRange) -> Ty {
186 let file = db.parse(pos.file_id).ok().unwrap();
187 let expr = algo::find_node_at_range::<ast::Expr>(file.syntax(), pos.range).unwrap();
188 let fn_def = expr.syntax().ancestors().find_map(ast::Fn::cast).unwrap();
189 let module = db.module_for_file(pos.file_id);
190 let func = *module.child_by_source(db)[keys::FUNCTION]
191 .get(&InFile::new(pos.file_id.into(), fn_def))
194 let (_body, source_map) = db.body_with_source_map(func.into());
195 if let Some(expr_id) = source_map.node_expr(InFile::new(pos.file_id.into(), &expr)) {
196 let infer = db.infer(func.into());
197 return infer[expr_id].clone();
199 panic!("Can't find expression")
202 fn infer(ra_fixture: &str) -> String {
203 infer_with_mismatches(ra_fixture, false)
206 fn infer_with_mismatches(content: &str, include_mismatches: bool) -> String {
207 let _tracing = setup_tracing();
208 let (db, file_id) = TestDB::with_single_file(content);
210 let mut buf = String::new();
212 let mut infer_def = |inference_result: Arc<InferenceResult>,
213 body_source_map: Arc<BodySourceMap>| {
214 let mut types: Vec<(InFile<SyntaxNode>, &Ty)> = Vec::new();
215 let mut mismatches: Vec<(InFile<SyntaxNode>, &TypeMismatch)> = Vec::new();
217 for (pat, ty) in inference_result.type_of_pat.iter() {
218 let syntax_ptr = match body_source_map.pat_syntax(pat) {
220 let root = db.parse_or_expand(sp.file_id).unwrap();
223 |it| it.to_node(&root).syntax().clone(),
224 |it| it.to_node(&root).syntax().clone(),
228 Err(SyntheticSyntax) => continue,
230 types.push((syntax_ptr.clone(), ty));
231 if let Some(mismatch) = inference_result.type_mismatch_for_pat(pat) {
232 mismatches.push((syntax_ptr, mismatch));
236 for (expr, ty) in inference_result.type_of_expr.iter() {
237 let node = match body_source_map.expr_syntax(expr) {
239 let root = db.parse_or_expand(sp.file_id).unwrap();
240 sp.map(|ptr| ptr.to_node(&root).syntax().clone())
242 Err(SyntheticSyntax) => continue,
244 types.push((node.clone(), ty));
245 if let Some(mismatch) = inference_result.type_mismatch_for_expr(expr) {
246 mismatches.push((node, mismatch));
250 // sort ranges for consistency
251 types.sort_by_key(|(node, _)| {
252 let range = node.value.text_range();
253 (range.start(), range.end())
255 for (node, ty) in &types {
256 let (range, text) = if let Some(self_param) = ast::SelfParam::cast(node.value.clone()) {
257 (self_param.name().unwrap().syntax().text_range(), "self".to_string())
259 (node.value.text_range(), node.value.text().to_string().replace("\n", " "))
261 let macro_prefix = if node.file_id != file_id.into() { "!" } else { "" };
271 if include_mismatches {
272 mismatches.sort_by_key(|(node, _)| {
273 let range = node.value.text_range();
274 (range.start(), range.end())
276 for (src_ptr, mismatch) in &mismatches {
277 let range = src_ptr.value.text_range();
278 let macro_prefix = if src_ptr.file_id != file_id.into() { "!" } else { "" };
281 "{}{:?}: expected {}, got {}\n",
284 mismatch.expected.display_test(&db),
285 mismatch.actual.display_test(&db),
291 let module = db.module_for_file(file_id);
292 let def_map = module.def_map(&db);
294 let mut defs: Vec<DefWithBodyId> = Vec::new();
295 visit_module(&db, &def_map, module.local_id, &mut |it| defs.push(it));
296 defs.sort_by_key(|def| match def {
297 DefWithBodyId::FunctionId(it) => {
298 let loc = it.lookup(&db);
299 loc.source(&db).value.syntax().text_range().start()
301 DefWithBodyId::ConstId(it) => {
302 let loc = it.lookup(&db);
303 loc.source(&db).value.syntax().text_range().start()
305 DefWithBodyId::StaticId(it) => {
306 let loc = it.lookup(&db);
307 loc.source(&db).value.syntax().text_range().start()
311 let (_body, source_map) = db.body_with_source_map(def);
312 let infer = db.infer(def);
313 infer_def(infer, source_map);
316 buf.truncate(buf.trim_end().len());
322 crate_def_map: &DefMap,
323 module_id: LocalModuleId,
324 cb: &mut dyn FnMut(DefWithBodyId),
326 visit_scope(db, crate_def_map, &crate_def_map[module_id].scope, cb);
327 for impl_id in crate_def_map[module_id].scope.impls() {
328 let impl_data = db.impl_data(impl_id);
329 for &item in impl_data.items.iter() {
331 AssocItemId::FunctionId(it) => {
334 let body = db.body(def);
335 visit_body(db, &body, cb);
337 AssocItemId::ConstId(it) => {
340 let body = db.body(def);
341 visit_body(db, &body, cb);
343 AssocItemId::TypeAliasId(_) => (),
350 crate_def_map: &DefMap,
352 cb: &mut dyn FnMut(DefWithBodyId),
354 for decl in scope.declarations() {
356 ModuleDefId::FunctionId(it) => {
359 let body = db.body(def);
360 visit_body(db, &body, cb);
362 ModuleDefId::ConstId(it) => {
365 let body = db.body(def);
366 visit_body(db, &body, cb);
368 ModuleDefId::StaticId(it) => {
371 let body = db.body(def);
372 visit_body(db, &body, cb);
374 ModuleDefId::TraitId(it) => {
375 let trait_data = db.trait_data(it);
376 for &(_, item) in trait_data.items.iter() {
378 AssocItemId::FunctionId(it) => cb(it.into()),
379 AssocItemId::ConstId(it) => cb(it.into()),
380 AssocItemId::TypeAliasId(_) => (),
384 ModuleDefId::ModuleId(it) => visit_module(db, crate_def_map, it.local_id, cb),
390 fn visit_body(db: &TestDB, body: &Body, cb: &mut dyn FnMut(DefWithBodyId)) {
391 for (_, def_map) in body.blocks(db) {
392 for (mod_id, _) in def_map.modules() {
393 visit_module(db, &def_map, mod_id, cb);
399 fn ellipsize(mut text: String, max_len: usize) -> String {
400 if text.len() <= max_len {
403 let ellipsis = "...";
404 let e_len = ellipsis.len();
405 let mut prefix_len = (max_len - e_len) / 2;
406 while !text.is_char_boundary(prefix_len) {
409 let mut suffix_len = max_len - e_len - prefix_len;
410 while !text.is_char_boundary(text.len() - suffix_len) {
413 text.replace_range(prefix_len..text.len() - suffix_len, ellipsis);
417 fn check_infer(ra_fixture: &str, expect: Expect) {
418 let mut actual = infer(ra_fixture);
420 expect.assert_eq(&actual);
423 fn check_infer_with_mismatches(ra_fixture: &str, expect: Expect) {
424 let mut actual = infer_with_mismatches(ra_fixture, true);
426 expect.assert_eq(&actual);
431 let (mut db, pos) = TestDB::with_position(
438 type Key<S: UnificationStoreBase> = <S as UnificationStoreBase>::Key;
440 pub trait UnificationStoreBase: Index<Output = Key<Self>> {
443 fn len(&self) -> usize;
446 pub trait UnificationStoreMut: UnificationStoreBase {
447 fn push(&mut self, value: Self::Key);
457 let module = db.module_for_file(pos.file_id);
458 let crate_def_map = module.def_map(&db);
459 visit_module(&db, &crate_def_map, module.local_id, &mut |def| {
469 type Key<S: UnificationStoreBase> = <S as UnificationStoreBase>::Key;
471 pub trait UnificationStoreBase: Index<Output = Key<Self>> {
474 fn len(&self) -> usize;
477 pub trait UnificationStoreMut: UnificationStoreBase {
478 fn push(&mut self, value: Self::Key);
489 db.set_file_text(pos.file_id, Arc::new(new_text));
491 let module = db.module_for_file(pos.file_id);
492 let crate_def_map = module.def_map(&db);
493 visit_module(&db, &crate_def_map, module.local_id, &mut |def| {