]> git.lizzy.rs Git - rust.git/blob - crates/hir_ty/src/chalk_ext.rs
Merge #10592
[rust.git] / crates / hir_ty / src / chalk_ext.rs
1 //! Various extensions traits for Chalk types.
2
3 use chalk_ir::{FloatTy, IntTy, Mutability, Scalar, UintTy};
4 use hir_def::{
5     builtin_type::{BuiltinFloat, BuiltinInt, BuiltinType, BuiltinUint},
6     type_ref::Rawness,
7     AssocContainerId, FunctionId, GenericDefId, HasModule, Lookup, TraitId,
8 };
9
10 use crate::{
11     db::HirDatabase, from_assoc_type_id, from_chalk_trait_id, from_foreign_def_id,
12     from_placeholder_idx, to_chalk_trait_id, AdtId, AliasEq, AliasTy, Binders, CallableDefId,
13     CallableSig, FnPointer, ImplTraitId, Interner, Lifetime, ProjectionTy, QuantifiedWhereClause,
14     Substitution, TraitRef, Ty, TyBuilder, TyKind, WhereClause,
15 };
16
17 pub trait TyExt {
18     fn is_unit(&self) -> bool;
19     fn is_never(&self) -> bool;
20     fn is_unknown(&self) -> bool;
21     fn is_ty_var(&self) -> bool;
22
23     fn as_adt(&self) -> Option<(hir_def::AdtId, &Substitution)>;
24     fn as_builtin(&self) -> Option<BuiltinType>;
25     fn as_tuple(&self) -> Option<&Substitution>;
26     fn as_fn_def(&self, db: &dyn HirDatabase) -> Option<FunctionId>;
27     fn as_reference(&self) -> Option<(&Ty, Lifetime, Mutability)>;
28     fn as_reference_or_ptr(&self) -> Option<(&Ty, Rawness, Mutability)>;
29     fn as_generic_def(&self, db: &dyn HirDatabase) -> Option<GenericDefId>;
30
31     fn callable_def(&self, db: &dyn HirDatabase) -> Option<CallableDefId>;
32     fn callable_sig(&self, db: &dyn HirDatabase) -> Option<CallableSig>;
33
34     fn strip_references(&self) -> &Ty;
35
36     /// If this is a `dyn Trait`, returns that trait.
37     fn dyn_trait(&self) -> Option<TraitId>;
38
39     fn impl_trait_bounds(&self, db: &dyn HirDatabase) -> Option<Vec<QuantifiedWhereClause>>;
40     fn associated_type_parent_trait(&self, db: &dyn HirDatabase) -> Option<TraitId>;
41
42     /// FIXME: Get rid of this, it's not a good abstraction
43     fn equals_ctor(&self, other: &Ty) -> bool;
44 }
45
46 impl TyExt for Ty {
47     fn is_unit(&self) -> bool {
48         matches!(self.kind(&Interner), TyKind::Tuple(0, _))
49     }
50
51     fn is_never(&self) -> bool {
52         matches!(self.kind(&Interner), TyKind::Never)
53     }
54
55     fn is_unknown(&self) -> bool {
56         matches!(self.kind(&Interner), TyKind::Error)
57     }
58
59     fn is_ty_var(&self) -> bool {
60         matches!(self.kind(&Interner), TyKind::InferenceVar(_, _))
61     }
62
63     fn as_adt(&self) -> Option<(hir_def::AdtId, &Substitution)> {
64         match self.kind(&Interner) {
65             TyKind::Adt(AdtId(adt), parameters) => Some((*adt, parameters)),
66             _ => None,
67         }
68     }
69
70     fn as_builtin(&self) -> Option<BuiltinType> {
71         match self.kind(&Interner) {
72             TyKind::Str => Some(BuiltinType::Str),
73             TyKind::Scalar(Scalar::Bool) => Some(BuiltinType::Bool),
74             TyKind::Scalar(Scalar::Char) => Some(BuiltinType::Char),
75             TyKind::Scalar(Scalar::Float(fty)) => Some(BuiltinType::Float(match fty {
76                 FloatTy::F64 => BuiltinFloat::F64,
77                 FloatTy::F32 => BuiltinFloat::F32,
78             })),
79             TyKind::Scalar(Scalar::Int(ity)) => Some(BuiltinType::Int(match ity {
80                 IntTy::Isize => BuiltinInt::Isize,
81                 IntTy::I8 => BuiltinInt::I8,
82                 IntTy::I16 => BuiltinInt::I16,
83                 IntTy::I32 => BuiltinInt::I32,
84                 IntTy::I64 => BuiltinInt::I64,
85                 IntTy::I128 => BuiltinInt::I128,
86             })),
87             TyKind::Scalar(Scalar::Uint(ity)) => Some(BuiltinType::Uint(match ity {
88                 UintTy::Usize => BuiltinUint::Usize,
89                 UintTy::U8 => BuiltinUint::U8,
90                 UintTy::U16 => BuiltinUint::U16,
91                 UintTy::U32 => BuiltinUint::U32,
92                 UintTy::U64 => BuiltinUint::U64,
93                 UintTy::U128 => BuiltinUint::U128,
94             })),
95             _ => None,
96         }
97     }
98
99     fn as_tuple(&self) -> Option<&Substitution> {
100         match self.kind(&Interner) {
101             TyKind::Tuple(_, substs) => Some(substs),
102             _ => None,
103         }
104     }
105
106     fn as_fn_def(&self, db: &dyn HirDatabase) -> Option<FunctionId> {
107         match self.callable_def(db) {
108             Some(CallableDefId::FunctionId(func)) => Some(func),
109             Some(CallableDefId::StructId(_) | CallableDefId::EnumVariantId(_)) | None => None,
110         }
111     }
112     fn as_reference(&self) -> Option<(&Ty, Lifetime, Mutability)> {
113         match self.kind(&Interner) {
114             TyKind::Ref(mutability, lifetime, ty) => Some((ty, lifetime.clone(), *mutability)),
115             _ => None,
116         }
117     }
118
119     fn as_reference_or_ptr(&self) -> Option<(&Ty, Rawness, Mutability)> {
120         match self.kind(&Interner) {
121             TyKind::Ref(mutability, _, ty) => Some((ty, Rawness::Ref, *mutability)),
122             TyKind::Raw(mutability, ty) => Some((ty, Rawness::RawPtr, *mutability)),
123             _ => None,
124         }
125     }
126
127     fn as_generic_def(&self, db: &dyn HirDatabase) -> Option<GenericDefId> {
128         match *self.kind(&Interner) {
129             TyKind::Adt(AdtId(adt), ..) => Some(adt.into()),
130             TyKind::FnDef(callable, ..) => {
131                 Some(db.lookup_intern_callable_def(callable.into()).into())
132             }
133             TyKind::AssociatedType(type_alias, ..) => Some(from_assoc_type_id(type_alias).into()),
134             TyKind::Foreign(type_alias, ..) => Some(from_foreign_def_id(type_alias).into()),
135             _ => None,
136         }
137     }
138
139     fn callable_def(&self, db: &dyn HirDatabase) -> Option<CallableDefId> {
140         match self.kind(&Interner) {
141             &TyKind::FnDef(def, ..) => Some(db.lookup_intern_callable_def(def.into())),
142             _ => None,
143         }
144     }
145
146     fn callable_sig(&self, db: &dyn HirDatabase) -> Option<CallableSig> {
147         match self.kind(&Interner) {
148             TyKind::Function(fn_ptr) => Some(CallableSig::from_fn_ptr(fn_ptr)),
149             TyKind::FnDef(def, parameters) => {
150                 let callable_def = db.lookup_intern_callable_def((*def).into());
151                 let sig = db.callable_item_signature(callable_def);
152                 Some(sig.substitute(&Interner, &parameters))
153             }
154             TyKind::Closure(.., substs) => {
155                 let sig_param = substs.at(&Interner, 0).assert_ty_ref(&Interner);
156                 sig_param.callable_sig(db)
157             }
158             _ => None,
159         }
160     }
161
162     fn dyn_trait(&self) -> Option<TraitId> {
163         let trait_ref = match self.kind(&Interner) {
164             TyKind::Dyn(dyn_ty) => dyn_ty.bounds.skip_binders().interned().get(0).and_then(|b| {
165                 match b.skip_binders() {
166                     WhereClause::Implemented(trait_ref) => Some(trait_ref),
167                     _ => None,
168                 }
169             }),
170             _ => None,
171         }?;
172         Some(from_chalk_trait_id(trait_ref.trait_id))
173     }
174
175     fn strip_references(&self) -> &Ty {
176         let mut t: &Ty = self;
177         while let TyKind::Ref(_mutability, _lifetime, ty) = t.kind(&Interner) {
178             t = ty;
179         }
180         t
181     }
182
183     fn impl_trait_bounds(&self, db: &dyn HirDatabase) -> Option<Vec<QuantifiedWhereClause>> {
184         match self.kind(&Interner) {
185             TyKind::OpaqueType(opaque_ty_id, subst) => {
186                 match db.lookup_intern_impl_trait_id((*opaque_ty_id).into()) {
187                     ImplTraitId::AsyncBlockTypeImplTrait(def, _expr) => {
188                         let krate = def.module(db.upcast()).krate();
189                         if let Some(future_trait) = db
190                             .lang_item(krate, "future_trait".into())
191                             .and_then(|item| item.as_trait())
192                         {
193                             // This is only used by type walking.
194                             // Parameters will be walked outside, and projection predicate is not used.
195                             // So just provide the Future trait.
196                             let impl_bound = Binders::empty(
197                                 &Interner,
198                                 WhereClause::Implemented(TraitRef {
199                                     trait_id: to_chalk_trait_id(future_trait),
200                                     substitution: Substitution::empty(&Interner),
201                                 }),
202                             );
203                             Some(vec![impl_bound])
204                         } else {
205                             None
206                         }
207                     }
208                     ImplTraitId::ReturnTypeImplTrait(func, idx) => {
209                         db.return_type_impl_traits(func).map(|it| {
210                             let data = (*it)
211                                 .as_ref()
212                                 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
213                             data.substitute(&Interner, &subst).into_value_and_skipped_binders().0
214                         })
215                     }
216                 }
217             }
218             TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
219                 let predicates = match db.lookup_intern_impl_trait_id(opaque_ty.opaque_ty_id.into())
220                 {
221                     ImplTraitId::ReturnTypeImplTrait(func, idx) => {
222                         db.return_type_impl_traits(func).map(|it| {
223                             let data = (*it)
224                                 .as_ref()
225                                 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
226                             data.substitute(&Interner, &opaque_ty.substitution)
227                         })
228                     }
229                     // It always has an parameter for Future::Output type.
230                     ImplTraitId::AsyncBlockTypeImplTrait(..) => unreachable!(),
231                 };
232
233                 predicates.map(|it| it.into_value_and_skipped_binders().0)
234             }
235             TyKind::Placeholder(idx) => {
236                 let id = from_placeholder_idx(db, *idx);
237                 let generic_params = db.generic_params(id.parent);
238                 let param_data = &generic_params.types[id.local_id];
239                 match param_data.provenance {
240                     hir_def::generics::TypeParamProvenance::ArgumentImplTrait => {
241                         let substs = TyBuilder::type_params_subst(db, id.parent);
242                         let predicates = db
243                             .generic_predicates(id.parent)
244                             .iter()
245                             .map(|pred| pred.clone().substitute(&Interner, &substs))
246                             .filter(|wc| match &wc.skip_binders() {
247                                 WhereClause::Implemented(tr) => {
248                                     &tr.self_type_parameter(&Interner) == self
249                                 }
250                                 WhereClause::AliasEq(AliasEq {
251                                     alias: AliasTy::Projection(proj),
252                                     ty: _,
253                                 }) => &proj.self_type_parameter(&Interner) == self,
254                                 _ => false,
255                             })
256                             .collect::<Vec<_>>();
257
258                         Some(predicates)
259                     }
260                     _ => None,
261                 }
262             }
263             _ => None,
264         }
265     }
266
267     fn associated_type_parent_trait(&self, db: &dyn HirDatabase) -> Option<TraitId> {
268         match self.kind(&Interner) {
269             TyKind::AssociatedType(id, ..) => {
270                 match from_assoc_type_id(*id).lookup(db.upcast()).container {
271                     AssocContainerId::TraitId(trait_id) => Some(trait_id),
272                     _ => None,
273                 }
274             }
275             TyKind::Alias(AliasTy::Projection(projection_ty)) => {
276                 match from_assoc_type_id(projection_ty.associated_ty_id)
277                     .lookup(db.upcast())
278                     .container
279                 {
280                     AssocContainerId::TraitId(trait_id) => Some(trait_id),
281                     _ => None,
282                 }
283             }
284             _ => None,
285         }
286     }
287
288     fn equals_ctor(&self, other: &Ty) -> bool {
289         match (self.kind(&Interner), other.kind(&Interner)) {
290             (TyKind::Adt(adt, ..), TyKind::Adt(adt2, ..)) => adt == adt2,
291             (TyKind::Slice(_), TyKind::Slice(_)) | (TyKind::Array(_, _), TyKind::Array(_, _)) => {
292                 true
293             }
294             (TyKind::FnDef(def_id, ..), TyKind::FnDef(def_id2, ..)) => def_id == def_id2,
295             (TyKind::OpaqueType(ty_id, ..), TyKind::OpaqueType(ty_id2, ..)) => ty_id == ty_id2,
296             (TyKind::AssociatedType(ty_id, ..), TyKind::AssociatedType(ty_id2, ..)) => {
297                 ty_id == ty_id2
298             }
299             (TyKind::Foreign(ty_id, ..), TyKind::Foreign(ty_id2, ..)) => ty_id == ty_id2,
300             (TyKind::Closure(id1, _), TyKind::Closure(id2, _)) => id1 == id2,
301             (TyKind::Ref(mutability, ..), TyKind::Ref(mutability2, ..))
302             | (TyKind::Raw(mutability, ..), TyKind::Raw(mutability2, ..)) => {
303                 mutability == mutability2
304             }
305             (
306                 TyKind::Function(FnPointer { num_binders, sig, .. }),
307                 TyKind::Function(FnPointer { num_binders: num_binders2, sig: sig2, .. }),
308             ) => num_binders == num_binders2 && sig == sig2,
309             (TyKind::Tuple(cardinality, _), TyKind::Tuple(cardinality2, _)) => {
310                 cardinality == cardinality2
311             }
312             (TyKind::Str, TyKind::Str) | (TyKind::Never, TyKind::Never) => true,
313             (TyKind::Scalar(scalar), TyKind::Scalar(scalar2)) => scalar == scalar2,
314             _ => false,
315         }
316     }
317 }
318
319 pub trait ProjectionTyExt {
320     fn trait_ref(&self, db: &dyn HirDatabase) -> TraitRef;
321     fn trait_(&self, db: &dyn HirDatabase) -> TraitId;
322 }
323
324 impl ProjectionTyExt for ProjectionTy {
325     fn trait_ref(&self, db: &dyn HirDatabase) -> TraitRef {
326         TraitRef {
327             trait_id: to_chalk_trait_id(self.trait_(db)),
328             substitution: self.substitution.clone(),
329         }
330     }
331
332     fn trait_(&self, db: &dyn HirDatabase) -> TraitId {
333         match from_assoc_type_id(self.associated_ty_id).lookup(db.upcast()).container {
334             AssocContainerId::TraitId(it) => it,
335             _ => panic!("projection ty without parent trait"),
336         }
337     }
338 }
339
340 pub trait TraitRefExt {
341     fn hir_trait_id(&self) -> TraitId;
342 }
343
344 impl TraitRefExt for TraitRef {
345     fn hir_trait_id(&self) -> TraitId {
346         from_chalk_trait_id(self.trait_id)
347     }
348 }