aboutsummaryrefslogtreecommitdiff
path: root/crates/hir_def/src
diff options
context:
space:
mode:
Diffstat (limited to 'crates/hir_def/src')
-rw-r--r--crates/hir_def/src/attr.rs6
-rw-r--r--crates/hir_def/src/body/lower.rs8
-rw-r--r--crates/hir_def/src/body/scope.rs2
-rw-r--r--crates/hir_def/src/body/tests.rs149
-rw-r--r--crates/hir_def/src/body/tests/block.rs10
-rw-r--r--crates/hir_def/src/generics.rs14
-rw-r--r--crates/hir_def/src/item_scope.rs2
-rw-r--r--crates/hir_def/src/item_tree/lower.rs8
-rw-r--r--crates/hir_def/src/item_tree/pretty.rs2
-rw-r--r--crates/hir_def/src/lib.rs70
-rw-r--r--crates/hir_def/src/nameres/collector.rs49
-rw-r--r--crates/hir_def/src/nameres/path_resolution.rs12
-rw-r--r--crates/hir_def/src/nameres/tests.rs1
-rw-r--r--crates/hir_def/src/nameres/tests/diagnostics.rs229
-rw-r--r--crates/hir_def/src/path/lower.rs4
-rw-r--r--crates/hir_def/src/resolver.rs10
-rw-r--r--crates/hir_def/src/test_db.rs152
-rw-r--r--crates/hir_def/src/type_ref.rs16
18 files changed, 127 insertions, 617 deletions
diff --git a/crates/hir_def/src/attr.rs b/crates/hir_def/src/attr.rs
index d9f9fadc1..d07adb084 100644
--- a/crates/hir_def/src/attr.rs
+++ b/crates/hir_def/src/attr.rs
@@ -583,13 +583,13 @@ impl AttrSourceMap {
583 .get(id.ast_index as usize) 583 .get(id.ast_index as usize)
584 .unwrap_or_else(|| panic!("cannot find doc comment at index {:?}", id)) 584 .unwrap_or_else(|| panic!("cannot find doc comment at index {:?}", id))
585 .clone() 585 .clone()
586 .map(|attr| Either::Right(attr)) 586 .map(Either::Right)
587 } else { 587 } else {
588 self.attrs 588 self.attrs
589 .get(id.ast_index as usize) 589 .get(id.ast_index as usize)
590 .unwrap_or_else(|| panic!("cannot find `Attr` at index {:?}", id)) 590 .unwrap_or_else(|| panic!("cannot find `Attr` at index {:?}", id))
591 .clone() 591 .clone()
592 .map(|attr| Either::Left(attr)) 592 .map(Either::Left)
593 } 593 }
594 } 594 }
595} 595}
@@ -606,7 +606,7 @@ pub struct DocsRangeMap {
606impl DocsRangeMap { 606impl DocsRangeMap {
607 pub fn map(&self, range: TextRange) -> Option<InFile<TextRange>> { 607 pub fn map(&self, range: TextRange) -> Option<InFile<TextRange>> {
608 let found = self.mapping.binary_search_by(|(probe, ..)| probe.ordering(range)).ok()?; 608 let found = self.mapping.binary_search_by(|(probe, ..)| probe.ordering(range)).ok()?;
609 let (line_docs_range, idx, original_line_src_range) = self.mapping[found].clone(); 609 let (line_docs_range, idx, original_line_src_range) = self.mapping[found];
610 if !line_docs_range.contains_range(range) { 610 if !line_docs_range.contains_range(range) {
611 return None; 611 return None;
612 } 612 }
diff --git a/crates/hir_def/src/body/lower.rs b/crates/hir_def/src/body/lower.rs
index da1fdac33..bed4c4994 100644
--- a/crates/hir_def/src/body/lower.rs
+++ b/crates/hir_def/src/body/lower.rs
@@ -1000,18 +1000,18 @@ impl From<ast::LiteralKind> for Literal {
1000 // FIXME: these should have actual values filled in, but unsure on perf impact 1000 // FIXME: these should have actual values filled in, but unsure on perf impact
1001 LiteralKind::IntNumber(lit) => { 1001 LiteralKind::IntNumber(lit) => {
1002 if let builtin @ Some(_) = lit.suffix().and_then(BuiltinFloat::from_suffix) { 1002 if let builtin @ Some(_) = lit.suffix().and_then(BuiltinFloat::from_suffix) {
1003 return Literal::Float(Default::default(), builtin); 1003 Literal::Float(Default::default(), builtin)
1004 } else if let builtin @ Some(_) = 1004 } else if let builtin @ Some(_) =
1005 lit.suffix().and_then(|it| BuiltinInt::from_suffix(&it)) 1005 lit.suffix().and_then(|it| BuiltinInt::from_suffix(it))
1006 { 1006 {
1007 Literal::Int(lit.value().unwrap_or(0) as i128, builtin) 1007 Literal::Int(lit.value().unwrap_or(0) as i128, builtin)
1008 } else { 1008 } else {
1009 let builtin = lit.suffix().and_then(|it| BuiltinUint::from_suffix(&it)); 1009 let builtin = lit.suffix().and_then(|it| BuiltinUint::from_suffix(it));
1010 Literal::Uint(lit.value().unwrap_or(0), builtin) 1010 Literal::Uint(lit.value().unwrap_or(0), builtin)
1011 } 1011 }
1012 } 1012 }
1013 LiteralKind::FloatNumber(lit) => { 1013 LiteralKind::FloatNumber(lit) => {
1014 let ty = lit.suffix().and_then(|it| BuiltinFloat::from_suffix(&it)); 1014 let ty = lit.suffix().and_then(|it| BuiltinFloat::from_suffix(it));
1015 Literal::Float(Default::default(), ty) 1015 Literal::Float(Default::default(), ty)
1016 } 1016 }
1017 LiteralKind::ByteString(bs) => { 1017 LiteralKind::ByteString(bs) => {
diff --git a/crates/hir_def/src/body/scope.rs b/crates/hir_def/src/body/scope.rs
index 6764de3a7..58a1fc81c 100644
--- a/crates/hir_def/src/body/scope.rs
+++ b/crates/hir_def/src/body/scope.rs
@@ -198,7 +198,7 @@ fn compute_expr_scopes(expr: ExprId, body: &Body, scopes: &mut ExprScopes, scope
198 } 198 }
199 Expr::Lambda { args, body: body_expr, .. } => { 199 Expr::Lambda { args, body: body_expr, .. } => {
200 let scope = scopes.new_scope(scope); 200 let scope = scopes.new_scope(scope);
201 scopes.add_params_bindings(body, scope, &args); 201 scopes.add_params_bindings(body, scope, args);
202 compute_expr_scopes(*body_expr, body, scopes, scope); 202 compute_expr_scopes(*body_expr, body, scopes, scope);
203 } 203 }
204 Expr::Match { expr, arms } => { 204 Expr::Match { expr, arms } => {
diff --git a/crates/hir_def/src/body/tests.rs b/crates/hir_def/src/body/tests.rs
index d4fae05a6..27d837d47 100644
--- a/crates/hir_def/src/body/tests.rs
+++ b/crates/hir_def/src/body/tests.rs
@@ -3,7 +3,7 @@ mod block;
3use base_db::{fixture::WithFixture, SourceDatabase}; 3use base_db::{fixture::WithFixture, SourceDatabase};
4use expect_test::Expect; 4use expect_test::Expect;
5 5
6use crate::{test_db::TestDB, ModuleDefId}; 6use crate::ModuleDefId;
7 7
8use super::*; 8use super::*;
9 9
@@ -28,11 +28,6 @@ fn lower(ra_fixture: &str) -> Arc<Body> {
28 db.body(fn_def.unwrap().into()) 28 db.body(fn_def.unwrap().into())
29} 29}
30 30
31fn check_diagnostics(ra_fixture: &str) {
32 let db: TestDB = TestDB::with_files(ra_fixture);
33 db.check_diagnostics();
34}
35
36fn block_def_map_at(ra_fixture: &str) -> String { 31fn block_def_map_at(ra_fixture: &str) -> String {
37 let (db, position) = crate::test_db::TestDB::with_position(ra_fixture); 32 let (db, position) = crate::test_db::TestDB::with_position(ra_fixture);
38 33
@@ -57,7 +52,7 @@ fn check_at(ra_fixture: &str, expect: Expect) {
57fn your_stack_belongs_to_me() { 52fn your_stack_belongs_to_me() {
58 cov_mark::check!(your_stack_belongs_to_me); 53 cov_mark::check!(your_stack_belongs_to_me);
59 lower( 54 lower(
60 " 55 r#"
61macro_rules! n_nuple { 56macro_rules! n_nuple {
62 ($e:tt) => (); 57 ($e:tt) => ();
63 ($($rest:tt)*) => {{ 58 ($($rest:tt)*) => {{
@@ -65,7 +60,7 @@ macro_rules! n_nuple {
65 }}; 60 }};
66} 61}
67fn main() { n_nuple!(1,2,3); } 62fn main() { n_nuple!(1,2,3); }
68", 63"#,
69 ); 64 );
70} 65}
71 66
@@ -73,7 +68,7 @@ fn main() { n_nuple!(1,2,3); }
73fn macro_resolve() { 68fn macro_resolve() {
74 // Regression test for a path resolution bug introduced with inner item handling. 69 // Regression test for a path resolution bug introduced with inner item handling.
75 lower( 70 lower(
76 r" 71 r#"
77macro_rules! vec { 72macro_rules! vec {
78 () => { () }; 73 () => { () };
79 ($elem:expr; $n:expr) => { () }; 74 ($elem:expr; $n:expr) => { () };
@@ -84,140 +79,6 @@ mod m {
84 let _ = vec![FileSet::default(); self.len()]; 79 let _ = vec![FileSet::default(); self.len()];
85 } 80 }
86} 81}
87 ", 82"#,
88 );
89}
90
91#[test]
92fn cfg_diagnostics() {
93 check_diagnostics(
94 r"
95fn f() {
96 // The three g̶e̶n̶d̶e̶r̶s̶ statements:
97
98 #[cfg(a)] fn f() {} // Item statement
99 //^^^^^^^^^^^^^^^^^^^ InactiveCode
100 #[cfg(a)] {} // Expression statement
101 //^^^^^^^^^^^^ InactiveCode
102 #[cfg(a)] let x = 0; // let statement
103 //^^^^^^^^^^^^^^^^^^^^ InactiveCode
104
105 abc(#[cfg(a)] 0);
106 //^^^^^^^^^^^ InactiveCode
107 let x = Struct {
108 #[cfg(a)] f: 0,
109 //^^^^^^^^^^^^^^ InactiveCode
110 };
111 match () {
112 () => (),
113 #[cfg(a)] () => (),
114 //^^^^^^^^^^^^^^^^^^ InactiveCode
115 }
116
117 #[cfg(a)] 0 // Trailing expression of block
118 //^^^^^^^^^^^ InactiveCode
119}
120 ",
121 );
122}
123
124#[test]
125fn macro_diag_builtin() {
126 check_diagnostics(
127 r#"
128#[rustc_builtin_macro]
129macro_rules! env {}
130
131#[rustc_builtin_macro]
132macro_rules! include {}
133
134#[rustc_builtin_macro]
135macro_rules! compile_error {}
136
137#[rustc_builtin_macro]
138macro_rules! format_args {
139 () => {}
140}
141
142fn f() {
143 // Test a handful of built-in (eager) macros:
144
145 include!(invalid);
146 //^^^^^^^^^^^^^^^^^ could not convert tokens
147 include!("does not exist");
148 //^^^^^^^^^^^^^^^^^^^^^^^^^^ failed to load file `does not exist`
149
150 env!(invalid);
151 //^^^^^^^^^^^^^ could not convert tokens
152
153 env!("OUT_DIR");
154 //^^^^^^^^^^^^^^^ `OUT_DIR` not set, enable "run build scripts" to fix
155
156 compile_error!("compile_error works");
157 //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ compile_error works
158
159 // Lazy:
160
161 format_args!();
162 //^^^^^^^^^^^^^^ no rule matches input tokens
163}
164 "#,
165 );
166}
167
168#[test]
169fn macro_rules_diag() {
170 check_diagnostics(
171 r#"
172macro_rules! m {
173 () => {};
174}
175fn f() {
176 m!();
177
178 m!(hi);
179 //^^^^^^ leftover tokens
180}
181 "#,
182 ); 83 );
183} 84}
184
185#[test]
186fn unresolved_macro_diag() {
187 check_diagnostics(
188 r#"
189fn f() {
190 m!();
191 //^^^^ UnresolvedMacroCall
192}
193 "#,
194 );
195}
196
197#[test]
198fn dollar_crate_in_builtin_macro() {
199 check_diagnostics(
200 r#"
201#[macro_export]
202#[rustc_builtin_macro]
203macro_rules! format_args {}
204
205#[macro_export]
206macro_rules! arg {
207 () => {}
208}
209
210#[macro_export]
211macro_rules! outer {
212 () => {
213 $crate::format_args!( "", $crate::arg!(1) )
214 };
215}
216
217fn f() {
218 outer!();
219 //^^^^^^^^ leftover tokens
220}
221 "#,
222 )
223}
diff --git a/crates/hir_def/src/body/tests/block.rs b/crates/hir_def/src/body/tests/block.rs
index bc3d0f138..15c10d053 100644
--- a/crates/hir_def/src/body/tests/block.rs
+++ b/crates/hir_def/src/body/tests/block.rs
@@ -163,14 +163,14 @@ fn legacy_macro_items() {
163 // correctly. 163 // correctly.
164 check_at( 164 check_at(
165 r#" 165 r#"
166macro_rules! hit { 166macro_rules! mark {
167 () => { 167 () => {
168 struct Hit {} 168 struct Hit {}
169 } 169 }
170} 170}
171 171
172fn f() { 172fn f() {
173 hit!(); 173 mark!();
174 $0 174 $0
175} 175}
176"#, 176"#,
@@ -193,20 +193,20 @@ use core::cov_mark;
193 193
194fn f() { 194fn f() {
195 fn nested() { 195 fn nested() {
196 cov_mark::hit!(Hit); 196 cov_mark::mark!(Hit);
197 $0 197 $0
198 } 198 }
199} 199}
200//- /core.rs crate:core 200//- /core.rs crate:core
201pub mod cov_mark { 201pub mod cov_mark {
202 #[macro_export] 202 #[macro_export]
203 macro_rules! _hit { 203 macro_rules! _mark {
204 ($name:ident) => { 204 ($name:ident) => {
205 struct $name {} 205 struct $name {}
206 } 206 }
207 } 207 }
208 208
209 pub use crate::_hit as hit; 209 pub use crate::_mark as mark;
210} 210}
211"#, 211"#,
212 expect![[r#" 212 expect![[r#"
diff --git a/crates/hir_def/src/generics.rs b/crates/hir_def/src/generics.rs
index 44d22b918..0f04b2bae 100644
--- a/crates/hir_def/src/generics.rs
+++ b/crates/hir_def/src/generics.rs
@@ -92,7 +92,7 @@ pub enum WherePredicateTypeTarget {
92 92
93#[derive(Default)] 93#[derive(Default)]
94pub(crate) struct SourceMap { 94pub(crate) struct SourceMap {
95 pub(crate) type_params: ArenaMap<LocalTypeParamId, Either<ast::Trait, ast::TypeParam>>, 95 pub(crate) type_params: ArenaMap<LocalTypeParamId, Either<ast::TypeParam, ast::Trait>>,
96 lifetime_params: ArenaMap<LocalLifetimeParamId, ast::LifetimeParam>, 96 lifetime_params: ArenaMap<LocalLifetimeParamId, ast::LifetimeParam>,
97 const_params: ArenaMap<LocalConstParamId, ast::ConstParam>, 97 const_params: ArenaMap<LocalConstParamId, ast::ConstParam>,
98} 98}
@@ -199,7 +199,7 @@ impl GenericParams {
199 default: None, 199 default: None,
200 provenance: TypeParamProvenance::TraitSelf, 200 provenance: TypeParamProvenance::TraitSelf,
201 }); 201 });
202 sm.type_params.insert(self_param_id, Either::Left(src.value.clone())); 202 sm.type_params.insert(self_param_id, Either::Right(src.value.clone()));
203 // add super traits as bounds on Self 203 // add super traits as bounds on Self
204 // i.e., trait Foo: Bar is equivalent to trait Foo where Self: Bar 204 // i.e., trait Foo: Bar is equivalent to trait Foo where Self: Bar
205 let self_param = TypeRef::Path(name![Self].into()); 205 let self_param = TypeRef::Path(name![Self].into());
@@ -277,10 +277,10 @@ impl GenericParams {
277 provenance: TypeParamProvenance::TypeParamList, 277 provenance: TypeParamProvenance::TypeParamList,
278 }; 278 };
279 let param_id = self.types.alloc(param); 279 let param_id = self.types.alloc(param);
280 sm.type_params.insert(param_id, Either::Right(type_param.clone())); 280 sm.type_params.insert(param_id, Either::Left(type_param.clone()));
281 281
282 let type_ref = TypeRef::Path(name.into()); 282 let type_ref = TypeRef::Path(name.into());
283 self.fill_bounds(&lower_ctx, &type_param, Either::Left(type_ref)); 283 self.fill_bounds(lower_ctx, &type_param, Either::Left(type_ref));
284 } 284 }
285 for lifetime_param in params.lifetime_params() { 285 for lifetime_param in params.lifetime_params() {
286 let name = 286 let name =
@@ -289,7 +289,7 @@ impl GenericParams {
289 let param_id = self.lifetimes.alloc(param); 289 let param_id = self.lifetimes.alloc(param);
290 sm.lifetime_params.insert(param_id, lifetime_param.clone()); 290 sm.lifetime_params.insert(param_id, lifetime_param.clone());
291 let lifetime_ref = LifetimeRef::new_name(name); 291 let lifetime_ref = LifetimeRef::new_name(name);
292 self.fill_bounds(&lower_ctx, &lifetime_param, Either::Right(lifetime_ref)); 292 self.fill_bounds(lower_ctx, &lifetime_param, Either::Right(lifetime_ref));
293 } 293 }
294 for const_param in params.const_params() { 294 for const_param in params.const_params() {
295 let name = const_param.name().map_or_else(Name::missing, |it| it.as_name()); 295 let name = const_param.name().map_or_else(Name::missing, |it| it.as_name());
@@ -413,7 +413,7 @@ impl GenericParams {
413} 413}
414 414
415impl HasChildSource<LocalTypeParamId> for GenericDefId { 415impl HasChildSource<LocalTypeParamId> for GenericDefId {
416 type Value = Either<ast::Trait, ast::TypeParam>; 416 type Value = Either<ast::TypeParam, ast::Trait>;
417 fn child_source( 417 fn child_source(
418 &self, 418 &self,
419 db: &dyn DefDatabase, 419 db: &dyn DefDatabase,
@@ -449,7 +449,7 @@ impl ChildBySource for GenericDefId {
449 let sm = sm.as_ref(); 449 let sm = sm.as_ref();
450 for (local_id, src) in sm.value.type_params.iter() { 450 for (local_id, src) in sm.value.type_params.iter() {
451 let id = TypeParamId { parent: *self, local_id }; 451 let id = TypeParamId { parent: *self, local_id };
452 if let Either::Right(type_param) = src { 452 if let Either::Left(type_param) = src {
453 res[keys::TYPE_PARAM].insert(sm.with_value(type_param.clone()), id) 453 res[keys::TYPE_PARAM].insert(sm.with_value(type_param.clone()), id)
454 } 454 }
455 } 455 }
diff --git a/crates/hir_def/src/item_scope.rs b/crates/hir_def/src/item_scope.rs
index 0f74f050d..08407ebfa 100644
--- a/crates/hir_def/src/item_scope.rs
+++ b/crates/hir_def/src/item_scope.rs
@@ -59,7 +59,7 @@ pub struct ItemScope {
59pub(crate) static BUILTIN_SCOPE: Lazy<FxHashMap<Name, PerNs>> = Lazy::new(|| { 59pub(crate) static BUILTIN_SCOPE: Lazy<FxHashMap<Name, PerNs>> = Lazy::new(|| {
60 BuiltinType::ALL 60 BuiltinType::ALL
61 .iter() 61 .iter()
62 .map(|(name, ty)| (name.clone(), PerNs::types(ty.clone().into(), Visibility::Public))) 62 .map(|(name, ty)| (name.clone(), PerNs::types((*ty).into(), Visibility::Public)))
63 .collect() 63 .collect()
64}); 64});
65 65
diff --git a/crates/hir_def/src/item_tree/lower.rs b/crates/hir_def/src/item_tree/lower.rs
index cfda7cb32..5b1386406 100644
--- a/crates/hir_def/src/item_tree/lower.rs
+++ b/crates/hir_def/src/item_tree/lower.rs
@@ -674,7 +674,7 @@ impl<'a> Ctx<'a> {
674 default: None, 674 default: None,
675 provenance: TypeParamProvenance::TraitSelf, 675 provenance: TypeParamProvenance::TraitSelf,
676 }); 676 });
677 sm.type_params.insert(self_param_id, Either::Left(trait_def.clone())); 677 sm.type_params.insert(self_param_id, Either::Right(trait_def.clone()));
678 // add super traits as bounds on Self 678 // add super traits as bounds on Self
679 // i.e., trait Foo: Bar is equivalent to trait Foo where Self: Bar 679 // i.e., trait Foo: Bar is equivalent to trait Foo where Self: Bar
680 let self_param = TypeRef::Path(name![Self].into()); 680 let self_param = TypeRef::Path(name![Self].into());
@@ -823,7 +823,7 @@ fn is_intrinsic_fn_unsafe(name: &Name) -> bool {
823 known::type_name, 823 known::type_name,
824 known::variant_count, 824 known::variant_count,
825 ] 825 ]
826 .contains(&name) 826 .contains(name)
827} 827}
828 828
829fn lower_abi(abi: ast::Abi) -> Interned<str> { 829fn lower_abi(abi: ast::Abi) -> Interned<str> {
@@ -855,7 +855,7 @@ impl UseTreeLowering<'_> {
855 // E.g. `use something::{inner}` (prefix is `None`, path is `something`) 855 // E.g. `use something::{inner}` (prefix is `None`, path is `something`)
856 // or `use something::{path::{inner::{innerer}}}` (prefix is `something::path`, path is `inner`) 856 // or `use something::{path::{inner::{innerer}}}` (prefix is `something::path`, path is `inner`)
857 Some(path) => { 857 Some(path) => {
858 match ModPath::from_src(self.db, path, &self.hygiene) { 858 match ModPath::from_src(self.db, path, self.hygiene) {
859 Some(it) => Some(it), 859 Some(it) => Some(it),
860 None => return None, // FIXME: report errors somewhere 860 None => return None, // FIXME: report errors somewhere
861 } 861 }
@@ -874,7 +874,7 @@ impl UseTreeLowering<'_> {
874 } else { 874 } else {
875 let is_glob = tree.star_token().is_some(); 875 let is_glob = tree.star_token().is_some();
876 let path = match tree.path() { 876 let path = match tree.path() {
877 Some(path) => Some(ModPath::from_src(self.db, path, &self.hygiene)?), 877 Some(path) => Some(ModPath::from_src(self.db, path, self.hygiene)?),
878 None => None, 878 None => None,
879 }; 879 };
880 let alias = tree.rename().map(|a| { 880 let alias = tree.rename().map(|a| {
diff --git a/crates/hir_def/src/item_tree/pretty.rs b/crates/hir_def/src/item_tree/pretty.rs
index cc9944a22..b1e1b70d0 100644
--- a/crates/hir_def/src/item_tree/pretty.rs
+++ b/crates/hir_def/src/item_tree/pretty.rs
@@ -426,7 +426,7 @@ impl<'a> Printer<'a> {
426 w!(self, " {{"); 426 w!(self, " {{");
427 self.indented(|this| { 427 self.indented(|this| {
428 for item in &**items { 428 for item in &**items {
429 this.print_mod_item((*item).into()); 429 this.print_mod_item(*item);
430 } 430 }
431 }); 431 });
432 wln!(self, "}}"); 432 wln!(self, "}}");
diff --git a/crates/hir_def/src/lib.rs b/crates/hir_def/src/lib.rs
index 987485acc..bb174aec8 100644
--- a/crates/hir_def/src/lib.rs
+++ b/crates/hir_def/src/lib.rs
@@ -112,6 +112,10 @@ impl ModuleId {
112 self.def_map(db).containing_module(self.local_id) 112 self.def_map(db).containing_module(self.local_id)
113 } 113 }
114 114
115 pub fn containing_block(&self) -> Option<BlockId> {
116 self.block
117 }
118
115 /// Returns `true` if this module represents a block expression. 119 /// Returns `true` if this module represents a block expression.
116 /// 120 ///
117 /// Returns `false` if this module is a submodule *inside* a block expression 121 /// Returns `false` if this module is a submodule *inside* a block expression
@@ -581,6 +585,18 @@ impl HasModule for GenericDefId {
581 } 585 }
582} 586}
583 587
588impl HasModule for TypeAliasId {
589 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
590 self.lookup(db).module(db)
591 }
592}
593
594impl HasModule for TraitId {
595 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
596 self.lookup(db).container
597 }
598}
599
584impl HasModule for StaticLoc { 600impl HasModule for StaticLoc {
585 fn module(&self, _db: &dyn db::DefDatabase) -> ModuleId { 601 fn module(&self, _db: &dyn db::DefDatabase) -> ModuleId {
586 self.container 602 self.container
@@ -731,13 +747,11 @@ fn macro_call_as_call_id(
731 ) 747 )
732 .map(MacroCallId::from) 748 .map(MacroCallId::from)
733 } else { 749 } else {
734 Ok(def 750 Ok(def.as_lazy_macro(
735 .as_lazy_macro( 751 db.upcast(),
736 db.upcast(), 752 krate,
737 krate, 753 MacroCallKind::FnLike { ast_id: call.ast_id, fragment },
738 MacroCallKind::FnLike { ast_id: call.ast_id, fragment }, 754 ))
739 )
740 .into())
741 }; 755 };
742 Ok(res) 756 Ok(res)
743} 757}
@@ -756,17 +770,15 @@ fn derive_macro_as_call_id(
756 .segments() 770 .segments()
757 .last() 771 .last()
758 .ok_or_else(|| UnresolvedMacro { path: item_attr.path.clone() })?; 772 .ok_or_else(|| UnresolvedMacro { path: item_attr.path.clone() })?;
759 let res = def 773 let res = def.as_lazy_macro(
760 .as_lazy_macro( 774 db.upcast(),
761 db.upcast(), 775 krate,
762 krate, 776 MacroCallKind::Derive {
763 MacroCallKind::Derive { 777 ast_id: item_attr.ast_id,
764 ast_id: item_attr.ast_id, 778 derive_name: last_segment.to_string(),
765 derive_name: last_segment.to_string(), 779 derive_attr_index: derive_attr.ast_index,
766 derive_attr_index: derive_attr.ast_index, 780 },
767 }, 781 );
768 )
769 .into();
770 Ok(res) 782 Ok(res)
771} 783}
772 784
@@ -794,17 +806,15 @@ fn attr_macro_as_call_id(
794 // The parentheses are always disposed here. 806 // The parentheses are always disposed here.
795 arg.delimiter = None; 807 arg.delimiter = None;
796 808
797 let res = def 809 let res = def.as_lazy_macro(
798 .as_lazy_macro( 810 db.upcast(),
799 db.upcast(), 811 krate,
800 krate, 812 MacroCallKind::Attr {
801 MacroCallKind::Attr { 813 ast_id: item_attr.ast_id,
802 ast_id: item_attr.ast_id, 814 attr_name: last_segment.to_string(),
803 attr_name: last_segment.to_string(), 815 attr_args: arg,
804 attr_args: arg, 816 invoc_attr_index: macro_attr.id.ast_index,
805 invoc_attr_index: macro_attr.id.ast_index, 817 },
806 }, 818 );
807 )
808 .into();
809 Ok(res) 819 Ok(res)
810} 820}
diff --git a/crates/hir_def/src/nameres/collector.rs b/crates/hir_def/src/nameres/collector.rs
index 93f30f23d..fc2c50fb8 100644
--- a/crates/hir_def/src/nameres/collector.rs
+++ b/crates/hir_def/src/nameres/collector.rs
@@ -500,7 +500,7 @@ impl DefCollector<'_> {
500 let (per_ns, _) = self.def_map.resolve_path( 500 let (per_ns, _) = self.def_map.resolve_path(
501 self.db, 501 self.db,
502 self.def_map.root, 502 self.def_map.root,
503 &path, 503 path,
504 BuiltinShadowMode::Other, 504 BuiltinShadowMode::Other,
505 ); 505 );
506 506
@@ -722,7 +722,7 @@ impl DefCollector<'_> {
722 if import.is_extern_crate { 722 if import.is_extern_crate {
723 let res = self.def_map.resolve_name_in_extern_prelude( 723 let res = self.def_map.resolve_name_in_extern_prelude(
724 self.db, 724 self.db,
725 &import 725 import
726 .path 726 .path
727 .as_ident() 727 .as_ident()
728 .expect("extern crate should have been desugared to one-element path"), 728 .expect("extern crate should have been desugared to one-element path"),
@@ -1351,7 +1351,7 @@ impl ModCollector<'_, '_> {
1351 let imports = Import::from_use( 1351 let imports = Import::from_use(
1352 self.def_collector.db, 1352 self.def_collector.db,
1353 krate, 1353 krate,
1354 &self.item_tree, 1354 self.item_tree,
1355 ItemTreeId::new(self.file_id, import_id), 1355 ItemTreeId::new(self.file_id, import_id),
1356 ); 1356 );
1357 self.def_collector.unresolved_imports.extend(imports.into_iter().map( 1357 self.def_collector.unresolved_imports.extend(imports.into_iter().map(
@@ -1368,7 +1368,7 @@ impl ModCollector<'_, '_> {
1368 import: Import::from_extern_crate( 1368 import: Import::from_extern_crate(
1369 self.def_collector.db, 1369 self.def_collector.db,
1370 krate, 1370 krate,
1371 &self.item_tree, 1371 self.item_tree,
1372 ItemTreeId::new(self.file_id, import_id), 1372 ItemTreeId::new(self.file_id, import_id),
1373 ), 1373 ),
1374 status: PartialResolvedImport::Unresolved, 1374 status: PartialResolvedImport::Unresolved,
@@ -1889,7 +1889,7 @@ impl ModCollector<'_, '_> {
1889 self.def_collector.def_map.with_ancestor_maps( 1889 self.def_collector.def_map.with_ancestor_maps(
1890 self.def_collector.db, 1890 self.def_collector.db,
1891 self.module_id, 1891 self.module_id,
1892 &mut |map, module| map[module].scope.get_legacy_macro(&name), 1892 &mut |map, module| map[module].scope.get_legacy_macro(name),
1893 ) 1893 )
1894 }) 1894 })
1895 }, 1895 },
@@ -1992,8 +1992,8 @@ mod tests {
1992 collector.def_map 1992 collector.def_map
1993 } 1993 }
1994 1994
1995 fn do_resolve(code: &str) -> DefMap { 1995 fn do_resolve(not_ra_fixture: &str) -> DefMap {
1996 let (db, _file_id) = TestDB::with_single_file(&code); 1996 let (db, _file_id) = TestDB::with_single_file(not_ra_fixture);
1997 let krate = db.test_crate(); 1997 let krate = db.test_crate();
1998 1998
1999 let edition = db.crate_graph()[krate].edition; 1999 let edition = db.crate_graph()[krate].edition;
@@ -2005,24 +2005,37 @@ mod tests {
2005 fn test_macro_expand_will_stop_1() { 2005 fn test_macro_expand_will_stop_1() {
2006 do_resolve( 2006 do_resolve(
2007 r#" 2007 r#"
2008 macro_rules! foo { 2008macro_rules! foo {
2009 ($($ty:ty)*) => { foo!($($ty)*); } 2009 ($($ty:ty)*) => { foo!($($ty)*); }
2010 } 2010}
2011 foo!(KABOOM); 2011foo!(KABOOM);
2012 "#, 2012"#,
2013 );
2014 do_resolve(
2015 r#"
2016macro_rules! foo {
2017 ($($ty:ty)*) => { foo!(() $($ty)*); }
2018}
2019foo!(KABOOM);
2020"#,
2013 ); 2021 );
2014 } 2022 }
2015 2023
2016 #[ignore] // this test does succeed, but takes quite a while :/ 2024 #[ignore]
2017 #[test] 2025 #[test]
2018 fn test_macro_expand_will_stop_2() { 2026 fn test_macro_expand_will_stop_2() {
2027 // FIXME: this test does succeed, but takes quite a while: 90 seconds in
2028 // the release mode. That's why the argument is not an ra_fixture --
2029 // otherwise injection highlighting gets stuck.
2030 //
2031 // We need to find a way to fail this faster.
2019 do_resolve( 2032 do_resolve(
2020 r#" 2033 r#"
2021 macro_rules! foo { 2034macro_rules! foo {
2022 ($($ty:ty)*) => { foo!($($ty)* $($ty)*); } 2035 ($($ty:ty)*) => { foo!($($ty)* $($ty)*); }
2023 } 2036}
2024 foo!(KABOOM); 2037foo!(KABOOM);
2025 "#, 2038"#,
2026 ); 2039 );
2027 } 2040 }
2028} 2041}
diff --git a/crates/hir_def/src/nameres/path_resolution.rs b/crates/hir_def/src/nameres/path_resolution.rs
index c984148c3..629bc7952 100644
--- a/crates/hir_def/src/nameres/path_resolution.rs
+++ b/crates/hir_def/src/nameres/path_resolution.rs
@@ -93,7 +93,7 @@ impl DefMap {
93 let mut vis = match visibility { 93 let mut vis = match visibility {
94 RawVisibility::Module(path) => { 94 RawVisibility::Module(path) => {
95 let (result, remaining) = 95 let (result, remaining) =
96 self.resolve_path(db, original_module, &path, BuiltinShadowMode::Module); 96 self.resolve_path(db, original_module, path, BuiltinShadowMode::Module);
97 if remaining.is_some() { 97 if remaining.is_some() {
98 return None; 98 return None;
99 } 99 }
@@ -205,7 +205,7 @@ impl DefMap {
205 None => return ResolvePathResult::empty(ReachedFixedPoint::Yes), 205 None => return ResolvePathResult::empty(ReachedFixedPoint::Yes),
206 }; 206 };
207 log::debug!("resolving {:?} in crate root (+ extern prelude)", segment); 207 log::debug!("resolving {:?} in crate root (+ extern prelude)", segment);
208 self.resolve_name_in_crate_root_or_extern_prelude(db, &segment) 208 self.resolve_name_in_crate_root_or_extern_prelude(db, segment)
209 } 209 }
210 PathKind::Plain => { 210 PathKind::Plain => {
211 let (_, segment) = match segments.next() { 211 let (_, segment) = match segments.next() {
@@ -222,7 +222,7 @@ impl DefMap {
222 if path.segments().len() == 1 { shadow } else { BuiltinShadowMode::Module }; 222 if path.segments().len() == 1 { shadow } else { BuiltinShadowMode::Module };
223 223
224 log::debug!("resolving {:?} in module", segment); 224 log::debug!("resolving {:?} in module", segment);
225 self.resolve_name_in_module(db, original_module, &segment, prefer_module) 225 self.resolve_name_in_module(db, original_module, segment, prefer_module)
226 } 226 }
227 PathKind::Super(lvl) => { 227 PathKind::Super(lvl) => {
228 let mut module = original_module; 228 let mut module = original_module;
@@ -269,7 +269,7 @@ impl DefMap {
269 Some((_, segment)) => segment, 269 Some((_, segment)) => segment,
270 None => return ResolvePathResult::empty(ReachedFixedPoint::Yes), 270 None => return ResolvePathResult::empty(ReachedFixedPoint::Yes),
271 }; 271 };
272 if let Some(def) = self.extern_prelude.get(&segment) { 272 if let Some(def) = self.extern_prelude.get(segment) {
273 log::debug!("absolute path {:?} resolved to crate {:?}", path, def); 273 log::debug!("absolute path {:?} resolved to crate {:?}", path, def);
274 PerNs::types(*def, Visibility::Public) 274 PerNs::types(*def, Visibility::Public)
275 } else { 275 } else {
@@ -319,13 +319,13 @@ impl DefMap {
319 }; 319 };
320 320
321 // Since it is a qualified path here, it should not contains legacy macros 321 // Since it is a qualified path here, it should not contains legacy macros
322 module_data.scope.get(&segment) 322 module_data.scope.get(segment)
323 } 323 }
324 ModuleDefId::AdtId(AdtId::EnumId(e)) => { 324 ModuleDefId::AdtId(AdtId::EnumId(e)) => {
325 // enum variant 325 // enum variant
326 cov_mark::hit!(can_import_enum_variant); 326 cov_mark::hit!(can_import_enum_variant);
327 let enum_data = db.enum_data(e); 327 let enum_data = db.enum_data(e);
328 match enum_data.variant(&segment) { 328 match enum_data.variant(segment) {
329 Some(local_id) => { 329 Some(local_id) => {
330 let variant = EnumVariantId { parent: e, local_id }; 330 let variant = EnumVariantId { parent: e, local_id };
331 match &*enum_data.variants[local_id].variant_data { 331 match &*enum_data.variants[local_id].variant_data {
diff --git a/crates/hir_def/src/nameres/tests.rs b/crates/hir_def/src/nameres/tests.rs
index 58c01354a..cf43f2a96 100644
--- a/crates/hir_def/src/nameres/tests.rs
+++ b/crates/hir_def/src/nameres/tests.rs
@@ -2,7 +2,6 @@ mod globs;
2mod incremental; 2mod incremental;
3mod macros; 3mod macros;
4mod mod_resolution; 4mod mod_resolution;
5mod diagnostics;
6mod primitives; 5mod primitives;
7 6
8use std::sync::Arc; 7use std::sync::Arc;
diff --git a/crates/hir_def/src/nameres/tests/diagnostics.rs b/crates/hir_def/src/nameres/tests/diagnostics.rs
deleted file mode 100644
index ec6670952..000000000
--- a/crates/hir_def/src/nameres/tests/diagnostics.rs
+++ /dev/null
@@ -1,229 +0,0 @@
1use base_db::fixture::WithFixture;
2
3use crate::test_db::TestDB;
4
5fn check_diagnostics(ra_fixture: &str) {
6 let db: TestDB = TestDB::with_files(ra_fixture);
7 db.check_diagnostics();
8}
9
10fn check_no_diagnostics(ra_fixture: &str) {
11 let db: TestDB = TestDB::with_files(ra_fixture);
12 db.check_no_diagnostics();
13}
14
15#[test]
16fn unresolved_import() {
17 check_diagnostics(
18 r"
19 use does_exist;
20 use does_not_exist;
21 //^^^^^^^^^^^^^^^^^^^ UnresolvedImport
22
23 mod does_exist {}
24 ",
25 );
26}
27
28#[test]
29fn unresolved_extern_crate() {
30 check_diagnostics(
31 r"
32 //- /main.rs crate:main deps:core
33 extern crate core;
34 extern crate doesnotexist;
35 //^^^^^^^^^^^^^^^^^^^^^^^^^^ UnresolvedExternCrate
36 //- /lib.rs crate:core
37 ",
38 );
39}
40
41#[test]
42fn extern_crate_self_as() {
43 cov_mark::check!(extern_crate_self_as);
44 check_diagnostics(
45 r"
46 //- /lib.rs
47 extern crate doesnotexist;
48 //^^^^^^^^^^^^^^^^^^^^^^^^^^ UnresolvedExternCrate
49 // Should not error.
50 extern crate self as foo;
51 struct Foo;
52 use foo::Foo as Bar;
53 ",
54 );
55}
56
57#[test]
58fn dedup_unresolved_import_from_unresolved_crate() {
59 check_diagnostics(
60 r"
61 //- /main.rs crate:main
62 mod a {
63 extern crate doesnotexist;
64 //^^^^^^^^^^^^^^^^^^^^^^^^^^ UnresolvedExternCrate
65
66 // Should not error, since we already errored for the missing crate.
67 use doesnotexist::{self, bla, *};
68
69 use crate::doesnotexist;
70 //^^^^^^^^^^^^^^^^^^^^^^^^ UnresolvedImport
71 }
72
73 mod m {
74 use super::doesnotexist;
75 //^^^^^^^^^^^^^^^^^^^^^^^^ UnresolvedImport
76 }
77 ",
78 );
79}
80
81#[test]
82fn unresolved_module() {
83 check_diagnostics(
84 r"
85 //- /lib.rs
86 mod foo;
87 mod bar;
88 //^^^^^^^^ UnresolvedModule
89 mod baz {}
90 //- /foo.rs
91 ",
92 );
93}
94
95#[test]
96fn inactive_item() {
97 // Additional tests in `cfg` crate. This only tests disabled cfgs.
98
99 check_diagnostics(
100 r#"
101 //- /lib.rs
102 #[cfg(no)] pub fn f() {}
103 //^^^^^^^^^^^^^^^^^^^^^^^^ UnconfiguredCode
104
105 #[cfg(no)] #[cfg(no2)] mod m;
106 //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ UnconfiguredCode
107
108 #[cfg(all(not(a), b))] enum E {}
109 //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ UnconfiguredCode
110
111 #[cfg(feature = "std")] use std;
112 //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ UnconfiguredCode
113 "#,
114 );
115}
116
117/// Tests that `cfg` attributes behind `cfg_attr` is handled properly.
118#[test]
119fn inactive_via_cfg_attr() {
120 cov_mark::check!(cfg_attr_active);
121 check_diagnostics(
122 r#"
123 //- /lib.rs
124 #[cfg_attr(not(never), cfg(no))] fn f() {}
125 //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ UnconfiguredCode
126
127 #[cfg_attr(not(never), cfg(not(no)))] fn f() {}
128
129 #[cfg_attr(never, cfg(no))] fn g() {}
130
131 #[cfg_attr(not(never), inline, cfg(no))] fn h() {}
132 //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ UnconfiguredCode
133 "#,
134 );
135}
136
137#[test]
138fn unresolved_legacy_scope_macro() {
139 check_diagnostics(
140 r#"
141 //- /lib.rs
142 macro_rules! m { () => {} }
143
144 m!();
145 m2!();
146 //^^^^^^ UnresolvedMacroCall
147 "#,
148 );
149}
150
151#[test]
152fn unresolved_module_scope_macro() {
153 check_diagnostics(
154 r#"
155 //- /lib.rs
156 mod mac {
157 #[macro_export]
158 macro_rules! m { () => {} }
159 }
160
161 self::m!();
162 self::m2!();
163 //^^^^^^^^^^^^ UnresolvedMacroCall
164 "#,
165 );
166}
167
168#[test]
169fn builtin_macro_fails_expansion() {
170 check_diagnostics(
171 r#"
172 //- /lib.rs
173 #[rustc_builtin_macro]
174 macro_rules! include { () => {} }
175
176 include!("doesntexist");
177 //^^^^^^^^^^^^^^^^^^^^^^^^ failed to load file `doesntexist`
178 "#,
179 );
180}
181
182#[test]
183fn include_macro_should_allow_empty_content() {
184 check_no_diagnostics(
185 r#"
186 //- /lib.rs
187 #[rustc_builtin_macro]
188 macro_rules! include { () => {} }
189
190 include!("bar.rs");
191 //- /bar.rs
192 // empty
193 "#,
194 );
195}
196
197#[test]
198fn good_out_dir_diagnostic() {
199 check_diagnostics(
200 r#"
201 #[rustc_builtin_macro]
202 macro_rules! include { () => {} }
203 #[rustc_builtin_macro]
204 macro_rules! env { () => {} }
205 #[rustc_builtin_macro]
206 macro_rules! concat { () => {} }
207
208 include!(concat!(env!("OUT_DIR"), "/out.rs"));
209 //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `OUT_DIR` not set, enable "run build scripts" to fix
210 "#,
211 );
212}
213
214#[test]
215fn register_attr_and_tool() {
216 cov_mark::check!(register_attr);
217 cov_mark::check!(register_tool);
218 check_no_diagnostics(
219 r#"
220#![register_tool(tool)]
221#![register_attr(attr)]
222
223#[tool::path]
224#[attr]
225struct S;
226 "#,
227 );
228 // NB: we don't currently emit diagnostics here
229}
diff --git a/crates/hir_def/src/path/lower.rs b/crates/hir_def/src/path/lower.rs
index f6220aa92..27345d07c 100644
--- a/crates/hir_def/src/path/lower.rs
+++ b/crates/hir_def/src/path/lower.rs
@@ -208,13 +208,13 @@ fn lower_generic_args_from_fn_path(
208 let params = params?; 208 let params = params?;
209 let mut param_types = Vec::new(); 209 let mut param_types = Vec::new();
210 for param in params.params() { 210 for param in params.params() {
211 let type_ref = TypeRef::from_ast_opt(&ctx, param.ty()); 211 let type_ref = TypeRef::from_ast_opt(ctx, param.ty());
212 param_types.push(type_ref); 212 param_types.push(type_ref);
213 } 213 }
214 let arg = GenericArg::Type(TypeRef::Tuple(param_types)); 214 let arg = GenericArg::Type(TypeRef::Tuple(param_types));
215 args.push(arg); 215 args.push(arg);
216 if let Some(ret_type) = ret_type { 216 if let Some(ret_type) = ret_type {
217 let type_ref = TypeRef::from_ast_opt(&ctx, ret_type.ty()); 217 let type_ref = TypeRef::from_ast_opt(ctx, ret_type.ty());
218 bindings.push(AssociatedTypeBinding { 218 bindings.push(AssociatedTypeBinding {
219 name: name![Output], 219 name: name![Output],
220 type_ref: Some(type_ref), 220 type_ref: Some(type_ref),
diff --git a/crates/hir_def/src/resolver.rs b/crates/hir_def/src/resolver.rs
index fb8a6f260..d4681fa3e 100644
--- a/crates/hir_def/src/resolver.rs
+++ b/crates/hir_def/src/resolver.rs
@@ -133,7 +133,7 @@ impl Resolver {
133 Some(it) => it, 133 Some(it) => it,
134 None => return PerNs::none(), 134 None => return PerNs::none(),
135 }; 135 };
136 let (module_res, segment_index) = item_map.resolve_path(db, module, &path, shadow); 136 let (module_res, segment_index) = item_map.resolve_path(db, module, path, shadow);
137 if segment_index.is_some() { 137 if segment_index.is_some() {
138 return PerNs::none(); 138 return PerNs::none();
139 } 139 }
@@ -150,7 +150,7 @@ impl Resolver {
150 path: &ModPath, 150 path: &ModPath,
151 ) -> Option<TraitId> { 151 ) -> Option<TraitId> {
152 let (item_map, module) = self.module_scope()?; 152 let (item_map, module) = self.module_scope()?;
153 let (module_res, ..) = item_map.resolve_path(db, module, &path, BuiltinShadowMode::Module); 153 let (module_res, ..) = item_map.resolve_path(db, module, path, BuiltinShadowMode::Module);
154 match module_res.take_types()? { 154 match module_res.take_types()? {
155 ModuleDefId::TraitId(it) => Some(it), 155 ModuleDefId::TraitId(it) => Some(it),
156 _ => None, 156 _ => None,
@@ -325,7 +325,7 @@ impl Resolver {
325 path: &ModPath, 325 path: &ModPath,
326 ) -> Option<MacroDefId> { 326 ) -> Option<MacroDefId> {
327 let (item_map, module) = self.module_scope()?; 327 let (item_map, module) = self.module_scope()?;
328 item_map.resolve_path(db, module, &path, BuiltinShadowMode::Other).0.take_macros() 328 item_map.resolve_path(db, module, path, BuiltinShadowMode::Other).0.take_macros()
329 } 329 }
330 330
331 pub fn process_all_names(&self, db: &dyn DefDatabase, f: &mut dyn FnMut(Name, ScopeDef)) { 331 pub fn process_all_names(&self, db: &dyn DefDatabase, f: &mut dyn FnMut(Name, ScopeDef)) {
@@ -561,7 +561,7 @@ impl ModuleItemMap {
561 path: &ModPath, 561 path: &ModPath,
562 ) -> Option<ResolveValueResult> { 562 ) -> Option<ResolveValueResult> {
563 let (module_def, idx) = 563 let (module_def, idx) =
564 self.def_map.resolve_path_locally(db, self.module_id, &path, BuiltinShadowMode::Other); 564 self.def_map.resolve_path_locally(db, self.module_id, path, BuiltinShadowMode::Other);
565 match idx { 565 match idx {
566 None => { 566 None => {
567 let value = to_value_ns(module_def)?; 567 let value = to_value_ns(module_def)?;
@@ -591,7 +591,7 @@ impl ModuleItemMap {
591 path: &ModPath, 591 path: &ModPath,
592 ) -> Option<(TypeNs, Option<usize>)> { 592 ) -> Option<(TypeNs, Option<usize>)> {
593 let (module_def, idx) = 593 let (module_def, idx) =
594 self.def_map.resolve_path_locally(db, self.module_id, &path, BuiltinShadowMode::Other); 594 self.def_map.resolve_path_locally(db, self.module_id, path, BuiltinShadowMode::Other);
595 let res = to_type_ns(module_def)?; 595 let res = to_type_ns(module_def)?;
596 Some((res, idx)) 596 Some((res, idx))
597 } 597 }
diff --git a/crates/hir_def/src/test_db.rs b/crates/hir_def/src/test_db.rs
index b20b066e2..2635b556e 100644
--- a/crates/hir_def/src/test_db.rs
+++ b/crates/hir_def/src/test_db.rs
@@ -6,19 +6,16 @@ use std::{
6}; 6};
7 7
8use base_db::{ 8use base_db::{
9 salsa, CrateId, FileId, FileLoader, FileLoaderDelegate, FilePosition, FileRange, Upcast, 9 salsa, AnchoredPath, CrateId, FileId, FileLoader, FileLoaderDelegate, FilePosition,
10 SourceDatabase, Upcast,
10}; 11};
11use base_db::{AnchoredPath, SourceDatabase};
12use hir_expand::{db::AstDatabase, InFile}; 12use hir_expand::{db::AstDatabase, InFile};
13use rustc_hash::FxHashMap;
14use rustc_hash::FxHashSet; 13use rustc_hash::FxHashSet;
15use syntax::{algo, ast, AstNode, SyntaxNode, SyntaxNodePtr, TextRange, TextSize}; 14use syntax::{algo, ast, AstNode};
16use test_utils::extract_annotations;
17 15
18use crate::{ 16use crate::{
19 body::BodyDiagnostic,
20 db::DefDatabase, 17 db::DefDatabase,
21 nameres::{diagnostics::DefDiagnosticKind, DefMap, ModuleSource}, 18 nameres::{DefMap, ModuleSource},
22 src::HasSource, 19 src::HasSource,
23 LocalModuleId, Lookup, ModuleDefId, ModuleId, 20 LocalModuleId, Lookup, ModuleDefId, ModuleId,
24}; 21};
@@ -245,145 +242,4 @@ impl TestDB {
245 }) 242 })
246 .collect() 243 .collect()
247 } 244 }
248
249 pub(crate) fn extract_annotations(&self) -> FxHashMap<FileId, Vec<(TextRange, String)>> {
250 let mut files = Vec::new();
251 let crate_graph = self.crate_graph();
252 for krate in crate_graph.iter() {
253 let crate_def_map = self.crate_def_map(krate);
254 for (module_id, _) in crate_def_map.modules() {
255 let file_id = crate_def_map[module_id].origin.file_id();
256 files.extend(file_id)
257 }
258 }
259 assert!(!files.is_empty());
260 files
261 .into_iter()
262 .filter_map(|file_id| {
263 let text = self.file_text(file_id);
264 let annotations = extract_annotations(&text);
265 if annotations.is_empty() {
266 return None;
267 }
268 Some((file_id, annotations))
269 })
270 .collect()
271 }
272
273 pub(crate) fn diagnostics(&self, cb: &mut dyn FnMut(FileRange, String)) {
274 let crate_graph = self.crate_graph();
275 for krate in crate_graph.iter() {
276 let crate_def_map = self.crate_def_map(krate);
277
278 for diag in crate_def_map.diagnostics() {
279 let (node, message): (InFile<SyntaxNode>, &str) = match &diag.kind {
280 DefDiagnosticKind::UnresolvedModule { ast, .. } => {
281 let node = ast.to_node(self.upcast());
282 (InFile::new(ast.file_id, node.syntax().clone()), "UnresolvedModule")
283 }
284 DefDiagnosticKind::UnresolvedExternCrate { ast, .. } => {
285 let node = ast.to_node(self.upcast());
286 (InFile::new(ast.file_id, node.syntax().clone()), "UnresolvedExternCrate")
287 }
288 DefDiagnosticKind::UnresolvedImport { id, .. } => {
289 let item_tree = id.item_tree(self.upcast());
290 let import = &item_tree[id.value];
291 let node = InFile::new(id.file_id(), import.ast_id).to_node(self.upcast());
292 (InFile::new(id.file_id(), node.syntax().clone()), "UnresolvedImport")
293 }
294 DefDiagnosticKind::UnconfiguredCode { ast, .. } => {
295 let node = ast.to_node(self.upcast());
296 (InFile::new(ast.file_id, node.syntax().clone()), "UnconfiguredCode")
297 }
298 DefDiagnosticKind::UnresolvedProcMacro { ast, .. } => {
299 (ast.to_node(self.upcast()), "UnresolvedProcMacro")
300 }
301 DefDiagnosticKind::UnresolvedMacroCall { ast, .. } => {
302 let node = ast.to_node(self.upcast());
303 (InFile::new(ast.file_id, node.syntax().clone()), "UnresolvedMacroCall")
304 }
305 DefDiagnosticKind::MacroError { ast, message } => {
306 (ast.to_node(self.upcast()), message.as_str())
307 }
308 DefDiagnosticKind::UnimplementedBuiltinMacro { ast } => {
309 let node = ast.to_node(self.upcast());
310 (
311 InFile::new(ast.file_id, node.syntax().clone()),
312 "UnimplementedBuiltinMacro",
313 )
314 }
315 };
316
317 let frange = node.as_ref().original_file_range(self);
318 cb(frange, message.to_string())
319 }
320
321 for (_module_id, module) in crate_def_map.modules() {
322 for decl in module.scope.declarations() {
323 if let ModuleDefId::FunctionId(it) = decl {
324 let source_map = self.body_with_source_map(it.into()).1;
325 for diag in source_map.diagnostics() {
326 let (ptr, message): (InFile<SyntaxNodePtr>, &str) = match diag {
327 BodyDiagnostic::InactiveCode { node, .. } => {
328 (node.clone().map(|it| it.into()), "InactiveCode")
329 }
330 BodyDiagnostic::MacroError { node, message } => {
331 (node.clone().map(|it| it.into()), message.as_str())
332 }
333 BodyDiagnostic::UnresolvedProcMacro { node } => {
334 (node.clone().map(|it| it.into()), "UnresolvedProcMacro")
335 }
336 BodyDiagnostic::UnresolvedMacroCall { node, .. } => {
337 (node.clone().map(|it| it.into()), "UnresolvedMacroCall")
338 }
339 };
340
341 let root = self.parse_or_expand(ptr.file_id).unwrap();
342 let node = ptr.map(|ptr| ptr.to_node(&root));
343 let frange = node.as_ref().original_file_range(self);
344 cb(frange, message.to_string())
345 }
346 }
347 }
348 }
349 }
350 }
351
352 pub(crate) fn check_diagnostics(&self) {
353 let db: &TestDB = self;
354 let annotations = db.extract_annotations();
355 assert!(!annotations.is_empty());
356
357 let mut actual: FxHashMap<FileId, Vec<(TextRange, String)>> = FxHashMap::default();
358 db.diagnostics(&mut |frange, message| {
359 actual.entry(frange.file_id).or_default().push((frange.range, message));
360 });
361
362 for (file_id, diags) in actual.iter_mut() {
363 diags.sort_by_key(|it| it.0.start());
364 let text = db.file_text(*file_id);
365 // For multiline spans, place them on line start
366 for (range, content) in diags {
367 if text[*range].contains('\n') {
368 *range = TextRange::new(range.start(), range.start() + TextSize::from(1));
369 *content = format!("... {}", content);
370 }
371 }
372 }
373
374 assert_eq!(annotations, actual);
375 }
376
377 pub(crate) fn check_no_diagnostics(&self) {
378 let db: &TestDB = self;
379 let annotations = db.extract_annotations();
380 assert!(annotations.is_empty());
381
382 let mut has_diagnostics = false;
383 db.diagnostics(&mut |_, _| {
384 has_diagnostics = true;
385 });
386
387 assert!(!has_diagnostics);
388 }
389} 245}
diff --git a/crates/hir_def/src/type_ref.rs b/crates/hir_def/src/type_ref.rs
index cbde6b940..ffe499973 100644
--- a/crates/hir_def/src/type_ref.rs
+++ b/crates/hir_def/src/type_ref.rs
@@ -128,7 +128,7 @@ impl TypeRef {
128 /// Converts an `ast::TypeRef` to a `hir::TypeRef`. 128 /// Converts an `ast::TypeRef` to a `hir::TypeRef`.
129 pub fn from_ast(ctx: &LowerCtx, node: ast::Type) -> Self { 129 pub fn from_ast(ctx: &LowerCtx, node: ast::Type) -> Self {
130 match node { 130 match node {
131 ast::Type::ParenType(inner) => TypeRef::from_ast_opt(&ctx, inner.ty()), 131 ast::Type::ParenType(inner) => TypeRef::from_ast_opt(ctx, inner.ty()),
132 ast::Type::TupleType(inner) => { 132 ast::Type::TupleType(inner) => {
133 TypeRef::Tuple(inner.fields().map(|it| TypeRef::from_ast(ctx, it)).collect()) 133 TypeRef::Tuple(inner.fields().map(|it| TypeRef::from_ast(ctx, it)).collect())
134 } 134 }
@@ -142,7 +142,7 @@ impl TypeRef {
142 .unwrap_or(TypeRef::Error) 142 .unwrap_or(TypeRef::Error)
143 } 143 }
144 ast::Type::PtrType(inner) => { 144 ast::Type::PtrType(inner) => {
145 let inner_ty = TypeRef::from_ast_opt(&ctx, inner.ty()); 145 let inner_ty = TypeRef::from_ast_opt(ctx, inner.ty());
146 let mutability = Mutability::from_mutable(inner.mut_token().is_some()); 146 let mutability = Mutability::from_mutable(inner.mut_token().is_some());
147 TypeRef::RawPtr(Box::new(inner_ty), mutability) 147 TypeRef::RawPtr(Box::new(inner_ty), mutability)
148 } 148 }
@@ -156,13 +156,13 @@ impl TypeRef {
156 .map(ConstScalar::usize_from_literal_expr) 156 .map(ConstScalar::usize_from_literal_expr)
157 .unwrap_or(ConstScalar::Unknown); 157 .unwrap_or(ConstScalar::Unknown);
158 158
159 TypeRef::Array(Box::new(TypeRef::from_ast_opt(&ctx, inner.ty())), len) 159 TypeRef::Array(Box::new(TypeRef::from_ast_opt(ctx, inner.ty())), len)
160 } 160 }
161 ast::Type::SliceType(inner) => { 161 ast::Type::SliceType(inner) => {
162 TypeRef::Slice(Box::new(TypeRef::from_ast_opt(&ctx, inner.ty()))) 162 TypeRef::Slice(Box::new(TypeRef::from_ast_opt(ctx, inner.ty())))
163 } 163 }
164 ast::Type::RefType(inner) => { 164 ast::Type::RefType(inner) => {
165 let inner_ty = TypeRef::from_ast_opt(&ctx, inner.ty()); 165 let inner_ty = TypeRef::from_ast_opt(ctx, inner.ty());
166 let lifetime = inner.lifetime().map(|lt| LifetimeRef::new(&lt)); 166 let lifetime = inner.lifetime().map(|lt| LifetimeRef::new(&lt));
167 let mutability = Mutability::from_mutable(inner.mut_token().is_some()); 167 let mutability = Mutability::from_mutable(inner.mut_token().is_some());
168 TypeRef::Reference(Box::new(inner_ty), lifetime, mutability) 168 TypeRef::Reference(Box::new(inner_ty), lifetime, mutability)
@@ -180,7 +180,7 @@ impl TypeRef {
180 is_varargs = param.dotdotdot_token().is_some(); 180 is_varargs = param.dotdotdot_token().is_some();
181 } 181 }
182 182
183 pl.params().map(|p| p.ty()).map(|it| TypeRef::from_ast_opt(&ctx, it)).collect() 183 pl.params().map(|p| p.ty()).map(|it| TypeRef::from_ast_opt(ctx, it)).collect()
184 } else { 184 } else {
185 Vec::new() 185 Vec::new()
186 }; 186 };
@@ -188,7 +188,7 @@ impl TypeRef {
188 TypeRef::Fn(params, is_varargs) 188 TypeRef::Fn(params, is_varargs)
189 } 189 }
190 // for types are close enough for our purposes to the inner type for now... 190 // for types are close enough for our purposes to the inner type for now...
191 ast::Type::ForType(inner) => TypeRef::from_ast_opt(&ctx, inner.ty()), 191 ast::Type::ForType(inner) => TypeRef::from_ast_opt(ctx, inner.ty()),
192 ast::Type::ImplTraitType(inner) => { 192 ast::Type::ImplTraitType(inner) => {
193 TypeRef::ImplTrait(type_bounds_from_ast(ctx, inner.type_bound_list())) 193 TypeRef::ImplTrait(type_bounds_from_ast(ctx, inner.type_bound_list()))
194 } 194 }
@@ -229,7 +229,7 @@ impl TypeRef {
229 TypeRef::RawPtr(type_ref, _) 229 TypeRef::RawPtr(type_ref, _)
230 | TypeRef::Reference(type_ref, ..) 230 | TypeRef::Reference(type_ref, ..)
231 | TypeRef::Array(type_ref, _) 231 | TypeRef::Array(type_ref, _)
232 | TypeRef::Slice(type_ref) => go(&type_ref, f), 232 | TypeRef::Slice(type_ref) => go(type_ref, f),
233 TypeRef::ImplTrait(bounds) | TypeRef::DynTrait(bounds) => { 233 TypeRef::ImplTrait(bounds) | TypeRef::DynTrait(bounds) => {
234 for bound in bounds { 234 for bound in bounds {
235 match bound.as_ref() { 235 match bound.as_ref() {