diff options
Diffstat (limited to 'crates/ra_hir/src')
-rw-r--r-- | crates/ra_hir/src/code_model.rs | 37 | ||||
-rw-r--r-- | crates/ra_hir/src/code_model/src.rs | 4 | ||||
-rw-r--r-- | crates/ra_hir/src/db.rs | 9 | ||||
-rw-r--r-- | crates/ra_hir/src/diagnostics.rs | 21 | ||||
-rw-r--r-- | crates/ra_hir/src/from_id.rs | 58 | ||||
-rw-r--r-- | crates/ra_hir/src/from_source.rs | 22 | ||||
-rw-r--r-- | crates/ra_hir/src/lib.rs | 1 | ||||
-rw-r--r-- | crates/ra_hir/src/nameres.rs | 508 | ||||
-rw-r--r-- | crates/ra_hir/src/nameres/collector.rs | 837 | ||||
-rw-r--r-- | crates/ra_hir/src/nameres/per_ns.rs | 80 | ||||
-rw-r--r-- | crates/ra_hir/src/nameres/tests.rs | 21 | ||||
-rw-r--r-- | crates/ra_hir/src/nameres/tests/globs.rs | 4 | ||||
-rw-r--r-- | crates/ra_hir/src/nameres/tests/incremental.rs | 7 | ||||
-rw-r--r-- | crates/ra_hir/src/nameres/tests/macros.rs | 10 | ||||
-rw-r--r-- | crates/ra_hir/src/resolve.rs | 108 | ||||
-rw-r--r-- | crates/ra_hir/src/source_binder.rs | 7 | ||||
-rw-r--r-- | crates/ra_hir/src/ty/tests.rs | 2 |
17 files changed, 183 insertions, 1553 deletions
diff --git a/crates/ra_hir/src/code_model.rs b/crates/ra_hir/src/code_model.rs index 5b78bdfef..f03b59217 100644 --- a/crates/ra_hir/src/code_model.rs +++ b/crates/ra_hir/src/code_model.rs | |||
@@ -9,7 +9,7 @@ use hir_def::{ | |||
9 | adt::VariantData, | 9 | adt::VariantData, |
10 | builtin_type::BuiltinType, | 10 | builtin_type::BuiltinType, |
11 | type_ref::{Mutability, TypeRef}, | 11 | type_ref::{Mutability, TypeRef}, |
12 | CrateModuleId, LocalEnumVariantId, LocalStructFieldId, ModuleId, | 12 | CrateModuleId, LocalEnumVariantId, LocalStructFieldId, ModuleId, UnionId, |
13 | }; | 13 | }; |
14 | use hir_expand::{ | 14 | use hir_expand::{ |
15 | diagnostics::DiagnosticSink, | 15 | diagnostics::DiagnosticSink, |
@@ -28,11 +28,11 @@ use crate::{ | |||
28 | TypeAliasId, | 28 | TypeAliasId, |
29 | }, | 29 | }, |
30 | impl_block::ImplBlock, | 30 | impl_block::ImplBlock, |
31 | nameres::{ImportId, ModuleScope, Namespace}, | 31 | nameres::{ImportId, Namespace}, |
32 | resolve::{Resolver, Scope, TypeNs}, | 32 | resolve::{Resolver, Scope, TypeNs}, |
33 | traits::TraitData, | 33 | traits::TraitData, |
34 | ty::{InferenceResult, TraitRef}, | 34 | ty::{InferenceResult, TraitRef}, |
35 | Either, HasSource, Name, Ty, | 35 | Either, HasSource, Name, ScopeDef, Ty, |
36 | }; | 36 | }; |
37 | 37 | ||
38 | /// hir::Crate describes a single crate. It's the main interface with which | 38 | /// hir::Crate describes a single crate. It's the main interface with which |
@@ -66,7 +66,7 @@ impl Crate { | |||
66 | } | 66 | } |
67 | 67 | ||
68 | pub fn root_module(self, db: &impl DefDatabase) -> Option<Module> { | 68 | pub fn root_module(self, db: &impl DefDatabase) -> Option<Module> { |
69 | let module_id = db.crate_def_map(self).root(); | 69 | let module_id = db.crate_def_map(self.crate_id).root(); |
70 | Some(Module::new(self, module_id)) | 70 | Some(Module::new(self, module_id)) |
71 | } | 71 | } |
72 | 72 | ||
@@ -120,7 +120,7 @@ impl Module { | |||
120 | 120 | ||
121 | /// Name of this module. | 121 | /// Name of this module. |
122 | pub fn name(self, db: &impl DefDatabase) -> Option<Name> { | 122 | pub fn name(self, db: &impl DefDatabase) -> Option<Name> { |
123 | let def_map = db.crate_def_map(self.krate()); | 123 | let def_map = db.crate_def_map(self.id.krate); |
124 | let parent = def_map[self.id.module_id].parent?; | 124 | let parent = def_map[self.id.module_id].parent?; |
125 | def_map[parent].children.iter().find_map(|(name, module_id)| { | 125 | def_map[parent].children.iter().find_map(|(name, module_id)| { |
126 | if *module_id == self.id.module_id { | 126 | if *module_id == self.id.module_id { |
@@ -151,20 +151,20 @@ impl Module { | |||
151 | /// might be missing `krate`. This can happen if a module's file is not included | 151 | /// might be missing `krate`. This can happen if a module's file is not included |
152 | /// in the module tree of any target in `Cargo.toml`. | 152 | /// in the module tree of any target in `Cargo.toml`. |
153 | pub fn crate_root(self, db: &impl DefDatabase) -> Module { | 153 | pub fn crate_root(self, db: &impl DefDatabase) -> Module { |
154 | let def_map = db.crate_def_map(self.krate()); | 154 | let def_map = db.crate_def_map(self.id.krate); |
155 | self.with_module_id(def_map.root()) | 155 | self.with_module_id(def_map.root()) |
156 | } | 156 | } |
157 | 157 | ||
158 | /// Finds a child module with the specified name. | 158 | /// Finds a child module with the specified name. |
159 | pub fn child(self, db: &impl HirDatabase, name: &Name) -> Option<Module> { | 159 | pub fn child(self, db: &impl HirDatabase, name: &Name) -> Option<Module> { |
160 | let def_map = db.crate_def_map(self.krate()); | 160 | let def_map = db.crate_def_map(self.id.krate); |
161 | let child_id = def_map[self.id.module_id].children.get(name)?; | 161 | let child_id = def_map[self.id.module_id].children.get(name)?; |
162 | Some(self.with_module_id(*child_id)) | 162 | Some(self.with_module_id(*child_id)) |
163 | } | 163 | } |
164 | 164 | ||
165 | /// Iterates over all child modules. | 165 | /// Iterates over all child modules. |
166 | pub fn children(self, db: &impl DefDatabase) -> impl Iterator<Item = Module> { | 166 | pub fn children(self, db: &impl DefDatabase) -> impl Iterator<Item = Module> { |
167 | let def_map = db.crate_def_map(self.krate()); | 167 | let def_map = db.crate_def_map(self.id.krate); |
168 | let children = def_map[self.id.module_id] | 168 | let children = def_map[self.id.module_id] |
169 | .children | 169 | .children |
170 | .iter() | 170 | .iter() |
@@ -175,7 +175,7 @@ impl Module { | |||
175 | 175 | ||
176 | /// Finds a parent module. | 176 | /// Finds a parent module. |
177 | pub fn parent(self, db: &impl DefDatabase) -> Option<Module> { | 177 | pub fn parent(self, db: &impl DefDatabase) -> Option<Module> { |
178 | let def_map = db.crate_def_map(self.krate()); | 178 | let def_map = db.crate_def_map(self.id.krate); |
179 | let parent_id = def_map[self.id.module_id].parent?; | 179 | let parent_id = def_map[self.id.module_id].parent?; |
180 | Some(self.with_module_id(parent_id)) | 180 | Some(self.with_module_id(parent_id)) |
181 | } | 181 | } |
@@ -191,12 +191,16 @@ impl Module { | |||
191 | } | 191 | } |
192 | 192 | ||
193 | /// Returns a `ModuleScope`: a set of items, visible in this module. | 193 | /// Returns a `ModuleScope`: a set of items, visible in this module. |
194 | pub fn scope(self, db: &impl HirDatabase) -> ModuleScope { | 194 | pub fn scope(self, db: &impl HirDatabase) -> Vec<(Name, ScopeDef, Option<ImportId>)> { |
195 | db.crate_def_map(self.krate())[self.id.module_id].scope.clone() | 195 | db.crate_def_map(self.id.krate)[self.id.module_id] |
196 | .scope | ||
197 | .entries() | ||
198 | .map(|(name, res)| (name.clone(), res.def.into(), res.import)) | ||
199 | .collect() | ||
196 | } | 200 | } |
197 | 201 | ||
198 | pub fn diagnostics(self, db: &impl HirDatabase, sink: &mut DiagnosticSink) { | 202 | pub fn diagnostics(self, db: &impl HirDatabase, sink: &mut DiagnosticSink) { |
199 | db.crate_def_map(self.krate()).add_diagnostics(db, self.id.module_id, sink); | 203 | db.crate_def_map(self.id.krate).add_diagnostics(db, self.id.module_id, sink); |
200 | for decl in self.declarations(db) { | 204 | for decl in self.declarations(db) { |
201 | match decl { | 205 | match decl { |
202 | crate::ModuleDef::Function(f) => f.diagnostics(db, sink), | 206 | crate::ModuleDef::Function(f) => f.diagnostics(db, sink), |
@@ -220,12 +224,12 @@ impl Module { | |||
220 | } | 224 | } |
221 | 225 | ||
222 | pub(crate) fn resolver(self, db: &impl DefDatabase) -> Resolver { | 226 | pub(crate) fn resolver(self, db: &impl DefDatabase) -> Resolver { |
223 | let def_map = db.crate_def_map(self.krate()); | 227 | let def_map = db.crate_def_map(self.id.krate); |
224 | Resolver::default().push_module_scope(def_map, self.id.module_id) | 228 | Resolver::default().push_module_scope(def_map, self.id.module_id) |
225 | } | 229 | } |
226 | 230 | ||
227 | pub fn declarations(self, db: &impl DefDatabase) -> Vec<ModuleDef> { | 231 | pub fn declarations(self, db: &impl DefDatabase) -> Vec<ModuleDef> { |
228 | let def_map = db.crate_def_map(self.krate()); | 232 | let def_map = db.crate_def_map(self.id.krate); |
229 | def_map[self.id.module_id] | 233 | def_map[self.id.module_id] |
230 | .scope | 234 | .scope |
231 | .entries() | 235 | .entries() |
@@ -233,6 +237,7 @@ impl Module { | |||
233 | .flat_map(|per_ns| { | 237 | .flat_map(|per_ns| { |
234 | per_ns.take_types().into_iter().chain(per_ns.take_values().into_iter()) | 238 | per_ns.take_types().into_iter().chain(per_ns.take_values().into_iter()) |
235 | }) | 239 | }) |
240 | .map(ModuleDef::from) | ||
236 | .collect() | 241 | .collect() |
237 | } | 242 | } |
238 | 243 | ||
@@ -336,12 +341,12 @@ impl Struct { | |||
336 | 341 | ||
337 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | 342 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
338 | pub struct Union { | 343 | pub struct Union { |
339 | pub(crate) id: StructId, | 344 | pub(crate) id: UnionId, |
340 | } | 345 | } |
341 | 346 | ||
342 | impl Union { | 347 | impl Union { |
343 | pub fn name(self, db: &impl DefDatabase) -> Option<Name> { | 348 | pub fn name(self, db: &impl DefDatabase) -> Option<Name> { |
344 | db.struct_data(self.id).name.clone() | 349 | db.union_data(self.id).name.clone() |
345 | } | 350 | } |
346 | 351 | ||
347 | pub fn module(self, db: &impl HirDatabase) -> Module { | 352 | pub fn module(self, db: &impl HirDatabase) -> Module { |
diff --git a/crates/ra_hir/src/code_model/src.rs b/crates/ra_hir/src/code_model/src.rs index bd0c3c226..6d116ee75 100644 --- a/crates/ra_hir/src/code_model/src.rs +++ b/crates/ra_hir/src/code_model/src.rs | |||
@@ -22,7 +22,7 @@ pub trait HasSource { | |||
22 | impl Module { | 22 | impl Module { |
23 | /// Returns a node which defines this module. That is, a file or a `mod foo {}` with items. | 23 | /// Returns a node which defines this module. That is, a file or a `mod foo {}` with items. |
24 | pub fn definition_source(self, db: &(impl DefDatabase + AstDatabase)) -> Source<ModuleSource> { | 24 | pub fn definition_source(self, db: &(impl DefDatabase + AstDatabase)) -> Source<ModuleSource> { |
25 | let def_map = db.crate_def_map(self.krate()); | 25 | let def_map = db.crate_def_map(self.id.krate); |
26 | let decl_id = def_map[self.id.module_id].declaration; | 26 | let decl_id = def_map[self.id.module_id].declaration; |
27 | let file_id = def_map[self.id.module_id].definition; | 27 | let file_id = def_map[self.id.module_id].definition; |
28 | let ast = ModuleSource::new(db, file_id, decl_id); | 28 | let ast = ModuleSource::new(db, file_id, decl_id); |
@@ -36,7 +36,7 @@ impl Module { | |||
36 | self, | 36 | self, |
37 | db: &(impl DefDatabase + AstDatabase), | 37 | db: &(impl DefDatabase + AstDatabase), |
38 | ) -> Option<Source<ast::Module>> { | 38 | ) -> Option<Source<ast::Module>> { |
39 | let def_map = db.crate_def_map(self.krate()); | 39 | let def_map = db.crate_def_map(self.id.krate); |
40 | let decl = def_map[self.id.module_id].declaration?; | 40 | let decl = def_map[self.id.module_id].declaration?; |
41 | let ast = decl.to_node(db); | 41 | let ast = decl.to_node(db); |
42 | Some(Source { file_id: decl.file_id(), ast }) | 42 | Some(Source { file_id: decl.file_id(), ast }) |
diff --git a/crates/ra_hir/src/db.rs b/crates/ra_hir/src/db.rs index 89ca4e39f..f45804c7c 100644 --- a/crates/ra_hir/src/db.rs +++ b/crates/ra_hir/src/db.rs | |||
@@ -11,7 +11,7 @@ use crate::{ | |||
11 | ids, | 11 | ids, |
12 | impl_block::{ImplBlock, ImplSourceMap, ModuleImplBlocks}, | 12 | impl_block::{ImplBlock, ImplSourceMap, ModuleImplBlocks}, |
13 | lang_item::{LangItemTarget, LangItems}, | 13 | lang_item::{LangItemTarget, LangItems}, |
14 | nameres::{CrateDefMap, Namespace}, | 14 | nameres::Namespace, |
15 | traits::TraitData, | 15 | traits::TraitData, |
16 | ty::{ | 16 | ty::{ |
17 | method_resolution::CrateImplBlocks, traits::Impl, CallableDef, FnSig, GenericPredicate, | 17 | method_resolution::CrateImplBlocks, traits::Impl, CallableDef, FnSig, GenericPredicate, |
@@ -23,8 +23,8 @@ use crate::{ | |||
23 | }; | 23 | }; |
24 | 24 | ||
25 | pub use hir_def::db::{ | 25 | pub use hir_def::db::{ |
26 | DefDatabase2, DefDatabase2Storage, EnumDataQuery, InternDatabase, InternDatabaseStorage, | 26 | CrateDefMapQuery, DefDatabase2, DefDatabase2Storage, EnumDataQuery, InternDatabase, |
27 | RawItemsQuery, RawItemsWithSourceMapQuery, StructDataQuery, | 27 | InternDatabaseStorage, RawItemsQuery, RawItemsWithSourceMapQuery, StructDataQuery, |
28 | }; | 28 | }; |
29 | pub use hir_expand::db::{ | 29 | pub use hir_expand::db::{ |
30 | AstDatabase, AstDatabaseStorage, AstIdMapQuery, MacroArgQuery, MacroDefQuery, MacroExpandQuery, | 30 | AstDatabase, AstDatabaseStorage, AstIdMapQuery, MacroArgQuery, MacroDefQuery, MacroExpandQuery, |
@@ -41,9 +41,6 @@ pub trait DefDatabase: HirDebugDatabase + DefDatabase2 { | |||
41 | #[salsa::invoke(crate::traits::TraitItemsIndex::trait_items_index)] | 41 | #[salsa::invoke(crate::traits::TraitItemsIndex::trait_items_index)] |
42 | fn trait_items_index(&self, module: Module) -> crate::traits::TraitItemsIndex; | 42 | fn trait_items_index(&self, module: Module) -> crate::traits::TraitItemsIndex; |
43 | 43 | ||
44 | #[salsa::invoke(CrateDefMap::crate_def_map_query)] | ||
45 | fn crate_def_map(&self, krate: Crate) -> Arc<CrateDefMap>; | ||
46 | |||
47 | #[salsa::invoke(ModuleImplBlocks::impls_in_module_with_source_map_query)] | 44 | #[salsa::invoke(ModuleImplBlocks::impls_in_module_with_source_map_query)] |
48 | fn impls_in_module_with_source_map( | 45 | fn impls_in_module_with_source_map( |
49 | &self, | 46 | &self, |
diff --git a/crates/ra_hir/src/diagnostics.rs b/crates/ra_hir/src/diagnostics.rs index a33af8f46..1751e7be3 100644 --- a/crates/ra_hir/src/diagnostics.rs +++ b/crates/ra_hir/src/diagnostics.rs | |||
@@ -3,10 +3,10 @@ | |||
3 | use std::any::Any; | 3 | use std::any::Any; |
4 | 4 | ||
5 | use ra_syntax::{ast, AstNode, AstPtr, SyntaxNodePtr}; | 5 | use ra_syntax::{ast, AstNode, AstPtr, SyntaxNodePtr}; |
6 | use relative_path::RelativePathBuf; | ||
7 | 6 | ||
8 | use crate::{db::AstDatabase, HirFileId, Name, Source}; | 7 | use crate::{db::AstDatabase, HirFileId, Name, Source}; |
9 | 8 | ||
9 | pub use hir_def::diagnostics::UnresolvedModule; | ||
10 | pub use hir_expand::diagnostics::{AstDiagnostic, Diagnostic, DiagnosticSink}; | 10 | pub use hir_expand::diagnostics::{AstDiagnostic, Diagnostic, DiagnosticSink}; |
11 | 11 | ||
12 | #[derive(Debug)] | 12 | #[derive(Debug)] |
@@ -30,25 +30,6 @@ impl Diagnostic for NoSuchField { | |||
30 | } | 30 | } |
31 | 31 | ||
32 | #[derive(Debug)] | 32 | #[derive(Debug)] |
33 | pub struct UnresolvedModule { | ||
34 | pub file: HirFileId, | ||
35 | pub decl: AstPtr<ast::Module>, | ||
36 | pub candidate: RelativePathBuf, | ||
37 | } | ||
38 | |||
39 | impl Diagnostic for UnresolvedModule { | ||
40 | fn message(&self) -> String { | ||
41 | "unresolved module".to_string() | ||
42 | } | ||
43 | fn source(&self) -> Source<SyntaxNodePtr> { | ||
44 | Source { file_id: self.file, ast: self.decl.into() } | ||
45 | } | ||
46 | fn as_any(&self) -> &(dyn Any + Send + 'static) { | ||
47 | self | ||
48 | } | ||
49 | } | ||
50 | |||
51 | #[derive(Debug)] | ||
52 | pub struct MissingFields { | 33 | pub struct MissingFields { |
53 | pub file: HirFileId, | 34 | pub file: HirFileId, |
54 | pub field_list: AstPtr<ast::RecordFieldList>, | 35 | pub field_list: AstPtr<ast::RecordFieldList>, |
diff --git a/crates/ra_hir/src/from_id.rs b/crates/ra_hir/src/from_id.rs new file mode 100644 index 000000000..c08203bca --- /dev/null +++ b/crates/ra_hir/src/from_id.rs | |||
@@ -0,0 +1,58 @@ | |||
1 | use hir_def::{AdtId, EnumVariantId, ModuleDefId}; | ||
2 | |||
3 | use crate::{Adt, EnumVariant, ModuleDef}; | ||
4 | |||
5 | macro_rules! from_id { | ||
6 | ($(($id:path, $ty:path)),*) => {$( | ||
7 | impl From<$id> for $ty { | ||
8 | fn from(id: $id) -> $ty { | ||
9 | $ty { id } | ||
10 | } | ||
11 | } | ||
12 | )*} | ||
13 | } | ||
14 | |||
15 | from_id![ | ||
16 | (hir_def::ModuleId, crate::Module), | ||
17 | (hir_def::StructId, crate::Struct), | ||
18 | (hir_def::UnionId, crate::Union), | ||
19 | (hir_def::EnumId, crate::Enum), | ||
20 | (hir_def::TypeAliasId, crate::TypeAlias), | ||
21 | (hir_def::TraitId, crate::Trait), | ||
22 | (hir_def::StaticId, crate::Static), | ||
23 | (hir_def::ConstId, crate::Const), | ||
24 | (hir_def::FunctionId, crate::Function), | ||
25 | (hir_expand::MacroDefId, crate::MacroDef) | ||
26 | ]; | ||
27 | |||
28 | impl From<AdtId> for Adt { | ||
29 | fn from(id: AdtId) -> Self { | ||
30 | match id { | ||
31 | AdtId::StructId(it) => Adt::Struct(it.into()), | ||
32 | AdtId::UnionId(it) => Adt::Union(it.into()), | ||
33 | AdtId::EnumId(it) => Adt::Enum(it.into()), | ||
34 | } | ||
35 | } | ||
36 | } | ||
37 | |||
38 | impl From<EnumVariantId> for EnumVariant { | ||
39 | fn from(id: EnumVariantId) -> Self { | ||
40 | EnumVariant { parent: id.parent.into(), id: id.local_id } | ||
41 | } | ||
42 | } | ||
43 | |||
44 | impl From<ModuleDefId> for ModuleDef { | ||
45 | fn from(id: ModuleDefId) -> Self { | ||
46 | match id { | ||
47 | ModuleDefId::ModuleId(it) => ModuleDef::Module(it.into()), | ||
48 | ModuleDefId::FunctionId(it) => ModuleDef::Function(it.into()), | ||
49 | ModuleDefId::AdtId(it) => ModuleDef::Adt(it.into()), | ||
50 | ModuleDefId::EnumVariantId(it) => ModuleDef::EnumVariant(it.into()), | ||
51 | ModuleDefId::ConstId(it) => ModuleDef::Const(it.into()), | ||
52 | ModuleDefId::StaticId(it) => ModuleDef::Static(it.into()), | ||
53 | ModuleDefId::TraitId(it) => ModuleDef::Trait(it.into()), | ||
54 | ModuleDefId::TypeAliasId(it) => ModuleDef::TypeAlias(it.into()), | ||
55 | ModuleDefId::BuiltinType(it) => ModuleDef::BuiltinType(it), | ||
56 | } | ||
57 | } | ||
58 | } | ||
diff --git a/crates/ra_hir/src/from_source.rs b/crates/ra_hir/src/from_source.rs index a9de01455..9899bdbbc 100644 --- a/crates/ra_hir/src/from_source.rs +++ b/crates/ra_hir/src/from_source.rs | |||
@@ -149,14 +149,20 @@ impl Module { | |||
149 | ModuleSource::SourceFile(_) => None, | 149 | ModuleSource::SourceFile(_) => None, |
150 | }; | 150 | }; |
151 | 151 | ||
152 | db.relevant_crates(src.file_id.original_file(db)) | 152 | db.relevant_crates(src.file_id.original_file(db)).iter().find_map(|&crate_id| { |
153 | .iter() | 153 | let def_map = db.crate_def_map(crate_id); |
154 | .map(|&crate_id| Crate { crate_id }) | 154 | |
155 | .find_map(|krate| { | 155 | let (module_id, _module_data) = |
156 | let def_map = db.crate_def_map(krate); | 156 | def_map.modules.iter().find(|(_module_id, module_data)| { |
157 | let module_id = def_map.find_module_by_source(src.file_id, decl_id)?; | 157 | if decl_id.is_some() { |
158 | Some(Module::new(krate, module_id)) | 158 | module_data.declaration == decl_id |
159 | }) | 159 | } else { |
160 | module_data.definition.map(|it| it.into()) == Some(src.file_id) | ||
161 | } | ||
162 | })?; | ||
163 | |||
164 | Some(Module::new(Crate { crate_id }, module_id)) | ||
165 | }) | ||
160 | } | 166 | } |
161 | } | 167 | } |
162 | 168 | ||
diff --git a/crates/ra_hir/src/lib.rs b/crates/ra_hir/src/lib.rs index 0ba17e571..52bad2228 100644 --- a/crates/ra_hir/src/lib.rs +++ b/crates/ra_hir/src/lib.rs | |||
@@ -47,6 +47,7 @@ mod resolve; | |||
47 | pub mod diagnostics; | 47 | pub mod diagnostics; |
48 | mod util; | 48 | mod util; |
49 | 49 | ||
50 | mod from_id; | ||
50 | mod code_model; | 51 | mod code_model; |
51 | 52 | ||
52 | pub mod from_source; | 53 | pub mod from_source; |
diff --git a/crates/ra_hir/src/nameres.rs b/crates/ra_hir/src/nameres.rs index 32a6ab474..bb775cfc9 100644 --- a/crates/ra_hir/src/nameres.rs +++ b/crates/ra_hir/src/nameres.rs | |||
@@ -47,512 +47,10 @@ | |||
47 | //! path and, upon success, we run macro expansion and "collect module" phase | 47 | //! path and, upon success, we run macro expansion and "collect module" phase |
48 | //! on the result | 48 | //! on the result |
49 | 49 | ||
50 | mod per_ns; | ||
51 | mod collector; | ||
52 | #[cfg(test)] | 50 | #[cfg(test)] |
53 | mod tests; | 51 | mod tests; |
54 | 52 | ||
55 | use std::sync::Arc; | 53 | pub use hir_def::nameres::{ |
56 | 54 | per_ns::{Namespace, PerNs}, | |
57 | use hir_def::{builtin_type::BuiltinType, CrateModuleId}; | 55 | raw::ImportId, |
58 | use hir_expand::diagnostics::DiagnosticSink; | ||
59 | use once_cell::sync::Lazy; | ||
60 | use ra_arena::Arena; | ||
61 | use ra_db::{Edition, FileId}; | ||
62 | use ra_prof::profile; | ||
63 | use ra_syntax::ast; | ||
64 | use rustc_hash::{FxHashMap, FxHashSet}; | ||
65 | use test_utils::tested_by; | ||
66 | |||
67 | use crate::{ | ||
68 | db::{AstDatabase, DefDatabase}, | ||
69 | ids::MacroDefId, | ||
70 | nameres::diagnostics::DefDiagnostic, | ||
71 | Adt, AstId, Crate, HirFileId, MacroDef, Module, ModuleDef, Name, Path, PathKind, Trait, | ||
72 | }; | 56 | }; |
73 | |||
74 | pub use self::per_ns::{Namespace, PerNs}; | ||
75 | |||
76 | pub use hir_def::nameres::raw::ImportId; | ||
77 | |||
78 | /// Contains all top-level defs from a macro-expanded crate | ||
79 | #[derive(Debug, PartialEq, Eq)] | ||
80 | pub struct CrateDefMap { | ||
81 | krate: Crate, | ||
82 | edition: Edition, | ||
83 | /// The prelude module for this crate. This either comes from an import | ||
84 | /// marked with the `prelude_import` attribute, or (in the normal case) from | ||
85 | /// a dependency (`std` or `core`). | ||
86 | prelude: Option<Module>, | ||
87 | extern_prelude: FxHashMap<Name, ModuleDef>, | ||
88 | root: CrateModuleId, | ||
89 | modules: Arena<CrateModuleId, ModuleData>, | ||
90 | |||
91 | /// Some macros are not well-behavior, which leads to infinite loop | ||
92 | /// e.g. macro_rules! foo { ($ty:ty) => { foo!($ty); } } | ||
93 | /// We mark it down and skip it in collector | ||
94 | /// | ||
95 | /// FIXME: | ||
96 | /// Right now it only handle a poison macro in a single crate, | ||
97 | /// such that if other crate try to call that macro, | ||
98 | /// the whole process will do again until it became poisoned in that crate. | ||
99 | /// We should handle this macro set globally | ||
100 | /// However, do we want to put it as a global variable? | ||
101 | poison_macros: FxHashSet<MacroDefId>, | ||
102 | |||
103 | diagnostics: Vec<DefDiagnostic>, | ||
104 | } | ||
105 | |||
106 | impl std::ops::Index<CrateModuleId> for CrateDefMap { | ||
107 | type Output = ModuleData; | ||
108 | fn index(&self, id: CrateModuleId) -> &ModuleData { | ||
109 | &self.modules[id] | ||
110 | } | ||
111 | } | ||
112 | |||
113 | #[derive(Default, Debug, PartialEq, Eq)] | ||
114 | pub struct ModuleData { | ||
115 | pub(crate) parent: Option<CrateModuleId>, | ||
116 | pub(crate) children: FxHashMap<Name, CrateModuleId>, | ||
117 | pub(crate) scope: ModuleScope, | ||
118 | /// None for root | ||
119 | pub(crate) declaration: Option<AstId<ast::Module>>, | ||
120 | /// None for inline modules. | ||
121 | /// | ||
122 | /// Note that non-inline modules, by definition, live inside non-macro file. | ||
123 | pub(crate) definition: Option<FileId>, | ||
124 | } | ||
125 | |||
126 | #[derive(Debug, Default, PartialEq, Eq, Clone)] | ||
127 | pub struct ModuleScope { | ||
128 | items: FxHashMap<Name, Resolution>, | ||
129 | /// Macros visable in current module in legacy textual scope | ||
130 | /// | ||
131 | /// For macros invoked by an unquatified identifier like `bar!()`, `legacy_macros` will be searched in first. | ||
132 | /// If it yields no result, then it turns to module scoped `macros`. | ||
133 | /// It macros with name quatified with a path like `crate::foo::bar!()`, `legacy_macros` will be skipped, | ||
134 | /// and only normal scoped `macros` will be searched in. | ||
135 | /// | ||
136 | /// Note that this automatically inherit macros defined textually before the definition of module itself. | ||
137 | /// | ||
138 | /// Module scoped macros will be inserted into `items` instead of here. | ||
139 | // FIXME: Macro shadowing in one module is not properly handled. Non-item place macros will | ||
140 | // be all resolved to the last one defined if shadowing happens. | ||
141 | legacy_macros: FxHashMap<Name, MacroDef>, | ||
142 | } | ||
143 | |||
144 | static BUILTIN_SCOPE: Lazy<FxHashMap<Name, Resolution>> = Lazy::new(|| { | ||
145 | BuiltinType::ALL | ||
146 | .iter() | ||
147 | .map(|(name, ty)| { | ||
148 | (name.clone(), Resolution { def: PerNs::types(ty.clone().into()), import: None }) | ||
149 | }) | ||
150 | .collect() | ||
151 | }); | ||
152 | |||
153 | /// Legacy macros can only be accessed through special methods like `get_legacy_macros`. | ||
154 | /// Other methods will only resolve values, types and module scoped macros only. | ||
155 | impl ModuleScope { | ||
156 | pub fn entries<'a>(&'a self) -> impl Iterator<Item = (&'a Name, &'a Resolution)> + 'a { | ||
157 | //FIXME: shadowing | ||
158 | self.items.iter().chain(BUILTIN_SCOPE.iter()) | ||
159 | } | ||
160 | |||
161 | /// Iterate over all module scoped macros | ||
162 | pub fn macros<'a>(&'a self) -> impl Iterator<Item = (&'a Name, MacroDef)> + 'a { | ||
163 | self.items | ||
164 | .iter() | ||
165 | .filter_map(|(name, res)| res.def.get_macros().map(|macro_| (name, macro_))) | ||
166 | } | ||
167 | |||
168 | /// Iterate over all legacy textual scoped macros visable at the end of the module | ||
169 | pub fn legacy_macros<'a>(&'a self) -> impl Iterator<Item = (&'a Name, MacroDef)> + 'a { | ||
170 | self.legacy_macros.iter().map(|(name, def)| (name, *def)) | ||
171 | } | ||
172 | |||
173 | /// Get a name from current module scope, legacy macros are not included | ||
174 | pub fn get(&self, name: &Name) -> Option<&Resolution> { | ||
175 | self.items.get(name).or_else(|| BUILTIN_SCOPE.get(name)) | ||
176 | } | ||
177 | |||
178 | pub fn traits<'a>(&'a self) -> impl Iterator<Item = Trait> + 'a { | ||
179 | self.items.values().filter_map(|r| match r.def.take_types() { | ||
180 | Some(ModuleDef::Trait(t)) => Some(t), | ||
181 | _ => None, | ||
182 | }) | ||
183 | } | ||
184 | |||
185 | fn get_legacy_macro(&self, name: &Name) -> Option<MacroDef> { | ||
186 | self.legacy_macros.get(name).copied() | ||
187 | } | ||
188 | } | ||
189 | |||
190 | #[derive(Debug, Clone, PartialEq, Eq, Default)] | ||
191 | pub struct Resolution { | ||
192 | /// None for unresolved | ||
193 | pub def: PerNs, | ||
194 | /// ident by which this is imported into local scope. | ||
195 | pub import: Option<ImportId>, | ||
196 | } | ||
197 | |||
198 | impl Resolution { | ||
199 | pub(crate) fn from_macro(macro_: MacroDef) -> Self { | ||
200 | Resolution { def: PerNs::macros(macro_), import: None } | ||
201 | } | ||
202 | } | ||
203 | |||
204 | #[derive(Debug, Clone)] | ||
205 | struct ResolvePathResult { | ||
206 | resolved_def: PerNs, | ||
207 | segment_index: Option<usize>, | ||
208 | reached_fixedpoint: ReachedFixedPoint, | ||
209 | } | ||
210 | |||
211 | impl ResolvePathResult { | ||
212 | fn empty(reached_fixedpoint: ReachedFixedPoint) -> ResolvePathResult { | ||
213 | ResolvePathResult::with(PerNs::none(), reached_fixedpoint, None) | ||
214 | } | ||
215 | |||
216 | fn with( | ||
217 | resolved_def: PerNs, | ||
218 | reached_fixedpoint: ReachedFixedPoint, | ||
219 | segment_index: Option<usize>, | ||
220 | ) -> ResolvePathResult { | ||
221 | ResolvePathResult { resolved_def, reached_fixedpoint, segment_index } | ||
222 | } | ||
223 | } | ||
224 | |||
225 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
226 | enum ResolveMode { | ||
227 | Import, | ||
228 | Other, | ||
229 | } | ||
230 | |||
231 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
232 | enum ReachedFixedPoint { | ||
233 | Yes, | ||
234 | No, | ||
235 | } | ||
236 | |||
237 | impl CrateDefMap { | ||
238 | pub(crate) fn crate_def_map_query( | ||
239 | // Note that this doesn't have `+ AstDatabase`! | ||
240 | // This gurantess that `CrateDefMap` is stable across reparses. | ||
241 | db: &impl DefDatabase, | ||
242 | krate: Crate, | ||
243 | ) -> Arc<CrateDefMap> { | ||
244 | let _p = profile("crate_def_map_query"); | ||
245 | let def_map = { | ||
246 | let edition = krate.edition(db); | ||
247 | let mut modules: Arena<CrateModuleId, ModuleData> = Arena::default(); | ||
248 | let root = modules.alloc(ModuleData::default()); | ||
249 | CrateDefMap { | ||
250 | krate, | ||
251 | edition, | ||
252 | extern_prelude: FxHashMap::default(), | ||
253 | prelude: None, | ||
254 | root, | ||
255 | modules, | ||
256 | poison_macros: FxHashSet::default(), | ||
257 | diagnostics: Vec::new(), | ||
258 | } | ||
259 | }; | ||
260 | let def_map = collector::collect_defs(db, def_map); | ||
261 | Arc::new(def_map) | ||
262 | } | ||
263 | |||
264 | pub(crate) fn krate(&self) -> Crate { | ||
265 | self.krate | ||
266 | } | ||
267 | |||
268 | pub(crate) fn root(&self) -> CrateModuleId { | ||
269 | self.root | ||
270 | } | ||
271 | |||
272 | pub(crate) fn prelude(&self) -> Option<Module> { | ||
273 | self.prelude | ||
274 | } | ||
275 | |||
276 | pub(crate) fn extern_prelude(&self) -> &FxHashMap<Name, ModuleDef> { | ||
277 | &self.extern_prelude | ||
278 | } | ||
279 | |||
280 | pub(crate) fn add_diagnostics( | ||
281 | &self, | ||
282 | db: &(impl DefDatabase + AstDatabase), | ||
283 | module: CrateModuleId, | ||
284 | sink: &mut DiagnosticSink, | ||
285 | ) { | ||
286 | self.diagnostics.iter().for_each(|it| it.add_to(db, module, sink)) | ||
287 | } | ||
288 | |||
289 | pub(crate) fn find_module_by_source( | ||
290 | &self, | ||
291 | file_id: HirFileId, | ||
292 | decl_id: Option<AstId<ast::Module>>, | ||
293 | ) -> Option<CrateModuleId> { | ||
294 | let (module_id, _module_data) = self.modules.iter().find(|(_module_id, module_data)| { | ||
295 | if decl_id.is_some() { | ||
296 | module_data.declaration == decl_id | ||
297 | } else { | ||
298 | module_data.definition.map(|it| it.into()) == Some(file_id) | ||
299 | } | ||
300 | })?; | ||
301 | Some(module_id) | ||
302 | } | ||
303 | |||
304 | pub(crate) fn resolve_path( | ||
305 | &self, | ||
306 | db: &impl DefDatabase, | ||
307 | original_module: CrateModuleId, | ||
308 | path: &Path, | ||
309 | ) -> (PerNs, Option<usize>) { | ||
310 | let res = self.resolve_path_fp_with_macro(db, ResolveMode::Other, original_module, path); | ||
311 | (res.resolved_def, res.segment_index) | ||
312 | } | ||
313 | |||
314 | // Returns Yes if we are sure that additions to `ItemMap` wouldn't change | ||
315 | // the result. | ||
316 | fn resolve_path_fp_with_macro( | ||
317 | &self, | ||
318 | db: &impl DefDatabase, | ||
319 | mode: ResolveMode, | ||
320 | original_module: CrateModuleId, | ||
321 | path: &Path, | ||
322 | ) -> ResolvePathResult { | ||
323 | let mut segments = path.segments.iter().enumerate(); | ||
324 | let mut curr_per_ns: PerNs = match path.kind { | ||
325 | PathKind::DollarCrate(crate_id) => { | ||
326 | let krate = Crate { crate_id }; | ||
327 | if krate == self.krate { | ||
328 | tested_by!(macro_dollar_crate_self); | ||
329 | PerNs::types(Module::new(self.krate, self.root).into()) | ||
330 | } else { | ||
331 | match krate.root_module(db) { | ||
332 | Some(module) => { | ||
333 | tested_by!(macro_dollar_crate_other); | ||
334 | PerNs::types(module.into()) | ||
335 | } | ||
336 | None => return ResolvePathResult::empty(ReachedFixedPoint::Yes), | ||
337 | } | ||
338 | } | ||
339 | } | ||
340 | PathKind::Crate => PerNs::types(Module::new(self.krate, self.root).into()), | ||
341 | PathKind::Self_ => PerNs::types(Module::new(self.krate, original_module).into()), | ||
342 | // plain import or absolute path in 2015: crate-relative with | ||
343 | // fallback to extern prelude (with the simplification in | ||
344 | // rust-lang/rust#57745) | ||
345 | // FIXME there must be a nicer way to write this condition | ||
346 | PathKind::Plain | PathKind::Abs | ||
347 | if self.edition == Edition::Edition2015 | ||
348 | && (path.kind == PathKind::Abs || mode == ResolveMode::Import) => | ||
349 | { | ||
350 | let segment = match segments.next() { | ||
351 | Some((_, segment)) => segment, | ||
352 | None => return ResolvePathResult::empty(ReachedFixedPoint::Yes), | ||
353 | }; | ||
354 | log::debug!("resolving {:?} in crate root (+ extern prelude)", segment); | ||
355 | self.resolve_name_in_crate_root_or_extern_prelude(&segment.name) | ||
356 | } | ||
357 | PathKind::Plain => { | ||
358 | let segment = match segments.next() { | ||
359 | Some((_, segment)) => segment, | ||
360 | None => return ResolvePathResult::empty(ReachedFixedPoint::Yes), | ||
361 | }; | ||
362 | log::debug!("resolving {:?} in module", segment); | ||
363 | self.resolve_name_in_module(db, original_module, &segment.name) | ||
364 | } | ||
365 | PathKind::Super => { | ||
366 | if let Some(p) = self.modules[original_module].parent { | ||
367 | PerNs::types(Module::new(self.krate, p).into()) | ||
368 | } else { | ||
369 | log::debug!("super path in root module"); | ||
370 | return ResolvePathResult::empty(ReachedFixedPoint::Yes); | ||
371 | } | ||
372 | } | ||
373 | PathKind::Abs => { | ||
374 | // 2018-style absolute path -- only extern prelude | ||
375 | let segment = match segments.next() { | ||
376 | Some((_, segment)) => segment, | ||
377 | None => return ResolvePathResult::empty(ReachedFixedPoint::Yes), | ||
378 | }; | ||
379 | if let Some(def) = self.extern_prelude.get(&segment.name) { | ||
380 | log::debug!("absolute path {:?} resolved to crate {:?}", path, def); | ||
381 | PerNs::types(*def) | ||
382 | } else { | ||
383 | return ResolvePathResult::empty(ReachedFixedPoint::No); // extern crate declarations can add to the extern prelude | ||
384 | } | ||
385 | } | ||
386 | PathKind::Type(_) => { | ||
387 | // This is handled in `infer::infer_path_expr` | ||
388 | // The result returned here does not matter | ||
389 | return ResolvePathResult::empty(ReachedFixedPoint::Yes); | ||
390 | } | ||
391 | }; | ||
392 | |||
393 | for (i, segment) in segments { | ||
394 | let curr = match curr_per_ns.take_types() { | ||
395 | Some(r) => r, | ||
396 | None => { | ||
397 | // we still have path segments left, but the path so far | ||
398 | // didn't resolve in the types namespace => no resolution | ||
399 | // (don't break here because `curr_per_ns` might contain | ||
400 | // something in the value namespace, and it would be wrong | ||
401 | // to return that) | ||
402 | return ResolvePathResult::empty(ReachedFixedPoint::No); | ||
403 | } | ||
404 | }; | ||
405 | // resolve segment in curr | ||
406 | |||
407 | curr_per_ns = match curr { | ||
408 | ModuleDef::Module(module) => { | ||
409 | if module.krate() != self.krate { | ||
410 | let path = | ||
411 | Path { segments: path.segments[i..].to_vec(), kind: PathKind::Self_ }; | ||
412 | log::debug!("resolving {:?} in other crate", path); | ||
413 | let defp_map = db.crate_def_map(module.krate()); | ||
414 | let (def, s) = defp_map.resolve_path(db, module.id.module_id, &path); | ||
415 | return ResolvePathResult::with( | ||
416 | def, | ||
417 | ReachedFixedPoint::Yes, | ||
418 | s.map(|s| s + i), | ||
419 | ); | ||
420 | } | ||
421 | |||
422 | // Since it is a qualified path here, it should not contains legacy macros | ||
423 | match self[module.id.module_id].scope.get(&segment.name) { | ||
424 | Some(res) => res.def, | ||
425 | _ => { | ||
426 | log::debug!("path segment {:?} not found", segment.name); | ||
427 | return ResolvePathResult::empty(ReachedFixedPoint::No); | ||
428 | } | ||
429 | } | ||
430 | } | ||
431 | ModuleDef::Adt(Adt::Enum(e)) => { | ||
432 | // enum variant | ||
433 | tested_by!(can_import_enum_variant); | ||
434 | match e.variant(db, &segment.name) { | ||
435 | Some(variant) => PerNs::both(variant.into(), variant.into()), | ||
436 | None => { | ||
437 | return ResolvePathResult::with( | ||
438 | PerNs::types(e.into()), | ||
439 | ReachedFixedPoint::Yes, | ||
440 | Some(i), | ||
441 | ); | ||
442 | } | ||
443 | } | ||
444 | } | ||
445 | s => { | ||
446 | // could be an inherent method call in UFCS form | ||
447 | // (`Struct::method`), or some other kind of associated item | ||
448 | log::debug!( | ||
449 | "path segment {:?} resolved to non-module {:?}, but is not last", | ||
450 | segment.name, | ||
451 | curr, | ||
452 | ); | ||
453 | |||
454 | return ResolvePathResult::with( | ||
455 | PerNs::types(s), | ||
456 | ReachedFixedPoint::Yes, | ||
457 | Some(i), | ||
458 | ); | ||
459 | } | ||
460 | }; | ||
461 | } | ||
462 | ResolvePathResult::with(curr_per_ns, ReachedFixedPoint::Yes, None) | ||
463 | } | ||
464 | |||
465 | fn resolve_name_in_crate_root_or_extern_prelude(&self, name: &Name) -> PerNs { | ||
466 | let from_crate_root = | ||
467 | self[self.root].scope.get(name).map_or_else(PerNs::none, |res| res.def); | ||
468 | let from_extern_prelude = self.resolve_name_in_extern_prelude(name); | ||
469 | |||
470 | from_crate_root.or(from_extern_prelude) | ||
471 | } | ||
472 | |||
473 | pub(crate) fn resolve_name_in_module( | ||
474 | &self, | ||
475 | db: &impl DefDatabase, | ||
476 | module: CrateModuleId, | ||
477 | name: &Name, | ||
478 | ) -> PerNs { | ||
479 | // Resolve in: | ||
480 | // - legacy scope of macro | ||
481 | // - current module / scope | ||
482 | // - extern prelude | ||
483 | // - std prelude | ||
484 | let from_legacy_macro = | ||
485 | self[module].scope.get_legacy_macro(name).map_or_else(PerNs::none, PerNs::macros); | ||
486 | let from_scope = self[module].scope.get(name).map_or_else(PerNs::none, |res| res.def); | ||
487 | let from_extern_prelude = | ||
488 | self.extern_prelude.get(name).map_or(PerNs::none(), |&it| PerNs::types(it)); | ||
489 | let from_prelude = self.resolve_in_prelude(db, name); | ||
490 | |||
491 | from_legacy_macro.or(from_scope).or(from_extern_prelude).or(from_prelude) | ||
492 | } | ||
493 | |||
494 | fn resolve_name_in_extern_prelude(&self, name: &Name) -> PerNs { | ||
495 | self.extern_prelude.get(name).map_or(PerNs::none(), |&it| PerNs::types(it)) | ||
496 | } | ||
497 | |||
498 | fn resolve_in_prelude(&self, db: &impl DefDatabase, name: &Name) -> PerNs { | ||
499 | if let Some(prelude) = self.prelude { | ||
500 | let keep; | ||
501 | let def_map = if prelude.krate() == self.krate { | ||
502 | self | ||
503 | } else { | ||
504 | // Extend lifetime | ||
505 | keep = db.crate_def_map(prelude.krate()); | ||
506 | &keep | ||
507 | }; | ||
508 | def_map[prelude.id.module_id].scope.get(name).map_or_else(PerNs::none, |res| res.def) | ||
509 | } else { | ||
510 | PerNs::none() | ||
511 | } | ||
512 | } | ||
513 | } | ||
514 | |||
515 | mod diagnostics { | ||
516 | use hir_expand::diagnostics::DiagnosticSink; | ||
517 | use ra_syntax::{ast, AstPtr}; | ||
518 | use relative_path::RelativePathBuf; | ||
519 | |||
520 | use crate::{ | ||
521 | db::{AstDatabase, DefDatabase}, | ||
522 | diagnostics::UnresolvedModule, | ||
523 | nameres::CrateModuleId, | ||
524 | AstId, | ||
525 | }; | ||
526 | |||
527 | #[derive(Debug, PartialEq, Eq)] | ||
528 | pub(super) enum DefDiagnostic { | ||
529 | UnresolvedModule { | ||
530 | module: CrateModuleId, | ||
531 | declaration: AstId<ast::Module>, | ||
532 | candidate: RelativePathBuf, | ||
533 | }, | ||
534 | } | ||
535 | |||
536 | impl DefDiagnostic { | ||
537 | pub(super) fn add_to( | ||
538 | &self, | ||
539 | db: &(impl DefDatabase + AstDatabase), | ||
540 | target_module: CrateModuleId, | ||
541 | sink: &mut DiagnosticSink, | ||
542 | ) { | ||
543 | match self { | ||
544 | DefDiagnostic::UnresolvedModule { module, declaration, candidate } => { | ||
545 | if *module != target_module { | ||
546 | return; | ||
547 | } | ||
548 | let decl = declaration.to_node(db); | ||
549 | sink.push(UnresolvedModule { | ||
550 | file: declaration.file_id(), | ||
551 | decl: AstPtr::new(&decl), | ||
552 | candidate: candidate.clone(), | ||
553 | }) | ||
554 | } | ||
555 | } | ||
556 | } | ||
557 | } | ||
558 | } | ||
diff --git a/crates/ra_hir/src/nameres/collector.rs b/crates/ra_hir/src/nameres/collector.rs deleted file mode 100644 index ee0a4c99f..000000000 --- a/crates/ra_hir/src/nameres/collector.rs +++ /dev/null | |||
@@ -1,837 +0,0 @@ | |||
1 | //! FIXME: write short doc here | ||
2 | |||
3 | use hir_def::{ | ||
4 | attr::Attr, | ||
5 | nameres::{mod_resolution::ModDir, raw}, | ||
6 | }; | ||
7 | use hir_expand::name; | ||
8 | use ra_cfg::CfgOptions; | ||
9 | use ra_db::FileId; | ||
10 | use ra_syntax::{ast, SmolStr}; | ||
11 | use rustc_hash::FxHashMap; | ||
12 | use test_utils::tested_by; | ||
13 | |||
14 | use crate::{ | ||
15 | db::DefDatabase, | ||
16 | ids::{AstItemDef, LocationCtx, MacroCallId, MacroCallLoc, MacroDefId, MacroFileKind}, | ||
17 | nameres::{ | ||
18 | diagnostics::DefDiagnostic, Crate, CrateDefMap, CrateModuleId, ModuleData, ModuleDef, | ||
19 | PerNs, ReachedFixedPoint, Resolution, ResolveMode, | ||
20 | }, | ||
21 | Adt, AstId, Const, Enum, Function, HirFileId, MacroDef, Module, Name, Path, PathKind, Static, | ||
22 | Struct, Trait, TypeAlias, Union, | ||
23 | }; | ||
24 | |||
25 | pub(super) fn collect_defs(db: &impl DefDatabase, mut def_map: CrateDefMap) -> CrateDefMap { | ||
26 | // populate external prelude | ||
27 | for dep in def_map.krate.dependencies(db) { | ||
28 | log::debug!("crate dep {:?} -> {:?}", dep.name, dep.krate); | ||
29 | if let Some(module) = dep.krate.root_module(db) { | ||
30 | def_map.extern_prelude.insert(dep.name.clone(), module.into()); | ||
31 | } | ||
32 | // look for the prelude | ||
33 | if def_map.prelude.is_none() { | ||
34 | let map = db.crate_def_map(dep.krate); | ||
35 | if map.prelude.is_some() { | ||
36 | def_map.prelude = map.prelude; | ||
37 | } | ||
38 | } | ||
39 | } | ||
40 | |||
41 | let crate_graph = db.crate_graph(); | ||
42 | let cfg_options = crate_graph.cfg_options(def_map.krate().crate_id()); | ||
43 | |||
44 | let mut collector = DefCollector { | ||
45 | db, | ||
46 | def_map, | ||
47 | glob_imports: FxHashMap::default(), | ||
48 | unresolved_imports: Vec::new(), | ||
49 | unexpanded_macros: Vec::new(), | ||
50 | mod_dirs: FxHashMap::default(), | ||
51 | macro_stack_monitor: MacroStackMonitor::default(), | ||
52 | cfg_options, | ||
53 | }; | ||
54 | collector.collect(); | ||
55 | collector.finish() | ||
56 | } | ||
57 | |||
58 | #[derive(Default)] | ||
59 | struct MacroStackMonitor { | ||
60 | counts: FxHashMap<MacroDefId, u32>, | ||
61 | |||
62 | /// Mainly use for test | ||
63 | validator: Option<Box<dyn Fn(u32) -> bool>>, | ||
64 | } | ||
65 | |||
66 | impl MacroStackMonitor { | ||
67 | fn increase(&mut self, macro_def_id: MacroDefId) { | ||
68 | *self.counts.entry(macro_def_id).or_default() += 1; | ||
69 | } | ||
70 | |||
71 | fn decrease(&mut self, macro_def_id: MacroDefId) { | ||
72 | *self.counts.entry(macro_def_id).or_default() -= 1; | ||
73 | } | ||
74 | |||
75 | fn is_poison(&self, macro_def_id: MacroDefId) -> bool { | ||
76 | let cur = *self.counts.get(¯o_def_id).unwrap_or(&0); | ||
77 | |||
78 | if let Some(validator) = &self.validator { | ||
79 | validator(cur) | ||
80 | } else { | ||
81 | cur > 100 | ||
82 | } | ||
83 | } | ||
84 | } | ||
85 | |||
86 | /// Walks the tree of module recursively | ||
87 | struct DefCollector<'a, DB> { | ||
88 | db: &'a DB, | ||
89 | def_map: CrateDefMap, | ||
90 | glob_imports: FxHashMap<CrateModuleId, Vec<(CrateModuleId, raw::ImportId)>>, | ||
91 | unresolved_imports: Vec<(CrateModuleId, raw::ImportId, raw::ImportData)>, | ||
92 | unexpanded_macros: Vec<(CrateModuleId, AstId<ast::MacroCall>, Path)>, | ||
93 | mod_dirs: FxHashMap<CrateModuleId, ModDir>, | ||
94 | |||
95 | /// Some macro use `$tt:tt which mean we have to handle the macro perfectly | ||
96 | /// To prevent stack overflow, we add a deep counter here for prevent that. | ||
97 | macro_stack_monitor: MacroStackMonitor, | ||
98 | |||
99 | cfg_options: &'a CfgOptions, | ||
100 | } | ||
101 | |||
102 | impl<DB> DefCollector<'_, DB> | ||
103 | where | ||
104 | DB: DefDatabase, | ||
105 | { | ||
106 | fn collect(&mut self) { | ||
107 | let crate_graph = self.db.crate_graph(); | ||
108 | let file_id = crate_graph.crate_root(self.def_map.krate.crate_id()); | ||
109 | let raw_items = self.db.raw_items(file_id.into()); | ||
110 | let module_id = self.def_map.root; | ||
111 | self.def_map.modules[module_id].definition = Some(file_id); | ||
112 | ModCollector { | ||
113 | def_collector: &mut *self, | ||
114 | module_id, | ||
115 | file_id: file_id.into(), | ||
116 | raw_items: &raw_items, | ||
117 | mod_dir: ModDir::root(), | ||
118 | } | ||
119 | .collect(raw_items.items()); | ||
120 | |||
121 | // main name resolution fixed-point loop. | ||
122 | let mut i = 0; | ||
123 | loop { | ||
124 | self.db.check_canceled(); | ||
125 | match (self.resolve_imports(), self.resolve_macros()) { | ||
126 | (ReachedFixedPoint::Yes, ReachedFixedPoint::Yes) => break, | ||
127 | _ => i += 1, | ||
128 | } | ||
129 | if i == 1000 { | ||
130 | log::error!("name resolution is stuck"); | ||
131 | break; | ||
132 | } | ||
133 | } | ||
134 | |||
135 | let unresolved_imports = std::mem::replace(&mut self.unresolved_imports, Vec::new()); | ||
136 | // show unresolved imports in completion, etc | ||
137 | for (module_id, import, import_data) in unresolved_imports { | ||
138 | self.record_resolved_import(module_id, PerNs::none(), import, &import_data) | ||
139 | } | ||
140 | } | ||
141 | |||
142 | /// Define a macro with `macro_rules`. | ||
143 | /// | ||
144 | /// It will define the macro in legacy textual scope, and if it has `#[macro_export]`, | ||
145 | /// then it is also defined in the root module scope. | ||
146 | /// You can `use` or invoke it by `crate::macro_name` anywhere, before or after the definition. | ||
147 | /// | ||
148 | /// It is surprising that the macro will never be in the current module scope. | ||
149 | /// These code fails with "unresolved import/macro", | ||
150 | /// ```rust,compile_fail | ||
151 | /// mod m { macro_rules! foo { () => {} } } | ||
152 | /// use m::foo as bar; | ||
153 | /// ``` | ||
154 | /// | ||
155 | /// ```rust,compile_fail | ||
156 | /// macro_rules! foo { () => {} } | ||
157 | /// self::foo!(); | ||
158 | /// crate::foo!(); | ||
159 | /// ``` | ||
160 | /// | ||
161 | /// Well, this code compiles, bacause the plain path `foo` in `use` is searched | ||
162 | /// in the legacy textual scope only. | ||
163 | /// ```rust | ||
164 | /// macro_rules! foo { () => {} } | ||
165 | /// use foo as bar; | ||
166 | /// ``` | ||
167 | fn define_macro( | ||
168 | &mut self, | ||
169 | module_id: CrateModuleId, | ||
170 | name: Name, | ||
171 | macro_: MacroDef, | ||
172 | export: bool, | ||
173 | ) { | ||
174 | // Textual scoping | ||
175 | self.define_legacy_macro(module_id, name.clone(), macro_); | ||
176 | |||
177 | // Module scoping | ||
178 | // In Rust, `#[macro_export]` macros are unconditionally visible at the | ||
179 | // crate root, even if the parent modules is **not** visible. | ||
180 | if export { | ||
181 | self.update(self.def_map.root, None, &[(name, Resolution::from_macro(macro_))]); | ||
182 | } | ||
183 | } | ||
184 | |||
185 | /// Define a legacy textual scoped macro in module | ||
186 | /// | ||
187 | /// We use a map `legacy_macros` to store all legacy textual scoped macros visable per module. | ||
188 | /// It will clone all macros from parent legacy scope, whose definition is prior to | ||
189 | /// the definition of current module. | ||
190 | /// And also, `macro_use` on a module will import all legacy macros visable inside to | ||
191 | /// current legacy scope, with possible shadowing. | ||
192 | fn define_legacy_macro(&mut self, module_id: CrateModuleId, name: Name, macro_: MacroDef) { | ||
193 | // Always shadowing | ||
194 | self.def_map.modules[module_id].scope.legacy_macros.insert(name, macro_); | ||
195 | } | ||
196 | |||
197 | /// Import macros from `#[macro_use] extern crate`. | ||
198 | fn import_macros_from_extern_crate( | ||
199 | &mut self, | ||
200 | current_module_id: CrateModuleId, | ||
201 | import: &raw::ImportData, | ||
202 | ) { | ||
203 | log::debug!( | ||
204 | "importing macros from extern crate: {:?} ({:?})", | ||
205 | import, | ||
206 | self.def_map.edition, | ||
207 | ); | ||
208 | |||
209 | let res = self.def_map.resolve_name_in_extern_prelude( | ||
210 | &import | ||
211 | .path | ||
212 | .as_ident() | ||
213 | .expect("extern crate should have been desugared to one-element path"), | ||
214 | ); | ||
215 | |||
216 | if let Some(ModuleDef::Module(m)) = res.take_types() { | ||
217 | tested_by!(macro_rules_from_other_crates_are_visible_with_macro_use); | ||
218 | self.import_all_macros_exported(current_module_id, m.krate()); | ||
219 | } | ||
220 | } | ||
221 | |||
222 | /// Import all exported macros from another crate | ||
223 | /// | ||
224 | /// Exported macros are just all macros in the root module scope. | ||
225 | /// Note that it contains not only all `#[macro_export]` macros, but also all aliases | ||
226 | /// created by `use` in the root module, ignoring the visibility of `use`. | ||
227 | fn import_all_macros_exported(&mut self, current_module_id: CrateModuleId, krate: Crate) { | ||
228 | let def_map = self.db.crate_def_map(krate); | ||
229 | for (name, def) in def_map[def_map.root].scope.macros() { | ||
230 | // `macro_use` only bring things into legacy scope. | ||
231 | self.define_legacy_macro(current_module_id, name.clone(), def); | ||
232 | } | ||
233 | } | ||
234 | |||
235 | fn resolve_imports(&mut self) -> ReachedFixedPoint { | ||
236 | let mut imports = std::mem::replace(&mut self.unresolved_imports, Vec::new()); | ||
237 | let mut resolved = Vec::new(); | ||
238 | imports.retain(|(module_id, import, import_data)| { | ||
239 | let (def, fp) = self.resolve_import(*module_id, import_data); | ||
240 | if fp == ReachedFixedPoint::Yes { | ||
241 | resolved.push((*module_id, def, *import, import_data.clone())) | ||
242 | } | ||
243 | fp == ReachedFixedPoint::No | ||
244 | }); | ||
245 | self.unresolved_imports = imports; | ||
246 | // Resolves imports, filling-in module scopes | ||
247 | let result = | ||
248 | if resolved.is_empty() { ReachedFixedPoint::Yes } else { ReachedFixedPoint::No }; | ||
249 | for (module_id, def, import, import_data) in resolved { | ||
250 | self.record_resolved_import(module_id, def, import, &import_data) | ||
251 | } | ||
252 | result | ||
253 | } | ||
254 | |||
255 | fn resolve_import( | ||
256 | &self, | ||
257 | module_id: CrateModuleId, | ||
258 | import: &raw::ImportData, | ||
259 | ) -> (PerNs, ReachedFixedPoint) { | ||
260 | log::debug!("resolving import: {:?} ({:?})", import, self.def_map.edition); | ||
261 | if import.is_extern_crate { | ||
262 | let res = self.def_map.resolve_name_in_extern_prelude( | ||
263 | &import | ||
264 | .path | ||
265 | .as_ident() | ||
266 | .expect("extern crate should have been desugared to one-element path"), | ||
267 | ); | ||
268 | (res, ReachedFixedPoint::Yes) | ||
269 | } else { | ||
270 | let res = self.def_map.resolve_path_fp_with_macro( | ||
271 | self.db, | ||
272 | ResolveMode::Import, | ||
273 | module_id, | ||
274 | &import.path, | ||
275 | ); | ||
276 | |||
277 | (res.resolved_def, res.reached_fixedpoint) | ||
278 | } | ||
279 | } | ||
280 | |||
281 | fn record_resolved_import( | ||
282 | &mut self, | ||
283 | module_id: CrateModuleId, | ||
284 | def: PerNs, | ||
285 | import_id: raw::ImportId, | ||
286 | import: &raw::ImportData, | ||
287 | ) { | ||
288 | if import.is_glob { | ||
289 | log::debug!("glob import: {:?}", import); | ||
290 | match def.take_types() { | ||
291 | Some(ModuleDef::Module(m)) => { | ||
292 | if import.is_prelude { | ||
293 | tested_by!(std_prelude); | ||
294 | self.def_map.prelude = Some(m); | ||
295 | } else if m.krate() != self.def_map.krate { | ||
296 | tested_by!(glob_across_crates); | ||
297 | // glob import from other crate => we can just import everything once | ||
298 | let item_map = self.db.crate_def_map(m.krate()); | ||
299 | let scope = &item_map[m.id.module_id].scope; | ||
300 | |||
301 | // Module scoped macros is included | ||
302 | let items = scope | ||
303 | .items | ||
304 | .iter() | ||
305 | .map(|(name, res)| (name.clone(), res.clone())) | ||
306 | .collect::<Vec<_>>(); | ||
307 | |||
308 | self.update(module_id, Some(import_id), &items); | ||
309 | } else { | ||
310 | // glob import from same crate => we do an initial | ||
311 | // import, and then need to propagate any further | ||
312 | // additions | ||
313 | let scope = &self.def_map[m.id.module_id].scope; | ||
314 | |||
315 | // Module scoped macros is included | ||
316 | let items = scope | ||
317 | .items | ||
318 | .iter() | ||
319 | .map(|(name, res)| (name.clone(), res.clone())) | ||
320 | .collect::<Vec<_>>(); | ||
321 | |||
322 | self.update(module_id, Some(import_id), &items); | ||
323 | // record the glob import in case we add further items | ||
324 | self.glob_imports | ||
325 | .entry(m.id.module_id) | ||
326 | .or_default() | ||
327 | .push((module_id, import_id)); | ||
328 | } | ||
329 | } | ||
330 | Some(ModuleDef::Adt(Adt::Enum(e))) => { | ||
331 | tested_by!(glob_enum); | ||
332 | // glob import from enum => just import all the variants | ||
333 | let variants = e.variants(self.db); | ||
334 | let resolutions = variants | ||
335 | .into_iter() | ||
336 | .filter_map(|variant| { | ||
337 | let res = Resolution { | ||
338 | def: PerNs::both(variant.into(), variant.into()), | ||
339 | import: Some(import_id), | ||
340 | }; | ||
341 | let name = variant.name(self.db)?; | ||
342 | Some((name, res)) | ||
343 | }) | ||
344 | .collect::<Vec<_>>(); | ||
345 | self.update(module_id, Some(import_id), &resolutions); | ||
346 | } | ||
347 | Some(d) => { | ||
348 | log::debug!("glob import {:?} from non-module/enum {:?}", import, d); | ||
349 | } | ||
350 | None => { | ||
351 | log::debug!("glob import {:?} didn't resolve as type", import); | ||
352 | } | ||
353 | } | ||
354 | } else { | ||
355 | match import.path.segments.last() { | ||
356 | Some(last_segment) => { | ||
357 | let name = import.alias.clone().unwrap_or_else(|| last_segment.name.clone()); | ||
358 | log::debug!("resolved import {:?} ({:?}) to {:?}", name, import, def); | ||
359 | |||
360 | // extern crates in the crate root are special-cased to insert entries into the extern prelude: rust-lang/rust#54658 | ||
361 | if import.is_extern_crate && module_id == self.def_map.root { | ||
362 | if let Some(def) = def.take_types() { | ||
363 | self.def_map.extern_prelude.insert(name.clone(), def); | ||
364 | } | ||
365 | } | ||
366 | |||
367 | let resolution = Resolution { def, import: Some(import_id) }; | ||
368 | self.update(module_id, Some(import_id), &[(name, resolution)]); | ||
369 | } | ||
370 | None => tested_by!(bogus_paths), | ||
371 | } | ||
372 | } | ||
373 | } | ||
374 | |||
375 | fn update( | ||
376 | &mut self, | ||
377 | module_id: CrateModuleId, | ||
378 | import: Option<raw::ImportId>, | ||
379 | resolutions: &[(Name, Resolution)], | ||
380 | ) { | ||
381 | self.update_recursive(module_id, import, resolutions, 0) | ||
382 | } | ||
383 | |||
384 | fn update_recursive( | ||
385 | &mut self, | ||
386 | module_id: CrateModuleId, | ||
387 | import: Option<raw::ImportId>, | ||
388 | resolutions: &[(Name, Resolution)], | ||
389 | depth: usize, | ||
390 | ) { | ||
391 | if depth > 100 { | ||
392 | // prevent stack overflows (but this shouldn't be possible) | ||
393 | panic!("infinite recursion in glob imports!"); | ||
394 | } | ||
395 | let module_items = &mut self.def_map.modules[module_id].scope; | ||
396 | let mut changed = false; | ||
397 | for (name, res) in resolutions { | ||
398 | let existing = module_items.items.entry(name.clone()).or_default(); | ||
399 | |||
400 | if existing.def.types.is_none() && res.def.types.is_some() { | ||
401 | existing.def.types = res.def.types; | ||
402 | existing.import = import.or(res.import); | ||
403 | changed = true; | ||
404 | } | ||
405 | if existing.def.values.is_none() && res.def.values.is_some() { | ||
406 | existing.def.values = res.def.values; | ||
407 | existing.import = import.or(res.import); | ||
408 | changed = true; | ||
409 | } | ||
410 | if existing.def.macros.is_none() && res.def.macros.is_some() { | ||
411 | existing.def.macros = res.def.macros; | ||
412 | existing.import = import.or(res.import); | ||
413 | changed = true; | ||
414 | } | ||
415 | |||
416 | if existing.def.is_none() | ||
417 | && res.def.is_none() | ||
418 | && existing.import.is_none() | ||
419 | && res.import.is_some() | ||
420 | { | ||
421 | existing.import = res.import; | ||
422 | } | ||
423 | } | ||
424 | |||
425 | if !changed { | ||
426 | return; | ||
427 | } | ||
428 | let glob_imports = self | ||
429 | .glob_imports | ||
430 | .get(&module_id) | ||
431 | .into_iter() | ||
432 | .flat_map(|v| v.iter()) | ||
433 | .cloned() | ||
434 | .collect::<Vec<_>>(); | ||
435 | for (glob_importing_module, glob_import) in glob_imports { | ||
436 | // We pass the glob import so that the tracked import in those modules is that glob import | ||
437 | self.update_recursive(glob_importing_module, Some(glob_import), resolutions, depth + 1); | ||
438 | } | ||
439 | } | ||
440 | |||
441 | fn resolve_macros(&mut self) -> ReachedFixedPoint { | ||
442 | let mut macros = std::mem::replace(&mut self.unexpanded_macros, Vec::new()); | ||
443 | let mut resolved = Vec::new(); | ||
444 | let mut res = ReachedFixedPoint::Yes; | ||
445 | macros.retain(|(module_id, ast_id, path)| { | ||
446 | let resolved_res = self.def_map.resolve_path_fp_with_macro( | ||
447 | self.db, | ||
448 | ResolveMode::Other, | ||
449 | *module_id, | ||
450 | path, | ||
451 | ); | ||
452 | |||
453 | if let Some(def) = resolved_res.resolved_def.get_macros() { | ||
454 | let call_id = self.db.intern_macro(MacroCallLoc { def: def.id, ast_id: *ast_id }); | ||
455 | resolved.push((*module_id, call_id, def.id)); | ||
456 | res = ReachedFixedPoint::No; | ||
457 | return false; | ||
458 | } | ||
459 | |||
460 | true | ||
461 | }); | ||
462 | |||
463 | self.unexpanded_macros = macros; | ||
464 | |||
465 | for (module_id, macro_call_id, macro_def_id) in resolved { | ||
466 | self.collect_macro_expansion(module_id, macro_call_id, macro_def_id); | ||
467 | } | ||
468 | |||
469 | res | ||
470 | } | ||
471 | |||
472 | fn collect_macro_expansion( | ||
473 | &mut self, | ||
474 | module_id: CrateModuleId, | ||
475 | macro_call_id: MacroCallId, | ||
476 | macro_def_id: MacroDefId, | ||
477 | ) { | ||
478 | if self.def_map.poison_macros.contains(¯o_def_id) { | ||
479 | return; | ||
480 | } | ||
481 | |||
482 | self.macro_stack_monitor.increase(macro_def_id); | ||
483 | |||
484 | if !self.macro_stack_monitor.is_poison(macro_def_id) { | ||
485 | let file_id: HirFileId = macro_call_id.as_file(MacroFileKind::Items); | ||
486 | let raw_items = self.db.raw_items(file_id); | ||
487 | let mod_dir = self.mod_dirs[&module_id].clone(); | ||
488 | ModCollector { | ||
489 | def_collector: &mut *self, | ||
490 | file_id, | ||
491 | module_id, | ||
492 | raw_items: &raw_items, | ||
493 | mod_dir, | ||
494 | } | ||
495 | .collect(raw_items.items()); | ||
496 | } else { | ||
497 | log::error!("Too deep macro expansion: {:?}", macro_call_id); | ||
498 | self.def_map.poison_macros.insert(macro_def_id); | ||
499 | } | ||
500 | |||
501 | self.macro_stack_monitor.decrease(macro_def_id); | ||
502 | } | ||
503 | |||
504 | fn finish(self) -> CrateDefMap { | ||
505 | self.def_map | ||
506 | } | ||
507 | } | ||
508 | |||
509 | /// Walks a single module, populating defs, imports and macros | ||
510 | struct ModCollector<'a, D> { | ||
511 | def_collector: D, | ||
512 | module_id: CrateModuleId, | ||
513 | file_id: HirFileId, | ||
514 | raw_items: &'a raw::RawItems, | ||
515 | mod_dir: ModDir, | ||
516 | } | ||
517 | |||
518 | impl<DB> ModCollector<'_, &'_ mut DefCollector<'_, DB>> | ||
519 | where | ||
520 | DB: DefDatabase, | ||
521 | { | ||
522 | fn collect(&mut self, items: &[raw::RawItem]) { | ||
523 | // Note: don't assert that inserted value is fresh: it's simply not true | ||
524 | // for macros. | ||
525 | self.def_collector.mod_dirs.insert(self.module_id, self.mod_dir.clone()); | ||
526 | |||
527 | // Prelude module is always considered to be `#[macro_use]`. | ||
528 | if let Some(prelude_module) = self.def_collector.def_map.prelude { | ||
529 | if prelude_module.krate() != self.def_collector.def_map.krate { | ||
530 | tested_by!(prelude_is_macro_use); | ||
531 | self.def_collector | ||
532 | .import_all_macros_exported(self.module_id, prelude_module.krate()); | ||
533 | } | ||
534 | } | ||
535 | |||
536 | // This should be processed eagerly instead of deferred to resolving. | ||
537 | // `#[macro_use] extern crate` is hoisted to imports macros before collecting | ||
538 | // any other items. | ||
539 | for item in items { | ||
540 | if self.is_cfg_enabled(item.attrs()) { | ||
541 | if let raw::RawItemKind::Import(import_id) = item.kind { | ||
542 | let import = self.raw_items[import_id].clone(); | ||
543 | if import.is_extern_crate && import.is_macro_use { | ||
544 | self.def_collector.import_macros_from_extern_crate(self.module_id, &import); | ||
545 | } | ||
546 | } | ||
547 | } | ||
548 | } | ||
549 | |||
550 | for item in items { | ||
551 | if self.is_cfg_enabled(item.attrs()) { | ||
552 | match item.kind { | ||
553 | raw::RawItemKind::Module(m) => { | ||
554 | self.collect_module(&self.raw_items[m], item.attrs()) | ||
555 | } | ||
556 | raw::RawItemKind::Import(import_id) => self | ||
557 | .def_collector | ||
558 | .unresolved_imports | ||
559 | .push((self.module_id, import_id, self.raw_items[import_id].clone())), | ||
560 | raw::RawItemKind::Def(def) => self.define_def(&self.raw_items[def]), | ||
561 | raw::RawItemKind::Macro(mac) => self.collect_macro(&self.raw_items[mac]), | ||
562 | } | ||
563 | } | ||
564 | } | ||
565 | } | ||
566 | |||
567 | fn collect_module(&mut self, module: &raw::ModuleData, attrs: &[Attr]) { | ||
568 | let path_attr = self.path_attr(attrs); | ||
569 | let is_macro_use = self.is_macro_use(attrs); | ||
570 | match module { | ||
571 | // inline module, just recurse | ||
572 | raw::ModuleData::Definition { name, items, ast_id } => { | ||
573 | let module_id = | ||
574 | self.push_child_module(name.clone(), AstId::new(self.file_id, *ast_id), None); | ||
575 | |||
576 | ModCollector { | ||
577 | def_collector: &mut *self.def_collector, | ||
578 | module_id, | ||
579 | file_id: self.file_id, | ||
580 | raw_items: self.raw_items, | ||
581 | mod_dir: self.mod_dir.descend_into_definition(name, path_attr), | ||
582 | } | ||
583 | .collect(&*items); | ||
584 | if is_macro_use { | ||
585 | self.import_all_legacy_macros(module_id); | ||
586 | } | ||
587 | } | ||
588 | // out of line module, resolve, parse and recurse | ||
589 | raw::ModuleData::Declaration { name, ast_id } => { | ||
590 | let ast_id = AstId::new(self.file_id, *ast_id); | ||
591 | match self.mod_dir.resolve_declaration( | ||
592 | self.def_collector.db, | ||
593 | self.file_id, | ||
594 | name, | ||
595 | path_attr, | ||
596 | ) { | ||
597 | Ok((file_id, mod_dir)) => { | ||
598 | let module_id = self.push_child_module(name.clone(), ast_id, Some(file_id)); | ||
599 | let raw_items = self.def_collector.db.raw_items(file_id.into()); | ||
600 | ModCollector { | ||
601 | def_collector: &mut *self.def_collector, | ||
602 | module_id, | ||
603 | file_id: file_id.into(), | ||
604 | raw_items: &raw_items, | ||
605 | mod_dir, | ||
606 | } | ||
607 | .collect(raw_items.items()); | ||
608 | if is_macro_use { | ||
609 | self.import_all_legacy_macros(module_id); | ||
610 | } | ||
611 | } | ||
612 | Err(candidate) => self.def_collector.def_map.diagnostics.push( | ||
613 | DefDiagnostic::UnresolvedModule { | ||
614 | module: self.module_id, | ||
615 | declaration: ast_id, | ||
616 | candidate, | ||
617 | }, | ||
618 | ), | ||
619 | }; | ||
620 | } | ||
621 | } | ||
622 | } | ||
623 | |||
624 | fn push_child_module( | ||
625 | &mut self, | ||
626 | name: Name, | ||
627 | declaration: AstId<ast::Module>, | ||
628 | definition: Option<FileId>, | ||
629 | ) -> CrateModuleId { | ||
630 | let modules = &mut self.def_collector.def_map.modules; | ||
631 | let res = modules.alloc(ModuleData::default()); | ||
632 | modules[res].parent = Some(self.module_id); | ||
633 | modules[res].declaration = Some(declaration); | ||
634 | modules[res].definition = definition; | ||
635 | modules[res].scope.legacy_macros = modules[self.module_id].scope.legacy_macros.clone(); | ||
636 | modules[self.module_id].children.insert(name.clone(), res); | ||
637 | let resolution = Resolution { | ||
638 | def: PerNs::types(Module::new(self.def_collector.def_map.krate, res).into()), | ||
639 | import: None, | ||
640 | }; | ||
641 | self.def_collector.update(self.module_id, None, &[(name, resolution)]); | ||
642 | res | ||
643 | } | ||
644 | |||
645 | fn define_def(&mut self, def: &raw::DefData) { | ||
646 | let module = Module::new(self.def_collector.def_map.krate, self.module_id); | ||
647 | let ctx = LocationCtx::new(self.def_collector.db, module.id, self.file_id); | ||
648 | |||
649 | macro_rules! def { | ||
650 | ($kind:ident, $ast_id:ident) => { | ||
651 | $kind { id: AstItemDef::from_ast_id(ctx, $ast_id) }.into() | ||
652 | }; | ||
653 | } | ||
654 | let name = def.name.clone(); | ||
655 | let def: PerNs = match def.kind { | ||
656 | raw::DefKind::Function(ast_id) => PerNs::values(def!(Function, ast_id)), | ||
657 | raw::DefKind::Struct(ast_id) => { | ||
658 | let s = def!(Struct, ast_id); | ||
659 | PerNs::both(s, s) | ||
660 | } | ||
661 | raw::DefKind::Union(ast_id) => { | ||
662 | let s = def!(Union, ast_id); | ||
663 | PerNs::both(s, s) | ||
664 | } | ||
665 | raw::DefKind::Enum(ast_id) => PerNs::types(def!(Enum, ast_id)), | ||
666 | raw::DefKind::Const(ast_id) => PerNs::values(def!(Const, ast_id)), | ||
667 | raw::DefKind::Static(ast_id) => PerNs::values(def!(Static, ast_id)), | ||
668 | raw::DefKind::Trait(ast_id) => PerNs::types(def!(Trait, ast_id)), | ||
669 | raw::DefKind::TypeAlias(ast_id) => PerNs::types(def!(TypeAlias, ast_id)), | ||
670 | }; | ||
671 | let resolution = Resolution { def, import: None }; | ||
672 | self.def_collector.update(self.module_id, None, &[(name, resolution)]) | ||
673 | } | ||
674 | |||
675 | fn collect_macro(&mut self, mac: &raw::MacroData) { | ||
676 | let ast_id = AstId::new(self.file_id, mac.ast_id); | ||
677 | |||
678 | // Case 1: macro rules, define a macro in crate-global mutable scope | ||
679 | if is_macro_rules(&mac.path) { | ||
680 | if let Some(name) = &mac.name { | ||
681 | let macro_id = | ||
682 | MacroDefId { ast_id, krate: self.def_collector.def_map.krate.crate_id }; | ||
683 | let macro_ = MacroDef { id: macro_id }; | ||
684 | self.def_collector.define_macro(self.module_id, name.clone(), macro_, mac.export); | ||
685 | } | ||
686 | return; | ||
687 | } | ||
688 | |||
689 | // Case 2: try to resolve in legacy scope and expand macro_rules, triggering | ||
690 | // recursive item collection. | ||
691 | if let Some(macro_def) = mac.path.as_ident().and_then(|name| { | ||
692 | self.def_collector.def_map[self.module_id].scope.get_legacy_macro(&name) | ||
693 | }) { | ||
694 | let def = macro_def.id; | ||
695 | let macro_call_id = self.def_collector.db.intern_macro(MacroCallLoc { def, ast_id }); | ||
696 | |||
697 | self.def_collector.collect_macro_expansion(self.module_id, macro_call_id, def); | ||
698 | return; | ||
699 | } | ||
700 | |||
701 | // Case 3: resolve in module scope, expand during name resolution. | ||
702 | // We rewrite simple path `macro_name` to `self::macro_name` to force resolve in module scope only. | ||
703 | let mut path = mac.path.clone(); | ||
704 | if path.is_ident() { | ||
705 | path.kind = PathKind::Self_; | ||
706 | } | ||
707 | self.def_collector.unexpanded_macros.push((self.module_id, ast_id, path)); | ||
708 | } | ||
709 | |||
710 | fn import_all_legacy_macros(&mut self, module_id: CrateModuleId) { | ||
711 | let macros = self.def_collector.def_map[module_id].scope.legacy_macros.clone(); | ||
712 | for (name, macro_) in macros { | ||
713 | self.def_collector.define_legacy_macro(self.module_id, name.clone(), macro_); | ||
714 | } | ||
715 | } | ||
716 | |||
717 | fn is_cfg_enabled(&self, attrs: &[Attr]) -> bool { | ||
718 | attrs.iter().all(|attr| attr.is_cfg_enabled(&self.def_collector.cfg_options) != Some(false)) | ||
719 | } | ||
720 | |||
721 | fn path_attr<'a>(&self, attrs: &'a [Attr]) -> Option<&'a SmolStr> { | ||
722 | attrs.iter().find_map(|attr| attr.as_path()) | ||
723 | } | ||
724 | |||
725 | fn is_macro_use<'a>(&self, attrs: &'a [Attr]) -> bool { | ||
726 | attrs.iter().any(|attr| attr.is_simple_atom("macro_use")) | ||
727 | } | ||
728 | } | ||
729 | |||
730 | fn is_macro_rules(path: &Path) -> bool { | ||
731 | path.as_ident() == Some(&name::MACRO_RULES) | ||
732 | } | ||
733 | |||
734 | #[cfg(test)] | ||
735 | mod tests { | ||
736 | use ra_db::SourceDatabase; | ||
737 | |||
738 | use super::*; | ||
739 | use crate::{db::DefDatabase, mock::MockDatabase, Crate}; | ||
740 | use ra_arena::Arena; | ||
741 | use rustc_hash::FxHashSet; | ||
742 | |||
743 | fn do_collect_defs( | ||
744 | db: &impl DefDatabase, | ||
745 | def_map: CrateDefMap, | ||
746 | monitor: MacroStackMonitor, | ||
747 | ) -> CrateDefMap { | ||
748 | let mut collector = DefCollector { | ||
749 | db, | ||
750 | def_map, | ||
751 | glob_imports: FxHashMap::default(), | ||
752 | unresolved_imports: Vec::new(), | ||
753 | unexpanded_macros: Vec::new(), | ||
754 | mod_dirs: FxHashMap::default(), | ||
755 | macro_stack_monitor: monitor, | ||
756 | cfg_options: &CfgOptions::default(), | ||
757 | }; | ||
758 | collector.collect(); | ||
759 | collector.finish() | ||
760 | } | ||
761 | |||
762 | fn do_limited_resolve(code: &str, limit: u32, poison_limit: u32) -> CrateDefMap { | ||
763 | let (db, _source_root, _) = MockDatabase::with_single_file(&code); | ||
764 | let crate_id = db.crate_graph().iter().next().unwrap(); | ||
765 | let krate = Crate { crate_id }; | ||
766 | |||
767 | let def_map = { | ||
768 | let edition = krate.edition(&db); | ||
769 | let mut modules: Arena<CrateModuleId, ModuleData> = Arena::default(); | ||
770 | let root = modules.alloc(ModuleData::default()); | ||
771 | CrateDefMap { | ||
772 | krate, | ||
773 | edition, | ||
774 | extern_prelude: FxHashMap::default(), | ||
775 | prelude: None, | ||
776 | root, | ||
777 | modules, | ||
778 | poison_macros: FxHashSet::default(), | ||
779 | diagnostics: Vec::new(), | ||
780 | } | ||
781 | }; | ||
782 | |||
783 | let mut monitor = MacroStackMonitor::default(); | ||
784 | monitor.validator = Some(Box::new(move |count| { | ||
785 | assert!(count < limit); | ||
786 | count >= poison_limit | ||
787 | })); | ||
788 | |||
789 | do_collect_defs(&db, def_map, monitor) | ||
790 | } | ||
791 | |||
792 | #[test] | ||
793 | fn test_macro_expand_limit_width() { | ||
794 | do_limited_resolve( | ||
795 | r#" | ||
796 | macro_rules! foo { | ||
797 | ($($ty:ty)*) => { foo!($($ty)*, $($ty)*); } | ||
798 | } | ||
799 | foo!(KABOOM); | ||
800 | "#, | ||
801 | 16, | ||
802 | 1000, | ||
803 | ); | ||
804 | } | ||
805 | |||
806 | #[test] | ||
807 | fn test_macro_expand_poisoned() { | ||
808 | let def = do_limited_resolve( | ||
809 | r#" | ||
810 | macro_rules! foo { | ||
811 | ($ty:ty) => { foo!($ty); } | ||
812 | } | ||
813 | foo!(KABOOM); | ||
814 | "#, | ||
815 | 100, | ||
816 | 16, | ||
817 | ); | ||
818 | |||
819 | assert_eq!(def.poison_macros.len(), 1); | ||
820 | } | ||
821 | |||
822 | #[test] | ||
823 | fn test_macro_expand_normal() { | ||
824 | let def = do_limited_resolve( | ||
825 | r#" | ||
826 | macro_rules! foo { | ||
827 | ($ident:ident) => { struct $ident {} } | ||
828 | } | ||
829 | foo!(Bar); | ||
830 | "#, | ||
831 | 16, | ||
832 | 16, | ||
833 | ); | ||
834 | |||
835 | assert_eq!(def.poison_macros.len(), 0); | ||
836 | } | ||
837 | } | ||
diff --git a/crates/ra_hir/src/nameres/per_ns.rs b/crates/ra_hir/src/nameres/per_ns.rs deleted file mode 100644 index 0da6789de..000000000 --- a/crates/ra_hir/src/nameres/per_ns.rs +++ /dev/null | |||
@@ -1,80 +0,0 @@ | |||
1 | //! FIXME: write short doc here | ||
2 | |||
3 | use crate::{MacroDef, ModuleDef}; | ||
4 | |||
5 | #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] | ||
6 | pub enum Namespace { | ||
7 | Types, | ||
8 | Values, | ||
9 | // Note that only type inference uses this enum, and it doesn't care about macros. | ||
10 | // Macro, | ||
11 | } | ||
12 | |||
13 | #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] | ||
14 | pub struct PerNs { | ||
15 | pub types: Option<ModuleDef>, | ||
16 | pub values: Option<ModuleDef>, | ||
17 | /// Since macros has different type, many methods simply ignore it. | ||
18 | /// We can only use special method like `get_macros` to access it. | ||
19 | pub macros: Option<MacroDef>, | ||
20 | } | ||
21 | |||
22 | impl Default for PerNs { | ||
23 | fn default() -> Self { | ||
24 | PerNs { types: None, values: None, macros: None } | ||
25 | } | ||
26 | } | ||
27 | |||
28 | impl PerNs { | ||
29 | pub fn none() -> PerNs { | ||
30 | PerNs { types: None, values: None, macros: None } | ||
31 | } | ||
32 | |||
33 | pub fn values(t: ModuleDef) -> PerNs { | ||
34 | PerNs { types: None, values: Some(t), macros: None } | ||
35 | } | ||
36 | |||
37 | pub fn types(t: ModuleDef) -> PerNs { | ||
38 | PerNs { types: Some(t), values: None, macros: None } | ||
39 | } | ||
40 | |||
41 | pub fn both(types: ModuleDef, values: ModuleDef) -> PerNs { | ||
42 | PerNs { types: Some(types), values: Some(values), macros: None } | ||
43 | } | ||
44 | |||
45 | pub fn macros(macro_: MacroDef) -> PerNs { | ||
46 | PerNs { types: None, values: None, macros: Some(macro_) } | ||
47 | } | ||
48 | |||
49 | pub fn is_none(&self) -> bool { | ||
50 | self.types.is_none() && self.values.is_none() && self.macros.is_none() | ||
51 | } | ||
52 | |||
53 | pub fn is_all(&self) -> bool { | ||
54 | self.types.is_some() && self.values.is_some() && self.macros.is_some() | ||
55 | } | ||
56 | |||
57 | pub fn take_types(self) -> Option<ModuleDef> { | ||
58 | self.types | ||
59 | } | ||
60 | |||
61 | pub fn take_values(self) -> Option<ModuleDef> { | ||
62 | self.values | ||
63 | } | ||
64 | |||
65 | pub fn get_macros(&self) -> Option<MacroDef> { | ||
66 | self.macros | ||
67 | } | ||
68 | |||
69 | pub fn only_macros(&self) -> PerNs { | ||
70 | PerNs { types: None, values: None, macros: self.macros } | ||
71 | } | ||
72 | |||
73 | pub fn or(self, other: PerNs) -> PerNs { | ||
74 | PerNs { | ||
75 | types: self.types.or(other.types), | ||
76 | values: self.values.or(other.values), | ||
77 | macros: self.macros.or(other.macros), | ||
78 | } | ||
79 | } | ||
80 | } | ||
diff --git a/crates/ra_hir/src/nameres/tests.rs b/crates/ra_hir/src/nameres/tests.rs index 8c6b40aaf..02db91a86 100644 --- a/crates/ra_hir/src/nameres/tests.rs +++ b/crates/ra_hir/src/nameres/tests.rs | |||
@@ -6,30 +6,25 @@ mod mod_resolution; | |||
6 | 6 | ||
7 | use std::sync::Arc; | 7 | use std::sync::Arc; |
8 | 8 | ||
9 | use hir_def::{db::DefDatabase2, nameres::*, CrateModuleId}; | ||
9 | use insta::assert_snapshot; | 10 | use insta::assert_snapshot; |
10 | use ra_db::SourceDatabase; | 11 | use ra_db::SourceDatabase; |
11 | use test_utils::covers; | 12 | // use test_utils::covers; |
12 | 13 | ||
13 | use crate::{ | 14 | use crate::mock::{CrateGraphFixture, MockDatabase}; |
14 | mock::{CrateGraphFixture, MockDatabase}, | ||
15 | Crate, | ||
16 | }; | ||
17 | |||
18 | use super::*; | ||
19 | 15 | ||
20 | fn compute_crate_def_map(fixture: &str, graph: Option<CrateGraphFixture>) -> Arc<CrateDefMap> { | 16 | fn compute_crate_def_map(fixture: &str, graph: Option<CrateGraphFixture>) -> Arc<CrateDefMap> { |
21 | let mut db = MockDatabase::with_files(fixture); | 17 | let mut db = MockDatabase::with_files(fixture); |
22 | if let Some(graph) = graph { | 18 | if let Some(graph) = graph { |
23 | db.set_crate_graph_from_fixture(graph); | 19 | db.set_crate_graph_from_fixture(graph); |
24 | } | 20 | } |
25 | let crate_id = db.crate_graph().iter().next().unwrap(); | 21 | let krate = db.crate_graph().iter().next().unwrap(); |
26 | let krate = Crate { crate_id }; | ||
27 | db.crate_def_map(krate) | 22 | db.crate_def_map(krate) |
28 | } | 23 | } |
29 | 24 | ||
30 | fn render_crate_def_map(map: &CrateDefMap) -> String { | 25 | fn render_crate_def_map(map: &CrateDefMap) -> String { |
31 | let mut buf = String::new(); | 26 | let mut buf = String::new(); |
32 | go(&mut buf, map, "\ncrate", map.root); | 27 | go(&mut buf, map, "\ncrate", map.root()); |
33 | return buf.trim().to_string(); | 28 | return buf.trim().to_string(); |
34 | 29 | ||
35 | fn go(buf: &mut String, map: &CrateDefMap, path: &str, module: CrateModuleId) { | 30 | fn go(buf: &mut String, map: &CrateDefMap, path: &str, module: CrateModuleId) { |
@@ -118,7 +113,7 @@ fn crate_def_map_smoke_test() { | |||
118 | 113 | ||
119 | #[test] | 114 | #[test] |
120 | fn bogus_paths() { | 115 | fn bogus_paths() { |
121 | covers!(bogus_paths); | 116 | // covers!(bogus_paths); |
122 | let map = def_map( | 117 | let map = def_map( |
123 | " | 118 | " |
124 | //- /lib.rs | 119 | //- /lib.rs |
@@ -233,7 +228,7 @@ fn re_exports() { | |||
233 | 228 | ||
234 | #[test] | 229 | #[test] |
235 | fn std_prelude() { | 230 | fn std_prelude() { |
236 | covers!(std_prelude); | 231 | // covers!(std_prelude); |
237 | let map = def_map_with_crate_graph( | 232 | let map = def_map_with_crate_graph( |
238 | " | 233 | " |
239 | //- /main.rs | 234 | //- /main.rs |
@@ -261,7 +256,7 @@ fn std_prelude() { | |||
261 | 256 | ||
262 | #[test] | 257 | #[test] |
263 | fn can_import_enum_variant() { | 258 | fn can_import_enum_variant() { |
264 | covers!(can_import_enum_variant); | 259 | // covers!(can_import_enum_variant); |
265 | let map = def_map( | 260 | let map = def_map( |
266 | " | 261 | " |
267 | //- /lib.rs | 262 | //- /lib.rs |
diff --git a/crates/ra_hir/src/nameres/tests/globs.rs b/crates/ra_hir/src/nameres/tests/globs.rs index 7ac22b47b..b3e4d8d94 100644 --- a/crates/ra_hir/src/nameres/tests/globs.rs +++ b/crates/ra_hir/src/nameres/tests/globs.rs | |||
@@ -75,7 +75,7 @@ fn glob_2() { | |||
75 | 75 | ||
76 | #[test] | 76 | #[test] |
77 | fn glob_across_crates() { | 77 | fn glob_across_crates() { |
78 | covers!(glob_across_crates); | 78 | // covers!(glob_across_crates); |
79 | let map = def_map_with_crate_graph( | 79 | let map = def_map_with_crate_graph( |
80 | " | 80 | " |
81 | //- /main.rs | 81 | //- /main.rs |
@@ -98,7 +98,7 @@ fn glob_across_crates() { | |||
98 | 98 | ||
99 | #[test] | 99 | #[test] |
100 | fn glob_enum() { | 100 | fn glob_enum() { |
101 | covers!(glob_enum); | 101 | // covers!(glob_enum); |
102 | let map = def_map( | 102 | let map = def_map( |
103 | " | 103 | " |
104 | //- /lib.rs | 104 | //- /lib.rs |
diff --git a/crates/ra_hir/src/nameres/tests/incremental.rs b/crates/ra_hir/src/nameres/tests/incremental.rs index af9c39760..723ece7b0 100644 --- a/crates/ra_hir/src/nameres/tests/incremental.rs +++ b/crates/ra_hir/src/nameres/tests/incremental.rs | |||
@@ -1,13 +1,12 @@ | |||
1 | use super::*; | ||
2 | |||
3 | use std::sync::Arc; | 1 | use std::sync::Arc; |
4 | 2 | ||
5 | use ra_db::{SourceDatabase, SourceDatabaseExt}; | 3 | use ra_db::{SourceDatabase, SourceDatabaseExt}; |
6 | 4 | ||
5 | use super::*; | ||
6 | |||
7 | fn check_def_map_is_not_recomputed(initial: &str, file_change: &str) { | 7 | fn check_def_map_is_not_recomputed(initial: &str, file_change: &str) { |
8 | let (mut db, pos) = MockDatabase::with_position(initial); | 8 | let (mut db, pos) = MockDatabase::with_position(initial); |
9 | let crate_id = db.crate_graph().iter().next().unwrap(); | 9 | let krate = db.crate_graph().iter().next().unwrap(); |
10 | let krate = Crate { crate_id }; | ||
11 | { | 10 | { |
12 | let events = db.log_executed(|| { | 11 | let events = db.log_executed(|| { |
13 | db.crate_def_map(krate); | 12 | db.crate_def_map(krate); |
diff --git a/crates/ra_hir/src/nameres/tests/macros.rs b/crates/ra_hir/src/nameres/tests/macros.rs index 4f52ad2c5..78bb0eb0d 100644 --- a/crates/ra_hir/src/nameres/tests/macros.rs +++ b/crates/ra_hir/src/nameres/tests/macros.rs | |||
@@ -187,7 +187,7 @@ fn unexpanded_macro_should_expand_by_fixedpoint_loop() { | |||
187 | 187 | ||
188 | #[test] | 188 | #[test] |
189 | fn macro_rules_from_other_crates_are_visible_with_macro_use() { | 189 | fn macro_rules_from_other_crates_are_visible_with_macro_use() { |
190 | covers!(macro_rules_from_other_crates_are_visible_with_macro_use); | 190 | // covers!(macro_rules_from_other_crates_are_visible_with_macro_use); |
191 | let map = def_map_with_crate_graph( | 191 | let map = def_map_with_crate_graph( |
192 | " | 192 | " |
193 | //- /main.rs | 193 | //- /main.rs |
@@ -241,7 +241,7 @@ fn macro_rules_from_other_crates_are_visible_with_macro_use() { | |||
241 | 241 | ||
242 | #[test] | 242 | #[test] |
243 | fn prelude_is_macro_use() { | 243 | fn prelude_is_macro_use() { |
244 | covers!(prelude_is_macro_use); | 244 | // covers!(prelude_is_macro_use); |
245 | let map = def_map_with_crate_graph( | 245 | let map = def_map_with_crate_graph( |
246 | " | 246 | " |
247 | //- /main.rs | 247 | //- /main.rs |
@@ -531,8 +531,8 @@ fn path_qualified_macros() { | |||
531 | 531 | ||
532 | #[test] | 532 | #[test] |
533 | fn macro_dollar_crate_is_correct_in_item() { | 533 | fn macro_dollar_crate_is_correct_in_item() { |
534 | covers!(macro_dollar_crate_self); | 534 | // covers!(macro_dollar_crate_self); |
535 | covers!(macro_dollar_crate_other); | 535 | // covers!(macro_dollar_crate_other); |
536 | let map = def_map_with_crate_graph( | 536 | let map = def_map_with_crate_graph( |
537 | " | 537 | " |
538 | //- /main.rs | 538 | //- /main.rs |
@@ -594,7 +594,7 @@ fn macro_dollar_crate_is_correct_in_item() { | |||
594 | 594 | ||
595 | #[test] | 595 | #[test] |
596 | fn macro_dollar_crate_is_correct_in_indirect_deps() { | 596 | fn macro_dollar_crate_is_correct_in_indirect_deps() { |
597 | covers!(macro_dollar_crate_other); | 597 | // covers!(macro_dollar_crate_other); |
598 | // From std | 598 | // From std |
599 | let map = def_map_with_crate_graph( | 599 | let map = def_map_with_crate_graph( |
600 | r#" | 600 | r#" |
diff --git a/crates/ra_hir/src/resolve.rs b/crates/ra_hir/src/resolve.rs index 75b24d386..3e3f8c252 100644 --- a/crates/ra_hir/src/resolve.rs +++ b/crates/ra_hir/src/resolve.rs | |||
@@ -3,8 +3,9 @@ use std::sync::Arc; | |||
3 | 3 | ||
4 | use hir_def::{ | 4 | use hir_def::{ |
5 | builtin_type::BuiltinType, | 5 | builtin_type::BuiltinType, |
6 | nameres::CrateDefMap, | ||
6 | path::{Path, PathKind}, | 7 | path::{Path, PathKind}, |
7 | CrateModuleId, | 8 | AdtId, CrateModuleId, ModuleDefId, |
8 | }; | 9 | }; |
9 | use hir_expand::name::{self, Name}; | 10 | use hir_expand::name::{self, Name}; |
10 | use rustc_hash::FxHashSet; | 11 | use rustc_hash::FxHashSet; |
@@ -18,7 +19,7 @@ use crate::{ | |||
18 | }, | 19 | }, |
19 | generics::GenericParams, | 20 | generics::GenericParams, |
20 | impl_block::ImplBlock, | 21 | impl_block::ImplBlock, |
21 | nameres::{CrateDefMap, PerNs}, | 22 | nameres::PerNs, |
22 | Adt, Const, Enum, EnumVariant, Function, MacroDef, ModuleDef, Static, Struct, Trait, TypeAlias, | 23 | Adt, Const, Enum, EnumVariant, Function, MacroDef, ModuleDef, Static, Struct, Trait, TypeAlias, |
23 | }; | 24 | }; |
24 | 25 | ||
@@ -90,7 +91,7 @@ impl Resolver { | |||
90 | pub(crate) fn resolve_known_trait(&self, db: &impl HirDatabase, path: &Path) -> Option<Trait> { | 91 | pub(crate) fn resolve_known_trait(&self, db: &impl HirDatabase, path: &Path) -> Option<Trait> { |
91 | let res = self.resolve_module_path(db, path).take_types()?; | 92 | let res = self.resolve_module_path(db, path).take_types()?; |
92 | match res { | 93 | match res { |
93 | ModuleDef::Trait(it) => Some(it), | 94 | ModuleDefId::TraitId(it) => Some(it.into()), |
94 | _ => None, | 95 | _ => None, |
95 | } | 96 | } |
96 | } | 97 | } |
@@ -103,7 +104,7 @@ impl Resolver { | |||
103 | ) -> Option<Struct> { | 104 | ) -> Option<Struct> { |
104 | let res = self.resolve_module_path(db, path).take_types()?; | 105 | let res = self.resolve_module_path(db, path).take_types()?; |
105 | match res { | 106 | match res { |
106 | ModuleDef::Adt(Adt::Struct(it)) => Some(it), | 107 | ModuleDefId::AdtId(AdtId::StructId(it)) => Some(it.into()), |
107 | _ => None, | 108 | _ => None, |
108 | } | 109 | } |
109 | } | 110 | } |
@@ -112,7 +113,7 @@ impl Resolver { | |||
112 | pub(crate) fn resolve_known_enum(&self, db: &impl HirDatabase, path: &Path) -> Option<Enum> { | 113 | pub(crate) fn resolve_known_enum(&self, db: &impl HirDatabase, path: &Path) -> Option<Enum> { |
113 | let res = self.resolve_module_path(db, path).take_types()?; | 114 | let res = self.resolve_module_path(db, path).take_types()?; |
114 | match res { | 115 | match res { |
115 | ModuleDef::Adt(Adt::Enum(it)) => Some(it), | 116 | ModuleDefId::AdtId(AdtId::EnumId(it)) => Some(it.into()), |
116 | _ => None, | 117 | _ => None, |
117 | } | 118 | } |
118 | } | 119 | } |
@@ -166,18 +167,18 @@ impl Resolver { | |||
166 | Scope::ModuleScope(m) => { | 167 | Scope::ModuleScope(m) => { |
167 | let (module_def, idx) = m.crate_def_map.resolve_path(db, m.module_id, path); | 168 | let (module_def, idx) = m.crate_def_map.resolve_path(db, m.module_id, path); |
168 | let res = match module_def.take_types()? { | 169 | let res = match module_def.take_types()? { |
169 | ModuleDef::Adt(it) => TypeNs::Adt(it), | 170 | ModuleDefId::AdtId(it) => TypeNs::Adt(it.into()), |
170 | ModuleDef::EnumVariant(it) => TypeNs::EnumVariant(it), | 171 | ModuleDefId::EnumVariantId(it) => TypeNs::EnumVariant(it.into()), |
171 | 172 | ||
172 | ModuleDef::TypeAlias(it) => TypeNs::TypeAlias(it), | 173 | ModuleDefId::TypeAliasId(it) => TypeNs::TypeAlias(it.into()), |
173 | ModuleDef::BuiltinType(it) => TypeNs::BuiltinType(it), | 174 | ModuleDefId::BuiltinType(it) => TypeNs::BuiltinType(it), |
174 | 175 | ||
175 | ModuleDef::Trait(it) => TypeNs::Trait(it), | 176 | ModuleDefId::TraitId(it) => TypeNs::Trait(it.into()), |
176 | 177 | ||
177 | ModuleDef::Function(_) | 178 | ModuleDefId::FunctionId(_) |
178 | | ModuleDef::Const(_) | 179 | | ModuleDefId::ConstId(_) |
179 | | ModuleDef::Static(_) | 180 | | ModuleDefId::StaticId(_) |
180 | | ModuleDef::Module(_) => return None, | 181 | | ModuleDefId::ModuleId(_) => return None, |
181 | }; | 182 | }; |
182 | return Some((res, idx)); | 183 | return Some((res, idx)); |
183 | } | 184 | } |
@@ -261,33 +262,35 @@ impl Resolver { | |||
261 | return match idx { | 262 | return match idx { |
262 | None => { | 263 | None => { |
263 | let value = match module_def.take_values()? { | 264 | let value = match module_def.take_values()? { |
264 | ModuleDef::Function(it) => ValueNs::Function(it), | 265 | ModuleDefId::FunctionId(it) => ValueNs::Function(it.into()), |
265 | ModuleDef::Adt(Adt::Struct(it)) => ValueNs::Struct(it), | 266 | ModuleDefId::AdtId(AdtId::StructId(it)) => { |
266 | ModuleDef::EnumVariant(it) => ValueNs::EnumVariant(it), | 267 | ValueNs::Struct(it.into()) |
267 | ModuleDef::Const(it) => ValueNs::Const(it), | 268 | } |
268 | ModuleDef::Static(it) => ValueNs::Static(it), | 269 | ModuleDefId::EnumVariantId(it) => ValueNs::EnumVariant(it.into()), |
269 | 270 | ModuleDefId::ConstId(it) => ValueNs::Const(it.into()), | |
270 | ModuleDef::Adt(Adt::Enum(_)) | 271 | ModuleDefId::StaticId(it) => ValueNs::Static(it.into()), |
271 | | ModuleDef::Adt(Adt::Union(_)) | 272 | |
272 | | ModuleDef::Trait(_) | 273 | ModuleDefId::AdtId(AdtId::EnumId(_)) |
273 | | ModuleDef::TypeAlias(_) | 274 | | ModuleDefId::AdtId(AdtId::UnionId(_)) |
274 | | ModuleDef::BuiltinType(_) | 275 | | ModuleDefId::TraitId(_) |
275 | | ModuleDef::Module(_) => return None, | 276 | | ModuleDefId::TypeAliasId(_) |
277 | | ModuleDefId::BuiltinType(_) | ||
278 | | ModuleDefId::ModuleId(_) => return None, | ||
276 | }; | 279 | }; |
277 | Some(ResolveValueResult::ValueNs(value)) | 280 | Some(ResolveValueResult::ValueNs(value)) |
278 | } | 281 | } |
279 | Some(idx) => { | 282 | Some(idx) => { |
280 | let ty = match module_def.take_types()? { | 283 | let ty = match module_def.take_types()? { |
281 | ModuleDef::Adt(it) => TypeNs::Adt(it), | 284 | ModuleDefId::AdtId(it) => TypeNs::Adt(it.into()), |
282 | ModuleDef::Trait(it) => TypeNs::Trait(it), | 285 | ModuleDefId::TraitId(it) => TypeNs::Trait(it.into()), |
283 | ModuleDef::TypeAlias(it) => TypeNs::TypeAlias(it), | 286 | ModuleDefId::TypeAliasId(it) => TypeNs::TypeAlias(it.into()), |
284 | ModuleDef::BuiltinType(it) => TypeNs::BuiltinType(it), | 287 | ModuleDefId::BuiltinType(it) => TypeNs::BuiltinType(it), |
285 | 288 | ||
286 | ModuleDef::Module(_) | 289 | ModuleDefId::ModuleId(_) |
287 | | ModuleDef::Function(_) | 290 | | ModuleDefId::FunctionId(_) |
288 | | ModuleDef::EnumVariant(_) | 291 | | ModuleDefId::EnumVariantId(_) |
289 | | ModuleDef::Const(_) | 292 | | ModuleDefId::ConstId(_) |
290 | | ModuleDef::Static(_) => return None, | 293 | | ModuleDefId::StaticId(_) => return None, |
291 | }; | 294 | }; |
292 | Some(ResolveValueResult::Partial(ty, idx)) | 295 | Some(ResolveValueResult::Partial(ty, idx)) |
293 | } | 296 | } |
@@ -315,7 +318,7 @@ impl Resolver { | |||
315 | path: &Path, | 318 | path: &Path, |
316 | ) -> Option<MacroDef> { | 319 | ) -> Option<MacroDef> { |
317 | let (item_map, module) = self.module()?; | 320 | let (item_map, module) = self.module()?; |
318 | item_map.resolve_path(db, module, path).0.get_macros() | 321 | item_map.resolve_path(db, module, path).0.get_macros().map(MacroDef::from) |
319 | } | 322 | } |
320 | 323 | ||
321 | pub(crate) fn process_all_names( | 324 | pub(crate) fn process_all_names( |
@@ -333,10 +336,11 @@ impl Resolver { | |||
333 | for scope in &self.scopes { | 336 | for scope in &self.scopes { |
334 | if let Scope::ModuleScope(m) = scope { | 337 | if let Scope::ModuleScope(m) = scope { |
335 | if let Some(prelude) = m.crate_def_map.prelude() { | 338 | if let Some(prelude) = m.crate_def_map.prelude() { |
336 | let prelude_def_map = db.crate_def_map(prelude.krate()); | 339 | let prelude_def_map = db.crate_def_map(prelude.krate); |
337 | traits.extend(prelude_def_map[prelude.id.module_id].scope.traits()); | 340 | traits |
341 | .extend(prelude_def_map[prelude.module_id].scope.traits().map(Trait::from)); | ||
338 | } | 342 | } |
339 | traits.extend(m.crate_def_map[m.module_id].scope.traits()); | 343 | traits.extend(m.crate_def_map[m.module_id].scope.traits().map(Trait::from)); |
340 | } | 344 | } |
341 | } | 345 | } |
342 | traits | 346 | traits |
@@ -351,7 +355,7 @@ impl Resolver { | |||
351 | } | 355 | } |
352 | 356 | ||
353 | pub(crate) fn krate(&self) -> Option<Crate> { | 357 | pub(crate) fn krate(&self) -> Option<Crate> { |
354 | self.module().map(|t| t.0.krate()) | 358 | self.module().map(|t| Crate { crate_id: t.0.krate() }) |
355 | } | 359 | } |
356 | 360 | ||
357 | pub(crate) fn where_predicates_in_scope<'a>( | 361 | pub(crate) fn where_predicates_in_scope<'a>( |
@@ -420,8 +424,10 @@ impl From<PerNs> for ScopeDef { | |||
420 | fn from(def: PerNs) -> Self { | 424 | fn from(def: PerNs) -> Self { |
421 | def.take_types() | 425 | def.take_types() |
422 | .or_else(|| def.take_values()) | 426 | .or_else(|| def.take_values()) |
423 | .map(ScopeDef::ModuleDef) | 427 | .map(|module_def_id| ScopeDef::ModuleDef(module_def_id.into())) |
424 | .or_else(|| def.get_macros().map(ScopeDef::MacroDef)) | 428 | .or_else(|| { |
429 | def.get_macros().map(|macro_def_id| ScopeDef::MacroDef(macro_def_id.into())) | ||
430 | }) | ||
425 | .unwrap_or(ScopeDef::Unknown) | 431 | .unwrap_or(ScopeDef::Unknown) |
426 | } | 432 | } |
427 | } | 433 | } |
@@ -441,18 +447,16 @@ impl Scope { | |||
441 | f(name.clone(), res.def.into()); | 447 | f(name.clone(), res.def.into()); |
442 | }); | 448 | }); |
443 | m.crate_def_map[m.module_id].scope.legacy_macros().for_each(|(name, macro_)| { | 449 | m.crate_def_map[m.module_id].scope.legacy_macros().for_each(|(name, macro_)| { |
444 | f(name.clone(), ScopeDef::MacroDef(macro_)); | 450 | f(name.clone(), ScopeDef::MacroDef(macro_.into())); |
445 | }); | 451 | }); |
446 | m.crate_def_map.extern_prelude().iter().for_each(|(name, def)| { | 452 | m.crate_def_map.extern_prelude().iter().for_each(|(name, &def)| { |
447 | f(name.clone(), ScopeDef::ModuleDef(*def)); | 453 | f(name.clone(), ScopeDef::ModuleDef(def.into())); |
448 | }); | 454 | }); |
449 | if let Some(prelude) = m.crate_def_map.prelude() { | 455 | if let Some(prelude) = m.crate_def_map.prelude() { |
450 | let prelude_def_map = db.crate_def_map(prelude.krate()); | 456 | let prelude_def_map = db.crate_def_map(prelude.krate); |
451 | prelude_def_map[prelude.id.module_id].scope.entries().for_each( | 457 | prelude_def_map[prelude.module_id].scope.entries().for_each(|(name, res)| { |
452 | |(name, res)| { | 458 | f(name.clone(), res.def.into()); |
453 | f(name.clone(), res.def.into()); | 459 | }); |
454 | }, | ||
455 | ); | ||
456 | } | 460 | } |
457 | } | 461 | } |
458 | Scope::GenericParams(gp) => { | 462 | Scope::GenericParams(gp) => { |
diff --git a/crates/ra_hir/src/source_binder.rs b/crates/ra_hir/src/source_binder.rs index a4ca59bba..66cb4b357 100644 --- a/crates/ra_hir/src/source_binder.rs +++ b/crates/ra_hir/src/source_binder.rs | |||
@@ -253,8 +253,11 @@ impl SourceAnalyzer { | |||
253 | Some(res) | 253 | Some(res) |
254 | }); | 254 | }); |
255 | 255 | ||
256 | let items = | 256 | let items = self |
257 | self.resolver.resolve_module_path(db, &path).take_types().map(PathResolution::Def); | 257 | .resolver |
258 | .resolve_module_path(db, &path) | ||
259 | .take_types() | ||
260 | .map(|it| PathResolution::Def(it.into())); | ||
258 | types.or(values).or(items).or_else(|| { | 261 | types.or(values).or(items).or_else(|| { |
259 | self.resolver.resolve_path_as_macro(db, &path).map(|def| PathResolution::Macro(def)) | 262 | self.resolver.resolve_path_as_macro(db, &path).map(|def| PathResolution::Macro(def)) |
260 | }) | 263 | }) |
diff --git a/crates/ra_hir/src/ty/tests.rs b/crates/ra_hir/src/ty/tests.rs index bfef48b16..f27155737 100644 --- a/crates/ra_hir/src/ty/tests.rs +++ b/crates/ra_hir/src/ty/tests.rs | |||
@@ -3403,7 +3403,7 @@ fn test() { S.foo()<|>; } | |||
3403 | 3403 | ||
3404 | #[test] | 3404 | #[test] |
3405 | fn infer_macro_with_dollar_crate_is_correct_in_expr() { | 3405 | fn infer_macro_with_dollar_crate_is_correct_in_expr() { |
3406 | covers!(macro_dollar_crate_other); | 3406 | // covers!(macro_dollar_crate_other); |
3407 | let (mut db, pos) = MockDatabase::with_position( | 3407 | let (mut db, pos) = MockDatabase::with_position( |
3408 | r#" | 3408 | r#" |
3409 | //- /main.rs | 3409 | //- /main.rs |