]> git.lizzy.rs Git - rust.git/blob - crates/hir_ty/src/chalk_ext.rs
clippy::redundant_closure
[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         if let Some(CallableDefId::FunctionId(func)) = self.callable_def(db) {
108             Some(func)
109         } else {
110             None
111         }
112     }
113     fn as_reference(&self) -> Option<(&Ty, Lifetime, Mutability)> {
114         match self.kind(&Interner) {
115             TyKind::Ref(mutability, lifetime, ty) => Some((ty, lifetime.clone(), *mutability)),
116             _ => None,
117         }
118     }
119
120     fn as_reference_or_ptr(&self) -> Option<(&Ty, Rawness, Mutability)> {
121         match self.kind(&Interner) {
122             TyKind::Ref(mutability, _, ty) => Some((ty, Rawness::Ref, *mutability)),
123             TyKind::Raw(mutability, ty) => Some((ty, Rawness::RawPtr, *mutability)),
124             _ => None,
125         }
126     }
127
128     fn as_generic_def(&self, db: &dyn HirDatabase) -> Option<GenericDefId> {
129         match *self.kind(&Interner) {
130             TyKind::Adt(AdtId(adt), ..) => Some(adt.into()),
131             TyKind::FnDef(callable, ..) => {
132                 Some(db.lookup_intern_callable_def(callable.into()).into())
133             }
134             TyKind::AssociatedType(type_alias, ..) => Some(from_assoc_type_id(type_alias).into()),
135             TyKind::Foreign(type_alias, ..) => Some(from_foreign_def_id(type_alias).into()),
136             _ => None,
137         }
138     }
139
140     fn callable_def(&self, db: &dyn HirDatabase) -> Option<CallableDefId> {
141         match self.kind(&Interner) {
142             &TyKind::FnDef(def, ..) => Some(db.lookup_intern_callable_def(def.into())),
143             _ => None,
144         }
145     }
146
147     fn callable_sig(&self, db: &dyn HirDatabase) -> Option<CallableSig> {
148         match self.kind(&Interner) {
149             TyKind::Function(fn_ptr) => Some(CallableSig::from_fn_ptr(fn_ptr)),
150             TyKind::FnDef(def, parameters) => {
151                 let callable_def = db.lookup_intern_callable_def((*def).into());
152                 let sig = db.callable_item_signature(callable_def);
153                 Some(sig.substitute(&Interner, &parameters))
154             }
155             TyKind::Closure(.., substs) => {
156                 let sig_param = substs.at(&Interner, 0).assert_ty_ref(&Interner);
157                 sig_param.callable_sig(db)
158             }
159             _ => None,
160         }
161     }
162
163     fn dyn_trait(&self) -> Option<TraitId> {
164         let trait_ref = match self.kind(&Interner) {
165             TyKind::Dyn(dyn_ty) => dyn_ty.bounds.skip_binders().interned().get(0).and_then(|b| {
166                 match b.skip_binders() {
167                     WhereClause::Implemented(trait_ref) => Some(trait_ref),
168                     _ => None,
169                 }
170             }),
171             _ => None,
172         }?;
173         Some(from_chalk_trait_id(trait_ref.trait_id))
174     }
175
176     fn strip_references(&self) -> &Ty {
177         let mut t: &Ty = self;
178         while let TyKind::Ref(_mutability, _lifetime, ty) = t.kind(&Interner) {
179             t = ty;
180         }
181         t
182     }
183
184     fn impl_trait_bounds(&self, db: &dyn HirDatabase) -> Option<Vec<QuantifiedWhereClause>> {
185         match self.kind(&Interner) {
186             TyKind::OpaqueType(opaque_ty_id, ..) => {
187                 match db.lookup_intern_impl_trait_id((*opaque_ty_id).into()) {
188                     ImplTraitId::AsyncBlockTypeImplTrait(def, _expr) => {
189                         let krate = def.module(db.upcast()).krate();
190                         if let Some(future_trait) = db
191                             .lang_item(krate, "future_trait".into())
192                             .and_then(|item| item.as_trait())
193                         {
194                             // This is only used by type walking.
195                             // Parameters will be walked outside, and projection predicate is not used.
196                             // So just provide the Future trait.
197                             let impl_bound = Binders::empty(
198                                 &Interner,
199                                 WhereClause::Implemented(TraitRef {
200                                     trait_id: to_chalk_trait_id(future_trait),
201                                     substitution: Substitution::empty(&Interner),
202                                 }),
203                             );
204                             Some(vec![impl_bound])
205                         } else {
206                             None
207                         }
208                     }
209                     ImplTraitId::ReturnTypeImplTrait(..) => None,
210                 }
211             }
212             TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
213                 let predicates = match db.lookup_intern_impl_trait_id(opaque_ty.opaque_ty_id.into())
214                 {
215                     ImplTraitId::ReturnTypeImplTrait(func, idx) => {
216                         db.return_type_impl_traits(func).map(|it| {
217                             let data = (*it)
218                                 .as_ref()
219                                 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
220                             data.substitute(&Interner, &opaque_ty.substitution)
221                         })
222                     }
223                     // It always has an parameter for Future::Output type.
224                     ImplTraitId::AsyncBlockTypeImplTrait(..) => unreachable!(),
225                 };
226
227                 predicates.map(|it| it.into_value_and_skipped_binders().0)
228             }
229             TyKind::Placeholder(idx) => {
230                 let id = from_placeholder_idx(db, *idx);
231                 let generic_params = db.generic_params(id.parent);
232                 let param_data = &generic_params.types[id.local_id];
233                 match param_data.provenance {
234                     hir_def::generics::TypeParamProvenance::ArgumentImplTrait => {
235                         let substs = TyBuilder::type_params_subst(db, id.parent);
236                         let predicates = db
237                             .generic_predicates(id.parent)
238                             .into_iter()
239                             .map(|pred| pred.clone().substitute(&Interner, &substs))
240                             .filter(|wc| match &wc.skip_binders() {
241                                 WhereClause::Implemented(tr) => {
242                                     &tr.self_type_parameter(&Interner) == self
243                                 }
244                                 WhereClause::AliasEq(AliasEq {
245                                     alias: AliasTy::Projection(proj),
246                                     ty: _,
247                                 }) => &proj.self_type_parameter(&Interner) == self,
248                                 _ => false,
249                             })
250                             .collect::<Vec<_>>();
251
252                         Some(predicates)
253                     }
254                     _ => None,
255                 }
256             }
257             _ => None,
258         }
259     }
260
261     fn associated_type_parent_trait(&self, db: &dyn HirDatabase) -> Option<TraitId> {
262         match self.kind(&Interner) {
263             TyKind::AssociatedType(id, ..) => {
264                 match from_assoc_type_id(*id).lookup(db.upcast()).container {
265                     AssocContainerId::TraitId(trait_id) => Some(trait_id),
266                     _ => None,
267                 }
268             }
269             TyKind::Alias(AliasTy::Projection(projection_ty)) => {
270                 match from_assoc_type_id(projection_ty.associated_ty_id)
271                     .lookup(db.upcast())
272                     .container
273                 {
274                     AssocContainerId::TraitId(trait_id) => Some(trait_id),
275                     _ => None,
276                 }
277             }
278             _ => None,
279         }
280     }
281
282     fn equals_ctor(&self, other: &Ty) -> bool {
283         match (self.kind(&Interner), other.kind(&Interner)) {
284             (TyKind::Adt(adt, ..), TyKind::Adt(adt2, ..)) => adt == adt2,
285             (TyKind::Slice(_), TyKind::Slice(_)) | (TyKind::Array(_, _), TyKind::Array(_, _)) => {
286                 true
287             }
288             (TyKind::FnDef(def_id, ..), TyKind::FnDef(def_id2, ..)) => def_id == def_id2,
289             (TyKind::OpaqueType(ty_id, ..), TyKind::OpaqueType(ty_id2, ..)) => ty_id == ty_id2,
290             (TyKind::AssociatedType(ty_id, ..), TyKind::AssociatedType(ty_id2, ..)) => {
291                 ty_id == ty_id2
292             }
293             (TyKind::Foreign(ty_id, ..), TyKind::Foreign(ty_id2, ..)) => ty_id == ty_id2,
294             (TyKind::Closure(id1, _), TyKind::Closure(id2, _)) => id1 == id2,
295             (TyKind::Ref(mutability, ..), TyKind::Ref(mutability2, ..))
296             | (TyKind::Raw(mutability, ..), TyKind::Raw(mutability2, ..)) => {
297                 mutability == mutability2
298             }
299             (
300                 TyKind::Function(FnPointer { num_binders, sig, .. }),
301                 TyKind::Function(FnPointer { num_binders: num_binders2, sig: sig2, .. }),
302             ) => num_binders == num_binders2 && sig == sig2,
303             (TyKind::Tuple(cardinality, _), TyKind::Tuple(cardinality2, _)) => {
304                 cardinality == cardinality2
305             }
306             (TyKind::Str, TyKind::Str) | (TyKind::Never, TyKind::Never) => true,
307             (TyKind::Scalar(scalar), TyKind::Scalar(scalar2)) => scalar == scalar2,
308             _ => false,
309         }
310     }
311 }
312
313 pub trait ProjectionTyExt {
314     fn trait_ref(&self, db: &dyn HirDatabase) -> TraitRef;
315     fn trait_(&self, db: &dyn HirDatabase) -> TraitId;
316 }
317
318 impl ProjectionTyExt for ProjectionTy {
319     fn trait_ref(&self, db: &dyn HirDatabase) -> TraitRef {
320         TraitRef {
321             trait_id: to_chalk_trait_id(self.trait_(db)),
322             substitution: self.substitution.clone(),
323         }
324     }
325
326     fn trait_(&self, db: &dyn HirDatabase) -> TraitId {
327         match from_assoc_type_id(self.associated_ty_id).lookup(db.upcast()).container {
328             AssocContainerId::TraitId(it) => it,
329             _ => panic!("projection ty without parent trait"),
330         }
331     }
332 }
333
334 pub trait TraitRefExt {
335     fn hir_trait_id(&self) -> TraitId;
336 }
337
338 impl TraitRefExt for TraitRef {
339     fn hir_trait_id(&self) -> TraitId {
340         from_chalk_trait_id(self.trait_id)
341     }
342 }