9 mod display_source_code;
11 use std::{env, sync::Arc};
13 use base_db::{fixture::WithFixture, FileRange, SourceDatabase, SourceDatabaseExt};
14 use expect_test::Expect;
16 body::{Body, BodySourceMap, SyntheticSyntax},
17 child_by_source::ChildBySource,
19 item_scope::ItemScope,
23 AssocItemId, DefWithBodyId, LocalModuleId, Lookup, ModuleDefId,
25 use hir_expand::{db::AstDatabase, InFile};
26 use once_cell::race::OnceBool;
30 ast::{self, AstNode, NameOwner},
33 use tracing_subscriber::{layer::SubscriberExt, EnvFilter, Registry};
34 use tracing_tree::HierarchicalLayer;
37 db::HirDatabase, display::HirDisplay, infer::TypeMismatch, test_db::TestDB, InferenceResult, Ty,
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.
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()) {
50 let filter = EnvFilter::from_env("CHALK_DEBUG");
51 let layer = HierarchicalLayer::default()
52 .with_indent_lines(true)
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))
60 fn check_types(ra_fixture: &str) {
61 check_types_impl(ra_fixture, false)
64 fn check_types_source_code(ra_fixture: &str) {
65 check_types_impl(ra_fixture, true)
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()
79 ty.display_test(&db).to_string()
81 assert_eq!(expected, actual);
85 assert!(checked_one, "no `//^` annotations found");
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))
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();
102 panic!("Can't find expression")
105 fn infer(ra_fixture: &str) -> String {
106 infer_with_mismatches(ra_fixture, false)
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);
113 let mut buf = String::new();
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();
120 for (pat, ty) in inference_result.type_of_pat.iter() {
121 let syntax_ptr = match body_source_map.pat_syntax(pat) {
123 let root = db.parse_or_expand(sp.file_id).unwrap();
126 |it| it.to_node(&root).syntax().clone(),
127 |it| it.to_node(&root).syntax().clone(),
131 Err(SyntheticSyntax) => continue,
133 types.push((syntax_ptr, ty));
136 for (expr, ty) in inference_result.type_of_expr.iter() {
137 let node = match body_source_map.expr_syntax(expr) {
139 let root = db.parse_or_expand(sp.file_id).unwrap();
140 sp.map(|ptr| ptr.to_node(&root).syntax().clone())
142 Err(SyntheticSyntax) => continue,
144 types.push((node.clone(), ty));
145 if let Some(mismatch) = inference_result.type_mismatch_for_expr(expr) {
146 mismatches.push((node, mismatch));
150 // sort ranges for consistency
151 types.sort_by_key(|(node, _)| {
152 let range = node.value.text_range();
153 (range.start(), range.end())
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())
159 (node.value.text_range(), node.value.text().to_string().replace("\n", " "))
161 let macro_prefix = if node.file_id != file_id.into() { "!" } else { "" };
171 if include_mismatches {
172 mismatches.sort_by_key(|(node, _)| {
173 let range = node.value.text_range();
174 (range.start(), range.end())
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 { "" };
181 "{}{:?}: expected {}, got {}\n",
184 mismatch.expected.display_test(&db),
185 mismatch.actual.display_test(&db),
191 let module = db.module_for_file(file_id);
192 let def_map = module.def_map(&db);
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()
201 DefWithBodyId::ConstId(it) => {
202 let loc = it.lookup(&db);
203 loc.source(&db).value.syntax().text_range().start()
205 DefWithBodyId::StaticId(it) => {
206 let loc = it.lookup(&db);
207 loc.source(&db).value.syntax().text_range().start()
211 let (_body, source_map) = db.body_with_source_map(def);
212 let infer = db.infer(def);
213 infer_def(infer, source_map);
216 buf.truncate(buf.trim_end().len());
222 crate_def_map: &DefMap,
223 module_id: LocalModuleId,
224 cb: &mut dyn FnMut(DefWithBodyId),
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() {
231 AssocItemId::FunctionId(it) => {
234 let body = db.body(def);
235 visit_body(db, &body, cb);
237 AssocItemId::ConstId(it) => {
240 let body = db.body(def);
241 visit_body(db, &body, cb);
243 AssocItemId::TypeAliasId(_) => (),
250 crate_def_map: &DefMap,
252 cb: &mut dyn FnMut(DefWithBodyId),
254 for decl in scope.declarations() {
256 ModuleDefId::FunctionId(it) => {
259 let body = db.body(def);
260 visit_body(db, &body, cb);
262 ModuleDefId::ConstId(it) => {
265 let body = db.body(def);
266 visit_body(db, &body, cb);
268 ModuleDefId::StaticId(it) => {
271 let body = db.body(def);
272 visit_body(db, &body, cb);
274 ModuleDefId::TraitId(it) => {
275 let trait_data = db.trait_data(it);
276 for &(_, item) in trait_data.items.iter() {
278 AssocItemId::FunctionId(it) => cb(it.into()),
279 AssocItemId::ConstId(it) => cb(it.into()),
280 AssocItemId::TypeAliasId(_) => (),
284 ModuleDefId::ModuleId(it) => visit_module(db, crate_def_map, it.local_id, cb),
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);
299 fn ellipsize(mut text: String, max_len: usize) -> String {
300 if text.len() <= max_len {
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) {
309 let mut suffix_len = max_len - e_len - prefix_len;
310 while !text.is_char_boundary(text.len() - suffix_len) {
313 text.replace_range(prefix_len..text.len() - suffix_len, ellipsis);
318 fn typing_whitespace_inside_a_function_should_not_invalidate_types() {
319 let (mut db, pos) = TestDB::with_position(
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| {
335 assert!(format!("{:?}", events).contains("infer"))
347 db.set_file_text(pos.file_id, Arc::new(new_text));
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| {
357 assert!(!format!("{:?}", events).contains("infer"), "{:#?}", events)
361 fn check_infer(ra_fixture: &str, expect: Expect) {
362 let mut actual = infer(ra_fixture);
364 expect.assert_eq(&actual);
367 fn check_infer_with_mismatches(ra_fixture: &str, expect: Expect) {
368 let mut actual = infer_with_mismatches(ra_fixture, true);
370 expect.assert_eq(&actual);
375 let (mut db, pos) = TestDB::with_position(
382 type Key<S: UnificationStoreBase> = <S as UnificationStoreBase>::Key;
384 pub trait UnificationStoreBase: Index<Output = Key<Self>> {
387 fn len(&self) -> usize;
390 pub trait UnificationStoreMut: UnificationStoreBase {
391 fn push(&mut self, value: Self::Key);
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| {
413 type Key<S: UnificationStoreBase> = <S as UnificationStoreBase>::Key;
415 pub trait UnificationStoreBase: Index<Output = Key<Self>> {
418 fn len(&self) -> usize;
421 pub trait UnificationStoreMut: UnificationStoreBase {
422 fn push(&mut self, value: Self::Key);
433 db.set_file_text(pos.file_id, Arc::new(new_text));
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| {