diff options
Diffstat (limited to 'crates/ra_hir')
33 files changed, 1771 insertions, 1695 deletions
diff --git a/crates/ra_hir/Cargo.toml b/crates/ra_hir/Cargo.toml index cc117f84d..edf1fa49b 100644 --- a/crates/ra_hir/Cargo.toml +++ b/crates/ra_hir/Cargo.toml | |||
@@ -5,9 +5,9 @@ version = "0.1.0" | |||
5 | authors = ["rust-analyzer developers"] | 5 | authors = ["rust-analyzer developers"] |
6 | 6 | ||
7 | [dependencies] | 7 | [dependencies] |
8 | arrayvec = "0.4.10" | 8 | arrayvec = "0.5.1" |
9 | log = "0.4.5" | 9 | log = "0.4.5" |
10 | relative-path = "0.4.0" | 10 | relative-path = "1.0.0" |
11 | rustc-hash = "1.0" | 11 | rustc-hash = "1.0" |
12 | parking_lot = "0.9.0" | 12 | parking_lot = "0.9.0" |
13 | ena = "0.13" | 13 | ena = "0.13" |
diff --git a/crates/ra_hir/src/adt.rs b/crates/ra_hir/src/adt.rs index 99d286215..3e9cd3c63 100644 --- a/crates/ra_hir/src/adt.rs +++ b/crates/ra_hir/src/adt.rs | |||
@@ -9,7 +9,7 @@ use ra_syntax::ast::{self, NameOwner, StructKind, TypeAscriptionOwner}; | |||
9 | use crate::{ | 9 | use crate::{ |
10 | db::{AstDatabase, DefDatabase, HirDatabase}, | 10 | db::{AstDatabase, DefDatabase, HirDatabase}, |
11 | type_ref::TypeRef, | 11 | type_ref::TypeRef, |
12 | AsName, Enum, EnumVariant, FieldSource, HasSource, Name, Source, Struct, StructField, | 12 | AsName, Enum, EnumVariant, FieldSource, HasSource, Module, Name, Source, Struct, StructField, |
13 | }; | 13 | }; |
14 | 14 | ||
15 | impl Struct { | 15 | impl Struct { |
@@ -170,12 +170,20 @@ impl VariantDef { | |||
170 | } | 170 | } |
171 | } | 171 | } |
172 | 172 | ||
173 | pub(crate) fn field(self, db: &impl HirDatabase, name: &Name) -> Option<StructField> { | 173 | pub fn field(self, db: &impl HirDatabase, name: &Name) -> Option<StructField> { |
174 | match self { | 174 | match self { |
175 | VariantDef::Struct(it) => it.field(db, name), | 175 | VariantDef::Struct(it) => it.field(db, name), |
176 | VariantDef::EnumVariant(it) => it.field(db, name), | 176 | VariantDef::EnumVariant(it) => it.field(db, name), |
177 | } | 177 | } |
178 | } | 178 | } |
179 | |||
180 | pub fn module(self, db: &impl HirDatabase) -> Module { | ||
181 | match self { | ||
182 | VariantDef::Struct(it) => it.module(db), | ||
183 | VariantDef::EnumVariant(it) => it.module(db), | ||
184 | } | ||
185 | } | ||
186 | |||
179 | pub(crate) fn variant_data(self, db: &impl DefDatabase) -> Arc<VariantData> { | 187 | pub(crate) fn variant_data(self, db: &impl DefDatabase) -> Arc<VariantData> { |
180 | match self { | 188 | match self { |
181 | VariantDef::Struct(it) => it.variant_data(db), | 189 | VariantDef::Struct(it) => it.variant_data(db), |
diff --git a/crates/ra_hir/src/attr.rs b/crates/ra_hir/src/attr.rs index f67e80bfd..bd159a566 100644 --- a/crates/ra_hir/src/attr.rs +++ b/crates/ra_hir/src/attr.rs | |||
@@ -63,14 +63,24 @@ impl Attr { | |||
63 | self.path.as_ident().map_or(false, |s| s.to_string() == name) | 63 | self.path.as_ident().map_or(false, |s| s.to_string() == name) |
64 | } | 64 | } |
65 | 65 | ||
66 | // FIXME: handle cfg_attr :-) | ||
66 | pub(crate) fn as_cfg(&self) -> Option<&Subtree> { | 67 | pub(crate) fn as_cfg(&self) -> Option<&Subtree> { |
67 | if self.is_simple_atom("cfg") { | 68 | if !self.is_simple_atom("cfg") { |
68 | match &self.input { | 69 | return None; |
69 | Some(AttrInput::TokenTree(subtree)) => Some(subtree), | 70 | } |
70 | _ => None, | 71 | match &self.input { |
71 | } | 72 | Some(AttrInput::TokenTree(subtree)) => Some(subtree), |
72 | } else { | 73 | _ => None, |
73 | None | 74 | } |
75 | } | ||
76 | |||
77 | pub(crate) fn as_path(&self) -> Option<&SmolStr> { | ||
78 | if !self.is_simple_atom("path") { | ||
79 | return None; | ||
80 | } | ||
81 | match &self.input { | ||
82 | Some(AttrInput::Literal(it)) => Some(it), | ||
83 | _ => None, | ||
74 | } | 84 | } |
75 | } | 85 | } |
76 | 86 | ||
diff --git a/crates/ra_hir/src/code_model.rs b/crates/ra_hir/src/code_model.rs index e3a7e8e3c..8eb3c577d 100644 --- a/crates/ra_hir/src/code_model.rs +++ b/crates/ra_hir/src/code_model.rs | |||
@@ -5,7 +5,7 @@ pub(crate) mod docs; | |||
5 | 5 | ||
6 | use std::sync::Arc; | 6 | use std::sync::Arc; |
7 | 7 | ||
8 | use ra_db::{CrateId, Edition, FileId, SourceRootId}; | 8 | use ra_db::{CrateId, Edition, FileId}; |
9 | use ra_syntax::ast::{self, NameOwner, TypeAscriptionOwner}; | 9 | use ra_syntax::ast::{self, NameOwner, TypeAscriptionOwner}; |
10 | 10 | ||
11 | use crate::{ | 11 | use crate::{ |
@@ -24,7 +24,7 @@ use crate::{ | |||
24 | U8, USIZE, | 24 | U8, USIZE, |
25 | }, | 25 | }, |
26 | nameres::{CrateModuleId, ImportId, ModuleScope, Namespace}, | 26 | nameres::{CrateModuleId, ImportId, ModuleScope, Namespace}, |
27 | resolve::{Resolver, TypeNs}, | 27 | resolve::{Resolver, Scope, TypeNs}, |
28 | traits::TraitData, | 28 | traits::TraitData, |
29 | ty::{ | 29 | ty::{ |
30 | primitive::{FloatBitness, FloatTy, IntBitness, IntTy, Signedness}, | 30 | primitive::{FloatBitness, FloatTy, IntBitness, IntTy, Signedness}, |
@@ -76,10 +76,8 @@ impl Crate { | |||
76 | crate_graph.edition(self.crate_id) | 76 | crate_graph.edition(self.crate_id) |
77 | } | 77 | } |
78 | 78 | ||
79 | // FIXME: should this be in source_binder? | 79 | pub fn all(db: &impl DefDatabase) -> Vec<Crate> { |
80 | pub fn source_root_crates(db: &impl DefDatabase, source_root: SourceRootId) -> Vec<Crate> { | 80 | db.crate_graph().iter().map(|crate_id| Crate { crate_id }).collect() |
81 | let crate_ids = db.source_root_crates(source_root); | ||
82 | crate_ids.iter().map(|&crate_id| Crate { crate_id }).collect() | ||
83 | } | 81 | } |
84 | } | 82 | } |
85 | 83 | ||
@@ -465,7 +463,7 @@ impl Enum { | |||
465 | // ...and add generic params, if present | 463 | // ...and add generic params, if present |
466 | let p = self.generic_params(db); | 464 | let p = self.generic_params(db); |
467 | let r = if !p.params.is_empty() { r.push_generic_params_scope(p) } else { r }; | 465 | let r = if !p.params.is_empty() { r.push_generic_params_scope(p) } else { r }; |
468 | r | 466 | r.push_scope(Scope::AdtScope(self.into())) |
469 | } | 467 | } |
470 | } | 468 | } |
471 | 469 | ||
@@ -569,6 +567,14 @@ impl DefWithBody { | |||
569 | DefWithBody::Static(s) => s.krate(db), | 567 | DefWithBody::Static(s) => s.krate(db), |
570 | } | 568 | } |
571 | } | 569 | } |
570 | |||
571 | pub fn module(self, db: &impl HirDatabase) -> Module { | ||
572 | match self { | ||
573 | DefWithBody::Const(c) => c.module(db), | ||
574 | DefWithBody::Function(f) => f.module(db), | ||
575 | DefWithBody::Static(s) => s.module(db), | ||
576 | } | ||
577 | } | ||
572 | } | 578 | } |
573 | 579 | ||
574 | pub trait HasBody: Copy { | 580 | pub trait HasBody: Copy { |
@@ -789,6 +795,20 @@ impl Const { | |||
789 | ImplBlock::containing(module_impls, self.into()) | 795 | ImplBlock::containing(module_impls, self.into()) |
790 | } | 796 | } |
791 | 797 | ||
798 | pub fn parent_trait(self, db: &impl DefDatabase) -> Option<Trait> { | ||
799 | db.trait_items_index(self.module(db)).get_parent_trait(self.into()) | ||
800 | } | ||
801 | |||
802 | pub fn container(self, db: &impl DefDatabase) -> Option<Container> { | ||
803 | if let Some(impl_block) = self.impl_block(db) { | ||
804 | Some(impl_block.into()) | ||
805 | } else if let Some(trait_) = self.parent_trait(db) { | ||
806 | Some(trait_.into()) | ||
807 | } else { | ||
808 | None | ||
809 | } | ||
810 | } | ||
811 | |||
792 | // FIXME: move to a more general type for 'body-having' items | 812 | // FIXME: move to a more general type for 'body-having' items |
793 | /// Builds a resolver for code inside this item. | 813 | /// Builds a resolver for code inside this item. |
794 | pub(crate) fn resolver(self, db: &impl HirDatabase) -> Resolver { | 814 | pub(crate) fn resolver(self, db: &impl HirDatabase) -> Resolver { |
@@ -1075,3 +1095,13 @@ impl From<AssocItem> for crate::generics::GenericDef { | |||
1075 | } | 1095 | } |
1076 | } | 1096 | } |
1077 | } | 1097 | } |
1098 | |||
1099 | impl AssocItem { | ||
1100 | pub fn module(self, db: &impl DefDatabase) -> Module { | ||
1101 | match self { | ||
1102 | AssocItem::Function(f) => f.module(db), | ||
1103 | AssocItem::Const(c) => c.module(db), | ||
1104 | AssocItem::TypeAlias(t) => t.module(db), | ||
1105 | } | ||
1106 | } | ||
1107 | } | ||
diff --git a/crates/ra_hir/src/code_model/docs.rs b/crates/ra_hir/src/code_model/docs.rs index 9675e397f..8533b4f5e 100644 --- a/crates/ra_hir/src/code_model/docs.rs +++ b/crates/ra_hir/src/code_model/docs.rs | |||
@@ -6,21 +6,19 @@ use ra_syntax::ast; | |||
6 | 6 | ||
7 | use crate::{ | 7 | use crate::{ |
8 | db::{AstDatabase, DefDatabase, HirDatabase}, | 8 | db::{AstDatabase, DefDatabase, HirDatabase}, |
9 | Const, Enum, EnumVariant, FieldSource, Function, HasSource, MacroDef, Module, Static, Struct, | 9 | Adt, Const, Enum, EnumVariant, FieldSource, Function, HasSource, MacroDef, Module, Static, |
10 | StructField, Trait, TypeAlias, Union, | 10 | Struct, StructField, Trait, TypeAlias, Union, |
11 | }; | 11 | }; |
12 | 12 | ||
13 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] | 13 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] |
14 | pub enum DocDef { | 14 | pub enum DocDef { |
15 | Module(Module), | 15 | Module(Module), |
16 | StructField(StructField), | 16 | StructField(StructField), |
17 | Struct(Struct), | 17 | Adt(Adt), |
18 | Enum(Enum), | ||
19 | EnumVariant(EnumVariant), | 18 | EnumVariant(EnumVariant), |
20 | Static(Static), | 19 | Static(Static), |
21 | Const(Const), | 20 | Const(Const), |
22 | Function(Function), | 21 | Function(Function), |
23 | Union(Union), | ||
24 | Trait(Trait), | 22 | Trait(Trait), |
25 | TypeAlias(TypeAlias), | 23 | TypeAlias(TypeAlias), |
26 | MacroDef(MacroDef), | 24 | MacroDef(MacroDef), |
@@ -29,13 +27,11 @@ pub enum DocDef { | |||
29 | impl_froms!( | 27 | impl_froms!( |
30 | DocDef: Module, | 28 | DocDef: Module, |
31 | StructField, | 29 | StructField, |
32 | Struct, | 30 | Adt(Struct, Enum, Union), |
33 | Enum, | ||
34 | EnumVariant, | 31 | EnumVariant, |
35 | Static, | 32 | Static, |
36 | Const, | 33 | Const, |
37 | Function, | 34 | Function, |
38 | Union, | ||
39 | Trait, | 35 | Trait, |
40 | TypeAlias, | 36 | TypeAlias, |
41 | MacroDef | 37 | MacroDef |
@@ -79,13 +75,15 @@ pub(crate) fn documentation_query( | |||
79 | FieldSource::Named(named) => docs_from_ast(&named), | 75 | FieldSource::Named(named) => docs_from_ast(&named), |
80 | FieldSource::Pos(..) => None, | 76 | FieldSource::Pos(..) => None, |
81 | }, | 77 | }, |
82 | DocDef::Struct(it) => docs_from_ast(&it.source(db).ast), | 78 | DocDef::Adt(it) => match it { |
83 | DocDef::Enum(it) => docs_from_ast(&it.source(db).ast), | 79 | Adt::Struct(it) => docs_from_ast(&it.source(db).ast), |
80 | Adt::Enum(it) => docs_from_ast(&it.source(db).ast), | ||
81 | Adt::Union(it) => docs_from_ast(&it.source(db).ast), | ||
82 | }, | ||
84 | DocDef::EnumVariant(it) => docs_from_ast(&it.source(db).ast), | 83 | DocDef::EnumVariant(it) => docs_from_ast(&it.source(db).ast), |
85 | DocDef::Static(it) => docs_from_ast(&it.source(db).ast), | 84 | DocDef::Static(it) => docs_from_ast(&it.source(db).ast), |
86 | DocDef::Const(it) => docs_from_ast(&it.source(db).ast), | 85 | DocDef::Const(it) => docs_from_ast(&it.source(db).ast), |
87 | DocDef::Function(it) => docs_from_ast(&it.source(db).ast), | 86 | DocDef::Function(it) => docs_from_ast(&it.source(db).ast), |
88 | DocDef::Union(it) => docs_from_ast(&it.source(db).ast), | ||
89 | DocDef::Trait(it) => docs_from_ast(&it.source(db).ast), | 87 | DocDef::Trait(it) => docs_from_ast(&it.source(db).ast), |
90 | DocDef::TypeAlias(it) => docs_from_ast(&it.source(db).ast), | 88 | DocDef::TypeAlias(it) => docs_from_ast(&it.source(db).ast), |
91 | DocDef::MacroDef(it) => docs_from_ast(&it.source(db).ast), | 89 | DocDef::MacroDef(it) => docs_from_ast(&it.source(db).ast), |
diff --git a/crates/ra_hir/src/db.rs b/crates/ra_hir/src/db.rs index 73d7d6fb6..489a3b19c 100644 --- a/crates/ra_hir/src/db.rs +++ b/crates/ra_hir/src/db.rs | |||
@@ -111,37 +111,37 @@ pub trait DefDatabase: InternDatabase + HirDebugDatabase { | |||
111 | #[salsa::invoke(CrateDefMap::crate_def_map_query)] | 111 | #[salsa::invoke(CrateDefMap::crate_def_map_query)] |
112 | fn crate_def_map(&self, krate: Crate) -> Arc<CrateDefMap>; | 112 | fn crate_def_map(&self, krate: Crate) -> Arc<CrateDefMap>; |
113 | 113 | ||
114 | #[salsa::invoke(crate::impl_block::impls_in_module_with_source_map_query)] | 114 | #[salsa::invoke(ModuleImplBlocks::impls_in_module_with_source_map_query)] |
115 | fn impls_in_module_with_source_map( | 115 | fn impls_in_module_with_source_map( |
116 | &self, | 116 | &self, |
117 | module: Module, | 117 | module: Module, |
118 | ) -> (Arc<ModuleImplBlocks>, Arc<ImplSourceMap>); | 118 | ) -> (Arc<ModuleImplBlocks>, Arc<ImplSourceMap>); |
119 | 119 | ||
120 | #[salsa::invoke(crate::impl_block::impls_in_module)] | 120 | #[salsa::invoke(ModuleImplBlocks::impls_in_module_query)] |
121 | fn impls_in_module(&self, module: Module) -> Arc<ModuleImplBlocks>; | 121 | fn impls_in_module(&self, module: Module) -> Arc<ModuleImplBlocks>; |
122 | 122 | ||
123 | #[salsa::invoke(crate::generics::GenericParams::generic_params_query)] | 123 | #[salsa::invoke(crate::generics::GenericParams::generic_params_query)] |
124 | fn generic_params(&self, def: GenericDef) -> Arc<GenericParams>; | 124 | fn generic_params(&self, def: GenericDef) -> Arc<GenericParams>; |
125 | 125 | ||
126 | #[salsa::invoke(crate::FnData::fn_data_query)] | 126 | #[salsa::invoke(FnData::fn_data_query)] |
127 | fn fn_data(&self, func: Function) -> Arc<FnData>; | 127 | fn fn_data(&self, func: Function) -> Arc<FnData>; |
128 | 128 | ||
129 | #[salsa::invoke(crate::type_alias::type_alias_data_query)] | 129 | #[salsa::invoke(TypeAliasData::type_alias_data_query)] |
130 | fn type_alias_data(&self, typ: TypeAlias) -> Arc<TypeAliasData>; | 130 | fn type_alias_data(&self, typ: TypeAlias) -> Arc<TypeAliasData>; |
131 | 131 | ||
132 | #[salsa::invoke(crate::ConstData::const_data_query)] | 132 | #[salsa::invoke(ConstData::const_data_query)] |
133 | fn const_data(&self, konst: Const) -> Arc<ConstData>; | 133 | fn const_data(&self, konst: Const) -> Arc<ConstData>; |
134 | 134 | ||
135 | #[salsa::invoke(crate::ConstData::static_data_query)] | 135 | #[salsa::invoke(ConstData::static_data_query)] |
136 | fn static_data(&self, konst: Static) -> Arc<ConstData>; | 136 | fn static_data(&self, konst: Static) -> Arc<ConstData>; |
137 | 137 | ||
138 | #[salsa::invoke(crate::lang_item::LangItems::module_lang_items_query)] | 138 | #[salsa::invoke(LangItems::module_lang_items_query)] |
139 | fn module_lang_items(&self, module: Module) -> Option<Arc<LangItems>>; | 139 | fn module_lang_items(&self, module: Module) -> Option<Arc<LangItems>>; |
140 | 140 | ||
141 | #[salsa::invoke(crate::lang_item::LangItems::crate_lang_items_query)] | 141 | #[salsa::invoke(LangItems::crate_lang_items_query)] |
142 | fn crate_lang_items(&self, krate: Crate) -> Arc<LangItems>; | 142 | fn crate_lang_items(&self, krate: Crate) -> Arc<LangItems>; |
143 | 143 | ||
144 | #[salsa::invoke(crate::lang_item::LangItems::lang_item_query)] | 144 | #[salsa::invoke(LangItems::lang_item_query)] |
145 | fn lang_item(&self, start_crate: Crate, item: SmolStr) -> Option<LangItemTarget>; | 145 | fn lang_item(&self, start_crate: Crate, item: SmolStr) -> Option<LangItemTarget>; |
146 | 146 | ||
147 | #[salsa::invoke(crate::code_model::docs::documentation_query)] | 147 | #[salsa::invoke(crate::code_model::docs::documentation_query)] |
diff --git a/crates/ra_hir/src/debug.rs b/crates/ra_hir/src/debug.rs index 87f3180c3..48b69000b 100644 --- a/crates/ra_hir/src/debug.rs +++ b/crates/ra_hir/src/debug.rs | |||
@@ -22,7 +22,7 @@ use std::fmt; | |||
22 | 22 | ||
23 | use ra_db::{CrateId, FileId}; | 23 | use ra_db::{CrateId, FileId}; |
24 | 24 | ||
25 | use crate::{db::HirDatabase, Crate, Module, Name}; | 25 | use crate::{db::HirDatabase, Crate, HirFileId, Module, Name}; |
26 | 26 | ||
27 | impl Crate { | 27 | impl Crate { |
28 | pub fn debug(self, db: &impl HirDebugDatabase) -> impl fmt::Debug + '_ { | 28 | pub fn debug(self, db: &impl HirDebugDatabase) -> impl fmt::Debug + '_ { |
@@ -36,6 +36,12 @@ impl Module { | |||
36 | } | 36 | } |
37 | } | 37 | } |
38 | 38 | ||
39 | impl HirFileId { | ||
40 | pub fn debug(self, db: &impl HirDebugDatabase) -> impl fmt::Debug + '_ { | ||
41 | debug_fn(move |fmt| db.debug_hir_file_id(self, fmt)) | ||
42 | } | ||
43 | } | ||
44 | |||
39 | pub trait HirDebugHelper: HirDatabase { | 45 | pub trait HirDebugHelper: HirDatabase { |
40 | fn crate_name(&self, _krate: CrateId) -> Option<String> { | 46 | fn crate_name(&self, _krate: CrateId) -> Option<String> { |
41 | None | 47 | None |
@@ -48,6 +54,7 @@ pub trait HirDebugHelper: HirDatabase { | |||
48 | pub trait HirDebugDatabase { | 54 | pub trait HirDebugDatabase { |
49 | fn debug_crate(&self, krate: Crate, fmt: &mut fmt::Formatter<'_>) -> fmt::Result; | 55 | fn debug_crate(&self, krate: Crate, fmt: &mut fmt::Formatter<'_>) -> fmt::Result; |
50 | fn debug_module(&self, module: Module, fmt: &mut fmt::Formatter<'_>) -> fmt::Result; | 56 | fn debug_module(&self, module: Module, fmt: &mut fmt::Formatter<'_>) -> fmt::Result; |
57 | fn debug_hir_file_id(&self, file_id: HirFileId, fmt: &mut fmt::Formatter<'_>) -> fmt::Result; | ||
51 | } | 58 | } |
52 | 59 | ||
53 | impl<DB: HirDebugHelper> HirDebugDatabase for DB { | 60 | impl<DB: HirDebugHelper> HirDebugDatabase for DB { |
@@ -62,12 +69,19 @@ impl<DB: HirDebugHelper> HirDebugDatabase for DB { | |||
62 | 69 | ||
63 | fn debug_module(&self, module: Module, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { | 70 | fn debug_module(&self, module: Module, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { |
64 | let file_id = module.definition_source(self).file_id.original_file(self); | 71 | let file_id = module.definition_source(self).file_id.original_file(self); |
65 | let path = self.file_path(file_id); | 72 | let path = self.file_path(file_id).unwrap_or_else(|| "N/A".to_string()); |
66 | fmt.debug_struct("Module") | 73 | fmt.debug_struct("Module") |
67 | .field("name", &module.name(self).unwrap_or_else(Name::missing)) | 74 | .field("name", &module.name(self).unwrap_or_else(Name::missing)) |
68 | .field("path", &path.unwrap_or_else(|| "N/A".to_string())) | 75 | .field("path", &path) |
69 | .finish() | 76 | .finish() |
70 | } | 77 | } |
78 | |||
79 | fn debug_hir_file_id(&self, file_id: HirFileId, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
80 | let original = file_id.original_file(self); | ||
81 | let path = self.file_path(original).unwrap_or_else(|| "N/A".to_string()); | ||
82 | let is_macro = file_id != original.into(); | ||
83 | fmt.debug_struct("HirFileId").field("path", &path).field("macro", &is_macro).finish() | ||
84 | } | ||
71 | } | 85 | } |
72 | 86 | ||
73 | fn debug_fn(f: impl Fn(&mut fmt::Formatter<'_>) -> fmt::Result) -> impl fmt::Debug { | 87 | fn debug_fn(f: impl Fn(&mut fmt::Formatter<'_>) -> fmt::Result) -> impl fmt::Debug { |
diff --git a/crates/ra_hir/src/from_source.rs b/crates/ra_hir/src/from_source.rs index a012f33f7..f80d8eb5f 100644 --- a/crates/ra_hir/src/from_source.rs +++ b/crates/ra_hir/src/from_source.rs | |||
@@ -189,14 +189,14 @@ impl Module { | |||
189 | ModuleSource::SourceFile(_) => None, | 189 | ModuleSource::SourceFile(_) => None, |
190 | }; | 190 | }; |
191 | 191 | ||
192 | let source_root_id = db.file_source_root(src.file_id.original_file(db)); | 192 | db.relevant_crates(src.file_id.original_file(db)) |
193 | db.source_root_crates(source_root_id).iter().map(|&crate_id| Crate { crate_id }).find_map( | 193 | .iter() |
194 | |krate| { | 194 | .map(|&crate_id| Crate { crate_id }) |
195 | .find_map(|krate| { | ||
195 | let def_map = db.crate_def_map(krate); | 196 | let def_map = db.crate_def_map(krate); |
196 | let module_id = def_map.find_module_by_source(src.file_id, decl_id)?; | 197 | let module_id = def_map.find_module_by_source(src.file_id, decl_id)?; |
197 | Some(Module { krate, module_id }) | 198 | Some(Module { krate, module_id }) |
198 | }, | 199 | }) |
199 | ) | ||
200 | } | 200 | } |
201 | } | 201 | } |
202 | 202 | ||
diff --git a/crates/ra_hir/src/ids.rs b/crates/ra_hir/src/ids.rs index a3b65cc79..499dcafea 100644 --- a/crates/ra_hir/src/ids.rs +++ b/crates/ra_hir/src/ids.rs | |||
@@ -50,16 +50,6 @@ impl HirFileId { | |||
50 | } | 50 | } |
51 | } | 51 | } |
52 | 52 | ||
53 | /// XXX: this is a temporary function, which should go away when we implement the | ||
54 | /// nameresolution+macro expansion combo. Prefer using `original_file` if | ||
55 | /// possible. | ||
56 | pub fn as_original_file(self) -> FileId { | ||
57 | match self.0 { | ||
58 | HirFileIdRepr::File(file_id) => file_id, | ||
59 | HirFileIdRepr::Macro(_r) => panic!("macro generated file: {:?}", self), | ||
60 | } | ||
61 | } | ||
62 | |||
63 | /// Get the crate which the macro lives in, if it is a macro file. | 53 | /// Get the crate which the macro lives in, if it is a macro file. |
64 | pub(crate) fn macro_crate(self, db: &impl AstDatabase) -> Option<Crate> { | 54 | pub(crate) fn macro_crate(self, db: &impl AstDatabase) -> Option<Crate> { |
65 | match self.0 { | 55 | match self.0 { |
@@ -95,11 +85,7 @@ impl HirFileId { | |||
95 | // Note: | 85 | // Note: |
96 | // The final goal we would like to make all parse_macro success, | 86 | // The final goal we would like to make all parse_macro success, |
97 | // such that the following log will not call anyway. | 87 | // such that the following log will not call anyway. |
98 | log::warn!( | 88 | log::warn!("fail on macro_parse: (reason: {})", err,); |
99 | "fail on macro_parse: (reason: {}) {}", | ||
100 | err, | ||
101 | macro_call_id.debug_dump(db) | ||
102 | ); | ||
103 | }) | 89 | }) |
104 | .ok()?; | 90 | .ok()?; |
105 | match macro_file.macro_file_kind { | 91 | match macro_file.macro_file_kind { |
@@ -377,35 +363,6 @@ impl AstItemDef<ast::TypeAliasDef> for TypeAliasId { | |||
377 | } | 363 | } |
378 | } | 364 | } |
379 | 365 | ||
380 | impl MacroCallId { | ||
381 | pub fn debug_dump(self, db: &impl AstDatabase) -> String { | ||
382 | let loc = self.loc(db); | ||
383 | let node = loc.ast_id.to_node(db); | ||
384 | let syntax_str = { | ||
385 | let mut res = String::new(); | ||
386 | node.syntax().text().for_each_chunk(|chunk| { | ||
387 | if !res.is_empty() { | ||
388 | res.push(' ') | ||
389 | } | ||
390 | res.push_str(chunk) | ||
391 | }); | ||
392 | res | ||
393 | }; | ||
394 | |||
395 | // dump the file name | ||
396 | let file_id: HirFileId = self.loc(db).ast_id.file_id(); | ||
397 | let original = file_id.original_file(db); | ||
398 | let macro_rules = db.macro_def(loc.def); | ||
399 | |||
400 | format!( | ||
401 | "macro call [file: {:?}] : {}\nhas rules: {}", | ||
402 | db.file_relative_path(original), | ||
403 | syntax_str, | ||
404 | macro_rules.is_some() | ||
405 | ) | ||
406 | } | ||
407 | } | ||
408 | |||
409 | /// This exists just for Chalk, because Chalk just has a single `StructId` where | 366 | /// This exists just for Chalk, because Chalk just has a single `StructId` where |
410 | /// we have different kinds of ADTs, primitive types and special type | 367 | /// we have different kinds of ADTs, primitive types and special type |
411 | /// constructors like tuples and function pointers. | 368 | /// constructors like tuples and function pointers. |
diff --git a/crates/ra_hir/src/impl_block.rs b/crates/ra_hir/src/impl_block.rs index 55dfc393b..33ef87563 100644 --- a/crates/ra_hir/src/impl_block.rs +++ b/crates/ra_hir/src/impl_block.rs | |||
@@ -176,6 +176,25 @@ pub struct ModuleImplBlocks { | |||
176 | } | 176 | } |
177 | 177 | ||
178 | impl ModuleImplBlocks { | 178 | impl ModuleImplBlocks { |
179 | pub(crate) fn impls_in_module_with_source_map_query( | ||
180 | db: &(impl DefDatabase + AstDatabase), | ||
181 | module: Module, | ||
182 | ) -> (Arc<ModuleImplBlocks>, Arc<ImplSourceMap>) { | ||
183 | let mut source_map = ImplSourceMap::default(); | ||
184 | let crate_graph = db.crate_graph(); | ||
185 | let cfg_options = crate_graph.cfg_options(module.krate.crate_id()); | ||
186 | |||
187 | let result = ModuleImplBlocks::collect(db, cfg_options, module, &mut source_map); | ||
188 | (Arc::new(result), Arc::new(source_map)) | ||
189 | } | ||
190 | |||
191 | pub(crate) fn impls_in_module_query( | ||
192 | db: &impl DefDatabase, | ||
193 | module: Module, | ||
194 | ) -> Arc<ModuleImplBlocks> { | ||
195 | db.impls_in_module_with_source_map(module).0 | ||
196 | } | ||
197 | |||
179 | fn collect( | 198 | fn collect( |
180 | db: &(impl DefDatabase + AstDatabase), | 199 | db: &(impl DefDatabase + AstDatabase), |
181 | cfg_options: &CfgOptions, | 200 | cfg_options: &CfgOptions, |
@@ -264,19 +283,3 @@ impl ModuleImplBlocks { | |||
264 | } | 283 | } |
265 | } | 284 | } |
266 | } | 285 | } |
267 | |||
268 | pub(crate) fn impls_in_module_with_source_map_query( | ||
269 | db: &(impl DefDatabase + AstDatabase), | ||
270 | module: Module, | ||
271 | ) -> (Arc<ModuleImplBlocks>, Arc<ImplSourceMap>) { | ||
272 | let mut source_map = ImplSourceMap::default(); | ||
273 | let crate_graph = db.crate_graph(); | ||
274 | let cfg_options = crate_graph.cfg_options(module.krate.crate_id()); | ||
275 | |||
276 | let result = ModuleImplBlocks::collect(db, cfg_options, module, &mut source_map); | ||
277 | (Arc::new(result), Arc::new(source_map)) | ||
278 | } | ||
279 | |||
280 | pub(crate) fn impls_in_module(db: &impl DefDatabase, module: Module) -> Arc<ModuleImplBlocks> { | ||
281 | db.impls_in_module_with_source_map(module).0 | ||
282 | } | ||
diff --git a/crates/ra_hir/src/lib.rs b/crates/ra_hir/src/lib.rs index 4340e9d34..ca261e8f5 100644 --- a/crates/ra_hir/src/lib.rs +++ b/crates/ra_hir/src/lib.rs | |||
@@ -51,6 +51,7 @@ mod lang_item; | |||
51 | mod generics; | 51 | mod generics; |
52 | mod resolve; | 52 | mod resolve; |
53 | pub mod diagnostics; | 53 | pub mod diagnostics; |
54 | mod util; | ||
54 | 55 | ||
55 | mod code_model; | 56 | mod code_model; |
56 | 57 | ||
@@ -71,7 +72,7 @@ pub use self::{ | |||
71 | either::Either, | 72 | either::Either, |
72 | expr::ExprScopes, | 73 | expr::ExprScopes, |
73 | from_source::FromSource, | 74 | from_source::FromSource, |
74 | generics::{GenericParam, GenericParams, HasGenericParams}, | 75 | generics::{GenericDef, GenericParam, GenericParams, HasGenericParams}, |
75 | ids::{HirFileId, MacroCallId, MacroCallLoc, MacroDefId, MacroFile}, | 76 | ids::{HirFileId, MacroCallId, MacroCallLoc, MacroDefId, MacroFile}, |
76 | impl_block::ImplBlock, | 77 | impl_block::ImplBlock, |
77 | name::Name, | 78 | name::Name, |
diff --git a/crates/ra_hir/src/mock.rs b/crates/ra_hir/src/mock.rs index f750986b8..0b278deb3 100644 --- a/crates/ra_hir/src/mock.rs +++ b/crates/ra_hir/src/mock.rs | |||
@@ -5,10 +5,10 @@ use std::{panic, sync::Arc}; | |||
5 | use parking_lot::Mutex; | 5 | use parking_lot::Mutex; |
6 | use ra_cfg::CfgOptions; | 6 | use ra_cfg::CfgOptions; |
7 | use ra_db::{ | 7 | use ra_db::{ |
8 | salsa, CrateGraph, CrateId, Edition, FileId, FilePosition, SourceDatabase, SourceRoot, | 8 | salsa, CrateGraph, CrateId, Edition, FileId, FileLoader, FileLoaderDelegate, FilePosition, |
9 | SourceRootId, | 9 | SourceDatabase, SourceDatabaseExt, SourceRoot, SourceRootId, |
10 | }; | 10 | }; |
11 | use relative_path::RelativePathBuf; | 11 | use relative_path::{RelativePath, RelativePathBuf}; |
12 | use rustc_hash::FxHashMap; | 12 | use rustc_hash::FxHashMap; |
13 | use test_utils::{extract_offset, parse_fixture, CURSOR_MARKER}; | 13 | use test_utils::{extract_offset, parse_fixture, CURSOR_MARKER}; |
14 | 14 | ||
@@ -17,6 +17,7 @@ use crate::{db, debug::HirDebugHelper, diagnostics::DiagnosticSink}; | |||
17 | pub const WORKSPACE: SourceRootId = SourceRootId(0); | 17 | pub const WORKSPACE: SourceRootId = SourceRootId(0); |
18 | 18 | ||
19 | #[salsa::database( | 19 | #[salsa::database( |
20 | ra_db::SourceDatabaseExtStorage, | ||
20 | ra_db::SourceDatabaseStorage, | 21 | ra_db::SourceDatabaseStorage, |
21 | db::InternDatabaseStorage, | 22 | db::InternDatabaseStorage, |
22 | db::AstDatabaseStorage, | 23 | db::AstDatabaseStorage, |
@@ -34,6 +35,22 @@ pub struct MockDatabase { | |||
34 | 35 | ||
35 | impl panic::RefUnwindSafe for MockDatabase {} | 36 | impl panic::RefUnwindSafe for MockDatabase {} |
36 | 37 | ||
38 | impl FileLoader for MockDatabase { | ||
39 | fn file_text(&self, file_id: FileId) -> Arc<String> { | ||
40 | FileLoaderDelegate(self).file_text(file_id) | ||
41 | } | ||
42 | fn resolve_relative_path( | ||
43 | &self, | ||
44 | anchor: FileId, | ||
45 | relative_path: &RelativePath, | ||
46 | ) -> Option<FileId> { | ||
47 | FileLoaderDelegate(self).resolve_relative_path(anchor, relative_path) | ||
48 | } | ||
49 | fn relevant_crates(&self, file_id: FileId) -> Arc<Vec<CrateId>> { | ||
50 | FileLoaderDelegate(self).relevant_crates(file_id) | ||
51 | } | ||
52 | } | ||
53 | |||
37 | impl HirDebugHelper for MockDatabase { | 54 | impl HirDebugHelper for MockDatabase { |
38 | fn crate_name(&self, krate: CrateId) -> Option<String> { | 55 | fn crate_name(&self, krate: CrateId) -> Option<String> { |
39 | self.crate_names.get(&krate).cloned() | 56 | self.crate_names.get(&krate).cloned() |
@@ -278,7 +295,10 @@ macro_rules! crate_graph { | |||
278 | $crate_path:literal, | 295 | $crate_path:literal, |
279 | $($edition:literal,)? | 296 | $($edition:literal,)? |
280 | [$($dep:literal),*] | 297 | [$($dep:literal),*] |
281 | $(,$cfg:expr)? | 298 | $(, cfg = { |
299 | $($key:literal $(= $value:literal)?),* | ||
300 | $(,)? | ||
301 | })? | ||
282 | ), | 302 | ), |
283 | )*) => {{ | 303 | )*) => {{ |
284 | let mut res = $crate::mock::CrateGraphFixture::default(); | 304 | let mut res = $crate::mock::CrateGraphFixture::default(); |
@@ -286,7 +306,19 @@ macro_rules! crate_graph { | |||
286 | #[allow(unused_mut, unused_assignments)] | 306 | #[allow(unused_mut, unused_assignments)] |
287 | let mut edition = ra_db::Edition::Edition2018; | 307 | let mut edition = ra_db::Edition::Edition2018; |
288 | $(edition = ra_db::Edition::from_string($edition);)? | 308 | $(edition = ra_db::Edition::from_string($edition);)? |
289 | let cfg_options = { ::ra_cfg::CfgOptions::default() $(; $cfg)? }; | 309 | let cfg_options = { |
310 | #[allow(unused_mut)] | ||
311 | let mut cfg = ::ra_cfg::CfgOptions::default(); | ||
312 | $( | ||
313 | $( | ||
314 | if 0 == 0 $(+ { drop($value); 1})? { | ||
315 | cfg.insert_atom($key.into()); | ||
316 | } | ||
317 | $(cfg.insert_key_value($key.into(), $value.into());)? | ||
318 | )* | ||
319 | )? | ||
320 | cfg | ||
321 | }; | ||
290 | res.0.push(( | 322 | res.0.push(( |
291 | $crate_name.to_string(), | 323 | $crate_name.to_string(), |
292 | ($crate_path.to_string(), edition, cfg_options, vec![$($dep.to_string()),*]) | 324 | ($crate_path.to_string(), edition, cfg_options, vec![$($dep.to_string()),*]) |
diff --git a/crates/ra_hir/src/nameres/collector.rs b/crates/ra_hir/src/nameres/collector.rs index cef2dc9d2..b5fe16bfa 100644 --- a/crates/ra_hir/src/nameres/collector.rs +++ b/crates/ra_hir/src/nameres/collector.rs | |||
@@ -7,14 +7,13 @@ use rustc_hash::FxHashMap; | |||
7 | use test_utils::tested_by; | 7 | use test_utils::tested_by; |
8 | 8 | ||
9 | use crate::{ | 9 | use crate::{ |
10 | attr::Attr, | ||
10 | db::DefDatabase, | 11 | db::DefDatabase, |
11 | ids::{AstItemDef, LocationCtx, MacroCallId, MacroCallLoc, MacroDefId, MacroFileKind}, | 12 | ids::{AstItemDef, LocationCtx, MacroCallId, MacroCallLoc, MacroDefId, MacroFileKind}, |
12 | name::MACRO_RULES, | 13 | name::MACRO_RULES, |
13 | nameres::{ | 14 | nameres::{ |
14 | diagnostics::DefDiagnostic, | 15 | diagnostics::DefDiagnostic, mod_resolution::ModDir, raw, Crate, CrateDefMap, CrateModuleId, |
15 | mod_resolution::{resolve_submodule, ParentModule}, | 16 | ModuleData, ModuleDef, PerNs, ReachedFixedPoint, Resolution, ResolveMode, |
16 | raw, Crate, CrateDefMap, CrateModuleId, ModuleData, ModuleDef, PerNs, ReachedFixedPoint, | ||
17 | Resolution, ResolveMode, | ||
18 | }, | 17 | }, |
19 | Adt, AstId, Const, Enum, Function, HirFileId, MacroDef, Module, Name, Path, PathKind, Static, | 18 | Adt, AstId, Const, Enum, Function, HirFileId, MacroDef, Module, Name, Path, PathKind, Static, |
20 | Struct, Trait, TypeAlias, Union, | 19 | Struct, Trait, TypeAlias, Union, |
@@ -45,6 +44,7 @@ pub(super) fn collect_defs(db: &impl DefDatabase, mut def_map: CrateDefMap) -> C | |||
45 | glob_imports: FxHashMap::default(), | 44 | glob_imports: FxHashMap::default(), |
46 | unresolved_imports: Vec::new(), | 45 | unresolved_imports: Vec::new(), |
47 | unexpanded_macros: Vec::new(), | 46 | unexpanded_macros: Vec::new(), |
47 | mod_dirs: FxHashMap::default(), | ||
48 | macro_stack_monitor: MacroStackMonitor::default(), | 48 | macro_stack_monitor: MacroStackMonitor::default(), |
49 | cfg_options, | 49 | cfg_options, |
50 | }; | 50 | }; |
@@ -87,6 +87,7 @@ struct DefCollector<'a, DB> { | |||
87 | glob_imports: FxHashMap<CrateModuleId, Vec<(CrateModuleId, raw::ImportId)>>, | 87 | glob_imports: FxHashMap<CrateModuleId, Vec<(CrateModuleId, raw::ImportId)>>, |
88 | unresolved_imports: Vec<(CrateModuleId, raw::ImportId, raw::ImportData)>, | 88 | unresolved_imports: Vec<(CrateModuleId, raw::ImportId, raw::ImportData)>, |
89 | unexpanded_macros: Vec<(CrateModuleId, AstId<ast::MacroCall>, Path)>, | 89 | unexpanded_macros: Vec<(CrateModuleId, AstId<ast::MacroCall>, Path)>, |
90 | mod_dirs: FxHashMap<CrateModuleId, ModDir>, | ||
90 | 91 | ||
91 | /// Some macro use `$tt:tt which mean we have to handle the macro perfectly | 92 | /// Some macro use `$tt:tt which mean we have to handle the macro perfectly |
92 | /// To prevent stack overflow, we add a deep counter here for prevent that. | 93 | /// To prevent stack overflow, we add a deep counter here for prevent that. |
@@ -107,11 +108,10 @@ where | |||
107 | self.def_map.modules[module_id].definition = Some(file_id); | 108 | self.def_map.modules[module_id].definition = Some(file_id); |
108 | ModCollector { | 109 | ModCollector { |
109 | def_collector: &mut *self, | 110 | def_collector: &mut *self, |
110 | attr_path: None, | ||
111 | module_id, | 111 | module_id, |
112 | file_id: file_id.into(), | 112 | file_id: file_id.into(), |
113 | raw_items: &raw_items, | 113 | raw_items: &raw_items, |
114 | parent_module: None, | 114 | mod_dir: ModDir::root(), |
115 | } | 115 | } |
116 | .collect(raw_items.items()); | 116 | .collect(raw_items.items()); |
117 | 117 | ||
@@ -481,13 +481,13 @@ where | |||
481 | if !self.macro_stack_monitor.is_poison(macro_def_id) { | 481 | if !self.macro_stack_monitor.is_poison(macro_def_id) { |
482 | let file_id: HirFileId = macro_call_id.as_file(MacroFileKind::Items); | 482 | let file_id: HirFileId = macro_call_id.as_file(MacroFileKind::Items); |
483 | let raw_items = self.db.raw_items(file_id); | 483 | let raw_items = self.db.raw_items(file_id); |
484 | let mod_dir = self.mod_dirs[&module_id].clone(); | ||
484 | ModCollector { | 485 | ModCollector { |
485 | def_collector: &mut *self, | 486 | def_collector: &mut *self, |
486 | file_id, | 487 | file_id, |
487 | attr_path: None, | ||
488 | module_id, | 488 | module_id, |
489 | raw_items: &raw_items, | 489 | raw_items: &raw_items, |
490 | parent_module: None, | 490 | mod_dir, |
491 | } | 491 | } |
492 | .collect(raw_items.items()); | 492 | .collect(raw_items.items()); |
493 | } else { | 493 | } else { |
@@ -508,9 +508,8 @@ struct ModCollector<'a, D> { | |||
508 | def_collector: D, | 508 | def_collector: D, |
509 | module_id: CrateModuleId, | 509 | module_id: CrateModuleId, |
510 | file_id: HirFileId, | 510 | file_id: HirFileId, |
511 | attr_path: Option<&'a SmolStr>, | ||
512 | raw_items: &'a raw::RawItems, | 511 | raw_items: &'a raw::RawItems, |
513 | parent_module: Option<ParentModule<'a>>, | 512 | mod_dir: ModDir, |
514 | } | 513 | } |
515 | 514 | ||
516 | impl<DB> ModCollector<'_, &'_ mut DefCollector<'_, DB>> | 515 | impl<DB> ModCollector<'_, &'_ mut DefCollector<'_, DB>> |
@@ -518,6 +517,10 @@ where | |||
518 | DB: DefDatabase, | 517 | DB: DefDatabase, |
519 | { | 518 | { |
520 | fn collect(&mut self, items: &[raw::RawItem]) { | 519 | fn collect(&mut self, items: &[raw::RawItem]) { |
520 | // Note: don't assert that inserted value is fresh: it's simply not true | ||
521 | // for macros. | ||
522 | self.def_collector.mod_dirs.insert(self.module_id, self.mod_dir.clone()); | ||
523 | |||
521 | // Prelude module is always considered to be `#[macro_use]`. | 524 | // Prelude module is always considered to be `#[macro_use]`. |
522 | if let Some(prelude_module) = self.def_collector.def_map.prelude { | 525 | if let Some(prelude_module) = self.def_collector.def_map.prelude { |
523 | if prelude_module.krate != self.def_collector.def_map.krate { | 526 | if prelude_module.krate != self.def_collector.def_map.krate { |
@@ -530,7 +533,7 @@ where | |||
530 | // `#[macro_use] extern crate` is hoisted to imports macros before collecting | 533 | // `#[macro_use] extern crate` is hoisted to imports macros before collecting |
531 | // any other items. | 534 | // any other items. |
532 | for item in items { | 535 | for item in items { |
533 | if self.is_cfg_enabled(&item.attrs) { | 536 | if self.is_cfg_enabled(item.attrs()) { |
534 | if let raw::RawItemKind::Import(import_id) = item.kind { | 537 | if let raw::RawItemKind::Import(import_id) = item.kind { |
535 | let import = self.raw_items[import_id].clone(); | 538 | let import = self.raw_items[import_id].clone(); |
536 | if import.is_extern_crate && import.is_macro_use { | 539 | if import.is_extern_crate && import.is_macro_use { |
@@ -541,9 +544,11 @@ where | |||
541 | } | 544 | } |
542 | 545 | ||
543 | for item in items { | 546 | for item in items { |
544 | if self.is_cfg_enabled(&item.attrs) { | 547 | if self.is_cfg_enabled(item.attrs()) { |
545 | match item.kind { | 548 | match item.kind { |
546 | raw::RawItemKind::Module(m) => self.collect_module(&self.raw_items[m]), | 549 | raw::RawItemKind::Module(m) => { |
550 | self.collect_module(&self.raw_items[m], item.attrs()) | ||
551 | } | ||
547 | raw::RawItemKind::Import(import_id) => self | 552 | raw::RawItemKind::Import(import_id) => self |
548 | .def_collector | 553 | .def_collector |
549 | .unresolved_imports | 554 | .unresolved_imports |
@@ -555,53 +560,48 @@ where | |||
555 | } | 560 | } |
556 | } | 561 | } |
557 | 562 | ||
558 | fn collect_module(&mut self, module: &raw::ModuleData) { | 563 | fn collect_module(&mut self, module: &raw::ModuleData, attrs: &[Attr]) { |
564 | let path_attr = self.path_attr(attrs); | ||
565 | let is_macro_use = self.is_macro_use(attrs); | ||
559 | match module { | 566 | match module { |
560 | // inline module, just recurse | 567 | // inline module, just recurse |
561 | raw::ModuleData::Definition { name, items, ast_id, attr_path, is_macro_use } => { | 568 | raw::ModuleData::Definition { name, items, ast_id } => { |
562 | let module_id = | 569 | let module_id = |
563 | self.push_child_module(name.clone(), ast_id.with_file_id(self.file_id), None); | 570 | self.push_child_module(name.clone(), ast_id.with_file_id(self.file_id), None); |
564 | let parent_module = ParentModule { name, attr_path: attr_path.as_ref() }; | ||
565 | 571 | ||
566 | ModCollector { | 572 | ModCollector { |
567 | def_collector: &mut *self.def_collector, | 573 | def_collector: &mut *self.def_collector, |
568 | module_id, | 574 | module_id, |
569 | attr_path: attr_path.as_ref(), | ||
570 | file_id: self.file_id, | 575 | file_id: self.file_id, |
571 | raw_items: self.raw_items, | 576 | raw_items: self.raw_items, |
572 | parent_module: Some(parent_module), | 577 | mod_dir: self.mod_dir.descend_into_definition(name, path_attr), |
573 | } | 578 | } |
574 | .collect(&*items); | 579 | .collect(&*items); |
575 | if *is_macro_use { | 580 | if is_macro_use { |
576 | self.import_all_legacy_macros(module_id); | 581 | self.import_all_legacy_macros(module_id); |
577 | } | 582 | } |
578 | } | 583 | } |
579 | // out of line module, resolve, parse and recurse | 584 | // out of line module, resolve, parse and recurse |
580 | raw::ModuleData::Declaration { name, ast_id, attr_path, is_macro_use } => { | 585 | raw::ModuleData::Declaration { name, ast_id } => { |
581 | let ast_id = ast_id.with_file_id(self.file_id); | 586 | let ast_id = ast_id.with_file_id(self.file_id); |
582 | let is_root = self.def_collector.def_map.modules[self.module_id].parent.is_none(); | 587 | match self.mod_dir.resolve_declaration( |
583 | match resolve_submodule( | ||
584 | self.def_collector.db, | 588 | self.def_collector.db, |
585 | self.file_id, | 589 | self.file_id, |
586 | self.attr_path, | ||
587 | name, | 590 | name, |
588 | is_root, | 591 | path_attr, |
589 | attr_path.as_ref(), | ||
590 | self.parent_module, | ||
591 | ) { | 592 | ) { |
592 | Ok(file_id) => { | 593 | Ok((file_id, mod_dir)) => { |
593 | let module_id = self.push_child_module(name.clone(), ast_id, Some(file_id)); | 594 | let module_id = self.push_child_module(name.clone(), ast_id, Some(file_id)); |
594 | let raw_items = self.def_collector.db.raw_items(file_id.into()); | 595 | let raw_items = self.def_collector.db.raw_items(file_id.into()); |
595 | ModCollector { | 596 | ModCollector { |
596 | def_collector: &mut *self.def_collector, | 597 | def_collector: &mut *self.def_collector, |
597 | module_id, | 598 | module_id, |
598 | attr_path: attr_path.as_ref(), | ||
599 | file_id: file_id.into(), | 599 | file_id: file_id.into(), |
600 | raw_items: &raw_items, | 600 | raw_items: &raw_items, |
601 | parent_module: None, | 601 | mod_dir, |
602 | } | 602 | } |
603 | .collect(raw_items.items()); | 603 | .collect(raw_items.items()); |
604 | if *is_macro_use { | 604 | if is_macro_use { |
605 | self.import_all_legacy_macros(module_id); | 605 | self.import_all_legacy_macros(module_id); |
606 | } | 606 | } |
607 | } | 607 | } |
@@ -714,12 +714,16 @@ where | |||
714 | } | 714 | } |
715 | } | 715 | } |
716 | 716 | ||
717 | fn is_cfg_enabled(&self, attrs: &raw::Attrs) -> bool { | 717 | fn is_cfg_enabled(&self, attrs: &[Attr]) -> bool { |
718 | attrs.as_ref().map_or(true, |attrs| { | 718 | attrs.iter().all(|attr| attr.is_cfg_enabled(&self.def_collector.cfg_options) != Some(false)) |
719 | attrs | 719 | } |
720 | .iter() | 720 | |
721 | .all(|attr| attr.is_cfg_enabled(&self.def_collector.cfg_options) != Some(false)) | 721 | fn path_attr<'a>(&self, attrs: &'a [Attr]) -> Option<&'a SmolStr> { |
722 | }) | 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")) | ||
723 | } | 727 | } |
724 | } | 728 | } |
725 | 729 | ||
@@ -747,6 +751,7 @@ mod tests { | |||
747 | glob_imports: FxHashMap::default(), | 751 | glob_imports: FxHashMap::default(), |
748 | unresolved_imports: Vec::new(), | 752 | unresolved_imports: Vec::new(), |
749 | unexpanded_macros: Vec::new(), | 753 | unexpanded_macros: Vec::new(), |
754 | mod_dirs: FxHashMap::default(), | ||
750 | macro_stack_monitor: monitor, | 755 | macro_stack_monitor: monitor, |
751 | cfg_options: &CfgOptions::default(), | 756 | cfg_options: &CfgOptions::default(), |
752 | }; | 757 | }; |
diff --git a/crates/ra_hir/src/nameres/mod_resolution.rs b/crates/ra_hir/src/nameres/mod_resolution.rs index 3aa32bd66..e8b808514 100644 --- a/crates/ra_hir/src/nameres/mod_resolution.rs +++ b/crates/ra_hir/src/nameres/mod_resolution.rs | |||
@@ -1,187 +1,87 @@ | |||
1 | //! This module resolves `mod foo;` declaration to file. | 1 | //! This module resolves `mod foo;` declaration to file. |
2 | 2 | use ra_db::FileId; | |
3 | use std::{borrow::Cow, sync::Arc}; | ||
4 | |||
5 | use ra_db::{FileId, SourceRoot}; | ||
6 | use ra_syntax::SmolStr; | 3 | use ra_syntax::SmolStr; |
7 | use relative_path::RelativePathBuf; | 4 | use relative_path::RelativePathBuf; |
8 | 5 | ||
9 | use crate::{db::DefDatabase, HirFileId, Name}; | 6 | use crate::{db::DefDatabase, HirFileId, Name}; |
10 | 7 | ||
11 | #[derive(Clone, Copy)] | 8 | #[derive(Clone, Debug)] |
12 | pub(super) struct ParentModule<'a> { | 9 | pub(super) struct ModDir { |
13 | pub(super) name: &'a Name, | 10 | /// `.` for `mod.rs`, `lib.rs` |
14 | pub(super) attr_path: Option<&'a SmolStr>, | 11 | /// `./foo` for `foo.rs` |
12 | /// `./foo/bar` for `mod bar { mod x; }` nested in `foo.rs` | ||
13 | path: RelativePathBuf, | ||
14 | /// inside `./foo.rs`, mods with `#[path]` should *not* be relative to `./foo/` | ||
15 | root_non_dir_owner: bool, | ||
15 | } | 16 | } |
16 | 17 | ||
17 | impl<'a> ParentModule<'a> { | 18 | impl ModDir { |
18 | fn attribute_path(&self) -> Option<&SmolStr> { | 19 | pub(super) fn root() -> ModDir { |
19 | self.attr_path.filter(|p| !p.is_empty()) | 20 | ModDir { path: RelativePathBuf::default(), root_non_dir_owner: false } |
20 | } | 21 | } |
21 | } | ||
22 | 22 | ||
23 | pub(super) fn resolve_submodule( | 23 | pub(super) fn descend_into_definition( |
24 | db: &impl DefDatabase, | 24 | &self, |
25 | file_id: HirFileId, | 25 | name: &Name, |
26 | mod_attr_path: Option<&SmolStr>, | 26 | attr_path: Option<&SmolStr>, |
27 | name: &Name, | 27 | ) -> ModDir { |
28 | is_root: bool, | 28 | let mut path = self.path.clone(); |
29 | attr_path: Option<&SmolStr>, | 29 | match attr_to_path(attr_path) { |
30 | parent_module: Option<ParentModule<'_>>, | 30 | None => path.push(&name.to_string()), |
31 | ) -> Result<FileId, RelativePathBuf> { | 31 | Some(attr_path) => { |
32 | let file_id = file_id.original_file(db); | 32 | if self.root_non_dir_owner { |
33 | let source_root_id = db.file_source_root(file_id); | 33 | // Workaround for relative path API: turn `lib.rs` into ``. |
34 | let path = db.file_relative_path(file_id); | 34 | if !path.pop() { |
35 | let root = RelativePathBuf::default(); | 35 | path = RelativePathBuf::default(); |
36 | let dir_path = path.parent().unwrap_or(&root); | 36 | } |
37 | let mod_name = path.file_stem().unwrap_or("unknown"); | ||
38 | |||
39 | let resolve_mode = match (attr_path.filter(|p| !p.is_empty()), parent_module) { | ||
40 | (Some(file_path), Some(parent_module)) => { | ||
41 | let file_path = normalize_attribute_path(file_path); | ||
42 | match parent_module.attribute_path() { | ||
43 | Some(parent_module_attr_path) => { | ||
44 | let path = dir_path | ||
45 | .join(format!( | ||
46 | "{}/{}", | ||
47 | normalize_attribute_path(parent_module_attr_path), | ||
48 | file_path | ||
49 | )) | ||
50 | .normalize(); | ||
51 | ResolutionMode::InlineModuleWithAttributePath( | ||
52 | InsideInlineModuleMode::WithAttributePath(path), | ||
53 | ) | ||
54 | } | ||
55 | None => { | ||
56 | let path = | ||
57 | dir_path.join(format!("{}/{}", parent_module.name, file_path)).normalize(); | ||
58 | ResolutionMode::InsideInlineModule(InsideInlineModuleMode::WithAttributePath( | ||
59 | path, | ||
60 | )) | ||
61 | } | 37 | } |
38 | path.push(attr_path); | ||
62 | } | 39 | } |
63 | } | 40 | } |
64 | (None, Some(parent_module)) => match parent_module.attribute_path() { | 41 | ModDir { path, root_non_dir_owner: false } |
65 | Some(parent_module_attr_path) => { | 42 | } |
66 | let path = dir_path.join(format!( | 43 | |
67 | "{}/{}.rs", | 44 | pub(super) fn resolve_declaration( |
68 | normalize_attribute_path(parent_module_attr_path), | 45 | &self, |
69 | name | 46 | db: &impl DefDatabase, |
70 | )); | 47 | file_id: HirFileId, |
71 | ResolutionMode::InlineModuleWithAttributePath(InsideInlineModuleMode::File(path)) | 48 | name: &Name, |
49 | attr_path: Option<&SmolStr>, | ||
50 | ) -> Result<(FileId, ModDir), RelativePathBuf> { | ||
51 | let empty_path = RelativePathBuf::default(); | ||
52 | let file_id = file_id.original_file(db); | ||
53 | |||
54 | let mut candidate_files = Vec::new(); | ||
55 | match attr_to_path(attr_path) { | ||
56 | Some(attr_path) => { | ||
57 | let base = if self.root_non_dir_owner { | ||
58 | self.path.parent().unwrap_or(&empty_path) | ||
59 | } else { | ||
60 | &self.path | ||
61 | }; | ||
62 | candidate_files.push(base.join(attr_path)) | ||
72 | } | 63 | } |
73 | None => { | 64 | None => { |
74 | let path = dir_path.join(format!("{}/{}.rs", parent_module.name, name)); | 65 | candidate_files.push(self.path.join(&format!("{}.rs", name))); |
75 | ResolutionMode::InsideInlineModule(InsideInlineModuleMode::File(path)) | 66 | candidate_files.push(self.path.join(&format!("{}/mod.rs", name))); |
76 | } | ||
77 | }, | ||
78 | (Some(file_path), None) => { | ||
79 | let file_path = normalize_attribute_path(file_path); | ||
80 | let path = dir_path.join(file_path.as_ref()).normalize(); | ||
81 | ResolutionMode::OutOfLine(OutOfLineMode::WithAttributePath(path)) | ||
82 | } | ||
83 | (None, None) => { | ||
84 | let is_dir_owner = is_root || mod_name == "mod" || mod_attr_path.is_some(); | ||
85 | if is_dir_owner { | ||
86 | let file_mod = dir_path.join(format!("{}.rs", name)); | ||
87 | let dir_mod = dir_path.join(format!("{}/mod.rs", name)); | ||
88 | ResolutionMode::OutOfLine(OutOfLineMode::RootOrModRs { | ||
89 | file: file_mod, | ||
90 | directory: dir_mod, | ||
91 | }) | ||
92 | } else { | ||
93 | let path = dir_path.join(format!("{}/{}.rs", mod_name, name)); | ||
94 | ResolutionMode::OutOfLine(OutOfLineMode::FileInDirectory(path)) | ||
95 | } | 67 | } |
96 | } | 68 | }; |
97 | }; | 69 | |
98 | 70 | for candidate in candidate_files.iter() { | |
99 | resolve_mode.resolve(db.source_root(source_root_id)) | 71 | if let Some(file_id) = db.resolve_relative_path(file_id, candidate) { |
100 | } | 72 | let mut root_non_dir_owner = false; |
101 | 73 | let mut mod_path = RelativePathBuf::new(); | |
102 | fn normalize_attribute_path(file_path: &SmolStr) -> Cow<str> { | 74 | if !(candidate.ends_with("mod.rs") || attr_path.is_some()) { |
103 | let current_dir = "./"; | 75 | root_non_dir_owner = true; |
104 | let windows_path_separator = r#"\"#; | 76 | mod_path.push(&name.to_string()); |
105 | let current_dir_normalize = if file_path.starts_with(current_dir) { | ||
106 | &file_path[current_dir.len()..] | ||
107 | } else { | ||
108 | file_path.as_str() | ||
109 | }; | ||
110 | if current_dir_normalize.contains(windows_path_separator) { | ||
111 | Cow::Owned(current_dir_normalize.replace(windows_path_separator, "/")) | ||
112 | } else { | ||
113 | Cow::Borrowed(current_dir_normalize) | ||
114 | } | ||
115 | } | ||
116 | |||
117 | enum OutOfLineMode { | ||
118 | RootOrModRs { file: RelativePathBuf, directory: RelativePathBuf }, | ||
119 | FileInDirectory(RelativePathBuf), | ||
120 | WithAttributePath(RelativePathBuf), | ||
121 | } | ||
122 | |||
123 | impl OutOfLineMode { | ||
124 | pub fn resolve(&self, source_root: Arc<SourceRoot>) -> Result<FileId, RelativePathBuf> { | ||
125 | match self { | ||
126 | OutOfLineMode::RootOrModRs { file, directory } => { | ||
127 | match source_root.file_by_relative_path(file) { | ||
128 | None => resolve_simple_path(source_root, directory).map_err(|_| file.clone()), | ||
129 | file_id => resolve_find_result(file_id, file), | ||
130 | } | 77 | } |
78 | return Ok((file_id, ModDir { path: mod_path, root_non_dir_owner })); | ||
131 | } | 79 | } |
132 | OutOfLineMode::FileInDirectory(path) => resolve_simple_path(source_root, path), | ||
133 | OutOfLineMode::WithAttributePath(path) => resolve_simple_path(source_root, path), | ||
134 | } | 80 | } |
81 | Err(candidate_files.remove(0)) | ||
135 | } | 82 | } |
136 | } | 83 | } |
137 | 84 | ||
138 | enum InsideInlineModuleMode { | 85 | fn attr_to_path(attr: Option<&SmolStr>) -> Option<RelativePathBuf> { |
139 | File(RelativePathBuf), | 86 | attr.and_then(|it| RelativePathBuf::from_path(&it.replace("\\", "/")).ok()) |
140 | WithAttributePath(RelativePathBuf), | ||
141 | } | ||
142 | |||
143 | impl InsideInlineModuleMode { | ||
144 | pub fn resolve(&self, source_root: Arc<SourceRoot>) -> Result<FileId, RelativePathBuf> { | ||
145 | match self { | ||
146 | InsideInlineModuleMode::File(path) => resolve_simple_path(source_root, path), | ||
147 | InsideInlineModuleMode::WithAttributePath(path) => { | ||
148 | resolve_simple_path(source_root, path) | ||
149 | } | ||
150 | } | ||
151 | } | ||
152 | } | ||
153 | |||
154 | enum ResolutionMode { | ||
155 | OutOfLine(OutOfLineMode), | ||
156 | InsideInlineModule(InsideInlineModuleMode), | ||
157 | InlineModuleWithAttributePath(InsideInlineModuleMode), | ||
158 | } | ||
159 | |||
160 | impl ResolutionMode { | ||
161 | pub fn resolve(&self, source_root: Arc<SourceRoot>) -> Result<FileId, RelativePathBuf> { | ||
162 | use self::ResolutionMode::*; | ||
163 | |||
164 | match self { | ||
165 | OutOfLine(mode) => mode.resolve(source_root), | ||
166 | InsideInlineModule(mode) => mode.resolve(source_root), | ||
167 | InlineModuleWithAttributePath(mode) => mode.resolve(source_root), | ||
168 | } | ||
169 | } | ||
170 | } | ||
171 | |||
172 | fn resolve_simple_path( | ||
173 | source_root: Arc<SourceRoot>, | ||
174 | path: &RelativePathBuf, | ||
175 | ) -> Result<FileId, RelativePathBuf> { | ||
176 | resolve_find_result(source_root.file_by_relative_path(path), path) | ||
177 | } | ||
178 | |||
179 | fn resolve_find_result( | ||
180 | file_id: Option<FileId>, | ||
181 | path: &RelativePathBuf, | ||
182 | ) -> Result<FileId, RelativePathBuf> { | ||
183 | match file_id { | ||
184 | Some(file_id) => Ok(file_id.clone()), | ||
185 | None => Err(path.clone()), | ||
186 | } | ||
187 | } | 87 | } |
diff --git a/crates/ra_hir/src/nameres/raw.rs b/crates/ra_hir/src/nameres/raw.rs index 623b343c4..57f2929c3 100644 --- a/crates/ra_hir/src/nameres/raw.rs +++ b/crates/ra_hir/src/nameres/raw.rs | |||
@@ -5,7 +5,7 @@ use std::{ops::Index, sync::Arc}; | |||
5 | use ra_arena::{impl_arena_id, map::ArenaMap, Arena, RawId}; | 5 | use ra_arena::{impl_arena_id, map::ArenaMap, Arena, RawId}; |
6 | use ra_syntax::{ | 6 | use ra_syntax::{ |
7 | ast::{self, AttrsOwner, NameOwner}, | 7 | ast::{self, AttrsOwner, NameOwner}, |
8 | AstNode, AstPtr, SmolStr, SourceFile, | 8 | AstNode, AstPtr, SourceFile, |
9 | }; | 9 | }; |
10 | use test_utils::tested_by; | 10 | use test_utils::tested_by; |
11 | 11 | ||
@@ -121,14 +121,20 @@ impl Index<Macro> for RawItems { | |||
121 | } | 121 | } |
122 | 122 | ||
123 | // Avoid heap allocation on items without attributes. | 123 | // Avoid heap allocation on items without attributes. |
124 | pub(super) type Attrs = Option<Arc<[Attr]>>; | 124 | type Attrs = Option<Arc<[Attr]>>; |
125 | 125 | ||
126 | #[derive(Debug, PartialEq, Eq, Clone)] | 126 | #[derive(Debug, PartialEq, Eq, Clone)] |
127 | pub(super) struct RawItem { | 127 | pub(super) struct RawItem { |
128 | pub(super) attrs: Attrs, | 128 | attrs: Attrs, |
129 | pub(super) kind: RawItemKind, | 129 | pub(super) kind: RawItemKind, |
130 | } | 130 | } |
131 | 131 | ||
132 | impl RawItem { | ||
133 | pub(super) fn attrs(&self) -> &[Attr] { | ||
134 | self.attrs.as_ref().map_or(&[], |it| &*it) | ||
135 | } | ||
136 | } | ||
137 | |||
132 | #[derive(Debug, PartialEq, Eq, Clone, Copy)] | 138 | #[derive(Debug, PartialEq, Eq, Clone, Copy)] |
133 | pub(super) enum RawItemKind { | 139 | pub(super) enum RawItemKind { |
134 | Module(Module), | 140 | Module(Module), |
@@ -143,19 +149,8 @@ impl_arena_id!(Module); | |||
143 | 149 | ||
144 | #[derive(Debug, PartialEq, Eq)] | 150 | #[derive(Debug, PartialEq, Eq)] |
145 | pub(super) enum ModuleData { | 151 | pub(super) enum ModuleData { |
146 | Declaration { | 152 | Declaration { name: Name, ast_id: FileAstId<ast::Module> }, |
147 | name: Name, | 153 | Definition { name: Name, ast_id: FileAstId<ast::Module>, items: Vec<RawItem> }, |
148 | ast_id: FileAstId<ast::Module>, | ||
149 | attr_path: Option<SmolStr>, | ||
150 | is_macro_use: bool, | ||
151 | }, | ||
152 | Definition { | ||
153 | name: Name, | ||
154 | ast_id: FileAstId<ast::Module>, | ||
155 | items: Vec<RawItem>, | ||
156 | attr_path: Option<SmolStr>, | ||
157 | is_macro_use: bool, | ||
158 | }, | ||
159 | } | 154 | } |
160 | 155 | ||
161 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | 156 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
@@ -286,28 +281,17 @@ impl<DB: AstDatabase> RawItemsCollector<&DB> { | |||
286 | let attrs = self.parse_attrs(&module); | 281 | let attrs = self.parse_attrs(&module); |
287 | 282 | ||
288 | let ast_id = self.source_ast_id_map.ast_id(&module); | 283 | let ast_id = self.source_ast_id_map.ast_id(&module); |
289 | // FIXME: cfg_attr | ||
290 | let is_macro_use = module.has_atom_attr("macro_use"); | ||
291 | if module.has_semi() { | 284 | if module.has_semi() { |
292 | let attr_path = extract_mod_path_attribute(&module); | 285 | let item = self.raw_items.modules.alloc(ModuleData::Declaration { name, ast_id }); |
293 | let item = self.raw_items.modules.alloc(ModuleData::Declaration { | ||
294 | name, | ||
295 | ast_id, | ||
296 | attr_path, | ||
297 | is_macro_use, | ||
298 | }); | ||
299 | self.push_item(current_module, attrs, RawItemKind::Module(item)); | 286 | self.push_item(current_module, attrs, RawItemKind::Module(item)); |
300 | return; | 287 | return; |
301 | } | 288 | } |
302 | 289 | ||
303 | if let Some(item_list) = module.item_list() { | 290 | if let Some(item_list) = module.item_list() { |
304 | let attr_path = extract_mod_path_attribute(&module); | ||
305 | let item = self.raw_items.modules.alloc(ModuleData::Definition { | 291 | let item = self.raw_items.modules.alloc(ModuleData::Definition { |
306 | name, | 292 | name, |
307 | ast_id, | 293 | ast_id, |
308 | items: Vec::new(), | 294 | items: Vec::new(), |
309 | attr_path, | ||
310 | is_macro_use, | ||
311 | }); | 295 | }); |
312 | self.process_module(Some(item), item_list); | 296 | self.process_module(Some(item), item_list); |
313 | self.push_item(current_module, attrs, RawItemKind::Module(item)); | 297 | self.push_item(current_module, attrs, RawItemKind::Module(item)); |
@@ -417,16 +401,3 @@ impl<DB: AstDatabase> RawItemsCollector<&DB> { | |||
417 | Attr::from_attrs_owner(self.file_id, item, self.db) | 401 | Attr::from_attrs_owner(self.file_id, item, self.db) |
418 | } | 402 | } |
419 | } | 403 | } |
420 | |||
421 | fn extract_mod_path_attribute(module: &ast::Module) -> Option<SmolStr> { | ||
422 | module.attrs().into_iter().find_map(|attr| { | ||
423 | attr.as_simple_key_value().and_then(|(name, value)| { | ||
424 | let is_path = name == "path"; | ||
425 | if is_path { | ||
426 | Some(value) | ||
427 | } else { | ||
428 | None | ||
429 | } | ||
430 | }) | ||
431 | }) | ||
432 | } | ||
diff --git a/crates/ra_hir/src/nameres/tests.rs b/crates/ra_hir/src/nameres/tests.rs index 34dd79574..8c6b40aaf 100644 --- a/crates/ra_hir/src/nameres/tests.rs +++ b/crates/ra_hir/src/nameres/tests.rs | |||
@@ -7,7 +7,6 @@ mod mod_resolution; | |||
7 | use std::sync::Arc; | 7 | use std::sync::Arc; |
8 | 8 | ||
9 | use insta::assert_snapshot; | 9 | use insta::assert_snapshot; |
10 | use ra_cfg::CfgOptions; | ||
11 | use ra_db::SourceDatabase; | 10 | use ra_db::SourceDatabase; |
12 | use test_utils::covers; | 11 | use test_utils::covers; |
13 | 12 | ||
@@ -561,12 +560,12 @@ fn cfg_test() { | |||
561 | "#, | 560 | "#, |
562 | crate_graph! { | 561 | crate_graph! { |
563 | "main": ("/main.rs", ["std"]), | 562 | "main": ("/main.rs", ["std"]), |
564 | "std": ("/lib.rs", [], CfgOptions::default() | 563 | "std": ("/lib.rs", [], cfg = { |
565 | .atom("test".into()) | 564 | "test", |
566 | .key_value("feature".into(), "foo".into()) | 565 | "feature" = "foo", |
567 | .key_value("feature".into(), "bar".into()) | 566 | "feature" = "bar", |
568 | .key_value("opt".into(), "42".into()) | 567 | "opt" = "42", |
569 | ), | 568 | }), |
570 | }, | 569 | }, |
571 | ); | 570 | ); |
572 | 571 | ||
diff --git a/crates/ra_hir/src/nameres/tests/incremental.rs b/crates/ra_hir/src/nameres/tests/incremental.rs index c41862a0b..af9c39760 100644 --- a/crates/ra_hir/src/nameres/tests/incremental.rs +++ b/crates/ra_hir/src/nameres/tests/incremental.rs | |||
@@ -2,7 +2,7 @@ use super::*; | |||
2 | 2 | ||
3 | use std::sync::Arc; | 3 | use std::sync::Arc; |
4 | 4 | ||
5 | use ra_db::SourceDatabase; | 5 | use ra_db::{SourceDatabase, SourceDatabaseExt}; |
6 | 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); |
diff --git a/crates/ra_hir/src/nameres/tests/macros.rs b/crates/ra_hir/src/nameres/tests/macros.rs index e4b408394..4f52ad2c5 100644 --- a/crates/ra_hir/src/nameres/tests/macros.rs +++ b/crates/ra_hir/src/nameres/tests/macros.rs | |||
@@ -38,21 +38,34 @@ fn macro_rules_can_define_modules() { | |||
38 | } | 38 | } |
39 | m!(n1); | 39 | m!(n1); |
40 | 40 | ||
41 | mod m { | ||
42 | m!(n3) | ||
43 | } | ||
44 | |||
41 | //- /n1.rs | 45 | //- /n1.rs |
42 | m!(n2) | 46 | m!(n2) |
43 | //- /n1/n2.rs | 47 | //- /n1/n2.rs |
44 | struct X; | 48 | struct X; |
49 | //- /m/n3.rs | ||
50 | struct Y; | ||
45 | ", | 51 | ", |
46 | ); | 52 | ); |
47 | assert_snapshot!(map, @r###" | 53 | assert_snapshot!(map, @r###" |
48 | â‹®crate | 54 | crate |
49 | â‹®n1: t | 55 | m: t |
50 | â‹® | 56 | n1: t |
51 | â‹®crate::n1 | 57 | |
52 | â‹®n2: t | 58 | crate::m |
53 | â‹® | 59 | n3: t |
54 | â‹®crate::n1::n2 | 60 | |
55 | â‹®X: t v | 61 | crate::m::n3 |
62 | Y: t v | ||
63 | |||
64 | crate::n1 | ||
65 | n2: t | ||
66 | |||
67 | crate::n1::n2 | ||
68 | X: t v | ||
56 | "###); | 69 | "###); |
57 | } | 70 | } |
58 | 71 | ||
diff --git a/crates/ra_hir/src/nameres/tests/mod_resolution.rs b/crates/ra_hir/src/nameres/tests/mod_resolution.rs index e3e6f1e95..f569aacdc 100644 --- a/crates/ra_hir/src/nameres/tests/mod_resolution.rs +++ b/crates/ra_hir/src/nameres/tests/mod_resolution.rs | |||
@@ -26,6 +26,33 @@ fn name_res_works_for_broken_modules() { | |||
26 | } | 26 | } |
27 | 27 | ||
28 | #[test] | 28 | #[test] |
29 | fn nested_module_resolution() { | ||
30 | let map = def_map( | ||
31 | " | ||
32 | //- /lib.rs | ||
33 | mod n1; | ||
34 | |||
35 | //- /n1.rs | ||
36 | mod n2; | ||
37 | |||
38 | //- /n1/n2.rs | ||
39 | struct X; | ||
40 | ", | ||
41 | ); | ||
42 | |||
43 | assert_snapshot!(map, @r###" | ||
44 | â‹®crate | ||
45 | â‹®n1: t | ||
46 | â‹® | ||
47 | â‹®crate::n1 | ||
48 | â‹®n2: t | ||
49 | â‹® | ||
50 | â‹®crate::n1::n2 | ||
51 | â‹®X: t v | ||
52 | "###); | ||
53 | } | ||
54 | |||
55 | #[test] | ||
29 | fn module_resolution_works_for_non_standard_filenames() { | 56 | fn module_resolution_works_for_non_standard_filenames() { |
30 | let map = def_map_with_crate_graph( | 57 | let map = def_map_with_crate_graph( |
31 | " | 58 | " |
@@ -53,18 +80,15 @@ fn module_resolution_works_for_non_standard_filenames() { | |||
53 | 80 | ||
54 | #[test] | 81 | #[test] |
55 | fn module_resolution_works_for_raw_modules() { | 82 | fn module_resolution_works_for_raw_modules() { |
56 | let map = def_map_with_crate_graph( | 83 | let map = def_map( |
57 | " | 84 | " |
58 | //- /library.rs | 85 | //- /lib.rs |
59 | mod r#async; | 86 | mod r#async; |
60 | use self::r#async::Bar; | 87 | use self::r#async::Bar; |
61 | 88 | ||
62 | //- /async.rs | 89 | //- /async.rs |
63 | pub struct Bar; | 90 | pub struct Bar; |
64 | ", | 91 | ", |
65 | crate_graph! { | ||
66 | "library": ("/library.rs", []), | ||
67 | }, | ||
68 | ); | 92 | ); |
69 | 93 | ||
70 | assert_snapshot!(map, @r###" | 94 | assert_snapshot!(map, @r###" |
@@ -79,9 +103,9 @@ fn module_resolution_works_for_raw_modules() { | |||
79 | 103 | ||
80 | #[test] | 104 | #[test] |
81 | fn module_resolution_decl_path() { | 105 | fn module_resolution_decl_path() { |
82 | let map = def_map_with_crate_graph( | 106 | let map = def_map( |
83 | r###" | 107 | r###" |
84 | //- /library.rs | 108 | //- /lib.rs |
85 | #[path = "bar/baz/foo.rs"] | 109 | #[path = "bar/baz/foo.rs"] |
86 | mod foo; | 110 | mod foo; |
87 | use self::foo::Bar; | 111 | use self::foo::Bar; |
@@ -89,9 +113,6 @@ fn module_resolution_decl_path() { | |||
89 | //- /bar/baz/foo.rs | 113 | //- /bar/baz/foo.rs |
90 | pub struct Bar; | 114 | pub struct Bar; |
91 | "###, | 115 | "###, |
92 | crate_graph! { | ||
93 | "library": ("/library.rs", []), | ||
94 | }, | ||
95 | ); | 116 | ); |
96 | 117 | ||
97 | assert_snapshot!(map, @r###" | 118 | assert_snapshot!(map, @r###" |
@@ -106,7 +127,7 @@ fn module_resolution_decl_path() { | |||
106 | 127 | ||
107 | #[test] | 128 | #[test] |
108 | fn module_resolution_module_with_path_in_mod_rs() { | 129 | fn module_resolution_module_with_path_in_mod_rs() { |
109 | let map = def_map_with_crate_graph( | 130 | let map = def_map( |
110 | r###" | 131 | r###" |
111 | //- /main.rs | 132 | //- /main.rs |
112 | mod foo; | 133 | mod foo; |
@@ -120,9 +141,6 @@ fn module_resolution_module_with_path_in_mod_rs() { | |||
120 | //- /foo/baz.rs | 141 | //- /foo/baz.rs |
121 | pub struct Baz; | 142 | pub struct Baz; |
122 | "###, | 143 | "###, |
123 | crate_graph! { | ||
124 | "main": ("/main.rs", []), | ||
125 | }, | ||
126 | ); | 144 | ); |
127 | 145 | ||
128 | assert_snapshot!(map, @r###" | 146 | assert_snapshot!(map, @r###" |
@@ -140,7 +158,7 @@ fn module_resolution_module_with_path_in_mod_rs() { | |||
140 | 158 | ||
141 | #[test] | 159 | #[test] |
142 | fn module_resolution_module_with_path_non_crate_root() { | 160 | fn module_resolution_module_with_path_non_crate_root() { |
143 | let map = def_map_with_crate_graph( | 161 | let map = def_map( |
144 | r###" | 162 | r###" |
145 | //- /main.rs | 163 | //- /main.rs |
146 | mod foo; | 164 | mod foo; |
@@ -154,9 +172,6 @@ fn module_resolution_module_with_path_non_crate_root() { | |||
154 | //- /baz.rs | 172 | //- /baz.rs |
155 | pub struct Baz; | 173 | pub struct Baz; |
156 | "###, | 174 | "###, |
157 | crate_graph! { | ||
158 | "main": ("/main.rs", []), | ||
159 | }, | ||
160 | ); | 175 | ); |
161 | 176 | ||
162 | assert_snapshot!(map, @r###" | 177 | assert_snapshot!(map, @r###" |
@@ -174,7 +189,7 @@ fn module_resolution_module_with_path_non_crate_root() { | |||
174 | 189 | ||
175 | #[test] | 190 | #[test] |
176 | fn module_resolution_module_decl_path_super() { | 191 | fn module_resolution_module_decl_path_super() { |
177 | let map = def_map_with_crate_graph( | 192 | let map = def_map( |
178 | r###" | 193 | r###" |
179 | //- /main.rs | 194 | //- /main.rs |
180 | #[path = "bar/baz/module.rs"] | 195 | #[path = "bar/baz/module.rs"] |
@@ -184,9 +199,6 @@ fn module_resolution_module_decl_path_super() { | |||
184 | //- /bar/baz/module.rs | 199 | //- /bar/baz/module.rs |
185 | use super::Baz; | 200 | use super::Baz; |
186 | "###, | 201 | "###, |
187 | crate_graph! { | ||
188 | "main": ("/main.rs", []), | ||
189 | }, | ||
190 | ); | 202 | ); |
191 | 203 | ||
192 | assert_snapshot!(map, @r###" | 204 | assert_snapshot!(map, @r###" |
@@ -201,7 +213,7 @@ fn module_resolution_module_decl_path_super() { | |||
201 | 213 | ||
202 | #[test] | 214 | #[test] |
203 | fn module_resolution_explicit_path_mod_rs() { | 215 | fn module_resolution_explicit_path_mod_rs() { |
204 | let map = def_map_with_crate_graph( | 216 | let map = def_map( |
205 | r###" | 217 | r###" |
206 | //- /main.rs | 218 | //- /main.rs |
207 | #[path = "module/mod.rs"] | 219 | #[path = "module/mod.rs"] |
@@ -210,9 +222,6 @@ fn module_resolution_explicit_path_mod_rs() { | |||
210 | //- /module/mod.rs | 222 | //- /module/mod.rs |
211 | pub struct Baz; | 223 | pub struct Baz; |
212 | "###, | 224 | "###, |
213 | crate_graph! { | ||
214 | "main": ("/main.rs", []), | ||
215 | }, | ||
216 | ); | 225 | ); |
217 | 226 | ||
218 | assert_snapshot!(map, @r###" | 227 | assert_snapshot!(map, @r###" |
@@ -226,7 +235,7 @@ fn module_resolution_explicit_path_mod_rs() { | |||
226 | 235 | ||
227 | #[test] | 236 | #[test] |
228 | fn module_resolution_relative_path() { | 237 | fn module_resolution_relative_path() { |
229 | let map = def_map_with_crate_graph( | 238 | let map = def_map( |
230 | r###" | 239 | r###" |
231 | //- /main.rs | 240 | //- /main.rs |
232 | mod foo; | 241 | mod foo; |
@@ -238,9 +247,6 @@ fn module_resolution_relative_path() { | |||
238 | //- /sub.rs | 247 | //- /sub.rs |
239 | pub struct Baz; | 248 | pub struct Baz; |
240 | "###, | 249 | "###, |
241 | crate_graph! { | ||
242 | "main": ("/main.rs", []), | ||
243 | }, | ||
244 | ); | 250 | ); |
245 | 251 | ||
246 | assert_snapshot!(map, @r###" | 252 | assert_snapshot!(map, @r###" |
@@ -257,7 +263,7 @@ fn module_resolution_relative_path() { | |||
257 | 263 | ||
258 | #[test] | 264 | #[test] |
259 | fn module_resolution_relative_path_2() { | 265 | fn module_resolution_relative_path_2() { |
260 | let map = def_map_with_crate_graph( | 266 | let map = def_map( |
261 | r###" | 267 | r###" |
262 | //- /main.rs | 268 | //- /main.rs |
263 | mod foo; | 269 | mod foo; |
@@ -269,9 +275,6 @@ fn module_resolution_relative_path_2() { | |||
269 | //- /sub.rs | 275 | //- /sub.rs |
270 | pub struct Baz; | 276 | pub struct Baz; |
271 | "###, | 277 | "###, |
272 | crate_graph! { | ||
273 | "main": ("/main.rs", []), | ||
274 | }, | ||
275 | ); | 278 | ); |
276 | 279 | ||
277 | assert_snapshot!(map, @r###" | 280 | assert_snapshot!(map, @r###" |
@@ -288,7 +291,7 @@ fn module_resolution_relative_path_2() { | |||
288 | 291 | ||
289 | #[test] | 292 | #[test] |
290 | fn module_resolution_explicit_path_mod_rs_2() { | 293 | fn module_resolution_explicit_path_mod_rs_2() { |
291 | let map = def_map_with_crate_graph( | 294 | let map = def_map( |
292 | r###" | 295 | r###" |
293 | //- /main.rs | 296 | //- /main.rs |
294 | #[path = "module/bar/mod.rs"] | 297 | #[path = "module/bar/mod.rs"] |
@@ -297,9 +300,6 @@ fn module_resolution_explicit_path_mod_rs_2() { | |||
297 | //- /module/bar/mod.rs | 300 | //- /module/bar/mod.rs |
298 | pub struct Baz; | 301 | pub struct Baz; |
299 | "###, | 302 | "###, |
300 | crate_graph! { | ||
301 | "main": ("/main.rs", []), | ||
302 | }, | ||
303 | ); | 303 | ); |
304 | 304 | ||
305 | assert_snapshot!(map, @r###" | 305 | assert_snapshot!(map, @r###" |
@@ -313,7 +313,7 @@ fn module_resolution_explicit_path_mod_rs_2() { | |||
313 | 313 | ||
314 | #[test] | 314 | #[test] |
315 | fn module_resolution_explicit_path_mod_rs_with_win_separator() { | 315 | fn module_resolution_explicit_path_mod_rs_with_win_separator() { |
316 | let map = def_map_with_crate_graph( | 316 | let map = def_map( |
317 | r###" | 317 | r###" |
318 | //- /main.rs | 318 | //- /main.rs |
319 | #[path = "module\bar\mod.rs"] | 319 | #[path = "module\bar\mod.rs"] |
@@ -322,9 +322,6 @@ fn module_resolution_explicit_path_mod_rs_with_win_separator() { | |||
322 | //- /module/bar/mod.rs | 322 | //- /module/bar/mod.rs |
323 | pub struct Baz; | 323 | pub struct Baz; |
324 | "###, | 324 | "###, |
325 | crate_graph! { | ||
326 | "main": ("/main.rs", []), | ||
327 | }, | ||
328 | ); | 325 | ); |
329 | 326 | ||
330 | assert_snapshot!(map, @r###" | 327 | assert_snapshot!(map, @r###" |
@@ -338,7 +335,7 @@ fn module_resolution_explicit_path_mod_rs_with_win_separator() { | |||
338 | 335 | ||
339 | #[test] | 336 | #[test] |
340 | fn module_resolution_decl_inside_inline_module_with_path_attribute() { | 337 | fn module_resolution_decl_inside_inline_module_with_path_attribute() { |
341 | let map = def_map_with_crate_graph( | 338 | let map = def_map( |
342 | r###" | 339 | r###" |
343 | //- /main.rs | 340 | //- /main.rs |
344 | #[path = "models"] | 341 | #[path = "models"] |
@@ -349,9 +346,6 @@ fn module_resolution_decl_inside_inline_module_with_path_attribute() { | |||
349 | //- /models/bar.rs | 346 | //- /models/bar.rs |
350 | pub struct Baz; | 347 | pub struct Baz; |
351 | "###, | 348 | "###, |
352 | crate_graph! { | ||
353 | "main": ("/main.rs", []), | ||
354 | }, | ||
355 | ); | 349 | ); |
356 | 350 | ||
357 | assert_snapshot!(map, @r###" | 351 | assert_snapshot!(map, @r###" |
@@ -368,7 +362,7 @@ fn module_resolution_decl_inside_inline_module_with_path_attribute() { | |||
368 | 362 | ||
369 | #[test] | 363 | #[test] |
370 | fn module_resolution_decl_inside_inline_module() { | 364 | fn module_resolution_decl_inside_inline_module() { |
371 | let map = def_map_with_crate_graph( | 365 | let map = def_map( |
372 | r###" | 366 | r###" |
373 | //- /main.rs | 367 | //- /main.rs |
374 | mod foo { | 368 | mod foo { |
@@ -378,9 +372,6 @@ fn module_resolution_decl_inside_inline_module() { | |||
378 | //- /foo/bar.rs | 372 | //- /foo/bar.rs |
379 | pub struct Baz; | 373 | pub struct Baz; |
380 | "###, | 374 | "###, |
381 | crate_graph! { | ||
382 | "main": ("/main.rs", []), | ||
383 | }, | ||
384 | ); | 375 | ); |
385 | 376 | ||
386 | assert_snapshot!(map, @r###" | 377 | assert_snapshot!(map, @r###" |
@@ -397,7 +388,7 @@ fn module_resolution_decl_inside_inline_module() { | |||
397 | 388 | ||
398 | #[test] | 389 | #[test] |
399 | fn module_resolution_decl_inside_inline_module_2_with_path_attribute() { | 390 | fn module_resolution_decl_inside_inline_module_2_with_path_attribute() { |
400 | let map = def_map_with_crate_graph( | 391 | let map = def_map( |
401 | r###" | 392 | r###" |
402 | //- /main.rs | 393 | //- /main.rs |
403 | #[path = "models/db"] | 394 | #[path = "models/db"] |
@@ -408,9 +399,6 @@ fn module_resolution_decl_inside_inline_module_2_with_path_attribute() { | |||
408 | //- /models/db/bar.rs | 399 | //- /models/db/bar.rs |
409 | pub struct Baz; | 400 | pub struct Baz; |
410 | "###, | 401 | "###, |
411 | crate_graph! { | ||
412 | "main": ("/main.rs", []), | ||
413 | }, | ||
414 | ); | 402 | ); |
415 | 403 | ||
416 | assert_snapshot!(map, @r###" | 404 | assert_snapshot!(map, @r###" |
@@ -427,7 +415,7 @@ fn module_resolution_decl_inside_inline_module_2_with_path_attribute() { | |||
427 | 415 | ||
428 | #[test] | 416 | #[test] |
429 | fn module_resolution_decl_inside_inline_module_3() { | 417 | fn module_resolution_decl_inside_inline_module_3() { |
430 | let map = def_map_with_crate_graph( | 418 | let map = def_map( |
431 | r###" | 419 | r###" |
432 | //- /main.rs | 420 | //- /main.rs |
433 | #[path = "models/db"] | 421 | #[path = "models/db"] |
@@ -439,9 +427,6 @@ fn module_resolution_decl_inside_inline_module_3() { | |||
439 | //- /models/db/users.rs | 427 | //- /models/db/users.rs |
440 | pub struct Baz; | 428 | pub struct Baz; |
441 | "###, | 429 | "###, |
442 | crate_graph! { | ||
443 | "main": ("/main.rs", []), | ||
444 | }, | ||
445 | ); | 430 | ); |
446 | 431 | ||
447 | assert_snapshot!(map, @r###" | 432 | assert_snapshot!(map, @r###" |
@@ -458,7 +443,7 @@ fn module_resolution_decl_inside_inline_module_3() { | |||
458 | 443 | ||
459 | #[test] | 444 | #[test] |
460 | fn module_resolution_decl_inside_inline_module_empty_path() { | 445 | fn module_resolution_decl_inside_inline_module_empty_path() { |
461 | let map = def_map_with_crate_graph( | 446 | let map = def_map( |
462 | r###" | 447 | r###" |
463 | //- /main.rs | 448 | //- /main.rs |
464 | #[path = ""] | 449 | #[path = ""] |
@@ -467,12 +452,9 @@ fn module_resolution_decl_inside_inline_module_empty_path() { | |||
467 | mod bar; | 452 | mod bar; |
468 | } | 453 | } |
469 | 454 | ||
470 | //- /foo/users.rs | 455 | //- /users.rs |
471 | pub struct Baz; | 456 | pub struct Baz; |
472 | "###, | 457 | "###, |
473 | crate_graph! { | ||
474 | "main": ("/main.rs", []), | ||
475 | }, | ||
476 | ); | 458 | ); |
477 | 459 | ||
478 | assert_snapshot!(map, @r###" | 460 | assert_snapshot!(map, @r###" |
@@ -489,32 +471,25 @@ fn module_resolution_decl_inside_inline_module_empty_path() { | |||
489 | 471 | ||
490 | #[test] | 472 | #[test] |
491 | fn module_resolution_decl_empty_path() { | 473 | fn module_resolution_decl_empty_path() { |
492 | let map = def_map_with_crate_graph( | 474 | let map = def_map( |
493 | r###" | 475 | r###" |
494 | //- /main.rs | 476 | //- /main.rs |
495 | #[path = ""] | 477 | #[path = ""] // Should try to read `/` (a directory) |
496 | mod foo; | 478 | mod foo; |
497 | 479 | ||
498 | //- /foo.rs | 480 | //- /foo.rs |
499 | pub struct Baz; | 481 | pub struct Baz; |
500 | "###, | 482 | "###, |
501 | crate_graph! { | ||
502 | "main": ("/main.rs", []), | ||
503 | }, | ||
504 | ); | 483 | ); |
505 | 484 | ||
506 | assert_snapshot!(map, @r###" | 485 | assert_snapshot!(map, @r###" |
507 | â‹®crate | 486 | â‹®crate |
508 | â‹®foo: t | ||
509 | â‹® | ||
510 | â‹®crate::foo | ||
511 | â‹®Baz: t v | ||
512 | "###); | 487 | "###); |
513 | } | 488 | } |
514 | 489 | ||
515 | #[test] | 490 | #[test] |
516 | fn module_resolution_decl_inside_inline_module_relative_path() { | 491 | fn module_resolution_decl_inside_inline_module_relative_path() { |
517 | let map = def_map_with_crate_graph( | 492 | let map = def_map( |
518 | r###" | 493 | r###" |
519 | //- /main.rs | 494 | //- /main.rs |
520 | #[path = "./models"] | 495 | #[path = "./models"] |
@@ -525,9 +500,6 @@ fn module_resolution_decl_inside_inline_module_relative_path() { | |||
525 | //- /models/bar.rs | 500 | //- /models/bar.rs |
526 | pub struct Baz; | 501 | pub struct Baz; |
527 | "###, | 502 | "###, |
528 | crate_graph! { | ||
529 | "main": ("/main.rs", []), | ||
530 | }, | ||
531 | ); | 503 | ); |
532 | 504 | ||
533 | assert_snapshot!(map, @r###" | 505 | assert_snapshot!(map, @r###" |
@@ -544,7 +516,7 @@ fn module_resolution_decl_inside_inline_module_relative_path() { | |||
544 | 516 | ||
545 | #[test] | 517 | #[test] |
546 | fn module_resolution_decl_inside_inline_module_in_crate_root() { | 518 | fn module_resolution_decl_inside_inline_module_in_crate_root() { |
547 | let map = def_map_with_crate_graph( | 519 | let map = def_map( |
548 | r###" | 520 | r###" |
549 | //- /main.rs | 521 | //- /main.rs |
550 | mod foo { | 522 | mod foo { |
@@ -556,9 +528,6 @@ fn module_resolution_decl_inside_inline_module_in_crate_root() { | |||
556 | //- /foo/baz.rs | 528 | //- /foo/baz.rs |
557 | pub struct Baz; | 529 | pub struct Baz; |
558 | "###, | 530 | "###, |
559 | crate_graph! { | ||
560 | "main": ("/main.rs", []), | ||
561 | }, | ||
562 | ); | 531 | ); |
563 | 532 | ||
564 | assert_snapshot!(map, @r###" | 533 | assert_snapshot!(map, @r###" |
@@ -576,7 +545,7 @@ fn module_resolution_decl_inside_inline_module_in_crate_root() { | |||
576 | 545 | ||
577 | #[test] | 546 | #[test] |
578 | fn module_resolution_decl_inside_inline_module_in_mod_rs() { | 547 | fn module_resolution_decl_inside_inline_module_in_mod_rs() { |
579 | let map = def_map_with_crate_graph( | 548 | let map = def_map( |
580 | r###" | 549 | r###" |
581 | //- /main.rs | 550 | //- /main.rs |
582 | mod foo; | 551 | mod foo; |
@@ -591,9 +560,6 @@ fn module_resolution_decl_inside_inline_module_in_mod_rs() { | |||
591 | //- /foo/bar/qwe.rs | 560 | //- /foo/bar/qwe.rs |
592 | pub struct Baz; | 561 | pub struct Baz; |
593 | "###, | 562 | "###, |
594 | crate_graph! { | ||
595 | "main": ("/main.rs", []), | ||
596 | }, | ||
597 | ); | 563 | ); |
598 | 564 | ||
599 | assert_snapshot!(map, @r###" | 565 | assert_snapshot!(map, @r###" |
@@ -614,7 +580,7 @@ fn module_resolution_decl_inside_inline_module_in_mod_rs() { | |||
614 | 580 | ||
615 | #[test] | 581 | #[test] |
616 | fn module_resolution_decl_inside_inline_module_in_non_crate_root() { | 582 | fn module_resolution_decl_inside_inline_module_in_non_crate_root() { |
617 | let map = def_map_with_crate_graph( | 583 | let map = def_map( |
618 | r###" | 584 | r###" |
619 | //- /main.rs | 585 | //- /main.rs |
620 | mod foo; | 586 | mod foo; |
@@ -626,12 +592,9 @@ fn module_resolution_decl_inside_inline_module_in_non_crate_root() { | |||
626 | } | 592 | } |
627 | use self::bar::baz::Baz; | 593 | use self::bar::baz::Baz; |
628 | 594 | ||
629 | //- /bar/qwe.rs | 595 | //- /foo/bar/qwe.rs |
630 | pub struct Baz; | 596 | pub struct Baz; |
631 | "###, | 597 | "###, |
632 | crate_graph! { | ||
633 | "main": ("/main.rs", []), | ||
634 | }, | ||
635 | ); | 598 | ); |
636 | 599 | ||
637 | assert_snapshot!(map, @r###" | 600 | assert_snapshot!(map, @r###" |
@@ -652,7 +615,7 @@ fn module_resolution_decl_inside_inline_module_in_non_crate_root() { | |||
652 | 615 | ||
653 | #[test] | 616 | #[test] |
654 | fn module_resolution_decl_inside_inline_module_in_non_crate_root_2() { | 617 | fn module_resolution_decl_inside_inline_module_in_non_crate_root_2() { |
655 | let map = def_map_with_crate_graph( | 618 | let map = def_map( |
656 | r###" | 619 | r###" |
657 | //- /main.rs | 620 | //- /main.rs |
658 | mod foo; | 621 | mod foo; |
@@ -667,9 +630,6 @@ fn module_resolution_decl_inside_inline_module_in_non_crate_root_2() { | |||
667 | //- /bar/baz.rs | 630 | //- /bar/baz.rs |
668 | pub struct Baz; | 631 | pub struct Baz; |
669 | "###, | 632 | "###, |
670 | crate_graph! { | ||
671 | "main": ("/main.rs", []), | ||
672 | }, | ||
673 | ); | 633 | ); |
674 | 634 | ||
675 | assert_snapshot!(map, @r###" | 635 | assert_snapshot!(map, @r###" |
@@ -709,7 +669,7 @@ fn unresolved_module_diagnostics() { | |||
709 | 669 | ||
710 | #[test] | 670 | #[test] |
711 | fn module_resolution_decl_inside_module_in_non_crate_root_2() { | 671 | fn module_resolution_decl_inside_module_in_non_crate_root_2() { |
712 | let map = def_map_with_crate_graph( | 672 | let map = def_map( |
713 | r###" | 673 | r###" |
714 | //- /main.rs | 674 | //- /main.rs |
715 | #[path="module/m2.rs"] | 675 | #[path="module/m2.rs"] |
@@ -721,9 +681,6 @@ fn module_resolution_decl_inside_module_in_non_crate_root_2() { | |||
721 | //- /module/submod.rs | 681 | //- /module/submod.rs |
722 | pub struct Baz; | 682 | pub struct Baz; |
723 | "###, | 683 | "###, |
724 | crate_graph! { | ||
725 | "main": ("/main.rs", []), | ||
726 | }, | ||
727 | ); | 684 | ); |
728 | 685 | ||
729 | assert_snapshot!(map, @r###" | 686 | assert_snapshot!(map, @r###" |
@@ -737,3 +694,66 @@ fn module_resolution_decl_inside_module_in_non_crate_root_2() { | |||
737 | â‹®Baz: t v | 694 | â‹®Baz: t v |
738 | "###); | 695 | "###); |
739 | } | 696 | } |
697 | |||
698 | #[test] | ||
699 | fn nested_out_of_line_module() { | ||
700 | let map = def_map( | ||
701 | r###" | ||
702 | //- /lib.rs | ||
703 | mod a { | ||
704 | mod b { | ||
705 | mod c; | ||
706 | } | ||
707 | } | ||
708 | |||
709 | //- /a/b/c.rs | ||
710 | struct X; | ||
711 | "###, | ||
712 | ); | ||
713 | |||
714 | assert_snapshot!(map, @r###" | ||
715 | crate | ||
716 | a: t | ||
717 | |||
718 | crate::a | ||
719 | b: t | ||
720 | |||
721 | crate::a::b | ||
722 | c: t | ||
723 | |||
724 | crate::a::b::c | ||
725 | X: t v | ||
726 | "###); | ||
727 | } | ||
728 | |||
729 | #[test] | ||
730 | fn nested_out_of_line_module_with_path() { | ||
731 | let map = def_map( | ||
732 | r###" | ||
733 | //- /lib.rs | ||
734 | mod a { | ||
735 | #[path = "d/e"] | ||
736 | mod b { | ||
737 | mod c; | ||
738 | } | ||
739 | } | ||
740 | |||
741 | //- /a/d/e/c.rs | ||
742 | struct X; | ||
743 | "###, | ||
744 | ); | ||
745 | |||
746 | assert_snapshot!(map, @r###" | ||
747 | crate | ||
748 | a: t | ||
749 | |||
750 | crate::a | ||
751 | b: t | ||
752 | |||
753 | crate::a::b | ||
754 | c: t | ||
755 | |||
756 | crate::a::b::c | ||
757 | X: t v | ||
758 | "###); | ||
759 | } | ||
diff --git a/crates/ra_hir/src/resolve.rs b/crates/ra_hir/src/resolve.rs index 39f8e1d8a..3c797c0c3 100644 --- a/crates/ra_hir/src/resolve.rs +++ b/crates/ra_hir/src/resolve.rs | |||
@@ -43,8 +43,10 @@ pub(crate) enum Scope { | |||
43 | ModuleScope(ModuleItemMap), | 43 | ModuleScope(ModuleItemMap), |
44 | /// Brings the generic parameters of an item into scope | 44 | /// Brings the generic parameters of an item into scope |
45 | GenericParams(Arc<GenericParams>), | 45 | GenericParams(Arc<GenericParams>), |
46 | /// Brings `Self` into scope | 46 | /// Brings `Self` in `impl` block into scope |
47 | ImplBlockScope(ImplBlock), | 47 | ImplBlockScope(ImplBlock), |
48 | /// Brings `Self` in enum, struct and union definitions into scope | ||
49 | AdtScope(Adt), | ||
48 | /// Local bindings | 50 | /// Local bindings |
49 | ExprScope(ExprScope), | 51 | ExprScope(ExprScope), |
50 | } | 52 | } |
@@ -54,6 +56,7 @@ pub enum TypeNs { | |||
54 | SelfType(ImplBlock), | 56 | SelfType(ImplBlock), |
55 | GenericParam(u32), | 57 | GenericParam(u32), |
56 | Adt(Adt), | 58 | Adt(Adt), |
59 | AdtSelfType(Adt), | ||
57 | EnumVariant(EnumVariant), | 60 | EnumVariant(EnumVariant), |
58 | TypeAlias(TypeAlias), | 61 | TypeAlias(TypeAlias), |
59 | BuiltinType(BuiltinType), | 62 | BuiltinType(BuiltinType), |
@@ -151,6 +154,12 @@ impl Resolver { | |||
151 | return Some((TypeNs::SelfType(*impl_), idx)); | 154 | return Some((TypeNs::SelfType(*impl_), idx)); |
152 | } | 155 | } |
153 | } | 156 | } |
157 | Scope::AdtScope(adt) => { | ||
158 | if first_name == &SELF_TYPE { | ||
159 | let idx = if path.segments.len() == 1 { None } else { Some(1) }; | ||
160 | return Some((TypeNs::AdtSelfType(*adt), idx)); | ||
161 | } | ||
162 | } | ||
154 | Scope::ModuleScope(m) => { | 163 | Scope::ModuleScope(m) => { |
155 | let (module_def, idx) = m.crate_def_map.resolve_path(db, m.module_id, path); | 164 | let (module_def, idx) = m.crate_def_map.resolve_path(db, m.module_id, path); |
156 | let res = match module_def.take_types()? { | 165 | let res = match module_def.take_types()? { |
@@ -200,7 +209,10 @@ impl Resolver { | |||
200 | let skip_to_mod = path.kind != PathKind::Plain && !path.is_self(); | 209 | let skip_to_mod = path.kind != PathKind::Plain && !path.is_self(); |
201 | for scope in self.scopes.iter().rev() { | 210 | for scope in self.scopes.iter().rev() { |
202 | match scope { | 211 | match scope { |
203 | Scope::ExprScope(_) | Scope::GenericParams(_) | Scope::ImplBlockScope(_) | 212 | Scope::AdtScope(_) |
213 | | Scope::ExprScope(_) | ||
214 | | Scope::GenericParams(_) | ||
215 | | Scope::ImplBlockScope(_) | ||
204 | if skip_to_mod => | 216 | if skip_to_mod => |
205 | { | 217 | { |
206 | continue | 218 | continue |
@@ -233,7 +245,13 @@ impl Resolver { | |||
233 | return Some(ResolveValueResult::Partial(ty, 1)); | 245 | return Some(ResolveValueResult::Partial(ty, 1)); |
234 | } | 246 | } |
235 | } | 247 | } |
236 | Scope::ImplBlockScope(_) => continue, | 248 | Scope::AdtScope(adt) if n_segments > 1 => { |
249 | if first_name == &SELF_TYPE { | ||
250 | let ty = TypeNs::AdtSelfType(*adt); | ||
251 | return Some(ResolveValueResult::Partial(ty, 1)); | ||
252 | } | ||
253 | } | ||
254 | Scope::ImplBlockScope(_) | Scope::AdtScope(_) => continue, | ||
237 | 255 | ||
238 | Scope::ModuleScope(m) => { | 256 | Scope::ModuleScope(m) => { |
239 | let (module_def, idx) = m.crate_def_map.resolve_path(db, m.module_id, path); | 257 | let (module_def, idx) = m.crate_def_map.resolve_path(db, m.module_id, path); |
@@ -389,7 +407,8 @@ pub enum ScopeDef { | |||
389 | ModuleDef(ModuleDef), | 407 | ModuleDef(ModuleDef), |
390 | MacroDef(MacroDef), | 408 | MacroDef(MacroDef), |
391 | GenericParam(u32), | 409 | GenericParam(u32), |
392 | SelfType(ImplBlock), | 410 | ImplSelfType(ImplBlock), |
411 | AdtSelfType(Adt), | ||
393 | LocalBinding(PatId), | 412 | LocalBinding(PatId), |
394 | Unknown, | 413 | Unknown, |
395 | } | 414 | } |
@@ -437,7 +456,10 @@ impl Scope { | |||
437 | } | 456 | } |
438 | } | 457 | } |
439 | Scope::ImplBlockScope(i) => { | 458 | Scope::ImplBlockScope(i) => { |
440 | f(SELF_TYPE, ScopeDef::SelfType(*i)); | 459 | f(SELF_TYPE, ScopeDef::ImplSelfType(*i)); |
460 | } | ||
461 | Scope::AdtScope(i) => { | ||
462 | f(SELF_TYPE, ScopeDef::AdtSelfType(*i)); | ||
441 | } | 463 | } |
442 | Scope::ExprScope(e) => { | 464 | Scope::ExprScope(e) => { |
443 | e.expr_scopes.entries(e.scope_id).iter().for_each(|e| { | 465 | e.expr_scopes.entries(e.scope_id).iter().for_each(|e| { |
diff --git a/crates/ra_hir/src/source_binder.rs b/crates/ra_hir/src/source_binder.rs index 088335e66..a907d6a9f 100644 --- a/crates/ra_hir/src/source_binder.rs +++ b/crates/ra_hir/src/source_binder.rs | |||
@@ -216,7 +216,7 @@ impl SourceAnalyzer { | |||
216 | let types = self.resolver.resolve_path_in_type_ns_fully(db, &path).map(|ty| match ty { | 216 | let types = self.resolver.resolve_path_in_type_ns_fully(db, &path).map(|ty| match ty { |
217 | TypeNs::SelfType(it) => PathResolution::SelfType(it), | 217 | TypeNs::SelfType(it) => PathResolution::SelfType(it), |
218 | TypeNs::GenericParam(it) => PathResolution::GenericParam(it), | 218 | TypeNs::GenericParam(it) => PathResolution::GenericParam(it), |
219 | TypeNs::Adt(it) => PathResolution::Def(it.into()), | 219 | TypeNs::AdtSelfType(it) | TypeNs::Adt(it) => PathResolution::Def(it.into()), |
220 | TypeNs::EnumVariant(it) => PathResolution::Def(it.into()), | 220 | TypeNs::EnumVariant(it) => PathResolution::Def(it.into()), |
221 | TypeNs::TypeAlias(it) => PathResolution::Def(it.into()), | 221 | TypeNs::TypeAlias(it) => PathResolution::Def(it.into()), |
222 | TypeNs::BuiltinType(it) => PathResolution::Def(it.into()), | 222 | TypeNs::BuiltinType(it) => PathResolution::Def(it.into()), |
diff --git a/crates/ra_hir/src/ty.rs b/crates/ra_hir/src/ty.rs index d161735e8..cc9746f6d 100644 --- a/crates/ra_hir/src/ty.rs +++ b/crates/ra_hir/src/ty.rs | |||
@@ -17,8 +17,8 @@ use std::sync::Arc; | |||
17 | use std::{fmt, iter, mem}; | 17 | use std::{fmt, iter, mem}; |
18 | 18 | ||
19 | use crate::{ | 19 | use crate::{ |
20 | db::HirDatabase, expr::ExprId, type_ref::Mutability, Adt, Crate, DefWithBody, GenericParams, | 20 | db::HirDatabase, expr::ExprId, type_ref::Mutability, util::make_mut_slice, Adt, Crate, |
21 | HasGenericParams, Name, Trait, TypeAlias, | 21 | DefWithBody, GenericParams, HasGenericParams, Name, Trait, TypeAlias, |
22 | }; | 22 | }; |
23 | use display::{HirDisplay, HirFormatter}; | 23 | use display::{HirDisplay, HirFormatter}; |
24 | 24 | ||
@@ -308,12 +308,9 @@ impl Substs { | |||
308 | } | 308 | } |
309 | 309 | ||
310 | pub fn walk_mut(&mut self, f: &mut impl FnMut(&mut Ty)) { | 310 | pub fn walk_mut(&mut self, f: &mut impl FnMut(&mut Ty)) { |
311 | // Without an Arc::make_mut_slice, we can't avoid the clone here: | 311 | for t in make_mut_slice(&mut self.0) { |
312 | let mut v: Vec<_> = self.0.iter().cloned().collect(); | ||
313 | for t in &mut v { | ||
314 | t.walk_mut(f); | 312 | t.walk_mut(f); |
315 | } | 313 | } |
316 | self.0 = v.into(); | ||
317 | } | 314 | } |
318 | 315 | ||
319 | pub fn as_single(&self) -> &Ty { | 316 | pub fn as_single(&self) -> &Ty { |
@@ -330,8 +327,7 @@ impl Substs { | |||
330 | .params_including_parent() | 327 | .params_including_parent() |
331 | .into_iter() | 328 | .into_iter() |
332 | .map(|p| Ty::Param { idx: p.idx, name: p.name.clone() }) | 329 | .map(|p| Ty::Param { idx: p.idx, name: p.name.clone() }) |
333 | .collect::<Vec<_>>() | 330 | .collect(), |
334 | .into(), | ||
335 | ) | 331 | ) |
336 | } | 332 | } |
337 | 333 | ||
@@ -342,8 +338,7 @@ impl Substs { | |||
342 | .params_including_parent() | 338 | .params_including_parent() |
343 | .into_iter() | 339 | .into_iter() |
344 | .map(|p| Ty::Bound(p.idx)) | 340 | .map(|p| Ty::Bound(p.idx)) |
345 | .collect::<Vec<_>>() | 341 | .collect(), |
346 | .into(), | ||
347 | ) | 342 | ) |
348 | } | 343 | } |
349 | 344 | ||
@@ -541,12 +536,9 @@ impl TypeWalk for FnSig { | |||
541 | } | 536 | } |
542 | 537 | ||
543 | fn walk_mut(&mut self, f: &mut impl FnMut(&mut Ty)) { | 538 | fn walk_mut(&mut self, f: &mut impl FnMut(&mut Ty)) { |
544 | // Without an Arc::make_mut_slice, we can't avoid the clone here: | 539 | for t in make_mut_slice(&mut self.params_and_return) { |
545 | let mut v: Vec<_> = self.params_and_return.iter().cloned().collect(); | ||
546 | for t in &mut v { | ||
547 | t.walk_mut(f); | 540 | t.walk_mut(f); |
548 | } | 541 | } |
549 | self.params_and_return = v.into(); | ||
550 | } | 542 | } |
551 | } | 543 | } |
552 | 544 | ||
@@ -756,11 +748,9 @@ impl TypeWalk for Ty { | |||
756 | p_ty.parameters.walk_mut(f); | 748 | p_ty.parameters.walk_mut(f); |
757 | } | 749 | } |
758 | Ty::Dyn(predicates) | Ty::Opaque(predicates) => { | 750 | Ty::Dyn(predicates) | Ty::Opaque(predicates) => { |
759 | let mut v: Vec<_> = predicates.iter().cloned().collect(); | 751 | for p in make_mut_slice(predicates) { |
760 | for p in &mut v { | ||
761 | p.walk_mut(f); | 752 | p.walk_mut(f); |
762 | } | 753 | } |
763 | *predicates = v.into(); | ||
764 | } | 754 | } |
765 | Ty::Param { .. } | Ty::Bound(_) | Ty::Infer(_) | Ty::Unknown => {} | 755 | Ty::Param { .. } | Ty::Bound(_) | Ty::Infer(_) | Ty::Unknown => {} |
766 | } | 756 | } |
diff --git a/crates/ra_hir/src/ty/infer.rs b/crates/ra_hir/src/ty/infer.rs index ca9aefc42..ebaff998e 100644 --- a/crates/ra_hir/src/ty/infer.rs +++ b/crates/ra_hir/src/ty/infer.rs | |||
@@ -14,7 +14,6 @@ | |||
14 | //! the `ena` crate, which is extracted from rustc. | 14 | //! the `ena` crate, which is extracted from rustc. |
15 | 15 | ||
16 | use std::borrow::Cow; | 16 | use std::borrow::Cow; |
17 | use std::iter::{repeat, repeat_with}; | ||
18 | use std::mem; | 17 | use std::mem; |
19 | use std::ops::Index; | 18 | use std::ops::Index; |
20 | use std::sync::Arc; | 19 | use std::sync::Arc; |
@@ -27,33 +26,39 @@ use ra_prof::profile; | |||
27 | use test_utils::tested_by; | 26 | use test_utils::tested_by; |
28 | 27 | ||
29 | use super::{ | 28 | use super::{ |
30 | autoderef, lower, method_resolution, op, primitive, | 29 | lower, primitive, |
31 | traits::{Guidance, Obligation, ProjectionPredicate, Solution}, | 30 | traits::{Guidance, Obligation, ProjectionPredicate, Solution}, |
32 | ApplicationTy, CallableDef, InEnvironment, ProjectionTy, Substs, TraitEnvironment, TraitRef, | 31 | ApplicationTy, InEnvironment, ProjectionTy, Substs, TraitEnvironment, TraitRef, Ty, TypableDef, |
33 | Ty, TypableDef, TypeCtor, TypeWalk, | 32 | TypeCtor, TypeWalk, |
34 | }; | 33 | }; |
35 | use crate::{ | 34 | use crate::{ |
36 | adt::VariantDef, | 35 | adt::VariantDef, |
37 | code_model::TypeAlias, | 36 | code_model::TypeAlias, |
38 | db::HirDatabase, | 37 | db::HirDatabase, |
39 | diagnostics::DiagnosticSink, | 38 | diagnostics::DiagnosticSink, |
40 | expr::{ | 39 | expr::{BindingAnnotation, Body, ExprId, PatId}, |
41 | self, Array, BinaryOp, BindingAnnotation, Body, Expr, ExprId, Literal, Pat, PatId, | ||
42 | RecordFieldPat, Statement, UnaryOp, | ||
43 | }, | ||
44 | generics::{GenericParams, HasGenericParams}, | ||
45 | lang_item::LangItemTarget, | ||
46 | name, | 40 | name, |
47 | nameres::Namespace, | 41 | path::known, |
48 | path::{known, GenericArg, GenericArgs}, | ||
49 | resolve::{Resolver, TypeNs}, | 42 | resolve::{Resolver, TypeNs}, |
50 | ty::infer::diagnostics::InferenceDiagnostic, | 43 | ty::infer::diagnostics::InferenceDiagnostic, |
51 | type_ref::{Mutability, TypeRef}, | 44 | type_ref::{Mutability, TypeRef}, |
52 | Adt, AssocItem, ConstData, DefWithBody, FnData, Function, HasBody, Name, Path, StructField, | 45 | Adt, AssocItem, ConstData, DefWithBody, FnData, Function, HasBody, Path, StructField, |
53 | }; | 46 | }; |
54 | 47 | ||
48 | macro_rules! ty_app { | ||
49 | ($ctor:pat, $param:pat) => { | ||
50 | crate::ty::Ty::Apply(crate::ty::ApplicationTy { ctor: $ctor, parameters: $param }) | ||
51 | }; | ||
52 | ($ctor:pat) => { | ||
53 | ty_app!($ctor, _) | ||
54 | }; | ||
55 | } | ||
56 | |||
55 | mod unify; | 57 | mod unify; |
56 | mod path; | 58 | mod path; |
59 | mod expr; | ||
60 | mod pat; | ||
61 | mod coerce; | ||
57 | 62 | ||
58 | /// The entry point of type inference. | 63 | /// The entry point of type inference. |
59 | pub fn infer_query(db: &impl HirDatabase, def: DefWithBody) -> Arc<InferenceResult> { | 64 | pub fn infer_query(db: &impl HirDatabase, def: DefWithBody) -> Arc<InferenceResult> { |
@@ -197,15 +202,6 @@ struct InferenceContext<'a, D: HirDatabase> { | |||
197 | coerce_unsized_map: FxHashMap<(TypeCtor, TypeCtor), usize>, | 202 | coerce_unsized_map: FxHashMap<(TypeCtor, TypeCtor), usize>, |
198 | } | 203 | } |
199 | 204 | ||
200 | macro_rules! ty_app { | ||
201 | ($ctor:pat, $param:pat) => { | ||
202 | Ty::Apply(ApplicationTy { ctor: $ctor, parameters: $param }) | ||
203 | }; | ||
204 | ($ctor:pat) => { | ||
205 | ty_app!($ctor, _) | ||
206 | }; | ||
207 | } | ||
208 | |||
209 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { | 205 | impl<'a, D: HirDatabase> InferenceContext<'a, D> { |
210 | fn new(db: &'a D, body: Arc<Body>, resolver: Resolver) -> Self { | 206 | fn new(db: &'a D, body: Arc<Body>, resolver: Resolver) -> Self { |
211 | InferenceContext { | 207 | InferenceContext { |
@@ -221,45 +217,6 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { | |||
221 | } | 217 | } |
222 | } | 218 | } |
223 | 219 | ||
224 | fn init_coerce_unsized_map( | ||
225 | db: &'a D, | ||
226 | resolver: &Resolver, | ||
227 | ) -> FxHashMap<(TypeCtor, TypeCtor), usize> { | ||
228 | let krate = resolver.krate().unwrap(); | ||
229 | let impls = match db.lang_item(krate, "coerce_unsized".into()) { | ||
230 | Some(LangItemTarget::Trait(trait_)) => db.impls_for_trait(krate, trait_), | ||
231 | _ => return FxHashMap::default(), | ||
232 | }; | ||
233 | |||
234 | impls | ||
235 | .iter() | ||
236 | .filter_map(|impl_block| { | ||
237 | // `CoerseUnsized` has one generic parameter for the target type. | ||
238 | let trait_ref = impl_block.target_trait_ref(db)?; | ||
239 | let cur_from_ty = trait_ref.substs.0.get(0)?; | ||
240 | let cur_to_ty = trait_ref.substs.0.get(1)?; | ||
241 | |||
242 | match (&cur_from_ty, cur_to_ty) { | ||
243 | (ty_app!(ctor1, st1), ty_app!(ctor2, st2)) => { | ||
244 | // FIXME: We return the first non-equal bound as the type parameter to coerce to unsized type. | ||
245 | // This works for smart-pointer-like coercion, which covers all impls from std. | ||
246 | st1.iter().zip(st2.iter()).enumerate().find_map(|(i, (ty1, ty2))| { | ||
247 | match (ty1, ty2) { | ||
248 | (Ty::Param { idx: p1, .. }, Ty::Param { idx: p2, .. }) | ||
249 | if p1 != p2 => | ||
250 | { | ||
251 | Some(((*ctor1, *ctor2), i)) | ||
252 | } | ||
253 | _ => None, | ||
254 | } | ||
255 | }) | ||
256 | } | ||
257 | _ => None, | ||
258 | } | ||
259 | }) | ||
260 | .collect() | ||
261 | } | ||
262 | |||
263 | fn resolve_all(mut self) -> InferenceResult { | 220 | fn resolve_all(mut self) -> InferenceResult { |
264 | // FIXME resolve obligations as well (use Guidance if necessary) | 221 | // FIXME resolve obligations as well (use Guidance if necessary) |
265 | let mut result = mem::replace(&mut self.result, InferenceResult::default()); | 222 | let mut result = mem::replace(&mut self.result, InferenceResult::default()); |
@@ -457,7 +414,9 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { | |||
457 | // recursive type | 414 | // recursive type |
458 | return tv.fallback_value(); | 415 | return tv.fallback_value(); |
459 | } | 416 | } |
460 | if let Some(known_ty) = self.var_unification_table.probe_value(inner).known() { | 417 | if let Some(known_ty) = |
418 | self.var_unification_table.inlined_probe_value(inner).known() | ||
419 | { | ||
461 | // known_ty may contain other variables that are known by now | 420 | // known_ty may contain other variables that are known by now |
462 | tv_stack.push(inner); | 421 | tv_stack.push(inner); |
463 | let result = self.resolve_ty_as_possible(tv_stack, known_ty.clone()); | 422 | let result = self.resolve_ty_as_possible(tv_stack, known_ty.clone()); |
@@ -485,7 +444,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { | |||
485 | match &*ty { | 444 | match &*ty { |
486 | Ty::Infer(tv) => { | 445 | Ty::Infer(tv) => { |
487 | let inner = tv.to_inner(); | 446 | let inner = tv.to_inner(); |
488 | match self.var_unification_table.probe_value(inner).known() { | 447 | match self.var_unification_table.inlined_probe_value(inner).known() { |
489 | Some(known_ty) => { | 448 | Some(known_ty) => { |
490 | // The known_ty can't be a type var itself | 449 | // The known_ty can't be a type var itself |
491 | ty = Cow::Owned(known_ty.clone()); | 450 | ty = Cow::Owned(known_ty.clone()); |
@@ -533,7 +492,9 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { | |||
533 | // recursive type | 492 | // recursive type |
534 | return tv.fallback_value(); | 493 | return tv.fallback_value(); |
535 | } | 494 | } |
536 | if let Some(known_ty) = self.var_unification_table.probe_value(inner).known() { | 495 | if let Some(known_ty) = |
496 | self.var_unification_table.inlined_probe_value(inner).known() | ||
497 | { | ||
537 | // known_ty may contain other variables that are known by now | 498 | // known_ty may contain other variables that are known by now |
538 | tv_stack.push(inner); | 499 | tv_stack.push(inner); |
539 | let result = self.resolve_ty_completely(tv_stack, known_ty.clone()); | 500 | let result = self.resolve_ty_completely(tv_stack, known_ty.clone()); |
@@ -559,6 +520,7 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { | |||
559 | match resolver.resolve_path_in_type_ns_fully(self.db, &path) { | 520 | match resolver.resolve_path_in_type_ns_fully(self.db, &path) { |
560 | Some(TypeNs::Adt(Adt::Struct(it))) => it.into(), | 521 | Some(TypeNs::Adt(Adt::Struct(it))) => it.into(), |
561 | Some(TypeNs::Adt(Adt::Union(it))) => it.into(), | 522 | Some(TypeNs::Adt(Adt::Union(it))) => it.into(), |
523 | Some(TypeNs::AdtSelfType(adt)) => adt.into(), | ||
562 | Some(TypeNs::EnumVariant(it)) => it.into(), | 524 | Some(TypeNs::EnumVariant(it)) => it.into(), |
563 | Some(TypeNs::TypeAlias(it)) => it.into(), | 525 | Some(TypeNs::TypeAlias(it)) => it.into(), |
564 | 526 | ||
@@ -594,1080 +556,6 @@ impl<'a, D: HirDatabase> InferenceContext<'a, D> { | |||
594 | } | 556 | } |
595 | } | 557 | } |
596 | 558 | ||
597 | fn infer_tuple_struct_pat( | ||
598 | &mut self, | ||
599 | path: Option<&Path>, | ||
600 | subpats: &[PatId], | ||
601 | expected: &Ty, | ||
602 | default_bm: BindingMode, | ||
603 | ) -> Ty { | ||
604 | let (ty, def) = self.resolve_variant(path); | ||
605 | |||
606 | self.unify(&ty, expected); | ||
607 | |||
608 | let substs = ty.substs().unwrap_or_else(Substs::empty); | ||
609 | |||
610 | for (i, &subpat) in subpats.iter().enumerate() { | ||
611 | let expected_ty = def | ||
612 | .and_then(|d| d.field(self.db, &Name::new_tuple_field(i))) | ||
613 | .map_or(Ty::Unknown, |field| field.ty(self.db)) | ||
614 | .subst(&substs); | ||
615 | let expected_ty = self.normalize_associated_types_in(expected_ty); | ||
616 | self.infer_pat(subpat, &expected_ty, default_bm); | ||
617 | } | ||
618 | |||
619 | ty | ||
620 | } | ||
621 | |||
622 | fn infer_record_pat( | ||
623 | &mut self, | ||
624 | path: Option<&Path>, | ||
625 | subpats: &[RecordFieldPat], | ||
626 | expected: &Ty, | ||
627 | default_bm: BindingMode, | ||
628 | id: PatId, | ||
629 | ) -> Ty { | ||
630 | let (ty, def) = self.resolve_variant(path); | ||
631 | if let Some(variant) = def { | ||
632 | self.write_variant_resolution(id.into(), variant); | ||
633 | } | ||
634 | |||
635 | self.unify(&ty, expected); | ||
636 | |||
637 | let substs = ty.substs().unwrap_or_else(Substs::empty); | ||
638 | |||
639 | for subpat in subpats { | ||
640 | let matching_field = def.and_then(|it| it.field(self.db, &subpat.name)); | ||
641 | let expected_ty = | ||
642 | matching_field.map_or(Ty::Unknown, |field| field.ty(self.db)).subst(&substs); | ||
643 | let expected_ty = self.normalize_associated_types_in(expected_ty); | ||
644 | self.infer_pat(subpat.pat, &expected_ty, default_bm); | ||
645 | } | ||
646 | |||
647 | ty | ||
648 | } | ||
649 | |||
650 | fn infer_pat(&mut self, pat: PatId, mut expected: &Ty, mut default_bm: BindingMode) -> Ty { | ||
651 | let body = Arc::clone(&self.body); // avoid borrow checker problem | ||
652 | |||
653 | let is_non_ref_pat = match &body[pat] { | ||
654 | Pat::Tuple(..) | ||
655 | | Pat::TupleStruct { .. } | ||
656 | | Pat::Record { .. } | ||
657 | | Pat::Range { .. } | ||
658 | | Pat::Slice { .. } => true, | ||
659 | // FIXME: Path/Lit might actually evaluate to ref, but inference is unimplemented. | ||
660 | Pat::Path(..) | Pat::Lit(..) => true, | ||
661 | Pat::Wild | Pat::Bind { .. } | Pat::Ref { .. } | Pat::Missing => false, | ||
662 | }; | ||
663 | if is_non_ref_pat { | ||
664 | while let Some((inner, mutability)) = expected.as_reference() { | ||
665 | expected = inner; | ||
666 | default_bm = match default_bm { | ||
667 | BindingMode::Move => BindingMode::Ref(mutability), | ||
668 | BindingMode::Ref(Mutability::Shared) => BindingMode::Ref(Mutability::Shared), | ||
669 | BindingMode::Ref(Mutability::Mut) => BindingMode::Ref(mutability), | ||
670 | } | ||
671 | } | ||
672 | } else if let Pat::Ref { .. } = &body[pat] { | ||
673 | tested_by!(match_ergonomics_ref); | ||
674 | // When you encounter a `&pat` pattern, reset to Move. | ||
675 | // This is so that `w` is by value: `let (_, &w) = &(1, &2);` | ||
676 | default_bm = BindingMode::Move; | ||
677 | } | ||
678 | |||
679 | // Lose mutability. | ||
680 | let default_bm = default_bm; | ||
681 | let expected = expected; | ||
682 | |||
683 | let ty = match &body[pat] { | ||
684 | Pat::Tuple(ref args) => { | ||
685 | let expectations = match expected.as_tuple() { | ||
686 | Some(parameters) => &*parameters.0, | ||
687 | _ => &[], | ||
688 | }; | ||
689 | let expectations_iter = expectations.iter().chain(repeat(&Ty::Unknown)); | ||
690 | |||
691 | let inner_tys = args | ||
692 | .iter() | ||
693 | .zip(expectations_iter) | ||
694 | .map(|(&pat, ty)| self.infer_pat(pat, ty, default_bm)) | ||
695 | .collect(); | ||
696 | |||
697 | Ty::apply(TypeCtor::Tuple { cardinality: args.len() as u16 }, Substs(inner_tys)) | ||
698 | } | ||
699 | Pat::Ref { pat, mutability } => { | ||
700 | let expectation = match expected.as_reference() { | ||
701 | Some((inner_ty, exp_mut)) => { | ||
702 | if *mutability != exp_mut { | ||
703 | // FIXME: emit type error? | ||
704 | } | ||
705 | inner_ty | ||
706 | } | ||
707 | _ => &Ty::Unknown, | ||
708 | }; | ||
709 | let subty = self.infer_pat(*pat, expectation, default_bm); | ||
710 | Ty::apply_one(TypeCtor::Ref(*mutability), subty) | ||
711 | } | ||
712 | Pat::TupleStruct { path: p, args: subpats } => { | ||
713 | self.infer_tuple_struct_pat(p.as_ref(), subpats, expected, default_bm) | ||
714 | } | ||
715 | Pat::Record { path: p, args: fields } => { | ||
716 | self.infer_record_pat(p.as_ref(), fields, expected, default_bm, pat) | ||
717 | } | ||
718 | Pat::Path(path) => { | ||
719 | // FIXME use correct resolver for the surrounding expression | ||
720 | let resolver = self.resolver.clone(); | ||
721 | self.infer_path(&resolver, &path, pat.into()).unwrap_or(Ty::Unknown) | ||
722 | } | ||
723 | Pat::Bind { mode, name: _, subpat } => { | ||
724 | let mode = if mode == &BindingAnnotation::Unannotated { | ||
725 | default_bm | ||
726 | } else { | ||
727 | BindingMode::convert(*mode) | ||
728 | }; | ||
729 | let inner_ty = if let Some(subpat) = subpat { | ||
730 | self.infer_pat(*subpat, expected, default_bm) | ||
731 | } else { | ||
732 | expected.clone() | ||
733 | }; | ||
734 | let inner_ty = self.insert_type_vars_shallow(inner_ty); | ||
735 | |||
736 | let bound_ty = match mode { | ||
737 | BindingMode::Ref(mutability) => { | ||
738 | Ty::apply_one(TypeCtor::Ref(mutability), inner_ty.clone()) | ||
739 | } | ||
740 | BindingMode::Move => inner_ty.clone(), | ||
741 | }; | ||
742 | let bound_ty = self.resolve_ty_as_possible(&mut vec![], bound_ty); | ||
743 | self.write_pat_ty(pat, bound_ty); | ||
744 | return inner_ty; | ||
745 | } | ||
746 | _ => Ty::Unknown, | ||
747 | }; | ||
748 | // use a new type variable if we got Ty::Unknown here | ||
749 | let ty = self.insert_type_vars_shallow(ty); | ||
750 | self.unify(&ty, expected); | ||
751 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
752 | self.write_pat_ty(pat, ty.clone()); | ||
753 | ty | ||
754 | } | ||
755 | |||
756 | fn substs_for_method_call( | ||
757 | &mut self, | ||
758 | def_generics: Option<Arc<GenericParams>>, | ||
759 | generic_args: Option<&GenericArgs>, | ||
760 | receiver_ty: &Ty, | ||
761 | ) -> Substs { | ||
762 | let (parent_param_count, param_count) = | ||
763 | def_generics.as_ref().map_or((0, 0), |g| (g.count_parent_params(), g.params.len())); | ||
764 | let mut substs = Vec::with_capacity(parent_param_count + param_count); | ||
765 | // Parent arguments are unknown, except for the receiver type | ||
766 | if let Some(parent_generics) = def_generics.and_then(|p| p.parent_params.clone()) { | ||
767 | for param in &parent_generics.params { | ||
768 | if param.name == name::SELF_TYPE { | ||
769 | substs.push(receiver_ty.clone()); | ||
770 | } else { | ||
771 | substs.push(Ty::Unknown); | ||
772 | } | ||
773 | } | ||
774 | } | ||
775 | // handle provided type arguments | ||
776 | if let Some(generic_args) = generic_args { | ||
777 | // if args are provided, it should be all of them, but we can't rely on that | ||
778 | for arg in generic_args.args.iter().take(param_count) { | ||
779 | match arg { | ||
780 | GenericArg::Type(type_ref) => { | ||
781 | let ty = self.make_ty(type_ref); | ||
782 | substs.push(ty); | ||
783 | } | ||
784 | } | ||
785 | } | ||
786 | }; | ||
787 | let supplied_params = substs.len(); | ||
788 | for _ in supplied_params..parent_param_count + param_count { | ||
789 | substs.push(Ty::Unknown); | ||
790 | } | ||
791 | assert_eq!(substs.len(), parent_param_count + param_count); | ||
792 | Substs(substs.into()) | ||
793 | } | ||
794 | |||
795 | fn register_obligations_for_call(&mut self, callable_ty: &Ty) { | ||
796 | if let Ty::Apply(a_ty) = callable_ty { | ||
797 | if let TypeCtor::FnDef(def) = a_ty.ctor { | ||
798 | let generic_predicates = self.db.generic_predicates(def.into()); | ||
799 | for predicate in generic_predicates.iter() { | ||
800 | let predicate = predicate.clone().subst(&a_ty.parameters); | ||
801 | if let Some(obligation) = Obligation::from_predicate(predicate) { | ||
802 | self.obligations.push(obligation); | ||
803 | } | ||
804 | } | ||
805 | // add obligation for trait implementation, if this is a trait method | ||
806 | match def { | ||
807 | CallableDef::Function(f) => { | ||
808 | if let Some(trait_) = f.parent_trait(self.db) { | ||
809 | // construct a TraitDef | ||
810 | let substs = a_ty.parameters.prefix( | ||
811 | trait_.generic_params(self.db).count_params_including_parent(), | ||
812 | ); | ||
813 | self.obligations.push(Obligation::Trait(TraitRef { trait_, substs })); | ||
814 | } | ||
815 | } | ||
816 | CallableDef::Struct(_) | CallableDef::EnumVariant(_) => {} | ||
817 | } | ||
818 | } | ||
819 | } | ||
820 | } | ||
821 | |||
822 | fn infer_method_call( | ||
823 | &mut self, | ||
824 | tgt_expr: ExprId, | ||
825 | receiver: ExprId, | ||
826 | args: &[ExprId], | ||
827 | method_name: &Name, | ||
828 | generic_args: Option<&GenericArgs>, | ||
829 | ) -> Ty { | ||
830 | let receiver_ty = self.infer_expr(receiver, &Expectation::none()); | ||
831 | let canonicalized_receiver = self.canonicalizer().canonicalize_ty(receiver_ty.clone()); | ||
832 | let resolved = method_resolution::lookup_method( | ||
833 | &canonicalized_receiver.value, | ||
834 | self.db, | ||
835 | method_name, | ||
836 | &self.resolver, | ||
837 | ); | ||
838 | let (derefed_receiver_ty, method_ty, def_generics) = match resolved { | ||
839 | Some((ty, func)) => { | ||
840 | let ty = canonicalized_receiver.decanonicalize_ty(ty); | ||
841 | self.write_method_resolution(tgt_expr, func); | ||
842 | ( | ||
843 | ty, | ||
844 | self.db.type_for_def(func.into(), Namespace::Values), | ||
845 | Some(func.generic_params(self.db)), | ||
846 | ) | ||
847 | } | ||
848 | None => (receiver_ty, Ty::Unknown, None), | ||
849 | }; | ||
850 | let substs = self.substs_for_method_call(def_generics, generic_args, &derefed_receiver_ty); | ||
851 | let method_ty = method_ty.apply_substs(substs); | ||
852 | let method_ty = self.insert_type_vars(method_ty); | ||
853 | self.register_obligations_for_call(&method_ty); | ||
854 | let (expected_receiver_ty, param_tys, ret_ty) = match method_ty.callable_sig(self.db) { | ||
855 | Some(sig) => { | ||
856 | if !sig.params().is_empty() { | ||
857 | (sig.params()[0].clone(), sig.params()[1..].to_vec(), sig.ret().clone()) | ||
858 | } else { | ||
859 | (Ty::Unknown, Vec::new(), sig.ret().clone()) | ||
860 | } | ||
861 | } | ||
862 | None => (Ty::Unknown, Vec::new(), Ty::Unknown), | ||
863 | }; | ||
864 | // Apply autoref so the below unification works correctly | ||
865 | // FIXME: return correct autorefs from lookup_method | ||
866 | let actual_receiver_ty = match expected_receiver_ty.as_reference() { | ||
867 | Some((_, mutability)) => Ty::apply_one(TypeCtor::Ref(mutability), derefed_receiver_ty), | ||
868 | _ => derefed_receiver_ty, | ||
869 | }; | ||
870 | self.unify(&expected_receiver_ty, &actual_receiver_ty); | ||
871 | |||
872 | self.check_call_arguments(args, ¶m_tys); | ||
873 | let ret_ty = self.normalize_associated_types_in(ret_ty); | ||
874 | ret_ty | ||
875 | } | ||
876 | |||
877 | /// Infer type of expression with possibly implicit coerce to the expected type. | ||
878 | /// Return the type after possible coercion. | ||
879 | fn infer_expr_coerce(&mut self, expr: ExprId, expected: &Expectation) -> Ty { | ||
880 | let ty = self.infer_expr_inner(expr, &expected); | ||
881 | let ty = if !self.coerce(&ty, &expected.ty) { | ||
882 | self.result | ||
883 | .type_mismatches | ||
884 | .insert(expr, TypeMismatch { expected: expected.ty.clone(), actual: ty.clone() }); | ||
885 | // Return actual type when type mismatch. | ||
886 | // This is needed for diagnostic when return type mismatch. | ||
887 | ty | ||
888 | } else if expected.ty == Ty::Unknown { | ||
889 | ty | ||
890 | } else { | ||
891 | expected.ty.clone() | ||
892 | }; | ||
893 | |||
894 | self.resolve_ty_as_possible(&mut vec![], ty) | ||
895 | } | ||
896 | |||
897 | /// Merge two types from different branches, with possible implicit coerce. | ||
898 | /// | ||
899 | /// Note that it is only possible that one type are coerced to another. | ||
900 | /// Coercing both types to another least upper bound type is not possible in rustc, | ||
901 | /// which will simply result in "incompatible types" error. | ||
902 | fn coerce_merge_branch<'t>(&mut self, ty1: &Ty, ty2: &Ty) -> Ty { | ||
903 | if self.coerce(ty1, ty2) { | ||
904 | ty2.clone() | ||
905 | } else if self.coerce(ty2, ty1) { | ||
906 | ty1.clone() | ||
907 | } else { | ||
908 | tested_by!(coerce_merge_fail_fallback); | ||
909 | // For incompatible types, we use the latter one as result | ||
910 | // to be better recovery for `if` without `else`. | ||
911 | ty2.clone() | ||
912 | } | ||
913 | } | ||
914 | |||
915 | /// Unify two types, but may coerce the first one to the second one | ||
916 | /// using "implicit coercion rules" if needed. | ||
917 | /// | ||
918 | /// See: https://doc.rust-lang.org/nomicon/coercions.html | ||
919 | fn coerce(&mut self, from_ty: &Ty, to_ty: &Ty) -> bool { | ||
920 | let from_ty = self.resolve_ty_shallow(from_ty).into_owned(); | ||
921 | let to_ty = self.resolve_ty_shallow(to_ty); | ||
922 | self.coerce_inner(from_ty, &to_ty) | ||
923 | } | ||
924 | |||
925 | fn coerce_inner(&mut self, mut from_ty: Ty, to_ty: &Ty) -> bool { | ||
926 | match (&from_ty, to_ty) { | ||
927 | // Never type will make type variable to fallback to Never Type instead of Unknown. | ||
928 | (ty_app!(TypeCtor::Never), Ty::Infer(InferTy::TypeVar(tv))) => { | ||
929 | let var = self.new_maybe_never_type_var(); | ||
930 | self.var_unification_table.union_value(*tv, TypeVarValue::Known(var)); | ||
931 | return true; | ||
932 | } | ||
933 | (ty_app!(TypeCtor::Never), _) => return true, | ||
934 | |||
935 | // Trivial cases, this should go after `never` check to | ||
936 | // avoid infer result type to be never | ||
937 | _ => { | ||
938 | if self.unify_inner_trivial(&from_ty, &to_ty) { | ||
939 | return true; | ||
940 | } | ||
941 | } | ||
942 | } | ||
943 | |||
944 | // Pointer weakening and function to pointer | ||
945 | match (&mut from_ty, to_ty) { | ||
946 | // `*mut T`, `&mut T, `&T`` -> `*const T` | ||
947 | // `&mut T` -> `&T` | ||
948 | // `&mut T` -> `*mut T` | ||
949 | (ty_app!(c1@TypeCtor::RawPtr(_)), ty_app!(c2@TypeCtor::RawPtr(Mutability::Shared))) | ||
950 | | (ty_app!(c1@TypeCtor::Ref(_)), ty_app!(c2@TypeCtor::RawPtr(Mutability::Shared))) | ||
951 | | (ty_app!(c1@TypeCtor::Ref(_)), ty_app!(c2@TypeCtor::Ref(Mutability::Shared))) | ||
952 | | (ty_app!(c1@TypeCtor::Ref(Mutability::Mut)), ty_app!(c2@TypeCtor::RawPtr(_))) => { | ||
953 | *c1 = *c2; | ||
954 | } | ||
955 | |||
956 | // Illegal mutablity conversion | ||
957 | ( | ||
958 | ty_app!(TypeCtor::RawPtr(Mutability::Shared)), | ||
959 | ty_app!(TypeCtor::RawPtr(Mutability::Mut)), | ||
960 | ) | ||
961 | | ( | ||
962 | ty_app!(TypeCtor::Ref(Mutability::Shared)), | ||
963 | ty_app!(TypeCtor::Ref(Mutability::Mut)), | ||
964 | ) => return false, | ||
965 | |||
966 | // `{function_type}` -> `fn()` | ||
967 | (ty_app!(TypeCtor::FnDef(_)), ty_app!(TypeCtor::FnPtr { .. })) => { | ||
968 | match from_ty.callable_sig(self.db) { | ||
969 | None => return false, | ||
970 | Some(sig) => { | ||
971 | let num_args = sig.params_and_return.len() as u16 - 1; | ||
972 | from_ty = | ||
973 | Ty::apply(TypeCtor::FnPtr { num_args }, Substs(sig.params_and_return)); | ||
974 | } | ||
975 | } | ||
976 | } | ||
977 | |||
978 | _ => {} | ||
979 | } | ||
980 | |||
981 | if let Some(ret) = self.try_coerce_unsized(&from_ty, &to_ty) { | ||
982 | return ret; | ||
983 | } | ||
984 | |||
985 | // Auto Deref if cannot coerce | ||
986 | match (&from_ty, to_ty) { | ||
987 | // FIXME: DerefMut | ||
988 | (ty_app!(TypeCtor::Ref(_), st1), ty_app!(TypeCtor::Ref(_), st2)) => { | ||
989 | self.unify_autoderef_behind_ref(&st1[0], &st2[0]) | ||
990 | } | ||
991 | |||
992 | // Otherwise, normal unify | ||
993 | _ => self.unify(&from_ty, to_ty), | ||
994 | } | ||
995 | } | ||
996 | |||
997 | /// Coerce a type using `from_ty: CoerceUnsized<ty_ty>` | ||
998 | /// | ||
999 | /// See: https://doc.rust-lang.org/nightly/std/marker/trait.CoerceUnsized.html | ||
1000 | fn try_coerce_unsized(&mut self, from_ty: &Ty, to_ty: &Ty) -> Option<bool> { | ||
1001 | let (ctor1, st1, ctor2, st2) = match (from_ty, to_ty) { | ||
1002 | (ty_app!(ctor1, st1), ty_app!(ctor2, st2)) => (ctor1, st1, ctor2, st2), | ||
1003 | _ => return None, | ||
1004 | }; | ||
1005 | |||
1006 | let coerce_generic_index = *self.coerce_unsized_map.get(&(*ctor1, *ctor2))?; | ||
1007 | |||
1008 | // Check `Unsize` first | ||
1009 | match self.check_unsize_and_coerce( | ||
1010 | st1.0.get(coerce_generic_index)?, | ||
1011 | st2.0.get(coerce_generic_index)?, | ||
1012 | 0, | ||
1013 | ) { | ||
1014 | Some(true) => {} | ||
1015 | ret => return ret, | ||
1016 | } | ||
1017 | |||
1018 | let ret = st1 | ||
1019 | .iter() | ||
1020 | .zip(st2.iter()) | ||
1021 | .enumerate() | ||
1022 | .filter(|&(idx, _)| idx != coerce_generic_index) | ||
1023 | .all(|(_, (ty1, ty2))| self.unify(ty1, ty2)); | ||
1024 | |||
1025 | Some(ret) | ||
1026 | } | ||
1027 | |||
1028 | /// Check if `from_ty: Unsize<to_ty>`, and coerce to `to_ty` if it holds. | ||
1029 | /// | ||
1030 | /// It should not be directly called. It is only used by `try_coerce_unsized`. | ||
1031 | /// | ||
1032 | /// See: https://doc.rust-lang.org/nightly/std/marker/trait.Unsize.html | ||
1033 | fn check_unsize_and_coerce(&mut self, from_ty: &Ty, to_ty: &Ty, depth: usize) -> Option<bool> { | ||
1034 | if depth > 1000 { | ||
1035 | panic!("Infinite recursion in coercion"); | ||
1036 | } | ||
1037 | |||
1038 | match (&from_ty, &to_ty) { | ||
1039 | // `[T; N]` -> `[T]` | ||
1040 | (ty_app!(TypeCtor::Array, st1), ty_app!(TypeCtor::Slice, st2)) => { | ||
1041 | Some(self.unify(&st1[0], &st2[0])) | ||
1042 | } | ||
1043 | |||
1044 | // `T` -> `dyn Trait` when `T: Trait` | ||
1045 | (_, Ty::Dyn(_)) => { | ||
1046 | // FIXME: Check predicates | ||
1047 | Some(true) | ||
1048 | } | ||
1049 | |||
1050 | // `(..., T)` -> `(..., U)` when `T: Unsize<U>` | ||
1051 | ( | ||
1052 | ty_app!(TypeCtor::Tuple { cardinality: len1 }, st1), | ||
1053 | ty_app!(TypeCtor::Tuple { cardinality: len2 }, st2), | ||
1054 | ) => { | ||
1055 | if len1 != len2 || *len1 == 0 { | ||
1056 | return None; | ||
1057 | } | ||
1058 | |||
1059 | match self.check_unsize_and_coerce( | ||
1060 | st1.last().unwrap(), | ||
1061 | st2.last().unwrap(), | ||
1062 | depth + 1, | ||
1063 | ) { | ||
1064 | Some(true) => {} | ||
1065 | ret => return ret, | ||
1066 | } | ||
1067 | |||
1068 | let ret = st1[..st1.len() - 1] | ||
1069 | .iter() | ||
1070 | .zip(&st2[..st2.len() - 1]) | ||
1071 | .all(|(ty1, ty2)| self.unify(ty1, ty2)); | ||
1072 | |||
1073 | Some(ret) | ||
1074 | } | ||
1075 | |||
1076 | // Foo<..., T, ...> is Unsize<Foo<..., U, ...>> if: | ||
1077 | // - T: Unsize<U> | ||
1078 | // - Foo is a struct | ||
1079 | // - Only the last field of Foo has a type involving T | ||
1080 | // - T is not part of the type of any other fields | ||
1081 | // - Bar<T>: Unsize<Bar<U>>, if the last field of Foo has type Bar<T> | ||
1082 | ( | ||
1083 | ty_app!(TypeCtor::Adt(Adt::Struct(struct1)), st1), | ||
1084 | ty_app!(TypeCtor::Adt(Adt::Struct(struct2)), st2), | ||
1085 | ) if struct1 == struct2 => { | ||
1086 | let fields = struct1.fields(self.db); | ||
1087 | let (last_field, prev_fields) = fields.split_last()?; | ||
1088 | |||
1089 | // Get the generic parameter involved in the last field. | ||
1090 | let unsize_generic_index = { | ||
1091 | let mut index = None; | ||
1092 | let mut multiple_param = false; | ||
1093 | last_field.ty(self.db).walk(&mut |ty| match ty { | ||
1094 | &Ty::Param { idx, .. } => { | ||
1095 | if index.is_none() { | ||
1096 | index = Some(idx); | ||
1097 | } else if Some(idx) != index { | ||
1098 | multiple_param = true; | ||
1099 | } | ||
1100 | } | ||
1101 | _ => {} | ||
1102 | }); | ||
1103 | |||
1104 | if multiple_param { | ||
1105 | return None; | ||
1106 | } | ||
1107 | index? | ||
1108 | }; | ||
1109 | |||
1110 | // Check other fields do not involve it. | ||
1111 | let mut multiple_used = false; | ||
1112 | prev_fields.iter().for_each(|field| { | ||
1113 | field.ty(self.db).walk(&mut |ty| match ty { | ||
1114 | &Ty::Param { idx, .. } if idx == unsize_generic_index => { | ||
1115 | multiple_used = true | ||
1116 | } | ||
1117 | _ => {} | ||
1118 | }) | ||
1119 | }); | ||
1120 | if multiple_used { | ||
1121 | return None; | ||
1122 | } | ||
1123 | |||
1124 | let unsize_generic_index = unsize_generic_index as usize; | ||
1125 | |||
1126 | // Check `Unsize` first | ||
1127 | match self.check_unsize_and_coerce( | ||
1128 | st1.get(unsize_generic_index)?, | ||
1129 | st2.get(unsize_generic_index)?, | ||
1130 | depth + 1, | ||
1131 | ) { | ||
1132 | Some(true) => {} | ||
1133 | ret => return ret, | ||
1134 | } | ||
1135 | |||
1136 | // Then unify other parameters | ||
1137 | let ret = st1 | ||
1138 | .iter() | ||
1139 | .zip(st2.iter()) | ||
1140 | .enumerate() | ||
1141 | .filter(|&(idx, _)| idx != unsize_generic_index) | ||
1142 | .all(|(_, (ty1, ty2))| self.unify(ty1, ty2)); | ||
1143 | |||
1144 | Some(ret) | ||
1145 | } | ||
1146 | |||
1147 | _ => None, | ||
1148 | } | ||
1149 | } | ||
1150 | |||
1151 | /// Unify `from_ty` to `to_ty` with optional auto Deref | ||
1152 | /// | ||
1153 | /// Note that the parameters are already stripped the outer reference. | ||
1154 | fn unify_autoderef_behind_ref(&mut self, from_ty: &Ty, to_ty: &Ty) -> bool { | ||
1155 | let canonicalized = self.canonicalizer().canonicalize_ty(from_ty.clone()); | ||
1156 | let to_ty = self.resolve_ty_shallow(&to_ty); | ||
1157 | // FIXME: Auto DerefMut | ||
1158 | for derefed_ty in | ||
1159 | autoderef::autoderef(self.db, &self.resolver.clone(), canonicalized.value.clone()) | ||
1160 | { | ||
1161 | let derefed_ty = canonicalized.decanonicalize_ty(derefed_ty.value); | ||
1162 | match (&*self.resolve_ty_shallow(&derefed_ty), &*to_ty) { | ||
1163 | // Stop when constructor matches. | ||
1164 | (ty_app!(from_ctor, st1), ty_app!(to_ctor, st2)) if from_ctor == to_ctor => { | ||
1165 | // It will not recurse to `coerce`. | ||
1166 | return self.unify_substs(st1, st2, 0); | ||
1167 | } | ||
1168 | _ => {} | ||
1169 | } | ||
1170 | } | ||
1171 | |||
1172 | false | ||
1173 | } | ||
1174 | |||
1175 | fn infer_expr(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty { | ||
1176 | let ty = self.infer_expr_inner(tgt_expr, expected); | ||
1177 | let could_unify = self.unify(&ty, &expected.ty); | ||
1178 | if !could_unify { | ||
1179 | self.result.type_mismatches.insert( | ||
1180 | tgt_expr, | ||
1181 | TypeMismatch { expected: expected.ty.clone(), actual: ty.clone() }, | ||
1182 | ); | ||
1183 | } | ||
1184 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
1185 | ty | ||
1186 | } | ||
1187 | |||
1188 | fn infer_expr_inner(&mut self, tgt_expr: ExprId, expected: &Expectation) -> Ty { | ||
1189 | let body = Arc::clone(&self.body); // avoid borrow checker problem | ||
1190 | let ty = match &body[tgt_expr] { | ||
1191 | Expr::Missing => Ty::Unknown, | ||
1192 | Expr::If { condition, then_branch, else_branch } => { | ||
1193 | // if let is desugared to match, so this is always simple if | ||
1194 | self.infer_expr(*condition, &Expectation::has_type(Ty::simple(TypeCtor::Bool))); | ||
1195 | |||
1196 | let then_ty = self.infer_expr_inner(*then_branch, &expected); | ||
1197 | let else_ty = match else_branch { | ||
1198 | Some(else_branch) => self.infer_expr_inner(*else_branch, &expected), | ||
1199 | None => Ty::unit(), | ||
1200 | }; | ||
1201 | |||
1202 | self.coerce_merge_branch(&then_ty, &else_ty) | ||
1203 | } | ||
1204 | Expr::Block { statements, tail } => self.infer_block(statements, *tail, expected), | ||
1205 | Expr::TryBlock { body } => { | ||
1206 | let _inner = self.infer_expr(*body, expected); | ||
1207 | // FIXME should be std::result::Result<{inner}, _> | ||
1208 | Ty::Unknown | ||
1209 | } | ||
1210 | Expr::Loop { body } => { | ||
1211 | self.infer_expr(*body, &Expectation::has_type(Ty::unit())); | ||
1212 | // FIXME handle break with value | ||
1213 | Ty::simple(TypeCtor::Never) | ||
1214 | } | ||
1215 | Expr::While { condition, body } => { | ||
1216 | // while let is desugared to a match loop, so this is always simple while | ||
1217 | self.infer_expr(*condition, &Expectation::has_type(Ty::simple(TypeCtor::Bool))); | ||
1218 | self.infer_expr(*body, &Expectation::has_type(Ty::unit())); | ||
1219 | Ty::unit() | ||
1220 | } | ||
1221 | Expr::For { iterable, body, pat } => { | ||
1222 | let iterable_ty = self.infer_expr(*iterable, &Expectation::none()); | ||
1223 | |||
1224 | let pat_ty = match self.resolve_into_iter_item() { | ||
1225 | Some(into_iter_item_alias) => { | ||
1226 | let pat_ty = self.new_type_var(); | ||
1227 | let projection = ProjectionPredicate { | ||
1228 | ty: pat_ty.clone(), | ||
1229 | projection_ty: ProjectionTy { | ||
1230 | associated_ty: into_iter_item_alias, | ||
1231 | parameters: Substs::single(iterable_ty), | ||
1232 | }, | ||
1233 | }; | ||
1234 | self.obligations.push(Obligation::Projection(projection)); | ||
1235 | self.resolve_ty_as_possible(&mut vec![], pat_ty) | ||
1236 | } | ||
1237 | None => Ty::Unknown, | ||
1238 | }; | ||
1239 | |||
1240 | self.infer_pat(*pat, &pat_ty, BindingMode::default()); | ||
1241 | self.infer_expr(*body, &Expectation::has_type(Ty::unit())); | ||
1242 | Ty::unit() | ||
1243 | } | ||
1244 | Expr::Lambda { body, args, arg_types } => { | ||
1245 | assert_eq!(args.len(), arg_types.len()); | ||
1246 | |||
1247 | let mut sig_tys = Vec::new(); | ||
1248 | |||
1249 | for (arg_pat, arg_type) in args.iter().zip(arg_types.iter()) { | ||
1250 | let expected = if let Some(type_ref) = arg_type { | ||
1251 | self.make_ty(type_ref) | ||
1252 | } else { | ||
1253 | Ty::Unknown | ||
1254 | }; | ||
1255 | let arg_ty = self.infer_pat(*arg_pat, &expected, BindingMode::default()); | ||
1256 | sig_tys.push(arg_ty); | ||
1257 | } | ||
1258 | |||
1259 | // add return type | ||
1260 | let ret_ty = self.new_type_var(); | ||
1261 | sig_tys.push(ret_ty.clone()); | ||
1262 | let sig_ty = Ty::apply( | ||
1263 | TypeCtor::FnPtr { num_args: sig_tys.len() as u16 - 1 }, | ||
1264 | Substs(sig_tys.into()), | ||
1265 | ); | ||
1266 | let closure_ty = Ty::apply_one( | ||
1267 | TypeCtor::Closure { def: self.body.owner(), expr: tgt_expr }, | ||
1268 | sig_ty, | ||
1269 | ); | ||
1270 | |||
1271 | // Eagerly try to relate the closure type with the expected | ||
1272 | // type, otherwise we often won't have enough information to | ||
1273 | // infer the body. | ||
1274 | self.coerce(&closure_ty, &expected.ty); | ||
1275 | |||
1276 | self.infer_expr(*body, &Expectation::has_type(ret_ty)); | ||
1277 | closure_ty | ||
1278 | } | ||
1279 | Expr::Call { callee, args } => { | ||
1280 | let callee_ty = self.infer_expr(*callee, &Expectation::none()); | ||
1281 | let (param_tys, ret_ty) = match callee_ty.callable_sig(self.db) { | ||
1282 | Some(sig) => (sig.params().to_vec(), sig.ret().clone()), | ||
1283 | None => { | ||
1284 | // Not callable | ||
1285 | // FIXME: report an error | ||
1286 | (Vec::new(), Ty::Unknown) | ||
1287 | } | ||
1288 | }; | ||
1289 | self.register_obligations_for_call(&callee_ty); | ||
1290 | self.check_call_arguments(args, ¶m_tys); | ||
1291 | let ret_ty = self.normalize_associated_types_in(ret_ty); | ||
1292 | ret_ty | ||
1293 | } | ||
1294 | Expr::MethodCall { receiver, args, method_name, generic_args } => self | ||
1295 | .infer_method_call(tgt_expr, *receiver, &args, &method_name, generic_args.as_ref()), | ||
1296 | Expr::Match { expr, arms } => { | ||
1297 | let input_ty = self.infer_expr(*expr, &Expectation::none()); | ||
1298 | |||
1299 | let mut result_ty = self.new_maybe_never_type_var(); | ||
1300 | |||
1301 | for arm in arms { | ||
1302 | for &pat in &arm.pats { | ||
1303 | let _pat_ty = self.infer_pat(pat, &input_ty, BindingMode::default()); | ||
1304 | } | ||
1305 | if let Some(guard_expr) = arm.guard { | ||
1306 | self.infer_expr( | ||
1307 | guard_expr, | ||
1308 | &Expectation::has_type(Ty::simple(TypeCtor::Bool)), | ||
1309 | ); | ||
1310 | } | ||
1311 | |||
1312 | let arm_ty = self.infer_expr_inner(arm.expr, &expected); | ||
1313 | result_ty = self.coerce_merge_branch(&result_ty, &arm_ty); | ||
1314 | } | ||
1315 | |||
1316 | result_ty | ||
1317 | } | ||
1318 | Expr::Path(p) => { | ||
1319 | // FIXME this could be more efficient... | ||
1320 | let resolver = expr::resolver_for_expr(self.body.clone(), self.db, tgt_expr); | ||
1321 | self.infer_path(&resolver, p, tgt_expr.into()).unwrap_or(Ty::Unknown) | ||
1322 | } | ||
1323 | Expr::Continue => Ty::simple(TypeCtor::Never), | ||
1324 | Expr::Break { expr } => { | ||
1325 | if let Some(expr) = expr { | ||
1326 | // FIXME handle break with value | ||
1327 | self.infer_expr(*expr, &Expectation::none()); | ||
1328 | } | ||
1329 | Ty::simple(TypeCtor::Never) | ||
1330 | } | ||
1331 | Expr::Return { expr } => { | ||
1332 | if let Some(expr) = expr { | ||
1333 | self.infer_expr(*expr, &Expectation::has_type(self.return_ty.clone())); | ||
1334 | } | ||
1335 | Ty::simple(TypeCtor::Never) | ||
1336 | } | ||
1337 | Expr::RecordLit { path, fields, spread } => { | ||
1338 | let (ty, def_id) = self.resolve_variant(path.as_ref()); | ||
1339 | if let Some(variant) = def_id { | ||
1340 | self.write_variant_resolution(tgt_expr.into(), variant); | ||
1341 | } | ||
1342 | |||
1343 | self.unify(&ty, &expected.ty); | ||
1344 | |||
1345 | let substs = ty.substs().unwrap_or_else(Substs::empty); | ||
1346 | for (field_idx, field) in fields.iter().enumerate() { | ||
1347 | let field_ty = def_id | ||
1348 | .and_then(|it| match it.field(self.db, &field.name) { | ||
1349 | Some(field) => Some(field), | ||
1350 | None => { | ||
1351 | self.push_diagnostic(InferenceDiagnostic::NoSuchField { | ||
1352 | expr: tgt_expr, | ||
1353 | field: field_idx, | ||
1354 | }); | ||
1355 | None | ||
1356 | } | ||
1357 | }) | ||
1358 | .map_or(Ty::Unknown, |field| field.ty(self.db)) | ||
1359 | .subst(&substs); | ||
1360 | self.infer_expr_coerce(field.expr, &Expectation::has_type(field_ty)); | ||
1361 | } | ||
1362 | if let Some(expr) = spread { | ||
1363 | self.infer_expr(*expr, &Expectation::has_type(ty.clone())); | ||
1364 | } | ||
1365 | ty | ||
1366 | } | ||
1367 | Expr::Field { expr, name } => { | ||
1368 | let receiver_ty = self.infer_expr(*expr, &Expectation::none()); | ||
1369 | let canonicalized = self.canonicalizer().canonicalize_ty(receiver_ty); | ||
1370 | let ty = autoderef::autoderef( | ||
1371 | self.db, | ||
1372 | &self.resolver.clone(), | ||
1373 | canonicalized.value.clone(), | ||
1374 | ) | ||
1375 | .find_map(|derefed_ty| match canonicalized.decanonicalize_ty(derefed_ty.value) { | ||
1376 | Ty::Apply(a_ty) => match a_ty.ctor { | ||
1377 | TypeCtor::Tuple { .. } => name | ||
1378 | .as_tuple_index() | ||
1379 | .and_then(|idx| a_ty.parameters.0.get(idx).cloned()), | ||
1380 | TypeCtor::Adt(Adt::Struct(s)) => s.field(self.db, name).map(|field| { | ||
1381 | self.write_field_resolution(tgt_expr, field); | ||
1382 | field.ty(self.db).subst(&a_ty.parameters) | ||
1383 | }), | ||
1384 | _ => None, | ||
1385 | }, | ||
1386 | _ => None, | ||
1387 | }) | ||
1388 | .unwrap_or(Ty::Unknown); | ||
1389 | let ty = self.insert_type_vars(ty); | ||
1390 | self.normalize_associated_types_in(ty) | ||
1391 | } | ||
1392 | Expr::Await { expr } => { | ||
1393 | let inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
1394 | let ty = match self.resolve_future_future_output() { | ||
1395 | Some(future_future_output_alias) => { | ||
1396 | let ty = self.new_type_var(); | ||
1397 | let projection = ProjectionPredicate { | ||
1398 | ty: ty.clone(), | ||
1399 | projection_ty: ProjectionTy { | ||
1400 | associated_ty: future_future_output_alias, | ||
1401 | parameters: Substs::single(inner_ty), | ||
1402 | }, | ||
1403 | }; | ||
1404 | self.obligations.push(Obligation::Projection(projection)); | ||
1405 | self.resolve_ty_as_possible(&mut vec![], ty) | ||
1406 | } | ||
1407 | None => Ty::Unknown, | ||
1408 | }; | ||
1409 | ty | ||
1410 | } | ||
1411 | Expr::Try { expr } => { | ||
1412 | let inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
1413 | let ty = match self.resolve_ops_try_ok() { | ||
1414 | Some(ops_try_ok_alias) => { | ||
1415 | let ty = self.new_type_var(); | ||
1416 | let projection = ProjectionPredicate { | ||
1417 | ty: ty.clone(), | ||
1418 | projection_ty: ProjectionTy { | ||
1419 | associated_ty: ops_try_ok_alias, | ||
1420 | parameters: Substs::single(inner_ty), | ||
1421 | }, | ||
1422 | }; | ||
1423 | self.obligations.push(Obligation::Projection(projection)); | ||
1424 | self.resolve_ty_as_possible(&mut vec![], ty) | ||
1425 | } | ||
1426 | None => Ty::Unknown, | ||
1427 | }; | ||
1428 | ty | ||
1429 | } | ||
1430 | Expr::Cast { expr, type_ref } => { | ||
1431 | let _inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
1432 | let cast_ty = self.make_ty(type_ref); | ||
1433 | // FIXME check the cast... | ||
1434 | cast_ty | ||
1435 | } | ||
1436 | Expr::Ref { expr, mutability } => { | ||
1437 | let expectation = | ||
1438 | if let Some((exp_inner, exp_mutability)) = &expected.ty.as_reference() { | ||
1439 | if *exp_mutability == Mutability::Mut && *mutability == Mutability::Shared { | ||
1440 | // FIXME: throw type error - expected mut reference but found shared ref, | ||
1441 | // which cannot be coerced | ||
1442 | } | ||
1443 | Expectation::has_type(Ty::clone(exp_inner)) | ||
1444 | } else { | ||
1445 | Expectation::none() | ||
1446 | }; | ||
1447 | // FIXME reference coercions etc. | ||
1448 | let inner_ty = self.infer_expr(*expr, &expectation); | ||
1449 | Ty::apply_one(TypeCtor::Ref(*mutability), inner_ty) | ||
1450 | } | ||
1451 | Expr::Box { expr } => { | ||
1452 | let inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
1453 | if let Some(box_) = self.resolve_boxed_box() { | ||
1454 | Ty::apply_one(TypeCtor::Adt(box_), inner_ty) | ||
1455 | } else { | ||
1456 | Ty::Unknown | ||
1457 | } | ||
1458 | } | ||
1459 | Expr::UnaryOp { expr, op } => { | ||
1460 | let inner_ty = self.infer_expr(*expr, &Expectation::none()); | ||
1461 | match op { | ||
1462 | UnaryOp::Deref => { | ||
1463 | let canonicalized = self.canonicalizer().canonicalize_ty(inner_ty); | ||
1464 | if let Some(derefed_ty) = | ||
1465 | autoderef::deref(self.db, &self.resolver, &canonicalized.value) | ||
1466 | { | ||
1467 | canonicalized.decanonicalize_ty(derefed_ty.value) | ||
1468 | } else { | ||
1469 | Ty::Unknown | ||
1470 | } | ||
1471 | } | ||
1472 | UnaryOp::Neg => { | ||
1473 | match &inner_ty { | ||
1474 | Ty::Apply(a_ty) => match a_ty.ctor { | ||
1475 | TypeCtor::Int(primitive::UncertainIntTy::Unknown) | ||
1476 | | TypeCtor::Int(primitive::UncertainIntTy::Known( | ||
1477 | primitive::IntTy { | ||
1478 | signedness: primitive::Signedness::Signed, | ||
1479 | .. | ||
1480 | }, | ||
1481 | )) | ||
1482 | | TypeCtor::Float(..) => inner_ty, | ||
1483 | _ => Ty::Unknown, | ||
1484 | }, | ||
1485 | Ty::Infer(InferTy::IntVar(..)) | Ty::Infer(InferTy::FloatVar(..)) => { | ||
1486 | inner_ty | ||
1487 | } | ||
1488 | // FIXME: resolve ops::Neg trait | ||
1489 | _ => Ty::Unknown, | ||
1490 | } | ||
1491 | } | ||
1492 | UnaryOp::Not => { | ||
1493 | match &inner_ty { | ||
1494 | Ty::Apply(a_ty) => match a_ty.ctor { | ||
1495 | TypeCtor::Bool | TypeCtor::Int(_) => inner_ty, | ||
1496 | _ => Ty::Unknown, | ||
1497 | }, | ||
1498 | Ty::Infer(InferTy::IntVar(..)) => inner_ty, | ||
1499 | // FIXME: resolve ops::Not trait for inner_ty | ||
1500 | _ => Ty::Unknown, | ||
1501 | } | ||
1502 | } | ||
1503 | } | ||
1504 | } | ||
1505 | Expr::BinaryOp { lhs, rhs, op } => match op { | ||
1506 | Some(op) => { | ||
1507 | let lhs_expectation = match op { | ||
1508 | BinaryOp::LogicOp(..) => Expectation::has_type(Ty::simple(TypeCtor::Bool)), | ||
1509 | _ => Expectation::none(), | ||
1510 | }; | ||
1511 | let lhs_ty = self.infer_expr(*lhs, &lhs_expectation); | ||
1512 | // FIXME: find implementation of trait corresponding to operation | ||
1513 | // symbol and resolve associated `Output` type | ||
1514 | let rhs_expectation = op::binary_op_rhs_expectation(*op, lhs_ty); | ||
1515 | let rhs_ty = self.infer_expr(*rhs, &Expectation::has_type(rhs_expectation)); | ||
1516 | |||
1517 | // FIXME: similar as above, return ty is often associated trait type | ||
1518 | op::binary_op_return_ty(*op, rhs_ty) | ||
1519 | } | ||
1520 | _ => Ty::Unknown, | ||
1521 | }, | ||
1522 | Expr::Index { base, index } => { | ||
1523 | let _base_ty = self.infer_expr(*base, &Expectation::none()); | ||
1524 | let _index_ty = self.infer_expr(*index, &Expectation::none()); | ||
1525 | // FIXME: use `std::ops::Index::Output` to figure out the real return type | ||
1526 | Ty::Unknown | ||
1527 | } | ||
1528 | Expr::Tuple { exprs } => { | ||
1529 | let mut tys = match &expected.ty { | ||
1530 | ty_app!(TypeCtor::Tuple { .. }, st) => st | ||
1531 | .iter() | ||
1532 | .cloned() | ||
1533 | .chain(repeat_with(|| self.new_type_var())) | ||
1534 | .take(exprs.len()) | ||
1535 | .collect::<Vec<_>>(), | ||
1536 | _ => (0..exprs.len()).map(|_| self.new_type_var()).collect(), | ||
1537 | }; | ||
1538 | |||
1539 | for (expr, ty) in exprs.iter().zip(tys.iter_mut()) { | ||
1540 | self.infer_expr_coerce(*expr, &Expectation::has_type(ty.clone())); | ||
1541 | } | ||
1542 | |||
1543 | Ty::apply(TypeCtor::Tuple { cardinality: tys.len() as u16 }, Substs(tys.into())) | ||
1544 | } | ||
1545 | Expr::Array(array) => { | ||
1546 | let elem_ty = match &expected.ty { | ||
1547 | ty_app!(TypeCtor::Array, st) | ty_app!(TypeCtor::Slice, st) => { | ||
1548 | st.as_single().clone() | ||
1549 | } | ||
1550 | _ => self.new_type_var(), | ||
1551 | }; | ||
1552 | |||
1553 | match array { | ||
1554 | Array::ElementList(items) => { | ||
1555 | for expr in items.iter() { | ||
1556 | self.infer_expr_coerce(*expr, &Expectation::has_type(elem_ty.clone())); | ||
1557 | } | ||
1558 | } | ||
1559 | Array::Repeat { initializer, repeat } => { | ||
1560 | self.infer_expr_coerce( | ||
1561 | *initializer, | ||
1562 | &Expectation::has_type(elem_ty.clone()), | ||
1563 | ); | ||
1564 | self.infer_expr( | ||
1565 | *repeat, | ||
1566 | &Expectation::has_type(Ty::simple(TypeCtor::Int( | ||
1567 | primitive::UncertainIntTy::Known(primitive::IntTy::usize()), | ||
1568 | ))), | ||
1569 | ); | ||
1570 | } | ||
1571 | } | ||
1572 | |||
1573 | Ty::apply_one(TypeCtor::Array, elem_ty) | ||
1574 | } | ||
1575 | Expr::Literal(lit) => match lit { | ||
1576 | Literal::Bool(..) => Ty::simple(TypeCtor::Bool), | ||
1577 | Literal::String(..) => { | ||
1578 | Ty::apply_one(TypeCtor::Ref(Mutability::Shared), Ty::simple(TypeCtor::Str)) | ||
1579 | } | ||
1580 | Literal::ByteString(..) => { | ||
1581 | let byte_type = Ty::simple(TypeCtor::Int(primitive::UncertainIntTy::Known( | ||
1582 | primitive::IntTy::u8(), | ||
1583 | ))); | ||
1584 | let slice_type = Ty::apply_one(TypeCtor::Slice, byte_type); | ||
1585 | Ty::apply_one(TypeCtor::Ref(Mutability::Shared), slice_type) | ||
1586 | } | ||
1587 | Literal::Char(..) => Ty::simple(TypeCtor::Char), | ||
1588 | Literal::Int(_v, ty) => Ty::simple(TypeCtor::Int(*ty)), | ||
1589 | Literal::Float(_v, ty) => Ty::simple(TypeCtor::Float(*ty)), | ||
1590 | }, | ||
1591 | }; | ||
1592 | // use a new type variable if we got Ty::Unknown here | ||
1593 | let ty = self.insert_type_vars_shallow(ty); | ||
1594 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
1595 | self.write_expr_ty(tgt_expr, ty.clone()); | ||
1596 | ty | ||
1597 | } | ||
1598 | |||
1599 | fn infer_block( | ||
1600 | &mut self, | ||
1601 | statements: &[Statement], | ||
1602 | tail: Option<ExprId>, | ||
1603 | expected: &Expectation, | ||
1604 | ) -> Ty { | ||
1605 | let mut diverges = false; | ||
1606 | for stmt in statements { | ||
1607 | match stmt { | ||
1608 | Statement::Let { pat, type_ref, initializer } => { | ||
1609 | let decl_ty = | ||
1610 | type_ref.as_ref().map(|tr| self.make_ty(tr)).unwrap_or(Ty::Unknown); | ||
1611 | |||
1612 | // Always use the declared type when specified | ||
1613 | let mut ty = decl_ty.clone(); | ||
1614 | |||
1615 | if let Some(expr) = initializer { | ||
1616 | let actual_ty = | ||
1617 | self.infer_expr_coerce(*expr, &Expectation::has_type(decl_ty.clone())); | ||
1618 | if decl_ty == Ty::Unknown { | ||
1619 | ty = actual_ty; | ||
1620 | } | ||
1621 | } | ||
1622 | |||
1623 | let ty = self.resolve_ty_as_possible(&mut vec![], ty); | ||
1624 | self.infer_pat(*pat, &ty, BindingMode::default()); | ||
1625 | } | ||
1626 | Statement::Expr(expr) => { | ||
1627 | if let ty_app!(TypeCtor::Never) = self.infer_expr(*expr, &Expectation::none()) { |