1 //! Various extensions traits for Chalk types.
3 use chalk_ir::{FloatTy, IntTy, Mutability, Scalar, UintTy};
5 builtin_type::{BuiltinFloat, BuiltinInt, BuiltinType, BuiltinUint},
7 AssocContainerId, FunctionId, GenericDefId, HasModule, Lookup, TraitId,
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,
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;
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>;
31 fn callable_def(&self, db: &dyn HirDatabase) -> Option<CallableDefId>;
32 fn callable_sig(&self, db: &dyn HirDatabase) -> Option<CallableSig>;
34 fn strip_references(&self) -> &Ty;
36 /// If this is a `dyn Trait`, returns that trait.
37 fn dyn_trait(&self) -> Option<TraitId>;
39 fn impl_trait_bounds(&self, db: &dyn HirDatabase) -> Option<Vec<QuantifiedWhereClause>>;
40 fn associated_type_parent_trait(&self, db: &dyn HirDatabase) -> Option<TraitId>;
42 /// FIXME: Get rid of this, it's not a good abstraction
43 fn equals_ctor(&self, other: &Ty) -> bool;
47 fn is_unit(&self) -> bool {
48 matches!(self.kind(&Interner), TyKind::Tuple(0, _))
51 fn is_never(&self) -> bool {
52 matches!(self.kind(&Interner), TyKind::Never)
55 fn is_unknown(&self) -> bool {
56 matches!(self.kind(&Interner), TyKind::Error)
59 fn is_ty_var(&self) -> bool {
60 matches!(self.kind(&Interner), TyKind::InferenceVar(_, _))
63 fn as_adt(&self) -> Option<(hir_def::AdtId, &Substitution)> {
64 match self.kind(&Interner) {
65 TyKind::Adt(AdtId(adt), parameters) => Some((*adt, parameters)),
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,
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,
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,
99 fn as_tuple(&self) -> Option<&Substitution> {
100 match self.kind(&Interner) {
101 TyKind::Tuple(_, substs) => Some(substs),
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,
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)),
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)),
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())
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()),
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())),
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, ¶meters))
154 TyKind::Closure(.., substs) => {
155 let sig_param = substs.at(&Interner, 0).assert_ty_ref(&Interner);
156 sig_param.callable_sig(db)
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),
172 Some(from_chalk_trait_id(trait_ref.trait_id))
175 fn strip_references(&self) -> &Ty {
176 let mut t: &Ty = self;
177 while let TyKind::Ref(_mutability, _lifetime, ty) = t.kind(&Interner) {
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())
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(
198 WhereClause::Implemented(TraitRef {
199 trait_id: to_chalk_trait_id(future_trait),
200 substitution: Substitution::empty(&Interner),
203 Some(vec![impl_bound])
208 ImplTraitId::ReturnTypeImplTrait(func, idx) => {
209 db.return_type_impl_traits(func).map(|it| {
212 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
213 data.substitute(&Interner, &subst).into_value_and_skipped_binders().0
218 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
219 let predicates = match db.lookup_intern_impl_trait_id(opaque_ty.opaque_ty_id.into())
221 ImplTraitId::ReturnTypeImplTrait(func, idx) => {
222 db.return_type_impl_traits(func).map(|it| {
225 .map(|rpit| rpit.impl_traits[idx as usize].bounds.clone());
226 data.substitute(&Interner, &opaque_ty.substitution)
229 // It always has an parameter for Future::Output type.
230 ImplTraitId::AsyncBlockTypeImplTrait(..) => unreachable!(),
233 predicates.map(|it| it.into_value_and_skipped_binders().0)
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);
243 .generic_predicates(id.parent)
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
250 WhereClause::AliasEq(AliasEq {
251 alias: AliasTy::Projection(proj),
253 }) => &proj.self_type_parameter(&Interner) == self,
256 .collect::<Vec<_>>();
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),
275 TyKind::Alias(AliasTy::Projection(projection_ty)) => {
276 match from_assoc_type_id(projection_ty.associated_ty_id)
280 AssocContainerId::TraitId(trait_id) => Some(trait_id),
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(_, _)) => {
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, ..)) => {
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
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
312 (TyKind::Str, TyKind::Str) | (TyKind::Never, TyKind::Never) => true,
313 (TyKind::Scalar(scalar), TyKind::Scalar(scalar2)) => scalar == scalar2,
319 pub trait ProjectionTyExt {
320 fn trait_ref(&self, db: &dyn HirDatabase) -> TraitRef;
321 fn trait_(&self, db: &dyn HirDatabase) -> TraitId;
324 impl ProjectionTyExt for ProjectionTy {
325 fn trait_ref(&self, db: &dyn HirDatabase) -> TraitRef {
327 trait_id: to_chalk_trait_id(self.trait_(db)),
328 substitution: self.substitution.clone(),
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"),
340 pub trait TraitRefExt {
341 fn hir_trait_id(&self) -> TraitId;
344 impl TraitRefExt for TraitRef {
345 fn hir_trait_id(&self) -> TraitId {
346 from_chalk_trait_id(self.trait_id)