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