]> git.lizzy.rs Git - rust.git/blob - crates/hir_ty/src/lib.rs
Merge #8385
[rust.git] / crates / hir_ty / src / lib.rs
1 //! The type system. We currently use this to infer types for completion, hover
2 //! information and various assists.
3 #[allow(unused)]
4 macro_rules! eprintln {
5     ($($tt:tt)*) => { stdx::eprintln!($($tt)*) };
6 }
7
8 mod autoderef;
9 pub mod primitive;
10 pub mod traits;
11 pub mod method_resolution;
12 mod op;
13 mod lower;
14 pub(crate) mod infer;
15 pub(crate) mod utils;
16 mod chalk_cast;
17 mod chalk_ext;
18 mod builder;
19 mod walk;
20 mod types;
21
22 pub mod display;
23 pub mod db;
24 pub mod diagnostics;
25
26 #[cfg(test)]
27 mod tests;
28 #[cfg(test)]
29 mod test_db;
30
31 use std::sync::Arc;
32
33 use base_db::salsa;
34 use chalk_ir::UintTy;
35 use hir_def::{
36     expr::ExprId, type_ref::Rawness, ConstParamId, LifetimeParamId, TraitId, TypeAliasId,
37     TypeParamId,
38 };
39
40 use crate::{db::HirDatabase, display::HirDisplay, utils::generics};
41
42 pub use autoderef::autoderef;
43 pub use builder::TyBuilder;
44 pub use chalk_ext::{ProjectionTyExt, TyExt};
45 pub use infer::{could_unify, InferenceResult};
46 pub use lower::{
47     associated_type_shorthand_candidates, callable_item_sig, CallableDefId, ImplTraitLoweringMode,
48     TyDefId, TyLoweringContext, ValueTyDefId,
49 };
50 pub use traits::{chalk::Interner, TraitEnvironment};
51 pub use types::*;
52 pub use walk::TypeWalk;
53
54 pub use chalk_ir::{
55     cast::Cast, AdtId, BoundVar, DebruijnIndex, Mutability, Safety, Scalar, TyVariableKind,
56 };
57
58 pub type ForeignDefId = chalk_ir::ForeignDefId<Interner>;
59 pub type AssocTypeId = chalk_ir::AssocTypeId<Interner>;
60 pub type FnDefId = chalk_ir::FnDefId<Interner>;
61 pub type ClosureId = chalk_ir::ClosureId<Interner>;
62 pub type OpaqueTyId = chalk_ir::OpaqueTyId<Interner>;
63 pub type PlaceholderIndex = chalk_ir::PlaceholderIndex;
64
65 pub type VariableKind = chalk_ir::VariableKind<Interner>;
66 pub type VariableKinds = chalk_ir::VariableKinds<Interner>;
67 pub type CanonicalVarKinds = chalk_ir::CanonicalVarKinds<Interner>;
68
69 pub type Lifetime = chalk_ir::Lifetime<Interner>;
70 pub type LifetimeData = chalk_ir::LifetimeData<Interner>;
71 pub type LifetimeOutlives = chalk_ir::LifetimeOutlives<Interner>;
72
73 pub type Const = chalk_ir::Const<Interner>;
74 pub type ConstData = chalk_ir::ConstData<Interner>;
75 pub type ConstValue = chalk_ir::ConstValue<Interner>;
76 pub type ConcreteConst = chalk_ir::ConcreteConst<Interner>;
77
78 pub type ChalkTraitId = chalk_ir::TraitId<Interner>;
79
80 pub type FnSig = chalk_ir::FnSig<Interner>;
81
82 // FIXME: get rid of this
83 pub fn subst_prefix(s: &Substitution, n: usize) -> Substitution {
84     Substitution::intern(s.interned()[..std::cmp::min(s.len(&Interner), n)].into())
85 }
86
87 /// Return an index of a parameter in the generic type parameter list by it's id.
88 pub fn param_idx(db: &dyn HirDatabase, id: TypeParamId) -> Option<usize> {
89     generics(db.upcast(), id.parent).param_idx(id)
90 }
91
92 pub fn wrap_empty_binders<T>(value: T) -> Binders<T>
93 where
94     T: TypeWalk,
95 {
96     Binders::empty(&Interner, value.shifted_in_from(DebruijnIndex::ONE))
97 }
98
99 pub fn make_only_type_binders<T>(num_vars: usize, value: T) -> Binders<T> {
100     Binders::new(
101         VariableKinds::from_iter(
102             &Interner,
103             std::iter::repeat(chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General))
104                 .take(num_vars),
105         ),
106         value,
107     )
108 }
109
110 impl TraitRef {
111     pub fn hir_trait_id(&self) -> TraitId {
112         from_chalk_trait_id(self.trait_id)
113     }
114 }
115
116 impl<T> Canonical<T> {
117     pub fn new(value: T, kinds: impl IntoIterator<Item = TyVariableKind>) -> Self {
118         let kinds = kinds.into_iter().map(|tk| {
119             chalk_ir::CanonicalVarKind::new(
120                 chalk_ir::VariableKind::Ty(tk),
121                 chalk_ir::UniverseIndex::ROOT,
122             )
123         });
124         Self { value, binders: chalk_ir::CanonicalVarKinds::from_iter(&Interner, kinds) }
125     }
126 }
127
128 /// A function signature as seen by type inference: Several parameter types and
129 /// one return type.
130 #[derive(Clone, PartialEq, Eq, Debug)]
131 pub struct CallableSig {
132     params_and_return: Arc<[Ty]>,
133     is_varargs: bool,
134 }
135
136 /// A polymorphic function signature.
137 pub type PolyFnSig = Binders<CallableSig>;
138
139 impl CallableSig {
140     pub fn from_params_and_return(mut params: Vec<Ty>, ret: Ty, is_varargs: bool) -> CallableSig {
141         params.push(ret);
142         CallableSig { params_and_return: params.into(), is_varargs }
143     }
144
145     pub fn from_fn_ptr(fn_ptr: &FnPointer) -> CallableSig {
146         CallableSig {
147             // FIXME: what to do about lifetime params? -> return PolyFnSig
148             params_and_return: fn_ptr
149                 .substitution
150                 .clone()
151                 .shifted_out_to(DebruijnIndex::ONE)
152                 .expect("unexpected lifetime vars in fn ptr")
153                 .0
154                 .interned()
155                 .iter()
156                 .map(|arg| arg.assert_ty_ref(&Interner).clone())
157                 .collect(),
158             is_varargs: fn_ptr.sig.variadic,
159         }
160     }
161
162     pub fn params(&self) -> &[Ty] {
163         &self.params_and_return[0..self.params_and_return.len() - 1]
164     }
165
166     pub fn ret(&self) -> &Ty {
167         &self.params_and_return[self.params_and_return.len() - 1]
168     }
169 }
170
171 impl Ty {
172     pub fn equals_ctor(&self, other: &Ty) -> bool {
173         match (self.kind(&Interner), other.kind(&Interner)) {
174             (TyKind::Adt(adt, ..), TyKind::Adt(adt2, ..)) => adt == adt2,
175             (TyKind::Slice(_), TyKind::Slice(_)) | (TyKind::Array(_, _), TyKind::Array(_, _)) => {
176                 true
177             }
178             (TyKind::FnDef(def_id, ..), TyKind::FnDef(def_id2, ..)) => def_id == def_id2,
179             (TyKind::OpaqueType(ty_id, ..), TyKind::OpaqueType(ty_id2, ..)) => ty_id == ty_id2,
180             (TyKind::AssociatedType(ty_id, ..), TyKind::AssociatedType(ty_id2, ..)) => {
181                 ty_id == ty_id2
182             }
183             (TyKind::Foreign(ty_id, ..), TyKind::Foreign(ty_id2, ..)) => ty_id == ty_id2,
184             (TyKind::Closure(id1, _), TyKind::Closure(id2, _)) => id1 == id2,
185             (TyKind::Ref(mutability, ..), TyKind::Ref(mutability2, ..))
186             | (TyKind::Raw(mutability, ..), TyKind::Raw(mutability2, ..)) => {
187                 mutability == mutability2
188             }
189             (
190                 TyKind::Function(FnPointer { num_binders, sig, .. }),
191                 TyKind::Function(FnPointer { num_binders: num_binders2, sig: sig2, .. }),
192             ) => num_binders == num_binders2 && sig == sig2,
193             (TyKind::Tuple(cardinality, _), TyKind::Tuple(cardinality2, _)) => {
194                 cardinality == cardinality2
195             }
196             (TyKind::Str, TyKind::Str) | (TyKind::Never, TyKind::Never) => true,
197             (TyKind::Scalar(scalar), TyKind::Scalar(scalar2)) => scalar == scalar2,
198             _ => false,
199         }
200     }
201
202     fn builtin_deref(&self) -> Option<Ty> {
203         match self.kind(&Interner) {
204             TyKind::Ref(.., ty) => Some(ty.clone()),
205             TyKind::Raw(.., ty) => Some(ty.clone()),
206             _ => None,
207         }
208     }
209
210     /// Returns the type parameters of this type if it has some (i.e. is an ADT
211     /// or function); so if `self` is `Option<u32>`, this returns the `u32`.
212     pub fn substs(&self) -> Option<&Substitution> {
213         match self.kind(&Interner) {
214             TyKind::Adt(_, substs)
215             | TyKind::FnDef(_, substs)
216             | TyKind::Tuple(_, substs)
217             | TyKind::OpaqueType(_, substs)
218             | TyKind::AssociatedType(_, substs)
219             | TyKind::Closure(.., substs) => Some(substs),
220             TyKind::Function(FnPointer { substitution: substs, .. }) => Some(&substs.0),
221             _ => None,
222         }
223     }
224
225     fn substs_mut(&mut self) -> Option<&mut Substitution> {
226         match self.interned_mut() {
227             TyKind::Adt(_, substs)
228             | TyKind::FnDef(_, substs)
229             | TyKind::Tuple(_, substs)
230             | TyKind::OpaqueType(_, substs)
231             | TyKind::AssociatedType(_, substs)
232             | TyKind::Closure(.., substs) => Some(substs),
233             TyKind::Function(FnPointer { substitution: substs, .. }) => Some(&mut substs.0),
234             _ => None,
235         }
236     }
237 }
238
239 #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
240 pub enum ImplTraitId {
241     ReturnTypeImplTrait(hir_def::FunctionId, u16),
242     AsyncBlockTypeImplTrait(hir_def::DefWithBodyId, ExprId),
243 }
244
245 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
246 pub struct ReturnTypeImplTraits {
247     pub(crate) impl_traits: Vec<ReturnTypeImplTrait>,
248 }
249
250 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
251 pub(crate) struct ReturnTypeImplTrait {
252     pub(crate) bounds: Binders<Vec<QuantifiedWhereClause>>,
253 }
254
255 pub fn to_foreign_def_id(id: TypeAliasId) -> ForeignDefId {
256     chalk_ir::ForeignDefId(salsa::InternKey::as_intern_id(&id))
257 }
258
259 pub fn from_foreign_def_id(id: ForeignDefId) -> TypeAliasId {
260     salsa::InternKey::from_intern_id(id.0)
261 }
262
263 pub fn to_assoc_type_id(id: TypeAliasId) -> AssocTypeId {
264     chalk_ir::AssocTypeId(salsa::InternKey::as_intern_id(&id))
265 }
266
267 pub fn from_assoc_type_id(id: AssocTypeId) -> TypeAliasId {
268     salsa::InternKey::from_intern_id(id.0)
269 }
270
271 pub fn from_placeholder_idx(db: &dyn HirDatabase, idx: PlaceholderIndex) -> TypeParamId {
272     assert_eq!(idx.ui, chalk_ir::UniverseIndex::ROOT);
273     let interned_id = salsa::InternKey::from_intern_id(salsa::InternId::from(idx.idx));
274     db.lookup_intern_type_param_id(interned_id)
275 }
276
277 pub fn to_placeholder_idx(db: &dyn HirDatabase, id: TypeParamId) -> PlaceholderIndex {
278     let interned_id = db.intern_type_param_id(id);
279     PlaceholderIndex {
280         ui: chalk_ir::UniverseIndex::ROOT,
281         idx: salsa::InternKey::as_intern_id(&interned_id).as_usize(),
282     }
283 }
284
285 pub fn lt_from_placeholder_idx(db: &dyn HirDatabase, idx: PlaceholderIndex) -> LifetimeParamId {
286     assert_eq!(idx.ui, chalk_ir::UniverseIndex::ROOT);
287     let interned_id = salsa::InternKey::from_intern_id(salsa::InternId::from(idx.idx));
288     db.lookup_intern_lifetime_param_id(interned_id)
289 }
290
291 pub fn const_from_placeholder_idx(db: &dyn HirDatabase, idx: PlaceholderIndex) -> ConstParamId {
292     assert_eq!(idx.ui, chalk_ir::UniverseIndex::ROOT);
293     let interned_id = salsa::InternKey::from_intern_id(salsa::InternId::from(idx.idx));
294     db.lookup_intern_const_param_id(interned_id)
295 }
296
297 pub fn to_chalk_trait_id(id: TraitId) -> ChalkTraitId {
298     chalk_ir::TraitId(salsa::InternKey::as_intern_id(&id))
299 }
300
301 pub fn from_chalk_trait_id(id: ChalkTraitId) -> TraitId {
302     salsa::InternKey::from_intern_id(id.0)
303 }
304
305 pub fn static_lifetime() -> Lifetime {
306     LifetimeData::Static.intern(&Interner)
307 }
308
309 pub fn dummy_usize_const() -> Const {
310     let usize_ty = chalk_ir::TyKind::Scalar(Scalar::Uint(UintTy::Usize)).intern(&Interner);
311     chalk_ir::ConstData {
312         ty: usize_ty,
313         value: chalk_ir::ConstValue::Concrete(chalk_ir::ConcreteConst { interned: () }),
314     }
315     .intern(&Interner)
316 }