diff options
Diffstat (limited to 'crates/hir_ty/src')
29 files changed, 2072 insertions, 1219 deletions
diff --git a/crates/hir_ty/src/autoderef.rs b/crates/hir_ty/src/autoderef.rs index f8e9db9ae..2c07494a9 100644 --- a/crates/hir_ty/src/autoderef.rs +++ b/crates/hir_ty/src/autoderef.rs | |||
@@ -6,14 +6,15 @@ | |||
6 | use std::iter::successors; | 6 | use std::iter::successors; |
7 | 7 | ||
8 | use base_db::CrateId; | 8 | use base_db::CrateId; |
9 | use chalk_ir::cast::Cast; | 9 | use chalk_ir::{cast::Cast, fold::Fold, interner::HasInterner, VariableKind}; |
10 | use hir_def::lang_item::LangItemTarget; | 10 | use hir_def::lang_item::LangItemTarget; |
11 | use hir_expand::name::name; | 11 | use hir_expand::name::name; |
12 | use log::{info, warn}; | 12 | use log::{info, warn}; |
13 | 13 | ||
14 | use crate::{ | 14 | use crate::{ |
15 | db::HirDatabase, AliasEq, AliasTy, BoundVar, Canonical, CanonicalVarKinds, DebruijnIndex, | 15 | db::HirDatabase, static_lifetime, AliasEq, AliasTy, BoundVar, Canonical, CanonicalVarKinds, |
16 | InEnvironment, Interner, ProjectionTyExt, Solution, Ty, TyBuilder, TyKind, | 16 | DebruijnIndex, InEnvironment, Interner, ProjectionTyExt, Solution, Substitution, Ty, TyBuilder, |
17 | TyKind, | ||
17 | }; | 18 | }; |
18 | 19 | ||
19 | const AUTODEREF_RECURSION_LIMIT: usize = 10; | 20 | const AUTODEREF_RECURSION_LIMIT: usize = 10; |
@@ -35,6 +36,7 @@ pub(crate) fn deref( | |||
35 | krate: CrateId, | 36 | krate: CrateId, |
36 | ty: InEnvironment<&Canonical<Ty>>, | 37 | ty: InEnvironment<&Canonical<Ty>>, |
37 | ) -> Option<Canonical<Ty>> { | 38 | ) -> Option<Canonical<Ty>> { |
39 | let _p = profile::span("deref"); | ||
38 | if let Some(derefed) = builtin_deref(&ty.goal.value) { | 40 | if let Some(derefed) = builtin_deref(&ty.goal.value) { |
39 | Some(Canonical { value: derefed, binders: ty.goal.binders.clone() }) | 41 | Some(Canonical { value: derefed, binders: ty.goal.binders.clone() }) |
40 | } else { | 42 | } else { |
@@ -55,6 +57,7 @@ fn deref_by_trait( | |||
55 | krate: CrateId, | 57 | krate: CrateId, |
56 | ty: InEnvironment<&Canonical<Ty>>, | 58 | ty: InEnvironment<&Canonical<Ty>>, |
57 | ) -> Option<Canonical<Ty>> { | 59 | ) -> Option<Canonical<Ty>> { |
60 | let _p = profile::span("deref_by_trait"); | ||
58 | let deref_trait = match db.lang_item(krate, "deref".into())? { | 61 | let deref_trait = match db.lang_item(krate, "deref".into())? { |
59 | LangItemTarget::TraitId(it) => it, | 62 | LangItemTarget::TraitId(it) => it, |
60 | _ => return None, | 63 | _ => return None, |
@@ -103,7 +106,7 @@ fn deref_by_trait( | |||
103 | binders: CanonicalVarKinds::from_iter( | 106 | binders: CanonicalVarKinds::from_iter( |
104 | &Interner, | 107 | &Interner, |
105 | ty.goal.binders.iter(&Interner).cloned().chain(Some(chalk_ir::WithKind::new( | 108 | ty.goal.binders.iter(&Interner).cloned().chain(Some(chalk_ir::WithKind::new( |
106 | chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General), | 109 | VariableKind::Ty(chalk_ir::TyVariableKind::General), |
107 | chalk_ir::UniverseIndex::ROOT, | 110 | chalk_ir::UniverseIndex::ROOT, |
108 | ))), | 111 | ))), |
109 | ), | 112 | ), |
@@ -136,7 +139,9 @@ fn deref_by_trait( | |||
136 | return None; | 139 | return None; |
137 | } | 140 | } |
138 | } | 141 | } |
139 | Some(Canonical { | 142 | // FIXME: we remove lifetime variables here since they can confuse |
143 | // the method resolution code later | ||
144 | Some(fixup_lifetime_variables(Canonical { | ||
140 | value: vars | 145 | value: vars |
141 | .value | 146 | .value |
142 | .subst | 147 | .subst |
@@ -144,7 +149,7 @@ fn deref_by_trait( | |||
144 | .assert_ty_ref(&Interner) | 149 | .assert_ty_ref(&Interner) |
145 | .clone(), | 150 | .clone(), |
146 | binders: vars.binders.clone(), | 151 | binders: vars.binders.clone(), |
147 | }) | 152 | })) |
148 | } | 153 | } |
149 | Solution::Ambig(_) => { | 154 | Solution::Ambig(_) => { |
150 | info!("Ambiguous solution for derefing {:?}: {:?}", ty.goal, solution); | 155 | info!("Ambiguous solution for derefing {:?}: {:?}", ty.goal, solution); |
@@ -152,3 +157,32 @@ fn deref_by_trait( | |||
152 | } | 157 | } |
153 | } | 158 | } |
154 | } | 159 | } |
160 | |||
161 | fn fixup_lifetime_variables<T: Fold<Interner, Result = T> + HasInterner<Interner = Interner>>( | ||
162 | c: Canonical<T>, | ||
163 | ) -> Canonical<T> { | ||
164 | // Removes lifetime variables from the Canonical, replacing them by static lifetimes. | ||
165 | let mut i = 0; | ||
166 | let subst = Substitution::from_iter( | ||
167 | &Interner, | ||
168 | c.binders.iter(&Interner).map(|vk| match vk.kind { | ||
169 | VariableKind::Ty(_) => { | ||
170 | let index = i; | ||
171 | i += 1; | ||
172 | BoundVar::new(DebruijnIndex::INNERMOST, index).to_ty(&Interner).cast(&Interner) | ||
173 | } | ||
174 | VariableKind::Lifetime => static_lifetime().cast(&Interner), | ||
175 | VariableKind::Const(_) => unimplemented!(), | ||
176 | }), | ||
177 | ); | ||
178 | let binders = CanonicalVarKinds::from_iter( | ||
179 | &Interner, | ||
180 | c.binders.iter(&Interner).filter(|vk| match vk.kind { | ||
181 | VariableKind::Ty(_) => true, | ||
182 | VariableKind::Lifetime => false, | ||
183 | VariableKind::Const(_) => true, | ||
184 | }), | ||
185 | ); | ||
186 | let value = subst.apply(c.value, &Interner); | ||
187 | Canonical { binders, value } | ||
188 | } | ||
diff --git a/crates/hir_ty/src/chalk_cast.rs b/crates/hir_ty/src/chalk_cast.rs deleted file mode 100644 index f27dee3fd..000000000 --- a/crates/hir_ty/src/chalk_cast.rs +++ /dev/null | |||
@@ -1,16 +0,0 @@ | |||
1 | //! Implementations of the Chalk `Cast` trait for our types. | ||
2 | |||
3 | use chalk_ir::interner::HasInterner; | ||
4 | |||
5 | use crate::{CallableSig, ReturnTypeImplTraits}; | ||
6 | |||
7 | macro_rules! has_interner { | ||
8 | ($t:ty) => { | ||
9 | impl HasInterner for $t { | ||
10 | type Interner = crate::Interner; | ||
11 | } | ||
12 | }; | ||
13 | } | ||
14 | |||
15 | has_interner!(CallableSig); | ||
16 | has_interner!(ReturnTypeImplTraits); | ||
diff --git a/crates/hir_ty/src/traits/chalk.rs b/crates/hir_ty/src/chalk_db.rs index b8c390b2e..8f054d06b 100644 --- a/crates/hir_ty/src/traits/chalk.rs +++ b/crates/hir_ty/src/chalk_db.rs | |||
@@ -1,50 +1,47 @@ | |||
1 | //! Conversion code from/to Chalk. | 1 | //! The implementation of `RustIrDatabase` for Chalk, which provides information |
2 | //! about the code that Chalk needs. | ||
2 | use std::sync::Arc; | 3 | use std::sync::Arc; |
3 | 4 | ||
4 | use log::debug; | 5 | use log::debug; |
5 | 6 | ||
6 | use chalk_ir::{fold::shift::Shift, CanonicalVarKinds}; | 7 | use chalk_ir::{cast::Cast, fold::shift::Shift, CanonicalVarKinds}; |
7 | use chalk_solve::rust_ir::{self, OpaqueTyDatumBound, WellKnownTrait}; | 8 | use chalk_solve::rust_ir::{self, OpaqueTyDatumBound, WellKnownTrait}; |
8 | 9 | ||
9 | use base_db::{salsa::InternKey, CrateId}; | 10 | use base_db::CrateId; |
10 | use hir_def::{ | 11 | use hir_def::{ |
11 | lang_item::{lang_attr, LangItemTarget}, | 12 | lang_item::{lang_attr, LangItemTarget}, |
12 | AssocContainerId, AssocItemId, HasModule, Lookup, TypeAliasId, | 13 | AssocContainerId, AssocItemId, GenericDefId, HasModule, Lookup, TypeAliasId, |
13 | }; | 14 | }; |
14 | use hir_expand::name::name; | 15 | use hir_expand::name::name; |
15 | 16 | ||
16 | use super::ChalkContext; | ||
17 | use crate::{ | 17 | use crate::{ |
18 | db::HirDatabase, | 18 | db::HirDatabase, |
19 | display::HirDisplay, | 19 | display::HirDisplay, |
20 | from_assoc_type_id, make_only_type_binders, | 20 | from_assoc_type_id, from_chalk_trait_id, make_only_type_binders, |
21 | mapping::{from_chalk, ToChalk, TypeAliasAsValue}, | ||
21 | method_resolution::{TyFingerprint, ALL_FLOAT_FPS, ALL_INT_FPS}, | 22 | method_resolution::{TyFingerprint, ALL_FLOAT_FPS, ALL_INT_FPS}, |
22 | to_assoc_type_id, to_chalk_trait_id, | 23 | to_assoc_type_id, to_chalk_trait_id, |
24 | traits::ChalkContext, | ||
23 | utils::generics, | 25 | utils::generics, |
24 | AliasEq, AliasTy, BoundVar, CallableDefId, DebruijnIndex, FnDefId, ProjectionTy, Substitution, | 26 | AliasEq, AliasTy, BoundVar, CallableDefId, DebruijnIndex, FnDefId, Interner, ProjectionTy, |
25 | TraitRef, TraitRefExt, Ty, TyBuilder, TyExt, TyKind, WhereClause, | 27 | ProjectionTyExt, QuantifiedWhereClause, Substitution, TraitRef, TraitRefExt, Ty, TyBuilder, |
28 | TyExt, TyKind, WhereClause, | ||
26 | }; | 29 | }; |
27 | use mapping::{convert_where_clauses, generic_predicate_to_inline_bound, TypeAliasAsValue}; | ||
28 | 30 | ||
29 | pub use self::interner::Interner; | 31 | pub(crate) type AssociatedTyDatum = chalk_solve::rust_ir::AssociatedTyDatum<Interner>; |
30 | pub(crate) use self::interner::*; | 32 | pub(crate) type TraitDatum = chalk_solve::rust_ir::TraitDatum<Interner>; |
31 | 33 | pub(crate) type StructDatum = chalk_solve::rust_ir::AdtDatum<Interner>; | |
32 | pub(super) mod tls; | 34 | pub(crate) type ImplDatum = chalk_solve::rust_ir::ImplDatum<Interner>; |
33 | mod interner; | 35 | pub(crate) type OpaqueTyDatum = chalk_solve::rust_ir::OpaqueTyDatum<Interner>; |
34 | mod mapping; | 36 | |
35 | 37 | pub(crate) type AssocTypeId = chalk_ir::AssocTypeId<Interner>; | |
36 | pub(crate) trait ToChalk { | 38 | pub(crate) type TraitId = chalk_ir::TraitId<Interner>; |
37 | type Chalk; | 39 | pub(crate) type AdtId = chalk_ir::AdtId<Interner>; |
38 | fn to_chalk(self, db: &dyn HirDatabase) -> Self::Chalk; | 40 | pub(crate) type ImplId = chalk_ir::ImplId<Interner>; |
39 | fn from_chalk(db: &dyn HirDatabase, chalk: Self::Chalk) -> Self; | 41 | pub(crate) type AssociatedTyValueId = chalk_solve::rust_ir::AssociatedTyValueId<Interner>; |
40 | } | 42 | pub(crate) type AssociatedTyValue = chalk_solve::rust_ir::AssociatedTyValue<Interner>; |
41 | 43 | pub(crate) type FnDefDatum = chalk_solve::rust_ir::FnDefDatum<Interner>; | |
42 | pub(crate) fn from_chalk<T, ChalkT>(db: &dyn HirDatabase, chalk: ChalkT) -> T | 44 | pub(crate) type Variances = chalk_ir::Variances<Interner>; |
43 | where | ||
44 | T: ToChalk<Chalk = ChalkT>, | ||
45 | { | ||
46 | T::from_chalk(db, chalk) | ||
47 | } | ||
48 | 45 | ||
49 | impl<'a> chalk_solve::RustIrDatabase<Interner> for ChalkContext<'a> { | 46 | impl<'a> chalk_solve::RustIrDatabase<Interner> for ChalkContext<'a> { |
50 | fn associated_ty_data(&self, id: AssocTypeId) -> Arc<AssociatedTyDatum> { | 47 | fn associated_ty_data(&self, id: AssocTypeId) -> Arc<AssociatedTyDatum> { |
@@ -82,7 +79,7 @@ impl<'a> chalk_solve::RustIrDatabase<Interner> for ChalkContext<'a> { | |||
82 | binders: &CanonicalVarKinds<Interner>, | 79 | binders: &CanonicalVarKinds<Interner>, |
83 | ) -> Vec<ImplId> { | 80 | ) -> Vec<ImplId> { |
84 | debug!("impls_for_trait {:?}", trait_id); | 81 | debug!("impls_for_trait {:?}", trait_id); |
85 | let trait_: hir_def::TraitId = from_chalk(self.db, trait_id); | 82 | let trait_: hir_def::TraitId = from_chalk_trait_id(trait_id); |
86 | 83 | ||
87 | let ty: Ty = parameters[0].assert_ty_ref(&Interner).clone(); | 84 | let ty: Ty = parameters[0].assert_ty_ref(&Interner).clone(); |
88 | 85 | ||
@@ -101,7 +98,7 @@ impl<'a> chalk_solve::RustIrDatabase<Interner> for ChalkContext<'a> { | |||
101 | None | 98 | None |
102 | } | 99 | } |
103 | 100 | ||
104 | let self_ty_fp = TyFingerprint::for_impl(&ty); | 101 | let self_ty_fp = TyFingerprint::for_trait_impl(&ty); |
105 | let fps: &[TyFingerprint] = match binder_kind(&ty, binders) { | 102 | let fps: &[TyFingerprint] = match binder_kind(&ty, binders) { |
106 | Some(chalk_ir::TyVariableKind::Integer) => &ALL_INT_FPS, | 103 | Some(chalk_ir::TyVariableKind::Integer) => &ALL_INT_FPS, |
107 | Some(chalk_ir::TyVariableKind::Float) => &ALL_FLOAT_FPS, | 104 | Some(chalk_ir::TyVariableKind::Float) => &ALL_FLOAT_FPS, |
@@ -164,7 +161,7 @@ impl<'a> chalk_solve::RustIrDatabase<Interner> for ChalkContext<'a> { | |||
164 | Some(LangItemTarget::TraitId(trait_)) => trait_, | 161 | Some(LangItemTarget::TraitId(trait_)) => trait_, |
165 | _ => return None, | 162 | _ => return None, |
166 | }; | 163 | }; |
167 | Some(trait_.to_chalk(self.db)) | 164 | Some(to_chalk_trait_id(trait_)) |
168 | } | 165 | } |
169 | 166 | ||
170 | fn program_clauses_for_env( | 167 | fn program_clauses_for_env( |
@@ -311,7 +308,7 @@ impl<'a> chalk_solve::RustIrDatabase<Interner> for ChalkContext<'a> { | |||
311 | } | 308 | } |
312 | 309 | ||
313 | fn trait_name(&self, trait_id: chalk_ir::TraitId<Interner>) -> String { | 310 | fn trait_name(&self, trait_id: chalk_ir::TraitId<Interner>) -> String { |
314 | let id = from_chalk(self.db, trait_id); | 311 | let id = from_chalk_trait_id(trait_id); |
315 | self.db.trait_data(id).name.to_string() | 312 | self.db.trait_data(id).name.to_string() |
316 | } | 313 | } |
317 | fn adt_name(&self, chalk_ir::AdtId(adt_id): AdtId) -> String { | 314 | fn adt_name(&self, chalk_ir::AdtId(adt_id): AdtId) -> String { |
@@ -416,7 +413,7 @@ pub(crate) fn trait_datum_query( | |||
416 | trait_id: TraitId, | 413 | trait_id: TraitId, |
417 | ) -> Arc<TraitDatum> { | 414 | ) -> Arc<TraitDatum> { |
418 | debug!("trait_datum {:?}", trait_id); | 415 | debug!("trait_datum {:?}", trait_id); |
419 | let trait_: hir_def::TraitId = from_chalk(db, trait_id); | 416 | let trait_ = from_chalk_trait_id(trait_id); |
420 | let trait_data = db.trait_data(trait_); | 417 | let trait_data = db.trait_data(trait_); |
421 | debug!("trait {:?} = {:?}", trait_id, trait_data.name); | 418 | debug!("trait {:?} = {:?}", trait_id, trait_data.name); |
422 | let generic_params = generics(db.upcast(), trait_.into()); | 419 | let generic_params = generics(db.upcast(), trait_.into()); |
@@ -679,38 +676,65 @@ pub(crate) fn adt_variance_query( | |||
679 | ) | 676 | ) |
680 | } | 677 | } |
681 | 678 | ||
682 | impl From<FnDefId> for crate::db::InternedCallableDefId { | 679 | pub(super) fn convert_where_clauses( |
683 | fn from(fn_def_id: FnDefId) -> Self { | 680 | db: &dyn HirDatabase, |
684 | InternKey::from_intern_id(fn_def_id.0) | 681 | def: GenericDefId, |
685 | } | 682 | substs: &Substitution, |
686 | } | 683 | ) -> Vec<chalk_ir::QuantifiedWhereClause<Interner>> { |
687 | 684 | let generic_predicates = db.generic_predicates(def); | |
688 | impl From<crate::db::InternedCallableDefId> for FnDefId { | 685 | let mut result = Vec::with_capacity(generic_predicates.len()); |
689 | fn from(callable_def_id: crate::db::InternedCallableDefId) -> Self { | 686 | for pred in generic_predicates.iter() { |
690 | chalk_ir::FnDefId(callable_def_id.as_intern_id()) | 687 | result.push(pred.clone().substitute(&Interner, substs)); |
691 | } | 688 | } |
692 | } | 689 | result |
693 | |||
694 | impl From<OpaqueTyId> for crate::db::InternedOpaqueTyId { | ||
695 | fn from(id: OpaqueTyId) -> Self { | ||
696 | InternKey::from_intern_id(id.0) | ||
697 | } | ||
698 | } | ||
699 | |||
700 | impl From<crate::db::InternedOpaqueTyId> for OpaqueTyId { | ||
701 | fn from(id: crate::db::InternedOpaqueTyId) -> Self { | ||
702 | chalk_ir::OpaqueTyId(id.as_intern_id()) | ||
703 | } | ||
704 | } | ||
705 | |||
706 | impl From<chalk_ir::ClosureId<Interner>> for crate::db::InternedClosureId { | ||
707 | fn from(id: chalk_ir::ClosureId<Interner>) -> Self { | ||
708 | Self::from_intern_id(id.0) | ||
709 | } | ||
710 | } | 690 | } |
711 | 691 | ||
712 | impl From<crate::db::InternedClosureId> for chalk_ir::ClosureId<Interner> { | 692 | pub(super) fn generic_predicate_to_inline_bound( |
713 | fn from(id: crate::db::InternedClosureId) -> Self { | 693 | db: &dyn HirDatabase, |
714 | chalk_ir::ClosureId(id.as_intern_id()) | 694 | pred: &QuantifiedWhereClause, |
695 | self_ty: &Ty, | ||
696 | ) -> Option<chalk_ir::Binders<rust_ir::InlineBound<Interner>>> { | ||
697 | // An InlineBound is like a GenericPredicate, except the self type is left out. | ||
698 | // We don't have a special type for this, but Chalk does. | ||
699 | let self_ty_shifted_in = self_ty.clone().shifted_in_from(&Interner, DebruijnIndex::ONE); | ||
700 | let (pred, binders) = pred.as_ref().into_value_and_skipped_binders(); | ||
701 | match pred { | ||
702 | WhereClause::Implemented(trait_ref) => { | ||
703 | if trait_ref.self_type_parameter(&Interner) != self_ty_shifted_in { | ||
704 | // we can only convert predicates back to type bounds if they | ||
705 | // have the expected self type | ||
706 | return None; | ||
707 | } | ||
708 | let args_no_self = trait_ref.substitution.as_slice(&Interner)[1..] | ||
709 | .iter() | ||
710 | .map(|ty| ty.clone().cast(&Interner)) | ||
711 | .collect(); | ||
712 | let trait_bound = rust_ir::TraitBound { trait_id: trait_ref.trait_id, args_no_self }; | ||
713 | Some(chalk_ir::Binders::new(binders, rust_ir::InlineBound::TraitBound(trait_bound))) | ||
714 | } | ||
715 | WhereClause::AliasEq(AliasEq { alias: AliasTy::Projection(projection_ty), ty }) => { | ||
716 | if projection_ty.self_type_parameter(&Interner) != self_ty_shifted_in { | ||
717 | return None; | ||
718 | } | ||
719 | let trait_ = projection_ty.trait_(db); | ||
720 | let args_no_self = projection_ty.substitution.as_slice(&Interner)[1..] | ||
721 | .iter() | ||
722 | .map(|ty| ty.clone().cast(&Interner)) | ||
723 | .collect(); | ||
724 | let alias_eq_bound = rust_ir::AliasEqBound { | ||
725 | value: ty.clone(), | ||
726 | trait_bound: rust_ir::TraitBound { | ||
727 | trait_id: to_chalk_trait_id(trait_), | ||
728 | args_no_self, | ||
729 | }, | ||
730 | associated_ty_id: projection_ty.associated_ty_id, | ||
731 | parameters: Vec::new(), // FIXME we don't support generic associated types yet | ||
732 | }; | ||
733 | Some(chalk_ir::Binders::new( | ||
734 | binders, | ||
735 | rust_ir::InlineBound::AliasEqBound(alias_eq_bound), | ||
736 | )) | ||
737 | } | ||
738 | _ => None, | ||
715 | } | 739 | } |
716 | } | 740 | } |
diff --git a/crates/hir_ty/src/chalk_ext.rs b/crates/hir_ty/src/chalk_ext.rs index 28ed3aac6..8c4542956 100644 --- a/crates/hir_ty/src/chalk_ext.rs +++ b/crates/hir_ty/src/chalk_ext.rs | |||
@@ -75,7 +75,7 @@ impl TyExt for Ty { | |||
75 | } | 75 | } |
76 | fn as_reference(&self) -> Option<(&Ty, Lifetime, Mutability)> { | 76 | fn as_reference(&self) -> Option<(&Ty, Lifetime, Mutability)> { |
77 | match self.kind(&Interner) { | 77 | match self.kind(&Interner) { |
78 | TyKind::Ref(mutability, lifetime, ty) => Some((ty, *lifetime, *mutability)), | 78 | TyKind::Ref(mutability, lifetime, ty) => Some((ty, lifetime.clone(), *mutability)), |
79 | _ => None, | 79 | _ => None, |
80 | } | 80 | } |
81 | } | 81 | } |
diff --git a/crates/hir_ty/src/db.rs b/crates/hir_ty/src/db.rs index 326c20240..9da0a02e3 100644 --- a/crates/hir_ty/src/db.rs +++ b/crates/hir_ty/src/db.rs | |||
@@ -1,4 +1,5 @@ | |||
1 | //! FIXME: write short doc here | 1 | //! The home of `HirDatabase`, which is the Salsa database containing all the |
2 | //! type inference-related queries. | ||
2 | 3 | ||
3 | use std::sync::Arc; | 4 | use std::sync::Arc; |
4 | 5 | ||
@@ -10,9 +11,9 @@ use hir_def::{ | |||
10 | use la_arena::ArenaMap; | 11 | use la_arena::ArenaMap; |
11 | 12 | ||
12 | use crate::{ | 13 | use crate::{ |
14 | chalk_db, | ||
13 | method_resolution::{InherentImpls, TraitImpls}, | 15 | method_resolution::{InherentImpls, TraitImpls}, |
14 | traits::chalk, | 16 | Binders, CallableDefId, FnDefId, ImplTraitId, InferenceResult, Interner, PolyFnSig, |
15 | Binders, CallableDefId, FnDefId, ImplTraitId, InferenceResult, PolyFnSig, | ||
16 | QuantifiedWhereClause, ReturnTypeImplTraits, TraitRef, Ty, TyDefId, ValueTyDefId, | 17 | QuantifiedWhereClause, ReturnTypeImplTraits, TraitRef, Ty, TyDefId, ValueTyDefId, |
17 | }; | 18 | }; |
18 | use hir_expand::name::Name; | 19 | use hir_expand::name::Name; |
@@ -69,6 +70,7 @@ pub trait HirDatabase: DefDatabase + Upcast<dyn DefDatabase> { | |||
69 | fn trait_environment(&self, def: GenericDefId) -> Arc<crate::TraitEnvironment>; | 70 | fn trait_environment(&self, def: GenericDefId) -> Arc<crate::TraitEnvironment>; |
70 | 71 | ||
71 | #[salsa::invoke(crate::lower::generic_defaults_query)] | 72 | #[salsa::invoke(crate::lower::generic_defaults_query)] |
73 | #[salsa::cycle(crate::lower::generic_defaults_recover)] | ||
72 | fn generic_defaults(&self, def: GenericDefId) -> Arc<[Binders<Ty>]>; | 74 | fn generic_defaults(&self, def: GenericDefId) -> Arc<[Binders<Ty>]>; |
73 | 75 | ||
74 | #[salsa::invoke(InherentImpls::inherent_impls_in_crate_query)] | 76 | #[salsa::invoke(InherentImpls::inherent_impls_in_crate_query)] |
@@ -94,47 +96,60 @@ pub trait HirDatabase: DefDatabase + Upcast<dyn DefDatabase> { | |||
94 | #[salsa::interned] | 96 | #[salsa::interned] |
95 | fn intern_closure(&self, id: (DefWithBodyId, ExprId)) -> InternedClosureId; | 97 | fn intern_closure(&self, id: (DefWithBodyId, ExprId)) -> InternedClosureId; |
96 | 98 | ||
97 | #[salsa::invoke(chalk::associated_ty_data_query)] | 99 | #[salsa::invoke(chalk_db::associated_ty_data_query)] |
98 | fn associated_ty_data(&self, id: chalk::AssocTypeId) -> Arc<chalk::AssociatedTyDatum>; | 100 | fn associated_ty_data(&self, id: chalk_db::AssocTypeId) -> Arc<chalk_db::AssociatedTyDatum>; |
99 | 101 | ||
100 | #[salsa::invoke(chalk::trait_datum_query)] | 102 | #[salsa::invoke(chalk_db::trait_datum_query)] |
101 | fn trait_datum(&self, krate: CrateId, trait_id: chalk::TraitId) -> Arc<chalk::TraitDatum>; | 103 | fn trait_datum(&self, krate: CrateId, trait_id: chalk_db::TraitId) |
104 | -> Arc<chalk_db::TraitDatum>; | ||
102 | 105 | ||
103 | #[salsa::invoke(chalk::struct_datum_query)] | 106 | #[salsa::invoke(chalk_db::struct_datum_query)] |
104 | fn struct_datum(&self, krate: CrateId, struct_id: chalk::AdtId) -> Arc<chalk::StructDatum>; | 107 | fn struct_datum( |
108 | &self, | ||
109 | krate: CrateId, | ||
110 | struct_id: chalk_db::AdtId, | ||
111 | ) -> Arc<chalk_db::StructDatum>; | ||
105 | 112 | ||
106 | #[salsa::invoke(crate::traits::chalk::impl_datum_query)] | 113 | #[salsa::invoke(chalk_db::impl_datum_query)] |
107 | fn impl_datum(&self, krate: CrateId, impl_id: chalk::ImplId) -> Arc<chalk::ImplDatum>; | 114 | fn impl_datum(&self, krate: CrateId, impl_id: chalk_db::ImplId) -> Arc<chalk_db::ImplDatum>; |
108 | 115 | ||
109 | #[salsa::invoke(crate::traits::chalk::fn_def_datum_query)] | 116 | #[salsa::invoke(chalk_db::fn_def_datum_query)] |
110 | fn fn_def_datum(&self, krate: CrateId, fn_def_id: FnDefId) -> Arc<chalk::FnDefDatum>; | 117 | fn fn_def_datum(&self, krate: CrateId, fn_def_id: FnDefId) -> Arc<chalk_db::FnDefDatum>; |
111 | 118 | ||
112 | #[salsa::invoke(crate::traits::chalk::fn_def_variance_query)] | 119 | #[salsa::invoke(chalk_db::fn_def_variance_query)] |
113 | fn fn_def_variance(&self, krate: CrateId, fn_def_id: FnDefId) -> chalk::Variances; | 120 | fn fn_def_variance(&self, krate: CrateId, fn_def_id: FnDefId) -> chalk_db::Variances; |
114 | 121 | ||
115 | #[salsa::invoke(crate::traits::chalk::adt_variance_query)] | 122 | #[salsa::invoke(chalk_db::adt_variance_query)] |
116 | fn adt_variance(&self, krate: CrateId, adt_id: chalk::AdtId) -> chalk::Variances; | 123 | fn adt_variance(&self, krate: CrateId, adt_id: chalk_db::AdtId) -> chalk_db::Variances; |
117 | 124 | ||
118 | #[salsa::invoke(crate::traits::chalk::associated_ty_value_query)] | 125 | #[salsa::invoke(chalk_db::associated_ty_value_query)] |
119 | fn associated_ty_value( | 126 | fn associated_ty_value( |
120 | &self, | 127 | &self, |
121 | krate: CrateId, | 128 | krate: CrateId, |
122 | id: chalk::AssociatedTyValueId, | 129 | id: chalk_db::AssociatedTyValueId, |
123 | ) -> Arc<chalk::AssociatedTyValue>; | 130 | ) -> Arc<chalk_db::AssociatedTyValue>; |
124 | 131 | ||
125 | #[salsa::invoke(crate::traits::trait_solve_query)] | 132 | #[salsa::invoke(trait_solve_wait)] |
133 | #[salsa::transparent] | ||
126 | fn trait_solve( | 134 | fn trait_solve( |
127 | &self, | 135 | &self, |
128 | krate: CrateId, | 136 | krate: CrateId, |
129 | goal: crate::Canonical<crate::InEnvironment<crate::DomainGoal>>, | 137 | goal: crate::Canonical<crate::InEnvironment<crate::DomainGoal>>, |
130 | ) -> Option<crate::Solution>; | 138 | ) -> Option<crate::Solution>; |
131 | 139 | ||
132 | #[salsa::invoke(crate::traits::chalk::program_clauses_for_chalk_env_query)] | 140 | #[salsa::invoke(crate::traits::trait_solve_query)] |
141 | fn trait_solve_query( | ||
142 | &self, | ||
143 | krate: CrateId, | ||
144 | goal: crate::Canonical<crate::InEnvironment<crate::DomainGoal>>, | ||
145 | ) -> Option<crate::Solution>; | ||
146 | |||
147 | #[salsa::invoke(chalk_db::program_clauses_for_chalk_env_query)] | ||
133 | fn program_clauses_for_chalk_env( | 148 | fn program_clauses_for_chalk_env( |
134 | &self, | 149 | &self, |
135 | krate: CrateId, | 150 | krate: CrateId, |
136 | env: chalk_ir::Environment<chalk::Interner>, | 151 | env: chalk_ir::Environment<Interner>, |
137 | ) -> chalk_ir::ProgramClauses<chalk::Interner>; | 152 | ) -> chalk_ir::ProgramClauses<Interner>; |
138 | } | 153 | } |
139 | 154 | ||
140 | fn infer_wait(db: &dyn HirDatabase, def: DefWithBodyId) -> Arc<InferenceResult> { | 155 | fn infer_wait(db: &dyn HirDatabase, def: DefWithBodyId) -> Arc<InferenceResult> { |
@@ -150,6 +165,15 @@ fn infer_wait(db: &dyn HirDatabase, def: DefWithBodyId) -> Arc<InferenceResult> | |||
150 | db.infer_query(def) | 165 | db.infer_query(def) |
151 | } | 166 | } |
152 | 167 | ||
168 | fn trait_solve_wait( | ||
169 | db: &dyn HirDatabase, | ||
170 | krate: CrateId, | ||
171 | goal: crate::Canonical<crate::InEnvironment<crate::DomainGoal>>, | ||
172 | ) -> Option<crate::Solution> { | ||
173 | let _p = profile::span("trait_solve::wait"); | ||
174 | db.trait_solve_query(krate, goal) | ||
175 | } | ||
176 | |||
153 | #[test] | 177 | #[test] |
154 | fn hir_database_is_object_safe() { | 178 | fn hir_database_is_object_safe() { |
155 | fn _assert_object_safe(_: &dyn HirDatabase) {} | 179 | fn _assert_object_safe(_: &dyn HirDatabase) {} |
diff --git a/crates/hir_ty/src/diagnostics.rs b/crates/hir_ty/src/diagnostics.rs index 86f937e1d..84fc8ce14 100644 --- a/crates/hir_ty/src/diagnostics.rs +++ b/crates/hir_ty/src/diagnostics.rs | |||
@@ -1,4 +1,4 @@ | |||
1 | //! FIXME: write short doc here | 1 | //! Type inference-based diagnostics. |
2 | mod expr; | 2 | mod expr; |
3 | mod match_check; | 3 | mod match_check; |
4 | mod unsafe_check; | 4 | mod unsafe_check; |
diff --git a/crates/hir_ty/src/diagnostics/decl_check.rs b/crates/hir_ty/src/diagnostics/decl_check.rs index 1c9f9ede7..075dc4131 100644 --- a/crates/hir_ty/src/diagnostics/decl_check.rs +++ b/crates/hir_ty/src/diagnostics/decl_check.rs | |||
@@ -35,6 +35,8 @@ use crate::{ | |||
35 | }; | 35 | }; |
36 | 36 | ||
37 | mod allow { | 37 | mod allow { |
38 | pub(super) const BAD_STYLE: &str = "bad_style"; | ||
39 | pub(super) const NONSTANDARD_STYLE: &str = "nonstandard_style"; | ||
38 | pub(super) const NON_SNAKE_CASE: &str = "non_snake_case"; | 40 | pub(super) const NON_SNAKE_CASE: &str = "non_snake_case"; |
39 | pub(super) const NON_UPPER_CASE_GLOBAL: &str = "non_upper_case_globals"; | 41 | pub(super) const NON_UPPER_CASE_GLOBAL: &str = "non_upper_case_globals"; |
40 | pub(super) const NON_CAMEL_CASE_TYPES: &str = "non_camel_case_types"; | 42 | pub(super) const NON_CAMEL_CASE_TYPES: &str = "non_camel_case_types"; |
@@ -83,10 +85,39 @@ impl<'a, 'b> DeclValidator<'a, 'b> { | |||
83 | } | 85 | } |
84 | 86 | ||
85 | /// Checks whether not following the convention is allowed for this item. | 87 | /// Checks whether not following the convention is allowed for this item. |
86 | /// | 88 | fn allowed(&self, id: AttrDefId, allow_name: &str, recursing: bool) -> bool { |
87 | /// Currently this method doesn't check parent attributes. | 89 | let is_allowed = |def_id| { |
88 | fn allowed(&self, id: AttrDefId, allow_name: &str) -> bool { | 90 | let attrs = self.db.attrs(def_id); |
89 | self.db.attrs(id).by_key("allow").tt_values().any(|tt| tt.to_string().contains(allow_name)) | 91 | // don't bug the user about directly no_mangle annotated stuff, they can't do anything about it |
92 | (!recursing && attrs.by_key("no_mangle").exists()) | ||
93 | || attrs.by_key("allow").tt_values().any(|tt| { | ||
94 | let allows = tt.to_string(); | ||
95 | allows.contains(allow_name) | ||
96 | || allows.contains(allow::BAD_STYLE) | ||
97 | || allows.contains(allow::NONSTANDARD_STYLE) | ||
98 | }) | ||
99 | }; | ||
100 | |||
101 | is_allowed(id) | ||
102 | // go upwards one step or give up | ||
103 | || match id { | ||
104 | AttrDefId::ModuleId(m) => m.containing_module(self.db.upcast()).map(|v| v.into()), | ||
105 | AttrDefId::FunctionId(f) => Some(f.lookup(self.db.upcast()).container.into()), | ||
106 | AttrDefId::StaticId(sid) => Some(sid.lookup(self.db.upcast()).container.into()), | ||
107 | AttrDefId::ConstId(cid) => Some(cid.lookup(self.db.upcast()).container.into()), | ||
108 | AttrDefId::TraitId(tid) => Some(tid.lookup(self.db.upcast()).container.into()), | ||
109 | AttrDefId::ImplId(iid) => Some(iid.lookup(self.db.upcast()).container.into()), | ||
110 | // These warnings should not explore macro definitions at all | ||
111 | AttrDefId::MacroDefId(_) => None, | ||
112 | // Will never occur under an enum/struct/union/type alias | ||
113 | AttrDefId::AdtId(_) => None, | ||
114 | AttrDefId::FieldId(_) => None, | ||
115 | AttrDefId::EnumVariantId(_) => None, | ||
116 | AttrDefId::TypeAliasId(_) => None, | ||
117 | AttrDefId::GenericParamId(_) => None, | ||
118 | } | ||
119 | .map(|mid| self.allowed(mid, allow_name, true)) | ||
120 | .unwrap_or(false) | ||
90 | } | 121 | } |
91 | 122 | ||
92 | fn validate_func(&mut self, func: FunctionId) { | 123 | fn validate_func(&mut self, func: FunctionId) { |
@@ -109,7 +140,7 @@ impl<'a, 'b> DeclValidator<'a, 'b> { | |||
109 | } | 140 | } |
110 | 141 | ||
111 | // Check whether non-snake case identifiers are allowed for this function. | 142 | // Check whether non-snake case identifiers are allowed for this function. |
112 | if self.allowed(func.into(), allow::NON_SNAKE_CASE) { | 143 | if self.allowed(func.into(), allow::NON_SNAKE_CASE, false) { |
113 | return; | 144 | return; |
114 | } | 145 | } |
115 | 146 | ||
@@ -328,8 +359,9 @@ impl<'a, 'b> DeclValidator<'a, 'b> { | |||
328 | fn validate_struct(&mut self, struct_id: StructId) { | 359 | fn validate_struct(&mut self, struct_id: StructId) { |
329 | let data = self.db.struct_data(struct_id); | 360 | let data = self.db.struct_data(struct_id); |
330 | 361 | ||
331 | let non_camel_case_allowed = self.allowed(struct_id.into(), allow::NON_CAMEL_CASE_TYPES); | 362 | let non_camel_case_allowed = |
332 | let non_snake_case_allowed = self.allowed(struct_id.into(), allow::NON_SNAKE_CASE); | 363 | self.allowed(struct_id.into(), allow::NON_CAMEL_CASE_TYPES, false); |
364 | let non_snake_case_allowed = self.allowed(struct_id.into(), allow::NON_SNAKE_CASE, false); | ||
333 | 365 | ||
334 | // Check the structure name. | 366 | // Check the structure name. |
335 | let struct_name = data.name.to_string(); | 367 | let struct_name = data.name.to_string(); |
@@ -461,7 +493,7 @@ impl<'a, 'b> DeclValidator<'a, 'b> { | |||
461 | let data = self.db.enum_data(enum_id); | 493 | let data = self.db.enum_data(enum_id); |
462 | 494 | ||
463 | // Check whether non-camel case names are allowed for this enum. | 495 | // Check whether non-camel case names are allowed for this enum. |
464 | if self.allowed(enum_id.into(), allow::NON_CAMEL_CASE_TYPES) { | 496 | if self.allowed(enum_id.into(), allow::NON_CAMEL_CASE_TYPES, false) { |
465 | return; | 497 | return; |
466 | } | 498 | } |
467 | 499 | ||
@@ -584,7 +616,7 @@ impl<'a, 'b> DeclValidator<'a, 'b> { | |||
584 | fn validate_const(&mut self, const_id: ConstId) { | 616 | fn validate_const(&mut self, const_id: ConstId) { |
585 | let data = self.db.const_data(const_id); | 617 | let data = self.db.const_data(const_id); |
586 | 618 | ||
587 | if self.allowed(const_id.into(), allow::NON_UPPER_CASE_GLOBAL) { | 619 | if self.allowed(const_id.into(), allow::NON_UPPER_CASE_GLOBAL, false) { |
588 | return; | 620 | return; |
589 | } | 621 | } |
590 | 622 | ||
@@ -632,7 +664,7 @@ impl<'a, 'b> DeclValidator<'a, 'b> { | |||
632 | return; | 664 | return; |
633 | } | 665 | } |
634 | 666 | ||
635 | if self.allowed(static_id.into(), allow::NON_UPPER_CASE_GLOBAL) { | 667 | if self.allowed(static_id.into(), allow::NON_UPPER_CASE_GLOBAL, false) { |
636 | return; | 668 | return; |
637 | } | 669 | } |
638 | 670 | ||
@@ -867,23 +899,116 @@ fn main() { | |||
867 | fn allow_attributes() { | 899 | fn allow_attributes() { |
868 | check_diagnostics( | 900 | check_diagnostics( |
869 | r#" | 901 | r#" |
870 | #[allow(non_snake_case)] | 902 | #[allow(non_snake_case)] |
871 | fn NonSnakeCaseName(SOME_VAR: u8) -> u8{ | 903 | fn NonSnakeCaseName(SOME_VAR: u8) -> u8{ |
872 | let OtherVar = SOME_VAR + 1; | 904 | // cov_flags generated output from elsewhere in this file |
873 | OtherVar | 905 | extern "C" { |
906 | #[no_mangle] | ||
907 | static lower_case: u8; | ||
874 | } | 908 | } |
875 | 909 | ||
876 | #[allow(non_snake_case, non_camel_case_types)] | 910 | let OtherVar = SOME_VAR + 1; |
877 | pub struct some_type { | 911 | OtherVar |
878 | SOME_FIELD: u8, | 912 | } |
879 | SomeField: u16, | 913 | |
914 | #[allow(nonstandard_style)] | ||
915 | mod CheckNonstandardStyle { | ||
916 | fn HiImABadFnName() {} | ||
917 | } | ||
918 | |||
919 | #[allow(bad_style)] | ||
920 | mod CheckBadStyle { | ||
921 | fn HiImABadFnName() {} | ||
922 | } | ||
923 | |||
924 | mod F { | ||
925 | #![allow(non_snake_case)] | ||
926 | fn CheckItWorksWithModAttr(BAD_NAME_HI: u8) {} | ||
927 | } | ||
928 | |||
929 | #[allow(non_snake_case, non_camel_case_types)] | ||
930 | pub struct some_type { | ||
931 | SOME_FIELD: u8, | ||
932 | SomeField: u16, | ||
933 | } | ||
934 | |||
935 | #[allow(non_upper_case_globals)] | ||
936 | pub const some_const: u8 = 10; | ||
937 | |||
938 | #[allow(non_upper_case_globals)] | ||
939 | pub static SomeStatic: u8 = 10; | ||
940 | "#, | ||
941 | ); | ||
880 | } | 942 | } |
881 | 943 | ||
882 | #[allow(non_upper_case_globals)] | 944 | #[test] |
883 | pub const some_const: u8 = 10; | 945 | fn allow_attributes_crate_attr() { |
946 | check_diagnostics( | ||
947 | r#" | ||
948 | #![allow(non_snake_case)] | ||
884 | 949 | ||
885 | #[allow(non_upper_case_globals)] | 950 | mod F { |
886 | pub static SomeStatic: u8 = 10; | 951 | fn CheckItWorksWithCrateAttr(BAD_NAME_HI: u8) {} |
952 | } | ||
953 | "#, | ||
954 | ); | ||
955 | } | ||
956 | |||
957 | #[test] | ||
958 | #[ignore] | ||
959 | fn bug_trait_inside_fn() { | ||
960 | // FIXME: | ||
961 | // This is broken, and in fact, should not even be looked at by this | ||
962 | // lint in the first place. There's weird stuff going on in the | ||
963 | // collection phase. | ||
964 | // It's currently being brought in by: | ||
965 | // * validate_func on `a` recursing into modules | ||
966 | // * then it finds the trait and then the function while iterating | ||
967 | // through modules | ||
968 | // * then validate_func is called on Dirty | ||
969 | // * ... which then proceeds to look at some unknown module taking no | ||
970 | // attrs from either the impl or the fn a, and then finally to the root | ||
971 | // module | ||
972 | // | ||
973 | // It should find the attribute on the trait, but it *doesn't even see | ||
974 | // the trait* as far as I can tell. | ||
975 | |||
976 | check_diagnostics( | ||
977 | r#" | ||
978 | trait T { fn a(); } | ||
979 | struct U {} | ||
980 | impl T for U { | ||
981 | fn a() { | ||
982 | // this comes out of bitflags, mostly | ||
983 | #[allow(non_snake_case)] | ||
984 | trait __BitFlags { | ||
985 | const HiImAlsoBad: u8 = 2; | ||
986 | #[inline] | ||
987 | fn Dirty(&self) -> bool { | ||
988 | false | ||
989 | } | ||
990 | } | ||
991 | |||
992 | } | ||
993 | } | ||
994 | "#, | ||
995 | ); | ||
996 | } | ||
997 | |||
998 | #[test] | ||
999 | #[ignore] | ||
1000 | fn bug_traits_arent_checked() { | ||
1001 | // FIXME: Traits and functions in traits aren't currently checked by | ||
1002 | // r-a, even though rustc will complain about them. | ||
1003 | check_diagnostics( | ||
1004 | r#" | ||
1005 | trait BAD_TRAIT { | ||
1006 | // ^^^^^^^^^ Trait `BAD_TRAIT` should have CamelCase name, e.g. `BadTrait` | ||
1007 | fn BAD_FUNCTION(); | ||
1008 | // ^^^^^^^^^^^^ Function `BAD_FUNCTION` should have snake_case name, e.g. `bad_function` | ||
1009 | fn BadFunction(); | ||
1010 | // ^^^^^^^^^^^^ Function `BadFunction` should have snake_case name, e.g. `bad_function` | ||
1011 | } | ||
887 | "#, | 1012 | "#, |
888 | ); | 1013 | ); |
889 | } | 1014 | } |
diff --git a/crates/hir_ty/src/display.rs b/crates/hir_ty/src/display.rs index d7a3977e5..4fb7d9cf2 100644 --- a/crates/hir_ty/src/display.rs +++ b/crates/hir_ty/src/display.rs | |||
@@ -1,4 +1,6 @@ | |||
1 | //! FIXME: write short doc here | 1 | //! The `HirDisplay` trait, which serves two purposes: Turning various bits from |
2 | //! HIR back into source code, and just displaying them for debugging/testing | ||
3 | //! purposes. | ||
2 | 4 | ||
3 | use std::{ | 5 | use std::{ |
4 | array, | 6 | array, |
@@ -7,6 +9,7 @@ use std::{ | |||
7 | 9 | ||
8 | use chalk_ir::BoundVar; | 10 | use chalk_ir::BoundVar; |
9 | use hir_def::{ | 11 | use hir_def::{ |
12 | body, | ||
10 | db::DefDatabase, | 13 | db::DefDatabase, |
11 | find_path, | 14 | find_path, |
12 | generics::TypeParamProvenance, | 15 | generics::TypeParamProvenance, |
@@ -16,15 +19,15 @@ use hir_def::{ | |||
16 | visibility::Visibility, | 19 | visibility::Visibility, |
17 | AssocContainerId, Lookup, ModuleId, TraitId, | 20 | AssocContainerId, Lookup, ModuleId, TraitId, |
18 | }; | 21 | }; |
19 | use hir_expand::name::Name; | 22 | use hir_expand::{hygiene::Hygiene, name::Name}; |
20 | 23 | ||
21 | use crate::{ | 24 | use crate::{ |
22 | const_from_placeholder_idx, db::HirDatabase, from_assoc_type_id, from_foreign_def_id, | 25 | const_from_placeholder_idx, db::HirDatabase, from_assoc_type_id, from_foreign_def_id, |
23 | from_placeholder_idx, lt_from_placeholder_idx, primitive, subst_prefix, to_assoc_type_id, | 26 | from_placeholder_idx, lt_from_placeholder_idx, mapping::from_chalk, primitive, subst_prefix, |
24 | traits::chalk::from_chalk, utils::generics, AdtId, AliasEq, AliasTy, CallableDefId, | 27 | to_assoc_type_id, utils::generics, AdtId, AliasEq, AliasTy, CallableDefId, CallableSig, Const, |
25 | CallableSig, Const, ConstValue, DomainGoal, GenericArg, ImplTraitId, Interner, Lifetime, | 28 | ConstValue, DomainGoal, GenericArg, ImplTraitId, Interner, Lifetime, LifetimeData, |
26 | LifetimeData, LifetimeOutlives, Mutability, OpaqueTy, ProjectionTy, ProjectionTyExt, | 29 | LifetimeOutlives, Mutability, OpaqueTy, ProjectionTy, ProjectionTyExt, QuantifiedWhereClause, |
27 | QuantifiedWhereClause, Scalar, TraitRef, TraitRefExt, Ty, TyExt, TyKind, WhereClause, | 30 | Scalar, TraitRef, TraitRefExt, Ty, TyExt, TyKind, WhereClause, |
28 | }; | 31 | }; |
29 | 32 | ||
30 | pub struct HirFormatter<'a> { | 33 | pub struct HirFormatter<'a> { |
@@ -265,7 +268,7 @@ impl HirDisplay for ProjectionTy { | |||
265 | write!(f, " as {}", trait_.name)?; | 268 | write!(f, " as {}", trait_.name)?; |
266 | if self.substitution.len(&Interner) > 1 { | 269 | if self.substitution.len(&Interner) > 1 { |
267 | write!(f, "<")?; | 270 | write!(f, "<")?; |
268 | f.write_joined(&self.substitution.interned()[1..], ", ")?; | 271 | f.write_joined(&self.substitution.as_slice(&Interner)[1..], ", ")?; |
269 | write!(f, ">")?; | 272 | write!(f, ">")?; |
270 | } | 273 | } |
271 | write!(f, ">::{}", f.db.type_alias_data(from_assoc_type_id(self.associated_ty_id)).name)?; | 274 | write!(f, ">::{}", f.db.type_alias_data(from_assoc_type_id(self.associated_ty_id)).name)?; |
@@ -416,7 +419,7 @@ impl HirDisplay for Ty { | |||
416 | write!(f, ",)")?; | 419 | write!(f, ",)")?; |
417 | } else { | 420 | } else { |
418 | write!(f, "(")?; | 421 | write!(f, "(")?; |
419 | f.write_joined(&*substs.interned(), ", ")?; | 422 | f.write_joined(&*substs.as_slice(&Interner), ", ")?; |
420 | write!(f, ")")?; | 423 | write!(f, ")")?; |
421 | } | 424 | } |
422 | } | 425 | } |
@@ -444,7 +447,7 @@ impl HirDisplay for Ty { | |||
444 | // We print all params except implicit impl Trait params. Still a bit weird; should we leave out parent and self? | 447 | // We print all params except implicit impl Trait params. Still a bit weird; should we leave out parent and self? |
445 | if total_len > 0 { | 448 | if total_len > 0 { |
446 | write!(f, "<")?; | 449 | write!(f, "<")?; |
447 | f.write_joined(¶meters.interned()[..total_len], ", ")?; | 450 | f.write_joined(¶meters.as_slice(&Interner)[..total_len], ", ")?; |
448 | write!(f, ">")?; | 451 | write!(f, ">")?; |
449 | } | 452 | } |
450 | } | 453 | } |
@@ -491,7 +494,7 @@ impl HirDisplay for Ty { | |||
491 | .map(|generic_def_id| f.db.generic_defaults(generic_def_id)) | 494 | .map(|generic_def_id| f.db.generic_defaults(generic_def_id)) |
492 | .filter(|defaults| !defaults.is_empty()) | 495 | .filter(|defaults| !defaults.is_empty()) |
493 | { | 496 | { |
494 | None => parameters.interned().as_ref(), | 497 | None => parameters.as_slice(&Interner), |
495 | Some(default_parameters) => { | 498 | Some(default_parameters) => { |
496 | let mut default_from = 0; | 499 | let mut default_from = 0; |
497 | for (i, parameter) in parameters.iter(&Interner).enumerate() { | 500 | for (i, parameter) in parameters.iter(&Interner).enumerate() { |
@@ -515,11 +518,11 @@ impl HirDisplay for Ty { | |||
515 | } | 518 | } |
516 | } | 519 | } |
517 | } | 520 | } |
518 | ¶meters.interned()[0..default_from] | 521 | ¶meters.as_slice(&Interner)[0..default_from] |
519 | } | 522 | } |
520 | } | 523 | } |
521 | } else { | 524 | } else { |
522 | parameters.interned().as_ref() | 525 | parameters.as_slice(&Interner) |
523 | }; | 526 | }; |
524 | if !parameters_to_write.is_empty() { | 527 | if !parameters_to_write.is_empty() { |
525 | write!(f, "<")?; | 528 | write!(f, "<")?; |
@@ -542,7 +545,7 @@ impl HirDisplay for Ty { | |||
542 | write!(f, "{}::{}", trait_.name, type_alias_data.name)?; | 545 | write!(f, "{}::{}", trait_.name, type_alias_data.name)?; |
543 | if parameters.len(&Interner) > 0 { | 546 | if parameters.len(&Interner) > 0 { |
544 | write!(f, "<")?; | 547 | write!(f, "<")?; |
545 | f.write_joined(&*parameters.interned(), ", ")?; | 548 | f.write_joined(&*parameters.as_slice(&Interner), ", ")?; |
546 | write!(f, ">")?; | 549 | write!(f, ">")?; |
547 | } | 550 | } |
548 | } else { | 551 | } else { |
@@ -749,13 +752,13 @@ fn write_bounds_like_dyn_trait( | |||
749 | // existential) here, which is the only thing that's | 752 | // existential) here, which is the only thing that's |
750 | // possible in actual Rust, and hence don't print it | 753 | // possible in actual Rust, and hence don't print it |
751 | write!(f, "{}", f.db.trait_data(trait_).name)?; | 754 | write!(f, "{}", f.db.trait_data(trait_).name)?; |
752 | if let [_, params @ ..] = &*trait_ref.substitution.interned().as_slice() { | 755 | if let [_, params @ ..] = &*trait_ref.substitution.as_slice(&Interner) { |
753 | if is_fn_trait { | 756 | if is_fn_trait { |
754 | if let Some(args) = | 757 | if let Some(args) = |
755 | params.first().and_then(|it| it.assert_ty_ref(&Interner).as_tuple()) | 758 | params.first().and_then(|it| it.assert_ty_ref(&Interner).as_tuple()) |
756 | { | 759 | { |
757 | write!(f, "(")?; | 760 | write!(f, "(")?; |
758 | f.write_joined(&*args.interned(), ", ")?; | 761 | f.write_joined(args.as_slice(&Interner), ", ")?; |
759 | write!(f, ")")?; | 762 | write!(f, ")")?; |
760 | } | 763 | } |
761 | } else if !params.is_empty() { | 764 | } else if !params.is_empty() { |
@@ -814,7 +817,7 @@ fn fmt_trait_ref(tr: &TraitRef, f: &mut HirFormatter, use_as: bool) -> Result<() | |||
814 | write!(f, "{}", f.db.trait_data(tr.hir_trait_id()).name)?; | 817 | write!(f, "{}", f.db.trait_data(tr.hir_trait_id()).name)?; |
815 | if tr.substitution.len(&Interner) > 1 { | 818 | if tr.substitution.len(&Interner) > 1 { |
816 | write!(f, "<")?; | 819 | write!(f, "<")?; |
817 | f.write_joined(&tr.substitution.interned()[1..], ", ")?; | 820 | f.write_joined(&tr.substitution.as_slice(&Interner)[1..], ", ")?; |
818 | write!(f, ">")?; | 821 | write!(f, ">")?; |
819 | } | 822 | } |
820 | Ok(()) | 823 | Ok(()) |
@@ -995,6 +998,18 @@ impl HirDisplay for TypeRef { | |||
995 | write!(f, "dyn ")?; | 998 | write!(f, "dyn ")?; |
996 | f.write_joined(bounds, " + ")?; | 999 | f.write_joined(bounds, " + ")?; |
997 | } | 1000 | } |
1001 | TypeRef::Macro(macro_call) => { | ||
1002 | let macro_call = macro_call.to_node(f.db.upcast()); | ||
1003 | let ctx = body::LowerCtx::with_hygiene(&Hygiene::new_unhygienic()); | ||
1004 | match macro_call.path() { | ||
1005 | Some(path) => match Path::from_src(path, &ctx) { | ||
1006 | Some(path) => path.hir_fmt(f)?, | ||
1007 | None => write!(f, "{{macro}}")?, | ||
1008 | }, | ||
1009 | None => write!(f, "{{macro}}")?, | ||
1010 | } | ||
1011 | write!(f, "!(..)")?; | ||
1012 | } | ||
998 | TypeRef::Error => write!(f, "{{error}}")?, | 1013 | TypeRef::Error => write!(f, "{{error}}")?, |
999 | } | 1014 | } |
1000 | Ok(()) | 1015 | Ok(()) |
diff --git a/crates/hir_ty/src/infer/expr.rs b/crates/hir_ty/src/infer/expr.rs index cbbfa8b5c..50497eecb 100644 --- a/crates/hir_ty/src/infer/expr.rs +++ b/crates/hir_ty/src/infer/expr.rs | |||
@@ -17,10 +17,11 @@ use syntax::ast::RangeOp; | |||
17 | use crate::{ | 17 | use crate::{ |
18 | autoderef, dummy_usize_const, | 18 | autoderef, dummy_usize_const, |
19 | lower::lower_to_chalk_mutability, | 19 | lower::lower_to_chalk_mutability, |
20 | mapping::from_chalk, | ||
20 | method_resolution, op, | 21 | method_resolution, op, |
21 | primitive::{self, UintTy}, | 22 | primitive::{self, UintTy}, |
22 | static_lifetime, to_chalk_trait_id, | 23 | static_lifetime, to_chalk_trait_id, |
23 | traits::{chalk::from_chalk, FnTrait}, | 24 | traits::FnTrait, |
24 | utils::{generics, Generics}, | 25 | utils::{generics, Generics}, |
25 | AdtId, Binders, CallableDefId, FnPointer, FnSig, FnSubst, InEnvironment, Interner, | 26 | AdtId, Binders, CallableDefId, FnPointer, FnSig, FnSubst, InEnvironment, Interner, |
26 | ProjectionTyExt, Rawness, Scalar, Substitution, TraitRef, Ty, TyBuilder, TyExt, TyKind, | 27 | ProjectionTyExt, Rawness, Scalar, Substitution, TraitRef, Ty, TyBuilder, TyExt, TyKind, |
@@ -462,7 +463,11 @@ impl<'a> InferenceContext<'a> { | |||
462 | }; | 463 | }; |
463 | match canonicalized.decanonicalize_ty(derefed_ty.value).kind(&Interner) { | 464 | match canonicalized.decanonicalize_ty(derefed_ty.value).kind(&Interner) { |
464 | TyKind::Tuple(_, substs) => name.as_tuple_index().and_then(|idx| { | 465 | TyKind::Tuple(_, substs) => name.as_tuple_index().and_then(|idx| { |
465 | substs.interned().get(idx).map(|a| a.assert_ty_ref(&Interner)).cloned() | 466 | substs |
467 | .as_slice(&Interner) | ||
468 | .get(idx) | ||
469 | .map(|a| a.assert_ty_ref(&Interner)) | ||
470 | .cloned() | ||
466 | }), | 471 | }), |
467 | TyKind::Adt(AdtId(hir_def::AdtId::StructId(s)), parameters) => { | 472 | TyKind::Adt(AdtId(hir_def::AdtId::StructId(s)), parameters) => { |
468 | let local_id = self.db.struct_data(*s).variant_data.field(name)?; | 473 | let local_id = self.db.struct_data(*s).variant_data.field(name)?; |
diff --git a/crates/hir_ty/src/infer/pat.rs b/crates/hir_ty/src/infer/pat.rs index a41e8e116..aea354cde 100644 --- a/crates/hir_ty/src/infer/pat.rs +++ b/crates/hir_ty/src/infer/pat.rs | |||
@@ -122,7 +122,7 @@ impl<'a> InferenceContext<'a> { | |||
122 | let ty = match &body[pat] { | 122 | let ty = match &body[pat] { |
123 | &Pat::Tuple { ref args, ellipsis } => { | 123 | &Pat::Tuple { ref args, ellipsis } => { |
124 | let expectations = match expected.as_tuple() { | 124 | let expectations = match expected.as_tuple() { |
125 | Some(parameters) => &*parameters.interned().as_slice(), | 125 | Some(parameters) => &*parameters.as_slice(&Interner), |
126 | _ => &[], | 126 | _ => &[], |
127 | }; | 127 | }; |
128 | 128 | ||
@@ -242,7 +242,7 @@ impl<'a> InferenceContext<'a> { | |||
242 | let (inner_ty, alloc_ty) = match expected.as_adt() { | 242 | let (inner_ty, alloc_ty) = match expected.as_adt() { |
243 | Some((adt, subst)) if adt == box_adt => ( | 243 | Some((adt, subst)) if adt == box_adt => ( |
244 | subst.at(&Interner, 0).assert_ty_ref(&Interner).clone(), | 244 | subst.at(&Interner, 0).assert_ty_ref(&Interner).clone(), |
245 | subst.interned().get(1).and_then(|a| a.ty(&Interner).cloned()), | 245 | subst.as_slice(&Interner).get(1).and_then(|a| a.ty(&Interner).cloned()), |
246 | ), | 246 | ), |
247 | _ => (self.result.standard_types.unknown.clone(), None), | 247 | _ => (self.result.standard_types.unknown.clone(), None), |
248 | }; | 248 | }; |
diff --git a/crates/hir_ty/src/infer/path.rs b/crates/hir_ty/src/infer/path.rs index f8955aa32..495282eba 100644 --- a/crates/hir_ty/src/infer/path.rs +++ b/crates/hir_ty/src/infer/path.rs | |||
@@ -101,7 +101,7 @@ impl<'a> InferenceContext<'a> { | |||
101 | let substs = ctx.substs_from_path(path, typable, true); | 101 | let substs = ctx.substs_from_path(path, typable, true); |
102 | let ty = TyBuilder::value_ty(self.db, typable) | 102 | let ty = TyBuilder::value_ty(self.db, typable) |
103 | .use_parent_substs(&parent_substs) | 103 | .use_parent_substs(&parent_substs) |
104 | .fill(substs.interned()[parent_substs.len(&Interner)..].iter().cloned()) | 104 | .fill(substs.as_slice(&Interner)[parent_substs.len(&Interner)..].iter().cloned()) |
105 | .build(); | 105 | .build(); |
106 | Some(ty) | 106 | Some(ty) |
107 | } | 107 | } |
diff --git a/crates/hir_ty/src/infer/unify.rs b/crates/hir_ty/src/infer/unify.rs index a887e20b0..d8e0b4320 100644 --- a/crates/hir_ty/src/infer/unify.rs +++ b/crates/hir_ty/src/infer/unify.rs | |||
@@ -332,6 +332,10 @@ impl InferenceTable { | |||
332 | | (TyKind::Slice(ty1), TyKind::Slice(ty2)) => self.unify_inner(ty1, ty2, depth + 1), | 332 | | (TyKind::Slice(ty1), TyKind::Slice(ty2)) => self.unify_inner(ty1, ty2, depth + 1), |
333 | _ => true, /* we checked equals_ctor already */ | 333 | _ => true, /* we checked equals_ctor already */ |
334 | } | 334 | } |
335 | } else if let (TyKind::Closure(.., substs1), TyKind::Closure(.., substs2)) = | ||
336 | (ty1.kind(&Interner), ty2.kind(&Interner)) | ||
337 | { | ||
338 | self.unify_substs(substs1, substs2, depth + 1) | ||
335 | } else { | 339 | } else { |
336 | self.unify_inner_trivial(&ty1, &ty2, depth) | 340 | self.unify_inner_trivial(&ty1, &ty2, depth) |
337 | } | 341 | } |
diff --git a/crates/hir_ty/src/traits/chalk/interner.rs b/crates/hir_ty/src/interner.rs index bd9395b7e..a1656115d 100644 --- a/crates/hir_ty/src/traits/chalk/interner.rs +++ b/crates/hir_ty/src/interner.rs | |||
@@ -1,61 +1,83 @@ | |||
1 | //! Implementation of the Chalk `Interner` trait, which allows customizing the | 1 | //! Implementation of the Chalk `Interner` trait, which allows customizing the |
2 | //! representation of the various objects Chalk deals with (types, goals etc.). | 2 | //! representation of the various objects Chalk deals with (types, goals etc.). |
3 | 3 | ||
4 | use super::tls; | 4 | use crate::{chalk_db, tls, GenericArg}; |
5 | use base_db::salsa::InternId; | 5 | use base_db::salsa::InternId; |
6 | use chalk_ir::{GenericArg, Goal, GoalData}; | 6 | use chalk_ir::{Goal, GoalData}; |
7 | use hir_def::TypeAliasId; | 7 | use hir_def::{ |
8 | intern::{impl_internable, InternStorage, Internable, Interned}, | ||
9 | TypeAliasId, | ||
10 | }; | ||
8 | use smallvec::SmallVec; | 11 | use smallvec::SmallVec; |
9 | use std::{fmt, sync::Arc}; | 12 | use std::{fmt, sync::Arc}; |
10 | 13 | ||
11 | #[derive(Debug, Copy, Clone, Hash, PartialOrd, Ord, PartialEq, Eq)] | 14 | #[derive(Debug, Copy, Clone, Hash, PartialOrd, Ord, PartialEq, Eq)] |
12 | pub struct Interner; | 15 | pub struct Interner; |
13 | 16 | ||
14 | pub(crate) type AssocTypeId = chalk_ir::AssocTypeId<Interner>; | 17 | #[derive(PartialEq, Eq, Hash, Debug)] |
15 | pub(crate) type AssociatedTyDatum = chalk_solve::rust_ir::AssociatedTyDatum<Interner>; | 18 | pub struct InternedWrapper<T>(T); |
16 | pub(crate) type TraitId = chalk_ir::TraitId<Interner>; | 19 | |
17 | pub(crate) type TraitDatum = chalk_solve::rust_ir::TraitDatum<Interner>; | 20 | impl<T> std::ops::Deref for InternedWrapper<T> { |
18 | pub(crate) type AdtId = chalk_ir::AdtId<Interner>; | 21 | type Target = T; |
19 | pub(crate) type StructDatum = chalk_solve::rust_ir::AdtDatum<Interner>; | 22 | |
20 | pub(crate) type ImplId = chalk_ir::ImplId<Interner>; | 23 | fn deref(&self) -> &Self::Target { |
21 | pub(crate) type ImplDatum = chalk_solve::rust_ir::ImplDatum<Interner>; | 24 | &self.0 |
22 | pub(crate) type AssociatedTyValueId = chalk_solve::rust_ir::AssociatedTyValueId<Interner>; | 25 | } |
23 | pub(crate) type AssociatedTyValue = chalk_solve::rust_ir::AssociatedTyValue<Interner>; | 26 | } |
24 | pub(crate) type FnDefDatum = chalk_solve::rust_ir::FnDefDatum<Interner>; | 27 | |
25 | pub(crate) type OpaqueTyId = chalk_ir::OpaqueTyId<Interner>; | 28 | impl_internable!( |
26 | pub(crate) type OpaqueTyDatum = chalk_solve::rust_ir::OpaqueTyDatum<Interner>; | 29 | InternedWrapper<Vec<chalk_ir::VariableKind<Interner>>>, |
27 | pub(crate) type Variances = chalk_ir::Variances<Interner>; | 30 | InternedWrapper<SmallVec<[GenericArg; 2]>>, |
31 | InternedWrapper<chalk_ir::TyData<Interner>>, | ||
32 | InternedWrapper<chalk_ir::LifetimeData<Interner>>, | ||
33 | InternedWrapper<chalk_ir::ConstData<Interner>>, | ||
34 | InternedWrapper<Vec<chalk_ir::CanonicalVarKind<Interner>>>, | ||
35 | InternedWrapper<Vec<chalk_ir::ProgramClause<Interner>>>, | ||
36 | InternedWrapper<Vec<chalk_ir::QuantifiedWhereClause<Interner>>>, | ||
37 | InternedWrapper<Vec<chalk_ir::Variance>>, | ||
38 | ); | ||
28 | 39 | ||
29 | impl chalk_ir::interner::Interner for Interner { | 40 | impl chalk_ir::interner::Interner for Interner { |
30 | type InternedType = Arc<chalk_ir::TyData<Self>>; | 41 | type InternedType = Interned<InternedWrapper<chalk_ir::TyData<Interner>>>; |
31 | type InternedLifetime = chalk_ir::LifetimeData<Self>; | 42 | type InternedLifetime = Interned<InternedWrapper<chalk_ir::LifetimeData<Self>>>; |
32 | type InternedConst = Arc<chalk_ir::ConstData<Self>>; | 43 | type InternedConst = Interned<InternedWrapper<chalk_ir::ConstData<Self>>>; |
33 | type InternedConcreteConst = (); | 44 | type InternedConcreteConst = (); |
34 | type InternedGenericArg = chalk_ir::GenericArgData<Self>; | 45 | type InternedGenericArg = chalk_ir::GenericArgData<Self>; |
35 | type InternedGoal = Arc<GoalData<Self>>; | 46 | type InternedGoal = Arc<GoalData<Self>>; |
36 | type InternedGoals = Vec<Goal<Self>>; | 47 | type InternedGoals = Vec<Goal<Self>>; |
37 | type InternedSubstitution = SmallVec<[GenericArg<Self>; 2]>; | 48 | type InternedSubstitution = Interned<InternedWrapper<SmallVec<[GenericArg; 2]>>>; |
38 | type InternedProgramClause = Arc<chalk_ir::ProgramClauseData<Self>>; | 49 | type InternedProgramClause = chalk_ir::ProgramClauseData<Self>; |
39 | type InternedProgramClauses = Arc<[chalk_ir::ProgramClause<Self>]>; | 50 | type InternedProgramClauses = Interned<InternedWrapper<Vec<chalk_ir::ProgramClause<Self>>>>; |
40 | type InternedQuantifiedWhereClauses = Vec<chalk_ir::QuantifiedWhereClause<Self>>; | 51 | type InternedQuantifiedWhereClauses = |
41 | type InternedVariableKinds = Vec<chalk_ir::VariableKind<Self>>; | 52 | Interned<InternedWrapper<Vec<chalk_ir::QuantifiedWhereClause<Self>>>>; |
42 | type InternedCanonicalVarKinds = Vec<chalk_ir::CanonicalVarKind<Self>>; | 53 | type InternedVariableKinds = Interned<InternedWrapper<Vec<chalk_ir::VariableKind<Interner>>>>; |
54 | type InternedCanonicalVarKinds = | ||
55 | Interned<InternedWrapper<Vec<chalk_ir::CanonicalVarKind<Self>>>>; | ||
43 | type InternedConstraints = Vec<chalk_ir::InEnvironment<chalk_ir::Constraint<Self>>>; | 56 | type InternedConstraints = Vec<chalk_ir::InEnvironment<chalk_ir::Constraint<Self>>>; |
44 | type InternedVariances = Arc<[chalk_ir::Variance]>; | 57 | type InternedVariances = Interned<InternedWrapper<Vec<chalk_ir::Variance>>>; |
45 | type DefId = InternId; | 58 | type DefId = InternId; |
46 | type InternedAdtId = hir_def::AdtId; | 59 | type InternedAdtId = hir_def::AdtId; |
47 | type Identifier = TypeAliasId; | 60 | type Identifier = TypeAliasId; |
48 | type FnAbi = (); | 61 | type FnAbi = (); |
49 | 62 | ||
50 | fn debug_adt_id(type_kind_id: AdtId, fmt: &mut fmt::Formatter<'_>) -> Option<fmt::Result> { | 63 | fn debug_adt_id( |
64 | type_kind_id: chalk_db::AdtId, | ||
65 | fmt: &mut fmt::Formatter<'_>, | ||
66 | ) -> Option<fmt::Result> { | ||
51 | tls::with_current_program(|prog| Some(prog?.debug_struct_id(type_kind_id, fmt))) | 67 | tls::with_current_program(|prog| Some(prog?.debug_struct_id(type_kind_id, fmt))) |
52 | } | 68 | } |
53 | 69 | ||
54 | fn debug_trait_id(type_kind_id: TraitId, fmt: &mut fmt::Formatter<'_>) -> Option<fmt::Result> { | 70 | fn debug_trait_id( |
71 | type_kind_id: chalk_db::TraitId, | ||
72 | fmt: &mut fmt::Formatter<'_>, | ||
73 | ) -> Option<fmt::Result> { | ||
55 | tls::with_current_program(|prog| Some(prog?.debug_trait_id(type_kind_id, fmt))) | 74 | tls::with_current_program(|prog| Some(prog?.debug_trait_id(type_kind_id, fmt))) |
56 | } | 75 | } |
57 | 76 | ||
58 | fn debug_assoc_type_id(id: AssocTypeId, fmt: &mut fmt::Formatter<'_>) -> Option<fmt::Result> { | 77 | fn debug_assoc_type_id( |
78 | id: chalk_db::AssocTypeId, | ||
79 | fmt: &mut fmt::Formatter<'_>, | ||
80 | ) -> Option<fmt::Result> { | ||
59 | tls::with_current_program(|prog| Some(prog?.debug_assoc_type_id(id, fmt))) | 81 | tls::with_current_program(|prog| Some(prog?.debug_assoc_type_id(id, fmt))) |
60 | } | 82 | } |
61 | 83 | ||
@@ -99,7 +121,7 @@ impl chalk_ir::interner::Interner for Interner { | |||
99 | } | 121 | } |
100 | 122 | ||
101 | fn debug_generic_arg( | 123 | fn debug_generic_arg( |
102 | parameter: &GenericArg<Interner>, | 124 | parameter: &GenericArg, |
103 | fmt: &mut fmt::Formatter<'_>, | 125 | fmt: &mut fmt::Formatter<'_>, |
104 | ) -> Option<fmt::Result> { | 126 | ) -> Option<fmt::Result> { |
105 | tls::with_current_program(|prog| Some(prog?.debug_generic_arg(parameter, fmt))) | 127 | tls::with_current_program(|prog| Some(prog?.debug_generic_arg(parameter, fmt))) |
@@ -194,30 +216,30 @@ impl chalk_ir::interner::Interner for Interner { | |||
194 | 216 | ||
195 | fn intern_ty(&self, kind: chalk_ir::TyKind<Self>) -> Self::InternedType { | 217 | fn intern_ty(&self, kind: chalk_ir::TyKind<Self>) -> Self::InternedType { |
196 | let flags = kind.compute_flags(self); | 218 | let flags = kind.compute_flags(self); |
197 | Arc::new(chalk_ir::TyData { kind, flags }) | 219 | Interned::new(InternedWrapper(chalk_ir::TyData { kind, flags })) |
198 | } | 220 | } |
199 | 221 | ||
200 | fn ty_data<'a>(&self, ty: &'a Self::InternedType) -> &'a chalk_ir::TyData<Self> { | 222 | fn ty_data<'a>(&self, ty: &'a Self::InternedType) -> &'a chalk_ir::TyData<Self> { |
201 | ty | 223 | &ty.0 |
202 | } | 224 | } |
203 | 225 | ||
204 | fn intern_lifetime(&self, lifetime: chalk_ir::LifetimeData<Self>) -> Self::InternedLifetime { | 226 | fn intern_lifetime(&self, lifetime: chalk_ir::LifetimeData<Self>) -> Self::InternedLifetime { |
205 | lifetime | 227 | Interned::new(InternedWrapper(lifetime)) |
206 | } | 228 | } |
207 | 229 | ||
208 | fn lifetime_data<'a>( | 230 | fn lifetime_data<'a>( |
209 | &self, | 231 | &self, |
210 | lifetime: &'a Self::InternedLifetime, | 232 | lifetime: &'a Self::InternedLifetime, |
211 | ) -> &'a chalk_ir::LifetimeData<Self> { | 233 | ) -> &'a chalk_ir::LifetimeData<Self> { |
212 | lifetime | 234 | &lifetime.0 |
213 | } | 235 | } |
214 | 236 | ||
215 | fn intern_const(&self, constant: chalk_ir::ConstData<Self>) -> Self::InternedConst { | 237 | fn intern_const(&self, constant: chalk_ir::ConstData<Self>) -> Self::InternedConst { |
216 | Arc::new(constant) | 238 | Interned::new(InternedWrapper(constant)) |
217 | } | 239 | } |
218 | 240 | ||
219 | fn const_data<'a>(&self, constant: &'a Self::InternedConst) -> &'a chalk_ir::ConstData<Self> { | 241 | fn const_data<'a>(&self, constant: &'a Self::InternedConst) -> &'a chalk_ir::ConstData<Self> { |
220 | constant | 242 | &constant.0 |
221 | } | 243 | } |
222 | 244 | ||
223 | fn const_eq( | 245 | fn const_eq( |
@@ -264,23 +286,23 @@ impl chalk_ir::interner::Interner for Interner { | |||
264 | 286 | ||
265 | fn intern_substitution<E>( | 287 | fn intern_substitution<E>( |
266 | &self, | 288 | &self, |
267 | data: impl IntoIterator<Item = Result<GenericArg<Self>, E>>, | 289 | data: impl IntoIterator<Item = Result<GenericArg, E>>, |
268 | ) -> Result<Self::InternedSubstitution, E> { | 290 | ) -> Result<Self::InternedSubstitution, E> { |
269 | data.into_iter().collect() | 291 | Ok(Interned::new(InternedWrapper(data.into_iter().collect::<Result<_, _>>()?))) |
270 | } | 292 | } |
271 | 293 | ||
272 | fn substitution_data<'a>( | 294 | fn substitution_data<'a>( |
273 | &self, | 295 | &self, |
274 | substitution: &'a Self::InternedSubstitution, | 296 | substitution: &'a Self::InternedSubstitution, |
275 | ) -> &'a [GenericArg<Self>] { | 297 | ) -> &'a [GenericArg] { |
276 | substitution | 298 | &substitution.as_ref().0 |
277 | } | 299 | } |
278 | 300 | ||
279 | fn intern_program_clause( | 301 | fn intern_program_clause( |
280 | &self, | 302 | &self, |
281 | data: chalk_ir::ProgramClauseData<Self>, | 303 | data: chalk_ir::ProgramClauseData<Self>, |
282 | ) -> Self::InternedProgramClause { | 304 | ) -> Self::InternedProgramClause { |
283 | Arc::new(data) | 305 | data |
284 | } | 306 | } |
285 | 307 | ||
286 | fn program_clause_data<'a>( | 308 | fn program_clause_data<'a>( |
@@ -294,7 +316,7 @@ impl chalk_ir::interner::Interner for Interner { | |||
294 | &self, | 316 | &self, |
295 | data: impl IntoIterator<Item = Result<chalk_ir::ProgramClause<Self>, E>>, | 317 | data: impl IntoIterator<Item = Result<chalk_ir::ProgramClause<Self>, E>>, |
296 | ) -> Result<Self::InternedProgramClauses, E> { | 318 | ) -> Result<Self::InternedProgramClauses, E> { |
297 | data.into_iter().collect() | 319 | Ok(Interned::new(InternedWrapper(data.into_iter().collect::<Result<_, _>>()?))) |
298 | } | 320 | } |
299 | 321 | ||
300 | fn program_clauses_data<'a>( | 322 | fn program_clauses_data<'a>( |
@@ -308,7 +330,7 @@ impl chalk_ir::interner::Interner for Interner { | |||
308 | &self, | 330 | &self, |
309 | data: impl IntoIterator<Item = Result<chalk_ir::QuantifiedWhereClause<Self>, E>>, | 331 | data: impl IntoIterator<Item = Result<chalk_ir::QuantifiedWhereClause<Self>, E>>, |
310 | ) -> Result<Self::InternedQuantifiedWhereClauses, E> { | 332 | ) -> Result<Self::InternedQuantifiedWhereClauses, E> { |
311 | data.into_iter().collect() | 333 | Ok(Interned::new(InternedWrapper(data.into_iter().collect::<Result<_, _>>()?))) |
312 | } | 334 | } |
313 | 335 | ||
314 | fn quantified_where_clauses_data<'a>( | 336 | fn quantified_where_clauses_data<'a>( |
@@ -322,21 +344,21 @@ impl chalk_ir::interner::Interner for Interner { | |||
322 | &self, | 344 | &self, |
323 | data: impl IntoIterator<Item = Result<chalk_ir::VariableKind<Self>, E>>, | 345 | data: impl IntoIterator<Item = Result<chalk_ir::VariableKind<Self>, E>>, |
324 | ) -> Result<Self::InternedVariableKinds, E> { | 346 | ) -> Result<Self::InternedVariableKinds, E> { |
325 | data.into_iter().collect() | 347 | Ok(Interned::new(InternedWrapper(data.into_iter().collect::<Result<_, _>>()?))) |
326 | } | 348 | } |
327 | 349 | ||
328 | fn variable_kinds_data<'a>( | 350 | fn variable_kinds_data<'a>( |
329 | &self, | 351 | &self, |
330 | parameter_kinds: &'a Self::InternedVariableKinds, | 352 | parameter_kinds: &'a Self::InternedVariableKinds, |
331 | ) -> &'a [chalk_ir::VariableKind<Self>] { | 353 | ) -> &'a [chalk_ir::VariableKind<Self>] { |
332 | ¶meter_kinds | 354 | ¶meter_kinds.as_ref().0 |
333 | } | 355 | } |
334 | 356 | ||
335 | fn intern_canonical_var_kinds<E>( | 357 | fn intern_canonical_var_kinds<E>( |
336 | &self, | 358 | &self, |
337 | data: impl IntoIterator<Item = Result<chalk_ir::CanonicalVarKind<Self>, E>>, | 359 | data: impl IntoIterator<Item = Result<chalk_ir::CanonicalVarKind<Self>, E>>, |
338 | ) -> Result<Self::InternedCanonicalVarKinds, E> { | 360 | ) -> Result<Self::InternedCanonicalVarKinds, E> { |
339 | data.into_iter().collect() | 361 | Ok(Interned::new(InternedWrapper(data.into_iter().collect::<Result<_, _>>()?))) |
340 | } | 362 | } |
341 | 363 | ||
342 | fn canonical_var_kinds_data<'a>( | 364 | fn canonical_var_kinds_data<'a>( |
@@ -376,7 +398,7 @@ impl chalk_ir::interner::Interner for Interner { | |||
376 | &self, | 398 | &self, |
377 | data: impl IntoIterator<Item = Result<chalk_ir::Variance, E>>, | 399 | data: impl IntoIterator<Item = Result<chalk_ir::Variance, E>>, |
378 | ) -> Result<Self::InternedVariances, E> { | 400 | ) -> Result<Self::InternedVariances, E> { |
379 | data.into_iter().collect() | 401 | Ok(Interned::new(InternedWrapper(data.into_iter().collect::<Result<_, _>>()?))) |
380 | } | 402 | } |
381 | 403 | ||
382 | fn variances_data<'a>( | 404 | fn variances_data<'a>( |
@@ -390,3 +412,12 @@ impl chalk_ir::interner::Interner for Interner { | |||
390 | impl chalk_ir::interner::HasInterner for Interner { | 412 | impl chalk_ir::interner::HasInterner for Interner { |
391 | type Interner = Self; | 413 | type Interner = Self; |
392 | } | 414 | } |
415 | |||
416 | #[macro_export] | ||
417 | macro_rules! has_interner { | ||
418 | ($t:ty) => { | ||
419 | impl HasInterner for $t { | ||
420 | type Interner = crate::Interner; | ||
421 | } | ||
422 | }; | ||
423 | } | ||
diff --git a/crates/hir_ty/src/lib.rs b/crates/hir_ty/src/lib.rs index 874c95411..0505fa4ae 100644 --- a/crates/hir_ty/src/lib.rs +++ b/crates/hir_ty/src/lib.rs | |||
@@ -7,21 +7,23 @@ macro_rules! eprintln { | |||
7 | } | 7 | } |
8 | 8 | ||
9 | mod autoderef; | 9 | mod autoderef; |
10 | pub mod primitive; | ||
11 | pub mod traits; | ||
12 | pub mod method_resolution; | ||
13 | mod op; | ||
14 | mod lower; | ||
15 | pub(crate) mod infer; | ||
16 | pub(crate) mod utils; | ||
17 | mod chalk_cast; | ||
18 | mod chalk_ext; | ||
19 | mod builder; | 10 | mod builder; |
11 | mod chalk_db; | ||
12 | mod chalk_ext; | ||
13 | mod infer; | ||
14 | mod interner; | ||
15 | mod lower; | ||
16 | mod mapping; | ||
17 | mod op; | ||
18 | mod tls; | ||
19 | mod utils; | ||
20 | mod walk; | 20 | mod walk; |
21 | |||
22 | pub mod display; | ||
23 | pub mod db; | 21 | pub mod db; |
24 | pub mod diagnostics; | 22 | pub mod diagnostics; |
23 | pub mod display; | ||
24 | pub mod method_resolution; | ||
25 | pub mod primitive; | ||
26 | pub mod traits; | ||
25 | 27 | ||
26 | #[cfg(test)] | 28 | #[cfg(test)] |
27 | mod tests; | 29 | mod tests; |
@@ -30,16 +32,12 @@ mod test_db; | |||
30 | 32 | ||
31 | use std::sync::Arc; | 33 | use std::sync::Arc; |
32 | 34 | ||
33 | use base_db::salsa; | ||
34 | use chalk_ir::{ | 35 | use chalk_ir::{ |
35 | fold::{Fold, Shift}, | 36 | fold::{Fold, Shift}, |
36 | interner::HasInterner, | 37 | interner::HasInterner, |
37 | UintTy, | 38 | UintTy, |
38 | }; | 39 | }; |
39 | use hir_def::{ | 40 | use hir_def::{expr::ExprId, type_ref::Rawness, TypeParamId}; |
40 | expr::ExprId, type_ref::Rawness, ConstParamId, LifetimeParamId, TraitId, TypeAliasId, | ||
41 | TypeParamId, | ||
42 | }; | ||
43 | 41 | ||
44 | use crate::{db::HirDatabase, display::HirDisplay, utils::generics}; | 42 | use crate::{db::HirDatabase, display::HirDisplay, utils::generics}; |
45 | 43 | ||
@@ -47,11 +45,18 @@ pub use autoderef::autoderef; | |||
47 | pub use builder::TyBuilder; | 45 | pub use builder::TyBuilder; |
48 | pub use chalk_ext::*; | 46 | pub use chalk_ext::*; |
49 | pub use infer::{could_unify, InferenceResult}; | 47 | pub use infer::{could_unify, InferenceResult}; |
48 | pub use interner::Interner; | ||
50 | pub use lower::{ | 49 | pub use lower::{ |
51 | associated_type_shorthand_candidates, callable_item_sig, CallableDefId, ImplTraitLoweringMode, | 50 | associated_type_shorthand_candidates, callable_item_sig, CallableDefId, ImplTraitLoweringMode, |
52 | TyDefId, TyLoweringContext, ValueTyDefId, | 51 | TyDefId, TyLoweringContext, ValueTyDefId, |
53 | }; | 52 | }; |
54 | pub use traits::{chalk::Interner, TraitEnvironment}; | 53 | pub use mapping::{ |
54 | const_from_placeholder_idx, from_assoc_type_id, from_chalk_trait_id, from_foreign_def_id, | ||
55 | from_placeholder_idx, lt_from_placeholder_idx, to_assoc_type_id, to_chalk_trait_id, | ||
56 | to_foreign_def_id, to_placeholder_idx, | ||
57 | }; | ||
58 | pub use traits::TraitEnvironment; | ||
59 | pub use utils::all_super_traits; | ||
55 | pub use walk::TypeWalk; | 60 | pub use walk::TypeWalk; |
56 | 61 | ||
57 | pub use chalk_ir::{ | 62 | pub use chalk_ir::{ |
@@ -94,6 +99,10 @@ pub type ConstValue = chalk_ir::ConstValue<Interner>; | |||
94 | pub type ConcreteConst = chalk_ir::ConcreteConst<Interner>; | 99 | pub type ConcreteConst = chalk_ir::ConcreteConst<Interner>; |
95 | 100 | ||
96 | pub type ChalkTraitId = chalk_ir::TraitId<Interner>; | 101 | pub type ChalkTraitId = chalk_ir::TraitId<Interner>; |
102 | pub type TraitRef = chalk_ir::TraitRef<Interner>; | ||
103 | pub type QuantifiedWhereClause = Binders<WhereClause>; | ||
104 | pub type QuantifiedWhereClauses = chalk_ir::QuantifiedWhereClauses<Interner>; | ||
105 | pub type Canonical<T> = chalk_ir::Canonical<T>; | ||
97 | 106 | ||
98 | pub type FnSig = chalk_ir::FnSig<Interner>; | 107 | pub type FnSig = chalk_ir::FnSig<Interner>; |
99 | 108 | ||
@@ -109,7 +118,7 @@ pub type WhereClause = chalk_ir::WhereClause<Interner>; | |||
109 | pub fn subst_prefix(s: &Substitution, n: usize) -> Substitution { | 118 | pub fn subst_prefix(s: &Substitution, n: usize) -> Substitution { |
110 | Substitution::from_iter( | 119 | Substitution::from_iter( |
111 | &Interner, | 120 | &Interner, |
112 | s.interned()[..std::cmp::min(s.len(&Interner), n)].iter().cloned(), | 121 | s.as_slice(&Interner)[..std::cmp::min(s.len(&Interner), n)].iter().cloned(), |
113 | ) | 122 | ) |
114 | } | 123 | } |
115 | 124 | ||
@@ -118,14 +127,14 @@ pub fn param_idx(db: &dyn HirDatabase, id: TypeParamId) -> Option<usize> { | |||
118 | generics(db.upcast(), id.parent).param_idx(id) | 127 | generics(db.upcast(), id.parent).param_idx(id) |
119 | } | 128 | } |
120 | 129 | ||
121 | pub fn wrap_empty_binders<T>(value: T) -> Binders<T> | 130 | pub(crate) fn wrap_empty_binders<T>(value: T) -> Binders<T> |
122 | where | 131 | where |
123 | T: Fold<Interner, Result = T> + HasInterner<Interner = Interner>, | 132 | T: Fold<Interner, Result = T> + HasInterner<Interner = Interner>, |
124 | { | 133 | { |
125 | Binders::empty(&Interner, value.shifted_in_from(&Interner, DebruijnIndex::ONE)) | 134 | Binders::empty(&Interner, value.shifted_in_from(&Interner, DebruijnIndex::ONE)) |
126 | } | 135 | } |
127 | 136 | ||
128 | pub fn make_only_type_binders<T: HasInterner<Interner = Interner>>( | 137 | pub(crate) fn make_only_type_binders<T: HasInterner<Interner = Interner>>( |
129 | num_vars: usize, | 138 | num_vars: usize, |
130 | value: T, | 139 | value: T, |
131 | ) -> Binders<T> { | 140 | ) -> Binders<T> { |
@@ -153,14 +162,6 @@ pub fn make_canonical<T: HasInterner<Interner = Interner>>( | |||
153 | Canonical { value, binders: chalk_ir::CanonicalVarKinds::from_iter(&Interner, kinds) } | 162 | Canonical { value, binders: chalk_ir::CanonicalVarKinds::from_iter(&Interner, kinds) } |
154 | } | 163 | } |
155 | 164 | ||
156 | pub type TraitRef = chalk_ir::TraitRef<Interner>; | ||
157 | |||
158 | pub type QuantifiedWhereClause = Binders<WhereClause>; | ||
159 | |||
160 | pub type QuantifiedWhereClauses = chalk_ir::QuantifiedWhereClauses<Interner>; | ||
161 | |||
162 | pub type Canonical<T> = chalk_ir::Canonical<T>; | ||
163 | |||
164 | /// A function signature as seen by type inference: Several parameter types and | 165 | /// A function signature as seen by type inference: Several parameter types and |
165 | /// one return type. | 166 | /// one return type. |
166 | #[derive(Clone, PartialEq, Eq, Debug)] | 167 | #[derive(Clone, PartialEq, Eq, Debug)] |
@@ -169,6 +170,8 @@ pub struct CallableSig { | |||
169 | is_varargs: bool, | 170 | is_varargs: bool, |
170 | } | 171 | } |
171 | 172 | ||
173 | has_interner!(CallableSig); | ||
174 | |||
172 | /// A polymorphic function signature. | 175 | /// A polymorphic function signature. |
173 | pub type PolyFnSig = Binders<CallableSig>; | 176 | pub type PolyFnSig = Binders<CallableSig>; |
174 | 177 | ||
@@ -187,7 +190,7 @@ impl CallableSig { | |||
187 | .shifted_out_to(&Interner, DebruijnIndex::ONE) | 190 | .shifted_out_to(&Interner, DebruijnIndex::ONE) |
188 | .expect("unexpected lifetime vars in fn ptr") | 191 | .expect("unexpected lifetime vars in fn ptr") |
189 | .0 | 192 | .0 |
190 | .interned() | 193 | .as_slice(&Interner) |
191 | .iter() | 194 | .iter() |
192 | .map(|arg| arg.assert_ty_ref(&Interner).clone()) | 195 | .map(|arg| arg.assert_ty_ref(&Interner).clone()) |
193 | .collect(), | 196 | .collect(), |
@@ -232,61 +235,13 @@ pub struct ReturnTypeImplTraits { | |||
232 | pub(crate) impl_traits: Vec<ReturnTypeImplTrait>, | 235 | pub(crate) impl_traits: Vec<ReturnTypeImplTrait>, |
233 | } | 236 | } |
234 | 237 | ||
238 | has_interner!(ReturnTypeImplTraits); | ||
239 | |||
235 | #[derive(Clone, PartialEq, Eq, Debug, Hash)] | 240 | #[derive(Clone, PartialEq, Eq, Debug, Hash)] |
236 | pub(crate) struct ReturnTypeImplTrait { | 241 | pub(crate) struct ReturnTypeImplTrait { |
237 | pub(crate) bounds: Binders<Vec<QuantifiedWhereClause>>, | 242 | pub(crate) bounds: Binders<Vec<QuantifiedWhereClause>>, |
238 | } | 243 | } |
239 | 244 | ||
240 | pub fn to_foreign_def_id(id: TypeAliasId) -> ForeignDefId { | ||
241 | chalk_ir::ForeignDefId(salsa::InternKey::as_intern_id(&id)) | ||
242 | } | ||
243 | |||
244 | pub fn from_foreign_def_id(id: ForeignDefId) -> TypeAliasId { | ||
245 | salsa::InternKey::from_intern_id(id.0) | ||
246 | } | ||
247 | |||
248 | pub fn to_assoc_type_id(id: TypeAliasId) -> AssocTypeId { | ||
249 | chalk_ir::AssocTypeId(salsa::InternKey::as_intern_id(&id)) | ||
250 | } | ||
251 | |||
252 | pub fn from_assoc_type_id(id: AssocTypeId) -> TypeAliasId { | ||
253 | salsa::InternKey::from_intern_id(id.0) | ||
254 | } | ||
255 | |||
256 | pub fn from_placeholder_idx(db: &dyn HirDatabase, idx: PlaceholderIndex) -> TypeParamId { | ||
257 | assert_eq!(idx.ui, chalk_ir::UniverseIndex::ROOT); | ||
258 | let interned_id = salsa::InternKey::from_intern_id(salsa::InternId::from(idx.idx)); | ||
259 | db.lookup_intern_type_param_id(interned_id) | ||
260 | } | ||
261 | |||
262 | pub fn to_placeholder_idx(db: &dyn HirDatabase, id: TypeParamId) -> PlaceholderIndex { | ||
263 | let interned_id = db.intern_type_param_id(id); | ||
264 | PlaceholderIndex { | ||
265 | ui: chalk_ir::UniverseIndex::ROOT, | ||
266 | idx: salsa::InternKey::as_intern_id(&interned_id).as_usize(), | ||
267 | } | ||
268 | } | ||
269 | |||
270 | pub fn lt_from_placeholder_idx(db: &dyn HirDatabase, idx: PlaceholderIndex) -> LifetimeParamId { | ||
271 | assert_eq!(idx.ui, chalk_ir::UniverseIndex::ROOT); | ||
272 | let interned_id = salsa::InternKey::from_intern_id(salsa::InternId::from(idx.idx)); | ||
273 | db.lookup_intern_lifetime_param_id(interned_id) | ||
274 | } | ||
275 | |||
276 | pub fn const_from_placeholder_idx(db: &dyn HirDatabase, idx: PlaceholderIndex) -> ConstParamId { | ||
277 | assert_eq!(idx.ui, chalk_ir::UniverseIndex::ROOT); | ||
278 | let interned_id = salsa::InternKey::from_intern_id(salsa::InternId::from(idx.idx)); | ||
279 | db.lookup_intern_const_param_id(interned_id) | ||
280 | } | ||
281 | |||
282 | pub fn to_chalk_trait_id(id: TraitId) -> ChalkTraitId { | ||
283 | chalk_ir::TraitId(salsa::InternKey::as_intern_id(&id)) | ||
284 | } | ||
285 | |||
286 | pub fn from_chalk_trait_id(id: ChalkTraitId) -> TraitId { | ||
287 | salsa::InternKey::from_intern_id(id.0) | ||
288 | } | ||
289 | |||
290 | pub fn static_lifetime() -> Lifetime { | 245 | pub fn static_lifetime() -> Lifetime { |
291 | LifetimeData::Static.intern(&Interner) | 246 | LifetimeData::Static.intern(&Interner) |
292 | } | 247 | } |
diff --git a/crates/hir_ty/src/lower.rs b/crates/hir_ty/src/lower.rs index 8a22d9ea3..c99dd8d0a 100644 --- a/crates/hir_ty/src/lower.rs +++ b/crates/hir_ty/src/lower.rs | |||
@@ -5,12 +5,14 @@ | |||
5 | //! - Building the type for an item: This happens through the `type_for_def` query. | 5 | //! - Building the type for an item: This happens through the `type_for_def` query. |
6 | //! | 6 | //! |
7 | //! This usually involves resolving names, collecting generic arguments etc. | 7 | //! This usually involves resolving names, collecting generic arguments etc. |
8 | use std::cell::{Cell, RefCell}; | ||
8 | use std::{iter, sync::Arc}; | 9 | use std::{iter, sync::Arc}; |
9 | 10 | ||
10 | use base_db::CrateId; | 11 | use base_db::CrateId; |
11 | use chalk_ir::{cast::Cast, fold::Shift, interner::HasInterner, Mutability, Safety}; | 12 | use chalk_ir::{cast::Cast, fold::Shift, interner::HasInterner, Mutability, Safety}; |
12 | use hir_def::{ | 13 | use hir_def::{ |
13 | adt::StructKind, | 14 | adt::StructKind, |
15 | body::{Expander, LowerCtx}, | ||
14 | builtin_type::BuiltinType, | 16 | builtin_type::BuiltinType, |
15 | generics::{TypeParamProvenance, WherePredicate, WherePredicateTypeTarget}, | 17 | generics::{TypeParamProvenance, WherePredicate, WherePredicateTypeTarget}, |
16 | path::{GenericArg, Path, PathSegment, PathSegments}, | 18 | path::{GenericArg, Path, PathSegment, PathSegments}, |
@@ -20,20 +22,22 @@ use hir_def::{ | |||
20 | GenericDefId, HasModule, ImplId, LocalFieldId, Lookup, StaticId, StructId, TraitId, | 22 | GenericDefId, HasModule, ImplId, LocalFieldId, Lookup, StaticId, StructId, TraitId, |
21 | TypeAliasId, TypeParamId, UnionId, VariantId, | 23 | TypeAliasId, TypeParamId, UnionId, VariantId, |
22 | }; | 24 | }; |
23 | use hir_expand::name::Name; | 25 | use hir_expand::{name::Name, ExpandResult}; |
24 | use la_arena::ArenaMap; | 26 | use la_arena::ArenaMap; |
25 | use smallvec::SmallVec; | 27 | use smallvec::SmallVec; |
26 | use stdx::impl_from; | 28 | use stdx::impl_from; |
29 | use syntax::ast; | ||
27 | 30 | ||
28 | use crate::{ | 31 | use crate::{ |
29 | db::HirDatabase, | 32 | db::HirDatabase, |
30 | dummy_usize_const, static_lifetime, to_assoc_type_id, to_chalk_trait_id, to_placeholder_idx, | 33 | dummy_usize_const, |
31 | traits::chalk::{Interner, ToChalk}, | 34 | mapping::ToChalk, |
35 | static_lifetime, to_assoc_type_id, to_chalk_trait_id, to_placeholder_idx, | ||
32 | utils::{ | 36 | utils::{ |
33 | all_super_trait_refs, associated_type_by_name_including_super_traits, generics, Generics, | 37 | all_super_trait_refs, associated_type_by_name_including_super_traits, generics, Generics, |
34 | }, | 38 | }, |
35 | AliasEq, AliasTy, Binders, BoundVar, CallableSig, DebruijnIndex, DynTy, FnPointer, FnSig, | 39 | AliasEq, AliasTy, Binders, BoundVar, CallableSig, DebruijnIndex, DynTy, FnPointer, FnSig, |
36 | FnSubst, ImplTraitId, OpaqueTy, PolyFnSig, ProjectionTy, QuantifiedWhereClause, | 40 | FnSubst, ImplTraitId, Interner, OpaqueTy, PolyFnSig, ProjectionTy, QuantifiedWhereClause, |
37 | QuantifiedWhereClauses, ReturnTypeImplTrait, ReturnTypeImplTraits, Substitution, | 41 | QuantifiedWhereClauses, ReturnTypeImplTrait, ReturnTypeImplTraits, Substitution, |
38 | TraitEnvironment, TraitRef, TraitRefExt, Ty, TyBuilder, TyKind, WhereClause, | 42 | TraitEnvironment, TraitRef, TraitRefExt, Ty, TyBuilder, TyKind, WhereClause, |
39 | }; | 43 | }; |
@@ -49,7 +53,7 @@ pub struct TyLoweringContext<'a> { | |||
49 | /// possible currently, so this should be fine for now. | 53 | /// possible currently, so this should be fine for now. |
50 | pub type_param_mode: TypeParamLoweringMode, | 54 | pub type_param_mode: TypeParamLoweringMode, |
51 | pub impl_trait_mode: ImplTraitLoweringMode, | 55 | pub impl_trait_mode: ImplTraitLoweringMode, |
52 | impl_trait_counter: std::cell::Cell<u16>, | 56 | impl_trait_counter: Cell<u16>, |
53 | /// When turning `impl Trait` into opaque types, we have to collect the | 57 | /// When turning `impl Trait` into opaque types, we have to collect the |
54 | /// bounds at the same time to get the IDs correct (without becoming too | 58 | /// bounds at the same time to get the IDs correct (without becoming too |
55 | /// complicated). I don't like using interior mutability (as for the | 59 | /// complicated). I don't like using interior mutability (as for the |
@@ -58,16 +62,17 @@ pub struct TyLoweringContext<'a> { | |||
58 | /// we're grouping the mutable data (the counter and this field) together | 62 | /// we're grouping the mutable data (the counter and this field) together |
59 | /// with the immutable context (the references to the DB and resolver). | 63 | /// with the immutable context (the references to the DB and resolver). |
60 | /// Splitting this up would be a possible fix. | 64 | /// Splitting this up would be a possible fix. |
61 | opaque_type_data: std::cell::RefCell<Vec<ReturnTypeImplTrait>>, | 65 | opaque_type_data: RefCell<Vec<ReturnTypeImplTrait>>, |
66 | expander: RefCell<Option<Expander>>, | ||
62 | } | 67 | } |
63 | 68 | ||
64 | impl<'a> TyLoweringContext<'a> { | 69 | impl<'a> TyLoweringContext<'a> { |
65 | pub fn new(db: &'a dyn HirDatabase, resolver: &'a Resolver) -> Self { | 70 | pub fn new(db: &'a dyn HirDatabase, resolver: &'a Resolver) -> Self { |
66 | let impl_trait_counter = std::cell::Cell::new(0); | 71 | let impl_trait_counter = Cell::new(0); |
67 | let impl_trait_mode = ImplTraitLoweringMode::Disallowed; | 72 | let impl_trait_mode = ImplTraitLoweringMode::Disallowed; |
68 | let type_param_mode = TypeParamLoweringMode::Placeholder; | 73 | let type_param_mode = TypeParamLoweringMode::Placeholder; |
69 | let in_binders = DebruijnIndex::INNERMOST; | 74 | let in_binders = DebruijnIndex::INNERMOST; |
70 | let opaque_type_data = std::cell::RefCell::new(Vec::new()); | 75 | let opaque_type_data = RefCell::new(Vec::new()); |
71 | Self { | 76 | Self { |
72 | db, | 77 | db, |
73 | resolver, | 78 | resolver, |
@@ -76,6 +81,7 @@ impl<'a> TyLoweringContext<'a> { | |||
76 | impl_trait_counter, | 81 | impl_trait_counter, |
77 | type_param_mode, | 82 | type_param_mode, |
78 | opaque_type_data, | 83 | opaque_type_data, |
84 | expander: RefCell::new(None), | ||
79 | } | 85 | } |
80 | } | 86 | } |
81 | 87 | ||
@@ -85,15 +91,18 @@ impl<'a> TyLoweringContext<'a> { | |||
85 | f: impl FnOnce(&TyLoweringContext) -> T, | 91 | f: impl FnOnce(&TyLoweringContext) -> T, |
86 | ) -> T { | 92 | ) -> T { |
87 | let opaque_ty_data_vec = self.opaque_type_data.replace(Vec::new()); | 93 | let opaque_ty_data_vec = self.opaque_type_data.replace(Vec::new()); |
94 | let expander = self.expander.replace(None); | ||
88 | let new_ctx = Self { | 95 | let new_ctx = Self { |
89 | in_binders: debruijn, | 96 | in_binders: debruijn, |
90 | impl_trait_counter: std::cell::Cell::new(self.impl_trait_counter.get()), | 97 | impl_trait_counter: Cell::new(self.impl_trait_counter.get()), |
91 | opaque_type_data: std::cell::RefCell::new(opaque_ty_data_vec), | 98 | opaque_type_data: RefCell::new(opaque_ty_data_vec), |
99 | expander: RefCell::new(expander), | ||
92 | ..*self | 100 | ..*self |
93 | }; | 101 | }; |
94 | let result = f(&new_ctx); | 102 | let result = f(&new_ctx); |
95 | self.impl_trait_counter.set(new_ctx.impl_trait_counter.get()); | 103 | self.impl_trait_counter.set(new_ctx.impl_trait_counter.get()); |
96 | self.opaque_type_data.replace(new_ctx.opaque_type_data.into_inner()); | 104 | self.opaque_type_data.replace(new_ctx.opaque_type_data.into_inner()); |
105 | self.expander.replace(new_ctx.expander.into_inner()); | ||
97 | result | 106 | result |
98 | } | 107 | } |
99 | 108 | ||
@@ -286,6 +295,53 @@ impl<'a> TyLoweringContext<'a> { | |||
286 | } | 295 | } |
287 | } | 296 | } |
288 | } | 297 | } |
298 | TypeRef::Macro(macro_call) => { | ||
299 | let (expander, recursion_start) = { | ||
300 | let mut expander = self.expander.borrow_mut(); | ||
301 | if expander.is_some() { | ||
302 | (Some(expander), false) | ||
303 | } else { | ||
304 | if let Some(module_id) = self.resolver.module() { | ||
305 | *expander = Some(Expander::new( | ||
306 | self.db.upcast(), | ||
307 | macro_call.file_id, | ||
308 | module_id, | ||
309 | )); | ||
310 | (Some(expander), true) | ||
311 | } else { | ||
312 | (None, false) | ||
313 | } | ||
314 | } | ||
315 | }; | ||
316 | let ty = if let Some(mut expander) = expander { | ||
317 | let expander_mut = expander.as_mut().unwrap(); | ||
318 | let macro_call = macro_call.to_node(self.db.upcast()); | ||
319 | match expander_mut.enter_expand::<ast::Type>(self.db.upcast(), macro_call) { | ||
320 | Ok(ExpandResult { value: Some((mark, expanded)), .. }) => { | ||
321 | let ctx = | ||
322 | LowerCtx::new(self.db.upcast(), expander_mut.current_file_id()); | ||
323 | let type_ref = TypeRef::from_ast(&ctx, expanded); | ||
324 | |||
325 | drop(expander); | ||
326 | let ty = self.lower_ty(&type_ref); | ||
327 | |||
328 | self.expander | ||
329 | .borrow_mut() | ||
330 | .as_mut() | ||
331 | .unwrap() | ||
332 | .exit(self.db.upcast(), mark); | ||
333 | Some(ty) | ||
334 | } | ||
335 | _ => None, | ||
336 | } | ||
337 | } else { | ||
338 | None | ||
339 | }; | ||
340 | if recursion_start { | ||
341 | *self.expander.borrow_mut() = None; | ||
342 | } | ||
343 | ty.unwrap_or_else(|| TyKind::Error.intern(&Interner)) | ||
344 | } | ||
289 | TypeRef::Error => TyKind::Error.intern(&Interner), | 345 | TypeRef::Error => TyKind::Error.intern(&Interner), |
290 | }; | 346 | }; |
291 | (ty, res) | 347 | (ty, res) |
@@ -358,17 +414,16 @@ impl<'a> TyLoweringContext<'a> { | |||
358 | self.lower_trait_ref_from_resolved_path(trait_, resolved_segment, self_ty); | 414 | self.lower_trait_ref_from_resolved_path(trait_, resolved_segment, self_ty); |
359 | let ty = if remaining_segments.len() == 1 { | 415 | let ty = if remaining_segments.len() == 1 { |
360 | let segment = remaining_segments.first().unwrap(); | 416 | let segment = remaining_segments.first().unwrap(); |
361 | let found = associated_type_by_name_including_super_traits( | 417 | let found = self |
362 | self.db, | 418 | .db |
363 | trait_ref, | 419 | .trait_data(trait_ref.hir_trait_id()) |
364 | &segment.name, | 420 | .associated_type_by_name(&segment.name); |
365 | ); | ||
366 | match found { | 421 | match found { |
367 | Some((super_trait_ref, associated_ty)) => { | 422 | Some(associated_ty) => { |
368 | // FIXME handle type parameters on the segment | 423 | // FIXME handle type parameters on the segment |
369 | TyKind::Alias(AliasTy::Projection(ProjectionTy { | 424 | TyKind::Alias(AliasTy::Projection(ProjectionTy { |
370 | associated_ty_id: to_assoc_type_id(associated_ty), | 425 | associated_ty_id: to_assoc_type_id(associated_ty), |
371 | substitution: super_trait_ref.substitution, | 426 | substitution: trait_ref.substitution, |
372 | })) | 427 | })) |
373 | .intern(&Interner) | 428 | .intern(&Interner) |
374 | } | 429 | } |
@@ -1033,6 +1088,27 @@ pub(crate) fn generic_defaults_query( | |||
1033 | defaults | 1088 | defaults |
1034 | } | 1089 | } |
1035 | 1090 | ||
1091 | pub(crate) fn generic_defaults_recover( | ||
1092 | db: &dyn HirDatabase, | ||
1093 | _cycle: &[String], | ||
1094 | def: &GenericDefId, | ||
1095 | ) -> Arc<[Binders<Ty>]> { | ||
1096 | let generic_params = generics(db.upcast(), *def); | ||
1097 | |||
1098 | // we still need one default per parameter | ||
1099 | let defaults = generic_params | ||
1100 | .iter() | ||
1101 | .enumerate() | ||
1102 | .map(|(idx, _)| { | ||
1103 | let ty = TyKind::Error.intern(&Interner); | ||
1104 | |||
1105 | crate::make_only_type_binders(idx, ty) | ||
1106 | }) | ||
1107 | .collect(); | ||
1108 | |||
1109 | defaults | ||
1110 | } | ||
1111 | |||
1036 | fn fn_sig_for_fn(db: &dyn HirDatabase, def: FunctionId) -> PolyFnSig { | 1112 | fn fn_sig_for_fn(db: &dyn HirDatabase, def: FunctionId) -> PolyFnSig { |
1037 | let data = db.function_data(def); | 1113 | let data = db.function_data(def); |
1038 | let resolver = def.resolver(db.upcast()); | 1114 | let resolver = def.resolver(db.upcast()); |
diff --git a/crates/hir_ty/src/mapping.rs b/crates/hir_ty/src/mapping.rs new file mode 100644 index 000000000..5e86fafe5 --- /dev/null +++ b/crates/hir_ty/src/mapping.rs | |||
@@ -0,0 +1,154 @@ | |||
1 | //! This module contains the implementations of the `ToChalk` trait, which | ||
2 | //! handles conversion between our data types and their corresponding types in | ||
3 | //! Chalk (in both directions); plus some helper functions for more specialized | ||
4 | //! conversions. | ||
5 | |||
6 | use chalk_solve::rust_ir; | ||
7 | |||
8 | use base_db::salsa::{self, InternKey}; | ||
9 | use hir_def::{ConstParamId, LifetimeParamId, TraitId, TypeAliasId, TypeParamId}; | ||
10 | |||
11 | use crate::{ | ||
12 | chalk_db, db::HirDatabase, AssocTypeId, CallableDefId, ChalkTraitId, FnDefId, ForeignDefId, | ||
13 | Interner, OpaqueTyId, PlaceholderIndex, | ||
14 | }; | ||
15 | |||
16 | pub(crate) trait ToChalk { | ||
17 | type Chalk; | ||
18 | fn to_chalk(self, db: &dyn HirDatabase) -> Self::Chalk; | ||
19 | fn from_chalk(db: &dyn HirDatabase, chalk: Self::Chalk) -> Self; | ||
20 | } | ||
21 | |||
22 | pub(crate) fn from_chalk<T, ChalkT>(db: &dyn HirDatabase, chalk: ChalkT) -> T | ||
23 | where | ||
24 | T: ToChalk<Chalk = ChalkT>, | ||
25 | { | ||
26 | T::from_chalk(db, chalk) | ||
27 | } | ||
28 | |||
29 | impl ToChalk for hir_def::ImplId { | ||
30 | type Chalk = chalk_db::ImplId; | ||
31 | |||
32 | fn to_chalk(self, _db: &dyn HirDatabase) -> chalk_db::ImplId { | ||
33 | chalk_ir::ImplId(self.as_intern_id()) | ||
34 | } | ||
35 | |||
36 | fn from_chalk(_db: &dyn HirDatabase, impl_id: chalk_db::ImplId) -> hir_def::ImplId { | ||
37 | InternKey::from_intern_id(impl_id.0) | ||
38 | } | ||
39 | } | ||
40 | |||
41 | impl ToChalk for CallableDefId { | ||
42 | type Chalk = FnDefId; | ||
43 | |||
44 | fn to_chalk(self, db: &dyn HirDatabase) -> FnDefId { | ||
45 | db.intern_callable_def(self).into() | ||
46 | } | ||
47 | |||
48 | fn from_chalk(db: &dyn HirDatabase, fn_def_id: FnDefId) -> CallableDefId { | ||
49 | db.lookup_intern_callable_def(fn_def_id.into()) | ||
50 | } | ||
51 | } | ||
52 | |||
53 | pub(crate) struct TypeAliasAsValue(pub(crate) TypeAliasId); | ||
54 | |||
55 | impl ToChalk for TypeAliasAsValue { | ||
56 | type Chalk = chalk_db::AssociatedTyValueId; | ||
57 | |||
58 | fn to_chalk(self, _db: &dyn HirDatabase) -> chalk_db::AssociatedTyValueId { | ||
59 | rust_ir::AssociatedTyValueId(self.0.as_intern_id()) | ||
60 | } | ||
61 | |||
62 | fn from_chalk( | ||
63 | _db: &dyn HirDatabase, | ||
64 | assoc_ty_value_id: chalk_db::AssociatedTyValueId, | ||
65 | ) -> TypeAliasAsValue { | ||
66 | TypeAliasAsValue(TypeAliasId::from_intern_id(assoc_ty_value_id.0)) | ||
67 | } | ||
68 | } | ||
69 | |||
70 | impl From<FnDefId> for crate::db::InternedCallableDefId { | ||
71 | fn from(fn_def_id: FnDefId) -> Self { | ||
72 | InternKey::from_intern_id(fn_def_id.0) | ||
73 | } | ||
74 | } | ||
75 | |||
76 | impl From<crate::db::InternedCallableDefId> for FnDefId { | ||
77 | fn from(callable_def_id: crate::db::InternedCallableDefId) -> Self { | ||
78 | chalk_ir::FnDefId(callable_def_id.as_intern_id()) | ||
79 | } | ||
80 | } | ||
81 | |||
82 | impl From<OpaqueTyId> for crate::db::InternedOpaqueTyId { | ||
83 | fn from(id: OpaqueTyId) -> Self { | ||
84 | InternKey::from_intern_id(id.0) | ||
85 | } | ||
86 | } | ||
87 | |||
88 | impl From<crate::db::InternedOpaqueTyId> for OpaqueTyId { | ||
89 | fn from(id: crate::db::InternedOpaqueTyId) -> Self { | ||
90 | chalk_ir::OpaqueTyId(id.as_intern_id()) | ||
91 | } | ||
92 | } | ||
93 | |||
94 | impl From<chalk_ir::ClosureId<Interner>> for crate::db::InternedClosureId { | ||
95 | fn from(id: chalk_ir::ClosureId<Interner>) -> Self { | ||
96 | Self::from_intern_id(id.0) | ||
97 | } | ||
98 | } | ||
99 | |||
100 | impl From<crate::db::InternedClosureId> for chalk_ir::ClosureId<Interner> { | ||
101 | fn from(id: crate::db::InternedClosureId) -> Self { | ||
102 | chalk_ir::ClosureId(id.as_intern_id()) | ||
103 | } | ||
104 | } | ||
105 | |||
106 | pub fn to_foreign_def_id(id: TypeAliasId) -> ForeignDefId { | ||
107 | chalk_ir::ForeignDefId(salsa::InternKey::as_intern_id(&id)) | ||
108 | } | ||
109 | |||
110 | pub fn from_foreign_def_id(id: ForeignDefId) -> TypeAliasId { | ||
111 | salsa::InternKey::from_intern_id(id.0) | ||
112 | } | ||
113 | |||
114 | pub fn to_assoc_type_id(id: TypeAliasId) -> AssocTypeId { | ||
115 | chalk_ir::AssocTypeId(salsa::InternKey::as_intern_id(&id)) | ||
116 | } | ||
117 | |||
118 | pub fn from_assoc_type_id(id: AssocTypeId) -> TypeAliasId { | ||
119 | salsa::InternKey::from_intern_id(id.0) | ||
120 | } | ||
121 | |||
122 | pub fn from_placeholder_idx(db: &dyn HirDatabase, idx: PlaceholderIndex) -> TypeParamId { | ||
123 | assert_eq!(idx.ui, chalk_ir::UniverseIndex::ROOT); | ||
124 | let interned_id = salsa::InternKey::from_intern_id(salsa::InternId::from(idx.idx)); | ||
125 | db.lookup_intern_type_param_id(interned_id) | ||
126 | } | ||
127 | |||
128 | pub fn to_placeholder_idx(db: &dyn HirDatabase, id: TypeParamId) -> PlaceholderIndex { | ||
129 | let interned_id = db.intern_type_param_id(id); | ||
130 | PlaceholderIndex { | ||
131 | ui: chalk_ir::UniverseIndex::ROOT, | ||
132 | idx: salsa::InternKey::as_intern_id(&interned_id).as_usize(), | ||
133 | } | ||
134 | } | ||
135 | |||
136 | pub fn lt_from_placeholder_idx(db: &dyn HirDatabase, idx: PlaceholderIndex) -> LifetimeParamId { | ||
137 | assert_eq!(idx.ui, chalk_ir::UniverseIndex::ROOT); | ||
138 | let interned_id = salsa::InternKey::from_intern_id(salsa::InternId::from(idx.idx)); | ||
139 | db.lookup_intern_lifetime_param_id(interned_id) | ||
140 | } | ||
141 | |||
142 | pub fn const_from_placeholder_idx(db: &dyn HirDatabase, idx: PlaceholderIndex) -> ConstParamId { | ||
143 | assert_eq!(idx.ui, chalk_ir::UniverseIndex::ROOT); | ||
144 | let interned_id = salsa::InternKey::from_intern_id(salsa::InternId::from(idx.idx)); | ||
145 | db.lookup_intern_const_param_id(interned_id) | ||
146 | } | ||
147 | |||
148 | pub fn to_chalk_trait_id(id: TraitId) -> ChalkTraitId { | ||
149 | chalk_ir::TraitId(salsa::InternKey::as_intern_id(&id)) | ||
150 | } | ||
151 | |||
152 | pub fn from_chalk_trait_id(id: ChalkTraitId) -> TraitId { | ||
153 | salsa::InternKey::from_intern_id(id.0) | ||
154 | } | ||
diff --git a/crates/hir_ty/src/method_resolution.rs b/crates/hir_ty/src/method_resolution.rs index be3e4f09a..48bbcfd9f 100644 --- a/crates/hir_ty/src/method_resolution.rs +++ b/crates/hir_ty/src/method_resolution.rs | |||
@@ -21,32 +21,36 @@ use crate::{ | |||
21 | primitive::{self, FloatTy, IntTy, UintTy}, | 21 | primitive::{self, FloatTy, IntTy, UintTy}, |
22 | static_lifetime, | 22 | static_lifetime, |
23 | utils::all_super_traits, | 23 | utils::all_super_traits, |
24 | AdtId, Canonical, CanonicalVarKinds, DebruijnIndex, FnPointer, FnSig, ForeignDefId, | 24 | AdtId, Canonical, CanonicalVarKinds, DebruijnIndex, ForeignDefId, InEnvironment, Interner, |
25 | InEnvironment, Interner, Scalar, Substitution, TraitEnvironment, TraitRefExt, Ty, TyBuilder, | 25 | Scalar, Substitution, TraitEnvironment, TraitRefExt, Ty, TyBuilder, TyExt, TyKind, |
26 | TyExt, TyKind, | ||
27 | }; | 26 | }; |
28 | 27 | ||
29 | /// This is used as a key for indexing impls. | 28 | /// This is used as a key for indexing impls. |
30 | #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] | 29 | #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] |
31 | pub enum TyFingerprint { | 30 | pub enum TyFingerprint { |
31 | // These are lang item impls: | ||
32 | Str, | 32 | Str, |
33 | Slice, | 33 | Slice, |
34 | Array, | 34 | Array, |
35 | Never, | 35 | Never, |
36 | RawPtr(Mutability), | 36 | RawPtr(Mutability), |
37 | Scalar(Scalar), | 37 | Scalar(Scalar), |
38 | // These can have user-defined impls: | ||
38 | Adt(hir_def::AdtId), | 39 | Adt(hir_def::AdtId), |
39 | Dyn(TraitId), | 40 | Dyn(TraitId), |
40 | Tuple(usize), | ||
41 | ForeignType(ForeignDefId), | 41 | ForeignType(ForeignDefId), |
42 | FnPtr(usize, FnSig), | 42 | // These only exist for trait impls |
43 | Unit, | ||
44 | Unnameable, | ||
45 | Function(u32), | ||
43 | } | 46 | } |
44 | 47 | ||
45 | impl TyFingerprint { | 48 | impl TyFingerprint { |
46 | /// Creates a TyFingerprint for looking up an impl. Only certain types can | 49 | /// Creates a TyFingerprint for looking up an inherent impl. Only certain |
47 | /// have impls: if we have some `struct S`, we can have an `impl S`, but not | 50 | /// types can have inherent impls: if we have some `struct S`, we can have |
48 | /// `impl &S`. Hence, this will return `None` for reference types and such. | 51 | /// an `impl S`, but not `impl &S`. Hence, this will return `None` for |
49 | pub fn for_impl(ty: &Ty) -> Option<TyFingerprint> { | 52 | /// reference types and such. |
53 | pub fn for_inherent_impl(ty: &Ty) -> Option<TyFingerprint> { | ||
50 | let fp = match ty.kind(&Interner) { | 54 | let fp = match ty.kind(&Interner) { |
51 | TyKind::Str => TyFingerprint::Str, | 55 | TyKind::Str => TyFingerprint::Str, |
52 | TyKind::Never => TyFingerprint::Never, | 56 | TyKind::Never => TyFingerprint::Never, |
@@ -54,17 +58,52 @@ impl TyFingerprint { | |||
54 | TyKind::Array(..) => TyFingerprint::Array, | 58 | TyKind::Array(..) => TyFingerprint::Array, |
55 | TyKind::Scalar(scalar) => TyFingerprint::Scalar(*scalar), | 59 | TyKind::Scalar(scalar) => TyFingerprint::Scalar(*scalar), |
56 | TyKind::Adt(AdtId(adt), _) => TyFingerprint::Adt(*adt), | 60 | TyKind::Adt(AdtId(adt), _) => TyFingerprint::Adt(*adt), |
57 | TyKind::Tuple(cardinality, _) => TyFingerprint::Tuple(*cardinality), | ||
58 | TyKind::Raw(mutability, ..) => TyFingerprint::RawPtr(*mutability), | 61 | TyKind::Raw(mutability, ..) => TyFingerprint::RawPtr(*mutability), |
59 | TyKind::Foreign(alias_id, ..) => TyFingerprint::ForeignType(*alias_id), | 62 | TyKind::Foreign(alias_id, ..) => TyFingerprint::ForeignType(*alias_id), |
60 | TyKind::Function(FnPointer { sig, substitution: substs, .. }) => { | ||
61 | TyFingerprint::FnPtr(substs.0.len(&Interner) - 1, *sig) | ||
62 | } | ||
63 | TyKind::Dyn(_) => ty.dyn_trait().map(|trait_| TyFingerprint::Dyn(trait_))?, | 63 | TyKind::Dyn(_) => ty.dyn_trait().map(|trait_| TyFingerprint::Dyn(trait_))?, |
64 | _ => return None, | 64 | _ => return None, |
65 | }; | 65 | }; |
66 | Some(fp) | 66 | Some(fp) |
67 | } | 67 | } |
68 | |||
69 | /// Creates a TyFingerprint for looking up a trait impl. | ||
70 | pub fn for_trait_impl(ty: &Ty) -> Option<TyFingerprint> { | ||
71 | let fp = match ty.kind(&Interner) { | ||
72 | TyKind::Str => TyFingerprint::Str, | ||
73 | TyKind::Never => TyFingerprint::Never, | ||
74 | TyKind::Slice(..) => TyFingerprint::Slice, | ||
75 | TyKind::Array(..) => TyFingerprint::Array, | ||
76 | TyKind::Scalar(scalar) => TyFingerprint::Scalar(*scalar), | ||
77 | TyKind::Adt(AdtId(adt), _) => TyFingerprint::Adt(*adt), | ||
78 | TyKind::Raw(mutability, ..) => TyFingerprint::RawPtr(*mutability), | ||
79 | TyKind::Foreign(alias_id, ..) => TyFingerprint::ForeignType(*alias_id), | ||
80 | TyKind::Dyn(_) => ty.dyn_trait().map(|trait_| TyFingerprint::Dyn(trait_))?, | ||
81 | TyKind::Ref(_, _, ty) => return TyFingerprint::for_trait_impl(ty), | ||
82 | TyKind::Tuple(_, subst) => { | ||
83 | let first_ty = subst.interned().get(0).map(|arg| arg.assert_ty_ref(&Interner)); | ||
84 | if let Some(ty) = first_ty { | ||
85 | return TyFingerprint::for_trait_impl(ty); | ||
86 | } else { | ||
87 | TyFingerprint::Unit | ||
88 | } | ||
89 | } | ||
90 | TyKind::AssociatedType(_, _) | ||
91 | | TyKind::OpaqueType(_, _) | ||
92 | | TyKind::FnDef(_, _) | ||
93 | | TyKind::Closure(_, _) | ||
94 | | TyKind::Generator(..) | ||
95 | | TyKind::GeneratorWitness(..) => TyFingerprint::Unnameable, | ||
96 | TyKind::Function(fn_ptr) => { | ||
97 | TyFingerprint::Function(fn_ptr.substitution.0.len(&Interner) as u32) | ||
98 | } | ||
99 | TyKind::Alias(_) | ||
100 | | TyKind::Placeholder(_) | ||
101 | | TyKind::BoundVar(_) | ||
102 | | TyKind::InferenceVar(_, _) | ||
103 | | TyKind::Error => return None, | ||
104 | }; | ||
105 | Some(fp) | ||
106 | } | ||
68 | } | 107 | } |
69 | 108 | ||
70 | pub(crate) const ALL_INT_FPS: [TyFingerprint; 12] = [ | 109 | pub(crate) const ALL_INT_FPS: [TyFingerprint; 12] = [ |
@@ -112,7 +151,7 @@ impl TraitImpls { | |||
112 | None => continue, | 151 | None => continue, |
113 | }; | 152 | }; |
114 | let self_ty = db.impl_self_ty(impl_id); | 153 | let self_ty = db.impl_self_ty(impl_id); |
115 | let self_ty_fp = TyFingerprint::for_impl(self_ty.skip_binders()); | 154 | let self_ty_fp = TyFingerprint::for_trait_impl(self_ty.skip_binders()); |
116 | impls | 155 | impls |
117 | .map | 156 | .map |
118 | .entry(target_trait) | 157 | .entry(target_trait) |
@@ -157,10 +196,13 @@ impl TraitImpls { | |||
157 | } | 196 | } |
158 | 197 | ||
159 | /// Queries all trait impls for the given type. | 198 | /// Queries all trait impls for the given type. |
160 | pub fn for_self_ty(&self, fp: TyFingerprint) -> impl Iterator<Item = ImplId> + '_ { | 199 | pub fn for_self_ty_without_blanket_impls( |
200 | &self, | ||
201 | fp: TyFingerprint, | ||
202 | ) -> impl Iterator<Item = ImplId> + '_ { | ||
161 | self.map | 203 | self.map |
162 | .values() | 204 | .values() |
163 | .flat_map(move |impls| impls.get(&None).into_iter().chain(impls.get(&Some(fp)))) | 205 | .flat_map(move |impls| impls.get(&Some(fp)).into_iter()) |
164 | .flat_map(|it| it.iter().copied()) | 206 | .flat_map(|it| it.iter().copied()) |
165 | } | 207 | } |
166 | 208 | ||
@@ -204,31 +246,43 @@ pub struct InherentImpls { | |||
204 | 246 | ||
205 | impl InherentImpls { | 247 | impl InherentImpls { |
206 | pub(crate) fn inherent_impls_in_crate_query(db: &dyn HirDatabase, krate: CrateId) -> Arc<Self> { | 248 | pub(crate) fn inherent_impls_in_crate_query(db: &dyn HirDatabase, krate: CrateId) -> Arc<Self> { |
207 | let mut map: FxHashMap<_, Vec<_>> = FxHashMap::default(); | 249 | let mut impls = Self { map: FxHashMap::default() }; |
208 | 250 | ||
209 | let crate_def_map = db.crate_def_map(krate); | 251 | let crate_def_map = db.crate_def_map(krate); |
210 | for (_module_id, module_data) in crate_def_map.modules() { | 252 | collect_def_map(db, &crate_def_map, &mut impls); |
211 | for impl_id in module_data.scope.impls() { | 253 | |
212 | let data = db.impl_data(impl_id); | 254 | return Arc::new(impls); |
213 | if data.target_trait.is_some() { | 255 | |
214 | continue; | 256 | fn collect_def_map(db: &dyn HirDatabase, def_map: &DefMap, impls: &mut InherentImpls) { |
257 | for (_module_id, module_data) in def_map.modules() { | ||
258 | for impl_id in module_data.scope.impls() { | ||
259 | let data = db.impl_data(impl_id); | ||
260 | if data.target_trait.is_some() { | ||
261 | continue; | ||
262 | } | ||
263 | |||
264 | let self_ty = db.impl_self_ty(impl_id); | ||
265 | let fp = TyFingerprint::for_inherent_impl(self_ty.skip_binders()); | ||
266 | if let Some(fp) = fp { | ||
267 | impls.map.entry(fp).or_default().push(impl_id); | ||
268 | } | ||
269 | // `fp` should only be `None` in error cases (either erroneous code or incomplete name resolution) | ||
215 | } | 270 | } |
216 | 271 | ||
217 | let self_ty = db.impl_self_ty(impl_id); | 272 | // To better support custom derives, collect impls in all unnamed const items. |
218 | if let Some(fp) = TyFingerprint::for_impl(self_ty.skip_binders()) { | 273 | // const _: () = { ... }; |
219 | map.entry(fp).or_default().push(impl_id); | 274 | for konst in module_data.scope.unnamed_consts() { |
275 | let body = db.body(konst.into()); | ||
276 | for (_, block_def_map) in body.blocks(db.upcast()) { | ||
277 | collect_def_map(db, &block_def_map, impls); | ||
278 | } | ||
220 | } | 279 | } |
221 | } | 280 | } |
222 | } | 281 | } |
223 | |||
224 | // NOTE: We're not collecting inherent impls from unnamed consts here, we intentionally only | ||
225 | // support trait impls there. | ||
226 | |||
227 | Arc::new(Self { map }) | ||
228 | } | 282 | } |
229 | 283 | ||
230 | pub fn for_self_ty(&self, self_ty: &Ty) -> &[ImplId] { | 284 | pub fn for_self_ty(&self, self_ty: &Ty) -> &[ImplId] { |
231 | match TyFingerprint::for_impl(self_ty) { | 285 | match TyFingerprint::for_inherent_impl(self_ty) { |
232 | Some(fp) => self.map.get(&fp).map(|vec| vec.as_ref()).unwrap_or(&[]), | 286 | Some(fp) => self.map.get(&fp).map(|vec| vec.as_ref()).unwrap_or(&[]), |
233 | None => &[], | 287 | None => &[], |
234 | } | 288 | } |
@@ -609,6 +663,7 @@ fn iterate_trait_method_candidates( | |||
609 | } | 663 | } |
610 | } | 664 | } |
611 | known_implemented = true; | 665 | known_implemented = true; |
666 | // FIXME: we shouldn't be ignoring the binders here | ||
612 | if callback(&self_ty.value, *item) { | 667 | if callback(&self_ty.value, *item) { |
613 | return true; | 668 | return true; |
614 | } | 669 | } |
diff --git a/crates/hir_ty/src/op.rs b/crates/hir_ty/src/op.rs index 0491c5cb4..0222de2bc 100644 --- a/crates/hir_ty/src/op.rs +++ b/crates/hir_ty/src/op.rs | |||
@@ -9,21 +9,55 @@ pub(super) fn binary_op_return_ty(op: BinaryOp, lhs_ty: Ty, rhs_ty: Ty) -> Ty { | |||
9 | BinaryOp::LogicOp(_) | BinaryOp::CmpOp(_) => TyKind::Scalar(Scalar::Bool).intern(&Interner), | 9 | BinaryOp::LogicOp(_) | BinaryOp::CmpOp(_) => TyKind::Scalar(Scalar::Bool).intern(&Interner), |
10 | BinaryOp::Assignment { .. } => TyBuilder::unit(), | 10 | BinaryOp::Assignment { .. } => TyBuilder::unit(), |
11 | BinaryOp::ArithOp(ArithOp::Shl) | BinaryOp::ArithOp(ArithOp::Shr) => { | 11 | BinaryOp::ArithOp(ArithOp::Shl) | BinaryOp::ArithOp(ArithOp::Shr) => { |
12 | match lhs_ty.kind(&Interner) { | 12 | // all integer combinations are valid here |
13 | if matches!( | ||
14 | lhs_ty.kind(&Interner), | ||
13 | TyKind::Scalar(Scalar::Int(_)) | 15 | TyKind::Scalar(Scalar::Int(_)) |
14 | | TyKind::Scalar(Scalar::Uint(_)) | 16 | | TyKind::Scalar(Scalar::Uint(_)) |
15 | | TyKind::Scalar(Scalar::Float(_)) => lhs_ty, | 17 | | TyKind::InferenceVar(_, TyVariableKind::Integer) |
16 | TyKind::InferenceVar(_, TyVariableKind::Integer) | 18 | ) && matches!( |
17 | | TyKind::InferenceVar(_, TyVariableKind::Float) => lhs_ty, | 19 | rhs_ty.kind(&Interner), |
18 | _ => TyKind::Error.intern(&Interner), | 20 | TyKind::Scalar(Scalar::Int(_)) |
21 | | TyKind::Scalar(Scalar::Uint(_)) | ||
22 | | TyKind::InferenceVar(_, TyVariableKind::Integer) | ||
23 | ) { | ||
24 | lhs_ty | ||
25 | } else { | ||
26 | TyKind::Error.intern(&Interner) | ||
19 | } | 27 | } |
20 | } | 28 | } |
21 | BinaryOp::ArithOp(_) => match rhs_ty.kind(&Interner) { | 29 | BinaryOp::ArithOp(_) => match (lhs_ty.kind(&Interner), rhs_ty.kind(&Interner)) { |
22 | TyKind::Scalar(Scalar::Int(_)) | 30 | // (int, int) | (uint, uint) | (float, float) |
23 | | TyKind::Scalar(Scalar::Uint(_)) | 31 | (TyKind::Scalar(Scalar::Int(_)), TyKind::Scalar(Scalar::Int(_))) |
24 | | TyKind::Scalar(Scalar::Float(_)) => rhs_ty, | 32 | | (TyKind::Scalar(Scalar::Uint(_)), TyKind::Scalar(Scalar::Uint(_))) |
25 | TyKind::InferenceVar(_, TyVariableKind::Integer) | 33 | | (TyKind::Scalar(Scalar::Float(_)), TyKind::Scalar(Scalar::Float(_))) => rhs_ty, |
26 | | TyKind::InferenceVar(_, TyVariableKind::Float) => rhs_ty, | 34 | // ({int}, int) | ({int}, uint) |
35 | (TyKind::InferenceVar(_, TyVariableKind::Integer), TyKind::Scalar(Scalar::Int(_))) | ||
36 | | (TyKind::InferenceVar(_, TyVariableKind::Integer), TyKind::Scalar(Scalar::Uint(_))) => { | ||
37 | rhs_ty | ||
38 | } | ||
39 | // (int, {int}) | (uint, {int}) | ||
40 | (TyKind::Scalar(Scalar::Int(_)), TyKind::InferenceVar(_, TyVariableKind::Integer)) | ||
41 | | (TyKind::Scalar(Scalar::Uint(_)), TyKind::InferenceVar(_, TyVariableKind::Integer)) => { | ||
42 | lhs_ty | ||
43 | } | ||
44 | // ({float} | float) | ||
45 | (TyKind::InferenceVar(_, TyVariableKind::Float), TyKind::Scalar(Scalar::Float(_))) => { | ||
46 | rhs_ty | ||
47 | } | ||
48 | // (float, {float}) | ||
49 | (TyKind::Scalar(Scalar::Float(_)), TyKind::InferenceVar(_, TyVariableKind::Float)) => { | ||
50 | lhs_ty | ||
51 | } | ||
52 | // ({int}, {int}) | ({float}, {float}) | ||
53 | ( | ||
54 | TyKind::InferenceVar(_, TyVariableKind::Integer), | ||
55 | TyKind::InferenceVar(_, TyVariableKind::Integer), | ||
56 | ) | ||
57 | | ( | ||
58 | TyKind::InferenceVar(_, TyVariableKind::Float), | ||
59 | TyKind::InferenceVar(_, TyVariableKind::Float), | ||
60 | ) => rhs_ty, | ||
27 | _ => TyKind::Error.intern(&Interner), | 61 | _ => TyKind::Error.intern(&Interner), |
28 | }, | 62 | }, |
29 | } | 63 | } |
diff --git a/crates/hir_ty/src/primitive.rs b/crates/hir_ty/src/primitive.rs index 2449addfb..d7f48c69a 100644 --- a/crates/hir_ty/src/primitive.rs +++ b/crates/hir_ty/src/primitive.rs | |||
@@ -1,7 +1,4 @@ | |||
1 | //! Defines primitive types, which have a couple of peculiarities: | 1 | //! A few helper functions for dealing with primitives. |
2 | //! | ||
3 | //! * during type inference, they can be uncertain (ie, `let x = 92;`) | ||
4 | //! * they don't belong to any particular crate. | ||
5 | 2 | ||
6 | pub use chalk_ir::{FloatTy, IntTy, UintTy}; | 3 | pub use chalk_ir::{FloatTy, IntTy, UintTy}; |
7 | pub use hir_def::builtin_type::{BuiltinFloat, BuiltinInt, BuiltinUint}; | 4 | pub use hir_def::builtin_type::{BuiltinFloat, BuiltinInt, BuiltinUint}; |
diff --git a/crates/hir_ty/src/tests/macros.rs b/crates/hir_ty/src/tests/macros.rs index 86e3d8b86..6588aa46c 100644 --- a/crates/hir_ty/src/tests/macros.rs +++ b/crates/hir_ty/src/tests/macros.rs | |||
@@ -1065,12 +1065,211 @@ fn macro_in_arm() { | |||
1065 | } | 1065 | } |
1066 | "#, | 1066 | "#, |
1067 | expect![[r#" | 1067 | expect![[r#" |
1068 | !0..2 '()': () | ||
1068 | 51..110 '{ ... }; }': () | 1069 | 51..110 '{ ... }; }': () |
1069 | 61..62 'x': u32 | 1070 | 61..62 'x': u32 |
1070 | 65..107 'match ... }': u32 | 1071 | 65..107 'match ... }': u32 |
1071 | 71..73 '()': () | 1072 | 71..73 '()': () |
1072 | 84..91 'unit!()': () | ||
1073 | 95..100 '92u32': u32 | 1073 | 95..100 '92u32': u32 |
1074 | "#]], | 1074 | "#]], |
1075 | ); | 1075 | ); |
1076 | } | 1076 | } |
1077 | |||
1078 | #[test] | ||
1079 | fn macro_in_type_alias_position() { | ||
1080 | check_infer( | ||
1081 | r#" | ||
1082 | macro_rules! U32 { | ||
1083 | () => { u32 }; | ||
1084 | } | ||
1085 | |||
1086 | trait Foo { | ||
1087 | type Ty; | ||
1088 | } | ||
1089 | |||
1090 | impl<T> Foo for T { | ||
1091 | type Ty = U32!(); | ||
1092 | } | ||
1093 | |||
1094 | type TayTo = U32!(); | ||
1095 | |||
1096 | fn testy() { | ||
1097 | let a: <() as Foo>::Ty; | ||
1098 | let b: TayTo; | ||
1099 | } | ||
1100 | "#, | ||
1101 | expect![[r#" | ||
1102 | 147..196 '{ ...yTo; }': () | ||
1103 | 157..158 'a': u32 | ||
1104 | 185..186 'b': u32 | ||
1105 | "#]], | ||
1106 | ); | ||
1107 | } | ||
1108 | |||
1109 | #[test] | ||
1110 | fn nested_macro_in_type_alias_position() { | ||
1111 | check_infer( | ||
1112 | r#" | ||
1113 | macro_rules! U32Inner2 { | ||
1114 | () => { u32 }; | ||
1115 | } | ||
1116 | |||
1117 | macro_rules! U32Inner1 { | ||
1118 | () => { U32Inner2!() }; | ||
1119 | } | ||
1120 | |||
1121 | macro_rules! U32 { | ||
1122 | () => { U32Inner1!() }; | ||
1123 | } | ||
1124 | |||
1125 | trait Foo { | ||
1126 | type Ty; | ||
1127 | } | ||
1128 | |||
1129 | impl<T> Foo for T { | ||
1130 | type Ty = U32!(); | ||
1131 | } | ||
1132 | |||
1133 | type TayTo = U32!(); | ||
1134 | |||
1135 | fn testy() { | ||
1136 | let a: <() as Foo>::Ty; | ||
1137 | let b: TayTo; | ||
1138 | } | ||
1139 | "#, | ||
1140 | expect![[r#" | ||
1141 | 259..308 '{ ...yTo; }': () | ||
1142 | 269..270 'a': u32 | ||
1143 | 297..298 'b': u32 | ||
1144 | "#]], | ||
1145 | ); | ||
1146 | } | ||
1147 | |||
1148 | #[test] | ||
1149 | fn macros_in_type_alias_position_generics() { | ||
1150 | check_infer( | ||
1151 | r#" | ||
1152 | struct Foo<A, B>(A, B); | ||
1153 | |||
1154 | macro_rules! U32 { | ||
1155 | () => { u32 }; | ||
1156 | } | ||
1157 | |||
1158 | macro_rules! Bar { | ||
1159 | () => { Foo<U32!(), U32!()> }; | ||
1160 | } | ||
1161 | |||
1162 | trait Moo { | ||
1163 | type Ty; | ||
1164 | } | ||
1165 | |||
1166 | impl<T> Moo for T { | ||
1167 | type Ty = Bar!(); | ||
1168 | } | ||
1169 | |||
1170 | type TayTo = Bar!(); | ||
1171 | |||
1172 | fn main() { | ||
1173 | let a: <() as Moo>::Ty; | ||
1174 | let b: TayTo; | ||
1175 | } | ||
1176 | "#, | ||
1177 | expect![[r#" | ||
1178 | 228..277 '{ ...yTo; }': () | ||
1179 | 238..239 'a': Foo<u32, u32> | ||
1180 | 266..267 'b': Foo<u32, u32> | ||
1181 | "#]], | ||
1182 | ); | ||
1183 | } | ||
1184 | |||
1185 | #[test] | ||
1186 | fn macros_in_type_position() { | ||
1187 | check_infer( | ||
1188 | r#" | ||
1189 | struct Foo<A, B>(A, B); | ||
1190 | |||
1191 | macro_rules! U32 { | ||
1192 | () => { u32 }; | ||
1193 | } | ||
1194 | |||
1195 | macro_rules! Bar { | ||
1196 | () => { Foo<U32!(), U32!()> }; | ||
1197 | } | ||
1198 | |||
1199 | fn main() { | ||
1200 | let a: Bar!(); | ||
1201 | } | ||
1202 | "#, | ||
1203 | expect![[r#" | ||
1204 | 133..155 '{ ...!(); }': () | ||
1205 | 143..144 'a': Foo<u32, u32> | ||
1206 | "#]], | ||
1207 | ); | ||
1208 | } | ||
1209 | |||
1210 | #[test] | ||
1211 | fn macros_in_type_generics() { | ||
1212 | check_infer( | ||
1213 | r#" | ||
1214 | struct Foo<A, B>(A, B); | ||
1215 | |||
1216 | macro_rules! U32 { | ||
1217 | () => { u32 }; | ||
1218 | } | ||
1219 | |||
1220 | macro_rules! Bar { | ||
1221 | () => { Foo<U32!(), U32!()> }; | ||
1222 | } | ||
1223 | |||
1224 | trait Moo { | ||
1225 | type Ty; | ||
1226 | } | ||
1227 | |||
1228 | impl<T> Moo for T { | ||
1229 | type Ty = Foo<Bar!(), Bar!()>; | ||
1230 | } | ||
1231 | |||
1232 | type TayTo = Foo<Bar!(), U32!()>; | ||
1233 | |||
1234 | fn main() { | ||
1235 | let a: <() as Moo>::Ty; | ||
1236 | let b: TayTo; | ||
1237 | } | ||
1238 | "#, | ||
1239 | expect![[r#" | ||
1240 | 254..303 '{ ...yTo; }': () | ||
1241 | 264..265 'a': Foo<Foo<u32, u32>, Foo<u32, u32>> | ||
1242 | 292..293 'b': Foo<Foo<u32, u32>, u32> | ||
1243 | "#]], | ||
1244 | ); | ||
1245 | } | ||
1246 | |||
1247 | #[test] | ||
1248 | fn infinitely_recursive_macro_type() { | ||
1249 | check_infer( | ||
1250 | r#" | ||
1251 | struct Bar<T, X>(T, X); | ||
1252 | |||
1253 | macro_rules! Foo { | ||
1254 | () => { Foo!() } | ||
1255 | } | ||
1256 | |||
1257 | macro_rules! U32 { | ||
1258 | () => { u32 } | ||
1259 | } | ||
1260 | |||
1261 | type A = Foo!(); | ||
1262 | type B = Bar<Foo!(), U32!()>; | ||
1263 | |||
1264 | fn main() { | ||
1265 | let a: A; | ||
1266 | let b: B; | ||
1267 | } | ||
1268 | "#, | ||
1269 | expect![[r#" | ||
1270 | 166..197 '{ ...: B; }': () | ||
1271 | 176..177 'a': {unknown} | ||
1272 | 190..191 'b': Bar<{unknown}, u32> | ||
1273 | "#]], | ||
1274 | ); | ||
1275 | } | ||
diff --git a/crates/hir_ty/src/tests/method_resolution.rs b/crates/hir_ty/src/tests/method_resolution.rs index 4b2c82b41..a4c132bc5 100644 --- a/crates/hir_ty/src/tests/method_resolution.rs +++ b/crates/hir_ty/src/tests/method_resolution.rs | |||
@@ -1294,7 +1294,7 @@ mod b { | |||
1294 | } | 1294 | } |
1295 | 1295 | ||
1296 | #[test] | 1296 | #[test] |
1297 | fn impl_in_unnamed_const() { | 1297 | fn trait_impl_in_unnamed_const() { |
1298 | check_types( | 1298 | check_types( |
1299 | r#" | 1299 | r#" |
1300 | struct S; | 1300 | struct S; |
@@ -1314,3 +1314,38 @@ fn f() { | |||
1314 | "#, | 1314 | "#, |
1315 | ); | 1315 | ); |
1316 | } | 1316 | } |
1317 | |||
1318 | #[test] | ||
1319 | fn inherent_impl_in_unnamed_const() { | ||
1320 | check_types( | ||
1321 | r#" | ||
1322 | struct S; | ||
1323 | |||
1324 | const _: () = { | ||
1325 | impl S { | ||
1326 | fn method(&self) -> u16 { 0 } | ||
1327 | |||
1328 | pub(super) fn super_method(&self) -> u16 { 0 } | ||
1329 | |||
1330 | pub(crate) fn crate_method(&self) -> u16 { 0 } | ||
1331 | |||
1332 | pub fn pub_method(&self) -> u16 { 0 } | ||
1333 | } | ||
1334 | }; | ||
1335 | |||
1336 | fn f() { | ||
1337 | S.method(); | ||
1338 | //^^^^^^^^^^ u16 | ||
1339 | |||
1340 | S.super_method(); | ||
1341 | //^^^^^^^^^^^^^^^^ u16 | ||
1342 | |||
1343 | S.crate_method(); | ||
1344 | //^^^^^^^^^^^^^^^^ u16 | ||
1345 | |||
1346 | S.pub_method(); | ||
1347 | //^^^^^^^^^^^^^^ u16 | ||
1348 | } | ||
1349 | "#, | ||
1350 | ); | ||
1351 | } | ||
diff --git a/crates/hir_ty/src/tests/patterns.rs b/crates/hir_ty/src/tests/patterns.rs index 85a28e76b..f514b3efe 100644 --- a/crates/hir_ty/src/tests/patterns.rs +++ b/crates/hir_ty/src/tests/patterns.rs | |||
@@ -1,6 +1,6 @@ | |||
1 | use expect_test::expect; | 1 | use expect_test::expect; |
2 | 2 | ||
3 | use super::{check_infer, check_infer_with_mismatches}; | 3 | use super::{check_infer, check_infer_with_mismatches, check_types}; |
4 | 4 | ||
5 | #[test] | 5 | #[test] |
6 | fn infer_pattern() { | 6 | fn infer_pattern() { |
@@ -825,3 +825,29 @@ fn foo(foo: Foo) { | |||
825 | "#]], | 825 | "#]], |
826 | ); | 826 | ); |
827 | } | 827 | } |
828 | |||
829 | #[test] | ||
830 | fn macro_pat() { | ||
831 | check_types( | ||
832 | r#" | ||
833 | macro_rules! pat { | ||
834 | ($name:ident) => { Enum::Variant1($name) } | ||
835 | } | ||
836 | |||
837 | enum Enum { | ||
838 | Variant1(u8), | ||
839 | Variant2, | ||
840 | } | ||
841 | |||
842 | fn f(e: Enum) { | ||
843 | match e { | ||
844 | pat!(bind) => { | ||
845 | bind; | ||
846 | //^^^^ u8 | ||
847 | } | ||
848 | Enum::Variant2 => {} | ||
849 | } | ||
850 | } | ||
851 | "#, | ||
852 | ) | ||
853 | } | ||
diff --git a/crates/hir_ty/src/tests/regression.rs b/crates/hir_ty/src/tests/regression.rs index b69f86050..d14f5c9bb 100644 --- a/crates/hir_ty/src/tests/regression.rs +++ b/crates/hir_ty/src/tests/regression.rs | |||
@@ -974,3 +974,79 @@ fn param_overrides_fn() { | |||
974 | "#, | 974 | "#, |
975 | ) | 975 | ) |
976 | } | 976 | } |
977 | |||
978 | #[test] | ||
979 | fn lifetime_from_chalk_during_deref() { | ||
980 | check_types( | ||
981 | r#" | ||
982 | #[lang = "deref"] | ||
983 | pub trait Deref { | ||
984 | type Target; | ||
985 | } | ||
986 | |||
987 | struct Box<T: ?Sized> {} | ||
988 | impl<T> Deref for Box<T> { | ||
989 | type Target = T; | ||
990 | |||
991 | fn deref(&self) -> &Self::Target { | ||
992 | loop {} | ||
993 | } | ||
994 | } | ||
995 | |||
996 | trait Iterator { | ||
997 | type Item; | ||
998 | } | ||
999 | |||
1000 | pub struct Iter<'a, T: 'a> { | ||
1001 | inner: Box<dyn IterTrait<'a, T, Item = &'a T> + 'a>, | ||
1002 | } | ||
1003 | |||
1004 | trait IterTrait<'a, T: 'a>: Iterator<Item = &'a T> { | ||
1005 | fn clone_box(&self); | ||
1006 | } | ||
1007 | |||
1008 | fn clone_iter<T>(s: Iter<T>) { | ||
1009 | s.inner.clone_box(); | ||
1010 | //^^^^^^^^^^^^^^^^^^^ () | ||
1011 | } | ||
1012 | "#, | ||
1013 | ) | ||
1014 | } | ||
1015 | |||
1016 | #[test] | ||
1017 | fn issue_8686() { | ||
1018 | check_infer( | ||
1019 | r#" | ||
1020 | pub trait Try: FromResidual { | ||
1021 | type Output; | ||
1022 | type Residual; | ||
1023 | } | ||
1024 | pub trait FromResidual<R = <Self as Try>::Residual> { | ||
1025 | fn from_residual(residual: R) -> Self; | ||
1026 | } | ||
1027 | |||
1028 | struct ControlFlow<B, C>; | ||
1029 | impl<B, C> Try for ControlFlow<B, C> { | ||
1030 | type Output = C; | ||
1031 | type Residual = ControlFlow<B, !>; | ||
1032 | } | ||
1033 | impl<B, C> FromResidual for ControlFlow<B, C> { | ||
1034 | fn from_residual(r: ControlFlow<B, !>) -> Self { ControlFlow } | ||
1035 | } | ||
1036 | |||
1037 | fn test() { | ||
1038 | ControlFlow::from_residual(ControlFlow::<u32, !>); | ||
1039 | } | ||
1040 | "#, | ||
1041 | expect![[r#" | ||
1042 | 144..152 'residual': R | ||
1043 | 365..366 'r': ControlFlow<B, !> | ||
1044 | 395..410 '{ ControlFlow }': ControlFlow<B, C> | ||
1045 | 397..408 'ControlFlow': ControlFlow<B, C> | ||
1046 | 424..482 '{ ...!>); }': () | ||
1047 | 430..456 'Contro...sidual': fn from_residual<ControlFlow<u32, {unknown}>, ControlFlow<u32, !>>(ControlFlow<u32, !>) -> ControlFlow<u32, {unknown}> | ||
1048 | 430..479 'Contro...2, !>)': ControlFlow<u32, {unknown}> | ||
1049 | 457..478 'Contro...32, !>': ControlFlow<u32, !> | ||
1050 | "#]], | ||
1051 | ); | ||
1052 | } | ||
diff --git a/crates/hir_ty/src/tests/simple.rs b/crates/hir_ty/src/tests/simple.rs index 84c5c05fd..0eefd70f2 100644 --- a/crates/hir_ty/src/tests/simple.rs +++ b/crates/hir_ty/src/tests/simple.rs | |||
@@ -1029,6 +1029,42 @@ fn infer_in_elseif() { | |||
1029 | } | 1029 | } |
1030 | 1030 | ||
1031 | #[test] | 1031 | #[test] |
1032 | fn infer_closure_unify() { | ||
1033 | check_infer( | ||
1034 | r#" | ||
1035 | fn foo(f: bool) { | ||
1036 | let a = |x| x; | ||
1037 | let b = |x| x; | ||
1038 | let id = if f { a } else { b }; | ||
1039 | id(123); | ||
1040 | } | ||
1041 | "#, | ||
1042 | expect![[r#" | ||
1043 | 7..8 'f': bool | ||
1044 | 16..106 '{ ...23); }': () | ||
1045 | 26..27 'a': |i32| -> i32 | ||
1046 | 30..35 '|x| x': |i32| -> i32 | ||
1047 | 31..32 'x': i32 | ||
1048 | 34..35 'x': i32 | ||
1049 | 45..46 'b': |i32| -> i32 | ||
1050 | 49..54 '|x| x': |i32| -> i32 | ||
1051 | 50..51 'x': i32 | ||
1052 | 53..54 'x': i32 | ||
1053 | 64..66 'id': |i32| -> i32 | ||
1054 | 69..90 'if f {... { b }': |i32| -> i32 | ||
1055 | 72..73 'f': bool | ||
1056 | 74..79 '{ a }': |i32| -> i32 | ||
1057 | 76..77 'a': |i32| -> i32 | ||
1058 | 85..90 '{ b }': |i32| -> i32 | ||
1059 | 87..88 'b': |i32| -> i32 | ||
1060 | 96..98 'id': |i32| -> i32 | ||
1061 | 96..103 'id(123)': i32 | ||
1062 | 99..102 '123': i32 | ||
1063 | "#]], | ||
1064 | ) | ||
1065 | } | ||
1066 | |||
1067 | #[test] | ||
1032 | fn infer_if_match_with_return() { | 1068 | fn infer_if_match_with_return() { |
1033 | check_infer( | 1069 | check_infer( |
1034 | r#" | 1070 | r#" |
@@ -1765,6 +1801,24 @@ fn main() { | |||
1765 | } | 1801 | } |
1766 | 1802 | ||
1767 | #[test] | 1803 | #[test] |
1804 | fn shadowing_primitive_with_inner_items() { | ||
1805 | check_types( | ||
1806 | r#" | ||
1807 | struct i32; | ||
1808 | struct Foo; | ||
1809 | |||
1810 | impl i32 { fn foo(&self) -> Foo { Foo } } | ||
1811 | |||
1812 | fn main() { | ||
1813 | fn inner() {} | ||
1814 | let x: i32 = i32; | ||
1815 | x.foo(); | ||
1816 | //^ Foo | ||
1817 | }"#, | ||
1818 | ); | ||
1819 | } | ||
1820 | |||
1821 | #[test] | ||
1768 | fn not_shadowing_primitive_by_module() { | 1822 | fn not_shadowing_primitive_by_module() { |
1769 | check_types( | 1823 | check_types( |
1770 | r#" | 1824 | r#" |
diff --git a/crates/hir_ty/src/tests/traits.rs b/crates/hir_ty/src/tests/traits.rs index 65b71fdfa..ffc7c8ef4 100644 --- a/crates/hir_ty/src/tests/traits.rs +++ b/crates/hir_ty/src/tests/traits.rs | |||
@@ -263,15 +263,14 @@ mod ops { | |||
263 | fn infer_from_bound_1() { | 263 | fn infer_from_bound_1() { |
264 | check_infer( | 264 | check_infer( |
265 | r#" | 265 | r#" |
266 | trait Trait<T> {} | 266 | trait Trait<T> {} |
267 | struct S<T>(T); | 267 | struct S<T>(T); |
268 | impl<U> Trait<U> for S<U> {} | 268 | impl<U> Trait<U> for S<U> {} |
269 | fn foo<T: Trait<u32>>(t: T) {} | 269 | fn foo<T: Trait<u32>>(t: T) {} |
270 | fn test() { | 270 | fn test() { |
271 | let s = S(unknown); | 271 | let s = S(unknown); |
272 | foo(s); | 272 | foo(s); |
273 | } | 273 | }"#, |
274 | "#, | ||
275 | expect![[r#" | 274 | expect![[r#" |
276 | 85..86 't': T | 275 | 85..86 't': T |
277 | 91..93 '{}': () | 276 | 91..93 '{}': () |
@@ -291,15 +290,14 @@ fn infer_from_bound_1() { | |||
291 | fn infer_from_bound_2() { | 290 | fn infer_from_bound_2() { |
292 | check_infer( | 291 | check_infer( |
293 | r#" | 292 | r#" |
294 | trait Trait<T> {} | 293 | trait Trait<T> {} |
295 | struct S<T>(T); | 294 | struct S<T>(T); |
296 | impl<U> Trait<U> for S<U> {} | 295 | impl<U> Trait<U> for S<U> {} |
297 | fn foo<U, T: Trait<U>>(t: T) -> U {} | 296 | fn foo<U, T: Trait<U>>(t: T) -> U {} |
298 | fn test() { | 297 | fn test() { |
299 | let s = S(unknown); | 298 | let s = S(unknown); |
300 | let x: u32 = foo(s); | 299 | let x: u32 = foo(s); |
301 | } | 300 | }"#, |
302 | "#, | ||
303 | expect![[r#" | 301 | expect![[r#" |
304 | 86..87 't': T | 302 | 86..87 't': T |
305 | 97..99 '{}': () | 303 | 97..99 '{}': () |
@@ -321,13 +319,12 @@ fn trait_default_method_self_bound_implements_trait() { | |||
321 | cov_mark::check!(trait_self_implements_self); | 319 | cov_mark::check!(trait_self_implements_self); |
322 | check_infer( | 320 | check_infer( |
323 | r#" | 321 | r#" |
324 | trait Trait { | 322 | trait Trait { |
325 | fn foo(&self) -> i64; | 323 | fn foo(&self) -> i64; |
326 | fn bar(&self) -> { | 324 | fn bar(&self) -> { |
327 | let x = self.foo(); | 325 | let x = self.foo(); |
328 | } | 326 | } |
329 | } | 327 | }"#, |
330 | "#, | ||
331 | expect![[r#" | 328 | expect![[r#" |
332 | 26..30 'self': &Self | 329 | 26..30 'self': &Self |
333 | 52..56 'self': &Self | 330 | 52..56 'self': &Self |
@@ -343,15 +340,14 @@ fn trait_default_method_self_bound_implements_trait() { | |||
343 | fn trait_default_method_self_bound_implements_super_trait() { | 340 | fn trait_default_method_self_bound_implements_super_trait() { |
344 | check_infer( | 341 | check_infer( |
345 | r#" | 342 | r#" |
346 | trait SuperTrait { | 343 | trait SuperTrait { |
347 | fn foo(&self) -> i64; | 344 | fn foo(&self) -> i64; |
348 | } | 345 | } |
349 | trait Trait: SuperTrait { | 346 | trait Trait: SuperTrait { |
350 | fn bar(&self) -> { | 347 | fn bar(&self) -> { |
351 | let x = self.foo(); | 348 | let x = self.foo(); |
352 | } | 349 | } |
353 | } | 350 | }"#, |
354 | "#, | ||
355 | expect![[r#" | 351 | expect![[r#" |
356 | 31..35 'self': &Self | 352 | 31..35 'self': &Self |
357 | 85..89 'self': &Self | 353 | 85..89 'self': &Self |
@@ -367,18 +363,17 @@ fn trait_default_method_self_bound_implements_super_trait() { | |||
367 | fn infer_project_associated_type() { | 363 | fn infer_project_associated_type() { |
368 | check_infer( | 364 | check_infer( |
369 | r#" | 365 | r#" |
370 | trait Iterable { | 366 | trait Iterable { |
371 | type Item; | 367 | type Item; |
372 | } | 368 | } |
373 | struct S; | 369 | struct S; |
374 | impl Iterable for S { type Item = u32; } | 370 | impl Iterable for S { type Item = u32; } |
375 | fn test<T: Iterable>() { | 371 | fn test<T: Iterable>() { |
376 | let x: <S as Iterable>::Item = 1; | 372 | let x: <S as Iterable>::Item = 1; |
377 | let y: <T as Iterable>::Item = no_matter; | 373 | let y: <T as Iterable>::Item = no_matter; |
378 | let z: T::Item = no_matter; | 374 | let z: T::Item = no_matter; |
379 | let a: <T>::Item = no_matter; | 375 | let a: <T>::Item = no_matter; |
380 | } | 376 | }"#, |
381 | "#, | ||
382 | expect![[r#" | 377 | expect![[r#" |
383 | 108..261 '{ ...ter; }': () | 378 | 108..261 '{ ...ter; }': () |
384 | 118..119 'x': u32 | 379 | 118..119 'x': u32 |
@@ -397,20 +392,19 @@ fn infer_project_associated_type() { | |||
397 | fn infer_return_associated_type() { | 392 | fn infer_return_associated_type() { |
398 | check_infer( | 393 | check_infer( |
399 | r#" | 394 | r#" |
400 | trait Iterable { | 395 | trait Iterable { |
401 | type Item; | 396 | type Item; |
402 | } | 397 | } |
403 | struct S; | 398 | struct S; |
404 | impl Iterable for S { type Item = u32; } | 399 | impl Iterable for S { type Item = u32; } |
405 | fn foo1<T: Iterable>(t: T) -> T::Item {} | 400 | fn foo1<T: Iterable>(t: T) -> T::Item {} |
406 | fn foo2<T: Iterable>(t: T) -> <T as Iterable>::Item {} | 401 | fn foo2<T: Iterable>(t: T) -> <T as Iterable>::Item {} |
407 | fn foo3<T: Iterable>(t: T) -> <T>::Item {} | 402 | fn foo3<T: Iterable>(t: T) -> <T>::Item {} |
408 | fn test() { | 403 | fn test() { |
409 | let x = foo1(S); | 404 | let x = foo1(S); |
410 | let y = foo2(S); | 405 | let y = foo2(S); |
411 | let z = foo3(S); | 406 | let z = foo3(S); |
412 | } | 407 | }"#, |
413 | "#, | ||
414 | expect![[r#" | 408 | expect![[r#" |
415 | 106..107 't': T | 409 | 106..107 't': T |
416 | 123..125 '{}': () | 410 | 123..125 '{}': () |
@@ -439,13 +433,12 @@ fn infer_return_associated_type() { | |||
439 | fn infer_associated_type_bound() { | 433 | fn infer_associated_type_bound() { |
440 | check_infer( | 434 | check_infer( |
441 | r#" | 435 | r#" |
442 | trait Iterable { | 436 | trait Iterable { |
443 | type Item; | 437 | type Item; |
444 | } | 438 | } |
445 | fn test<T: Iterable<Item=u32>>() { | 439 | fn test<T: Iterable<Item=u32>>() { |
446 | let y: T::Item = unknown; | 440 | let y: T::Item = unknown; |
447 | } | 441 | }"#, |
448 | "#, | ||
449 | expect![[r#" | 442 | expect![[r#" |
450 | 67..100 '{ ...own; }': () | 443 | 67..100 '{ ...own; }': () |
451 | 77..78 'y': u32 | 444 | 77..78 'y': u32 |
@@ -458,9 +451,8 @@ fn infer_associated_type_bound() { | |||
458 | fn infer_const_body() { | 451 | fn infer_const_body() { |
459 | check_infer( | 452 | check_infer( |
460 | r#" | 453 | r#" |
461 | const A: u32 = 1 + 1; | 454 | const A: u32 = 1 + 1; |
462 | static B: u64 = { let x = 1; x }; | 455 | static B: u64 = { let x = 1; x };"#, |
463 | "#, | ||
464 | expect![[r#" | 456 | expect![[r#" |
465 | 15..16 '1': u32 | 457 | 15..16 '1': u32 |
466 | 15..20 '1 + 1': u32 | 458 | 15..20 '1 + 1': u32 |
@@ -477,13 +469,12 @@ fn infer_const_body() { | |||
477 | fn tuple_struct_fields() { | 469 | fn tuple_struct_fields() { |
478 | check_infer( | 470 | check_infer( |
479 | r#" | 471 | r#" |
480 | struct S(i32, u64); | 472 | struct S(i32, u64); |
481 | fn test() -> u64 { | 473 | fn test() -> u64 { |
482 | let a = S(4, 6); | 474 | let a = S(4, 6); |
483 | let b = a.0; | 475 | let b = a.0; |
484 | a.1 | 476 | a.1 |
485 | } | 477 | }"#, |
486 | "#, | ||
487 | expect![[r#" | 478 | expect![[r#" |
488 | 37..86 '{ ... a.1 }': u64 | 479 | 37..86 '{ ... a.1 }': u64 |
489 | 47..48 'a': S | 480 | 47..48 'a': S |
@@ -504,13 +495,12 @@ fn tuple_struct_fields() { | |||
504 | fn tuple_struct_with_fn() { | 495 | fn tuple_struct_with_fn() { |
505 | check_infer( | 496 | check_infer( |
506 | r#" | 497 | r#" |
507 | struct S(fn(u32) -> u64); | 498 | struct S(fn(u32) -> u64); |
508 | fn test() -> u64 { | 499 | fn test() -> u64 { |
509 | let a = S(|i| 2*i); | 500 | let a = S(|i| 2*i); |
510 | let b = a.0(4); | 501 | let b = a.0(4); |
511 | a.0(2) | 502 | a.0(2) |
512 | } | 503 | }"#, |
513 | "#, | ||
514 | expect![[r#" | 504 | expect![[r#" |
515 | 43..101 '{ ...0(2) }': u64 | 505 | 43..101 '{ ...0(2) }': u64 |
516 | 53..54 'a': S | 506 | 53..54 'a': S |
@@ -949,27 +939,26 @@ fn test<T: ApplyL>(t: T) { | |||
949 | fn argument_impl_trait() { | 939 | fn argument_impl_trait() { |
950 | check_infer_with_mismatches( | 940 | check_infer_with_mismatches( |
951 | r#" | 941 | r#" |
952 | trait Trait<T> { | 942 | trait Trait<T> { |
953 | fn foo(&self) -> T; | 943 | fn foo(&self) -> T; |
954 | fn foo2(&self) -> i64; | 944 | fn foo2(&self) -> i64; |
955 | } | 945 | } |
956 | fn bar(x: impl Trait<u16>) {} | 946 | fn bar(x: impl Trait<u16>) {} |
957 | struct S<T>(T); | 947 | struct S<T>(T); |
958 | impl<T> Trait<T> for S<T> {} | 948 | impl<T> Trait<T> for S<T> {} |
959 | 949 | ||
960 | fn test(x: impl Trait<u64>, y: &impl Trait<u32>) { | 950 | fn test(x: impl Trait<u64>, y: &impl Trait<u32>) { |
961 | x; | 951 | x; |
962 | y; | 952 | y; |
963 | let z = S(1); | 953 | let z = S(1); |
964 | bar(z); | 954 | bar(z); |
965 | x.foo(); | 955 | x.foo(); |
966 | y.foo(); | 956 | y.foo(); |
967 | z.foo(); | 957 | z.foo(); |
968 | x.foo2(); | 958 | x.foo2(); |
969 | y.foo2(); | 959 | y.foo2(); |
970 | z.foo2(); | 960 | z.foo2(); |
971 | } | 961 | }"#, |
972 | "#, | ||
973 | expect![[r#" | 962 | expect![[r#" |
974 | 29..33 'self': &Self | 963 | 29..33 'self': &Self |
975 | 54..58 'self': &Self | 964 | 54..58 'self': &Self |
@@ -1007,30 +996,29 @@ fn argument_impl_trait() { | |||
1007 | fn argument_impl_trait_type_args_1() { | 996 | fn argument_impl_trait_type_args_1() { |
1008 | check_infer_with_mismatches( | 997 | check_infer_with_mismatches( |
1009 | r#" | 998 | r#" |
1010 | trait Trait {} | 999 | trait Trait {} |
1011 | trait Foo { | 1000 | trait Foo { |
1012 | // this function has an implicit Self param, an explicit type param, | 1001 | // this function has an implicit Self param, an explicit type param, |
1013 | // and an implicit impl Trait param! | 1002 | // and an implicit impl Trait param! |
1014 | fn bar<T>(x: impl Trait) -> T { loop {} } | 1003 | fn bar<T>(x: impl Trait) -> T { loop {} } |
1015 | } | 1004 | } |
1016 | fn foo<T>(x: impl Trait) -> T { loop {} } | 1005 | fn foo<T>(x: impl Trait) -> T { loop {} } |
1017 | struct S; | 1006 | struct S; |
1018 | impl Trait for S {} | 1007 | impl Trait for S {} |
1019 | struct F; | 1008 | struct F; |
1020 | impl Foo for F {} | 1009 | impl Foo for F {} |
1021 | 1010 | ||
1022 | fn test() { | 1011 | fn test() { |
1023 | Foo::bar(S); | 1012 | Foo::bar(S); |
1024 | <F as Foo>::bar(S); | 1013 | <F as Foo>::bar(S); |
1025 | F::bar(S); | 1014 | F::bar(S); |
1026 | Foo::bar::<u32>(S); | 1015 | Foo::bar::<u32>(S); |
1027 | <F as Foo>::bar::<u32>(S); | 1016 | <F as Foo>::bar::<u32>(S); |
1028 | 1017 | ||
1029 | foo(S); | 1018 | foo(S); |
1030 | foo::<u32>(S); | 1019 | foo::<u32>(S); |
1031 | foo::<u32, i32>(S); // we should ignore the extraneous i32 | 1020 | foo::<u32, i32>(S); // we should ignore the extraneous i32 |
1032 | } | 1021 | }"#, |
1033 | "#, | ||
1034 | expect![[r#" | 1022 | expect![[r#" |
1035 | 155..156 'x': impl Trait | 1023 | 155..156 'x': impl Trait |
1036 | 175..186 '{ loop {} }': T | 1024 | 175..186 '{ loop {} }': T |
@@ -1073,21 +1061,20 @@ fn argument_impl_trait_type_args_1() { | |||
1073 | fn argument_impl_trait_type_args_2() { | 1061 | fn argument_impl_trait_type_args_2() { |
1074 | check_infer_with_mismatches( | 1062 | check_infer_with_mismatches( |
1075 | r#" | 1063 | r#" |
1076 | trait Trait {} | 1064 | trait Trait {} |
1077 | struct S; | 1065 | struct S; |
1078 | impl Trait for S {} | 1066 | impl Trait for S {} |
1079 | struct F<T>; | 1067 | struct F<T>; |
1080 | impl<T> F<T> { | 1068 | impl<T> F<T> { |
1081 | fn foo<U>(self, x: impl Trait) -> (T, U) { loop {} } | 1069 | fn foo<U>(self, x: impl Trait) -> (T, U) { loop {} } |
1082 | } | 1070 | } |
1083 | 1071 | ||
1084 | fn test() { | 1072 | fn test() { |
1085 | F.foo(S); | 1073 | F.foo(S); |
1086 | F::<u32>.foo(S); | 1074 | F::<u32>.foo(S); |
1087 | F::<u32>.foo::<i32>(S); | 1075 | F::<u32>.foo::<i32>(S); |
1088 | F::<u32>.foo::<i32, u32>(S); // extraneous argument should be ignored | 1076 | F::<u32>.foo::<i32, u32>(S); // extraneous argument should be ignored |
1089 | } | 1077 | }"#, |
1090 | "#, | ||
1091 | expect![[r#" | 1078 | expect![[r#" |
1092 | 87..91 'self': F<T> | 1079 | 87..91 'self': F<T> |
1093 | 93..94 'x': impl Trait | 1080 | 93..94 'x': impl Trait |
@@ -1115,15 +1102,14 @@ fn argument_impl_trait_type_args_2() { | |||
1115 | fn argument_impl_trait_to_fn_pointer() { | 1102 | fn argument_impl_trait_to_fn_pointer() { |
1116 | check_infer_with_mismatches( | 1103 | check_infer_with_mismatches( |
1117 | r#" | 1104 | r#" |
1118 | trait Trait {} | 1105 | trait Trait {} |
1119 | fn foo(x: impl Trait) { loop {} } | 1106 | fn foo(x: impl Trait) { loop {} } |
1120 | struct S; | 1107 | struct S; |
1121 | impl Trait for S {} | 1108 | impl Trait for S {} |
1122 | 1109 | ||
1123 | fn test() { | 1110 | fn test() { |
1124 | let f: fn(S) -> () = foo; | 1111 | let f: fn(S) -> () = foo; |
1125 | } | 1112 | }"#, |
1126 | "#, | ||
1127 | expect![[r#" | 1113 | expect![[r#" |
1128 | 22..23 'x': impl Trait | 1114 | 22..23 'x': impl Trait |
1129 | 37..48 '{ loop {} }': () | 1115 | 37..48 '{ loop {} }': () |
@@ -1140,24 +1126,23 @@ fn argument_impl_trait_to_fn_pointer() { | |||
1140 | fn impl_trait() { | 1126 | fn impl_trait() { |
1141 | check_infer( | 1127 | check_infer( |
1142 | r#" | 1128 | r#" |
1143 | trait Trait<T> { | 1129 | trait Trait<T> { |
1144 | fn foo(&self) -> T; | 1130 | fn foo(&self) -> T; |
1145 | fn foo2(&self) -> i64; | 1131 | fn foo2(&self) -> i64; |
1146 | } | 1132 | } |
1147 | fn bar() -> impl Trait<u64> {} | 1133 | fn bar() -> impl Trait<u64> {} |
1148 | 1134 | ||
1149 | fn test(x: impl Trait<u64>, y: &impl Trait<u64>) { | 1135 | fn test(x: impl Trait<u64>, y: &impl Trait<u64>) { |
1150 | x; | 1136 | x; |
1151 | y; | 1137 | y; |
1152 | let z = bar(); | 1138 | let z = bar(); |
1153 | x.foo(); | 1139 | x.foo(); |
1154 | y.foo(); | 1140 | y.foo(); |
1155 | z.foo(); | 1141 | z.foo(); |
1156 | x.foo2(); | 1142 | x.foo2(); |
1157 | y.foo2(); | 1143 | y.foo2(); |
1158 | z.foo2(); | 1144 | z.foo2(); |
1159 | } | 1145 | }"#, |
1160 | "#, | ||
1161 | expect![[r#" | 1146 | expect![[r#" |
1162 | 29..33 'self': &Self | 1147 | 29..33 'self': &Self |
1163 | 54..58 'self': &Self | 1148 | 54..58 'self': &Self |
@@ -1191,16 +1176,15 @@ fn simple_return_pos_impl_trait() { | |||
1191 | cov_mark::check!(lower_rpit); | 1176 | cov_mark::check!(lower_rpit); |
1192 | check_infer( | 1177 | check_infer( |
1193 | r#" | 1178 | r#" |
1194 | trait Trait<T> { | 1179 | trait Trait<T> { |
1195 | fn foo(&self) -> T; | 1180 | fn foo(&self) -> T; |
1196 | } | 1181 | } |
1197 | fn bar() -> impl Trait<u64> { loop {} } | 1182 | fn bar() -> impl Trait<u64> { loop {} } |
1198 | 1183 | ||
1199 | fn test() { | 1184 | fn test() { |
1200 | let a = bar(); | 1185 | let a = bar(); |
1201 | a.foo(); | 1186 | a.foo(); |
1202 | } | 1187 | }"#, |
1203 | "#, | ||
1204 | expect![[r#" | 1188 | expect![[r#" |
1205 | 29..33 'self': &Self | 1189 | 29..33 'self': &Self |
1206 | 71..82 '{ loop {} }': ! | 1190 | 71..82 '{ loop {} }': ! |
@@ -1220,25 +1204,24 @@ fn simple_return_pos_impl_trait() { | |||
1220 | fn more_return_pos_impl_trait() { | 1204 | fn more_return_pos_impl_trait() { |
1221 | check_infer( | 1205 | check_infer( |
1222 | r#" | 1206 | r#" |
1223 | trait Iterator { | 1207 | trait Iterator { |
1224 | type Item; | 1208 | type Item; |
1225 | fn next(&mut self) -> Self::Item; | 1209 | fn next(&mut self) -> Self::Item; |
1226 | } | 1210 | } |
1227 | trait Trait<T> { | 1211 | trait Trait<T> { |
1228 | fn foo(&self) -> T; | 1212 | fn foo(&self) -> T; |
1229 | } | 1213 | } |
1230 | fn bar() -> (impl Iterator<Item = impl Trait<u32>>, impl Trait<u64>) { loop {} } | 1214 | fn bar() -> (impl Iterator<Item = impl Trait<u32>>, impl Trait<u64>) { loop {} } |
1231 | fn baz<T>(t: T) -> (impl Iterator<Item = impl Trait<T>>, impl Trait<T>) { loop {} } | 1215 | fn baz<T>(t: T) -> (impl Iterator<Item = impl Trait<T>>, impl Trait<T>) { loop {} } |
1232 | 1216 | ||
1233 | fn test() { | 1217 | fn test() { |
1234 | let (a, b) = bar(); | 1218 | let (a, b) = bar(); |
1235 | a.next().foo(); | 1219 | a.next().foo(); |
1236 | b.foo(); | 1220 | b.foo(); |
1237 | let (c, d) = baz(1u128); | 1221 | let (c, d) = baz(1u128); |
1238 | c.next().foo(); | 1222 | c.next().foo(); |
1239 | d.foo(); | 1223 | d.foo(); |
1240 | } | 1224 | }"#, |
1241 | "#, | ||
1242 | expect![[r#" | 1225 | expect![[r#" |
1243 | 49..53 'self': &mut Self | 1226 | 49..53 'self': &mut Self |
1244 | 101..105 'self': &Self | 1227 | 101..105 'self': &Self |
@@ -1279,24 +1262,23 @@ fn more_return_pos_impl_trait() { | |||
1279 | fn dyn_trait() { | 1262 | fn dyn_trait() { |
1280 | check_infer( | 1263 | check_infer( |
1281 | r#" | 1264 | r#" |
1282 | trait Trait<T> { | 1265 | trait Trait<T> { |
1283 | fn foo(&self) -> T; | 1266 | fn foo(&self) -> T; |
1284 | fn foo2(&self) -> i64; | 1267 | fn foo2(&self) -> i64; |
1285 | } | 1268 | } |
1286 | fn bar() -> dyn Trait<u64> {} | 1269 | fn bar() -> dyn Trait<u64> {} |
1287 | 1270 | ||
1288 | fn test(x: dyn Trait<u64>, y: &dyn Trait<u64>) { | 1271 | fn test(x: dyn Trait<u64>, y: &dyn Trait<u64>) { |
1289 | x; | 1272 | x; |
1290 | y; | 1273 | y; |
1291 | let z = bar(); | 1274 | let z = bar(); |
1292 | x.foo(); | 1275 | x.foo(); |
1293 | y.foo(); | 1276 | y.foo(); |
1294 | z.foo(); | 1277 | z.foo(); |
1295 | x.foo2(); | 1278 | x.foo2(); |
1296 | y.foo2(); | 1279 | y.foo2(); |
1297 | z.foo2(); | 1280 | z.foo2(); |
1298 | } | 1281 | }"#, |
1299 | "#, | ||
1300 | expect![[r#" | 1282 | expect![[r#" |
1301 | 29..33 'self': &Self | 1283 | 29..33 'self': &Self |
1302 | 54..58 'self': &Self | 1284 | 54..58 'self': &Self |
@@ -1329,22 +1311,21 @@ fn dyn_trait() { | |||
1329 | fn dyn_trait_in_impl() { | 1311 | fn dyn_trait_in_impl() { |
1330 | check_infer( | 1312 | check_infer( |
1331 | r#" | 1313 | r#" |
1332 | trait Trait<T, U> { | 1314 | trait Trait<T, U> { |
1333 | fn foo(&self) -> (T, U); | 1315 | fn foo(&self) -> (T, U); |
1334 | } | 1316 | } |
1335 | struct S<T, U> {} | 1317 | struct S<T, U> {} |
1336 | impl<T, U> S<T, U> { | 1318 | impl<T, U> S<T, U> { |
1337 | fn bar(&self) -> &dyn Trait<T, U> { loop {} } | 1319 | fn bar(&self) -> &dyn Trait<T, U> { loop {} } |
1338 | } | 1320 | } |
1339 | trait Trait2<T, U> { | 1321 | trait Trait2<T, U> { |
1340 | fn baz(&self) -> (T, U); | 1322 | fn baz(&self) -> (T, U); |
1341 | } | 1323 | } |
1342 | impl<T, U> Trait2<T, U> for dyn Trait<T, U> { } | 1324 | impl<T, U> Trait2<T, U> for dyn Trait<T, U> { } |
1343 | 1325 | ||
1344 | fn test(s: S<u32, i32>) { | 1326 | fn test(s: S<u32, i32>) { |
1345 | s.bar().baz(); | 1327 | s.bar().baz(); |
1346 | } | 1328 | }"#, |
1347 | "#, | ||
1348 | expect![[r#" | 1329 | expect![[r#" |
1349 | 32..36 'self': &Self | 1330 | 32..36 'self': &Self |
1350 | 102..106 'self': &S<T, U> | 1331 | 102..106 'self': &S<T, U> |
@@ -1365,20 +1346,19 @@ fn dyn_trait_in_impl() { | |||
1365 | fn dyn_trait_bare() { | 1346 | fn dyn_trait_bare() { |
1366 | check_infer( | 1347 | check_infer( |
1367 | r#" | 1348 | r#" |
1368 | trait Trait { | 1349 | trait Trait { |
1369 | fn foo(&self) -> u64; | 1350 | fn foo(&self) -> u64; |
1370 | } | 1351 | } |
1371 | fn bar() -> Trait {} | 1352 | fn bar() -> Trait {} |
1372 | 1353 | ||
1373 | fn test(x: Trait, y: &Trait) -> u64 { | 1354 | fn test(x: Trait, y: &Trait) -> u64 { |
1374 | x; | 1355 | x; |
1375 | y; | 1356 | y; |
1376 | let z = bar(); | 1357 | let z = bar(); |
1377 | x.foo(); | 1358 | x.foo(); |
1378 | y.foo(); | 1359 | y.foo(); |
1379 | z.foo(); | 1360 | z.foo(); |
1380 | } | 1361 | }"#, |
1381 | "#, | ||
1382 | expect![[r#" |