]> git.lizzy.rs Git - rust.git/blob - crates/hir_ty/src/lib.rs
15b61bedc18f004d95c66415e9119346723d7caa
[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
4 #[allow(unused)]
5 macro_rules! eprintln {
6     ($($tt:tt)*) => { stdx::eprintln!($($tt)*) };
7 }
8
9 mod autoderef;
10 mod builder;
11 mod chalk_db;
12 mod chalk_ext;
13 pub mod consteval;
14 mod infer;
15 mod interner;
16 mod lower;
17 mod mapping;
18 mod op;
19 mod tls;
20 mod utils;
21 mod walk;
22 pub mod db;
23 pub mod diagnostics;
24 pub mod display;
25 pub mod method_resolution;
26 pub mod primitive;
27 pub mod traits;
28
29 #[cfg(test)]
30 mod tests;
31 #[cfg(test)]
32 mod test_db;
33
34 use std::sync::Arc;
35
36 use chalk_ir::{
37     fold::{Fold, Shift},
38     interner::HasInterner,
39     UintTy,
40 };
41 use hir_def::{
42     expr::ExprId,
43     type_ref::{ConstScalar, Rawness},
44     TypeParamId,
45 };
46
47 use crate::{db::HirDatabase, display::HirDisplay, utils::generics};
48
49 pub use autoderef::autoderef;
50 pub use builder::TyBuilder;
51 pub use chalk_ext::*;
52 pub use infer::{could_unify, InferenceResult};
53 pub use interner::Interner;
54 pub use lower::{
55     associated_type_shorthand_candidates, callable_item_sig, CallableDefId, ImplTraitLoweringMode,
56     TyDefId, TyLoweringContext, ValueTyDefId,
57 };
58 pub use mapping::{
59     const_from_placeholder_idx, from_assoc_type_id, from_chalk_trait_id, from_foreign_def_id,
60     from_placeholder_idx, lt_from_placeholder_idx, to_assoc_type_id, to_chalk_trait_id,
61     to_foreign_def_id, to_placeholder_idx,
62 };
63 pub use traits::TraitEnvironment;
64 pub use utils::all_super_traits;
65 pub use walk::TypeWalk;
66
67 pub use chalk_ir::{
68     cast::Cast, AdtId, BoundVar, DebruijnIndex, Mutability, Safety, Scalar, TyVariableKind,
69 };
70
71 pub type ForeignDefId = chalk_ir::ForeignDefId<Interner>;
72 pub type AssocTypeId = chalk_ir::AssocTypeId<Interner>;
73 pub type FnDefId = chalk_ir::FnDefId<Interner>;
74 pub type ClosureId = chalk_ir::ClosureId<Interner>;
75 pub type OpaqueTyId = chalk_ir::OpaqueTyId<Interner>;
76 pub type PlaceholderIndex = chalk_ir::PlaceholderIndex;
77
78 pub type VariableKind = chalk_ir::VariableKind<Interner>;
79 pub type VariableKinds = chalk_ir::VariableKinds<Interner>;
80 pub type CanonicalVarKinds = chalk_ir::CanonicalVarKinds<Interner>;
81 pub type Binders<T> = chalk_ir::Binders<T>;
82 pub type Substitution = chalk_ir::Substitution<Interner>;
83 pub type GenericArg = chalk_ir::GenericArg<Interner>;
84 pub type GenericArgData = chalk_ir::GenericArgData<Interner>;
85
86 pub type Ty = chalk_ir::Ty<Interner>;
87 pub type TyKind = chalk_ir::TyKind<Interner>;
88 pub type DynTy = chalk_ir::DynTy<Interner>;
89 pub type FnPointer = chalk_ir::FnPointer<Interner>;
90 // pub type FnSubst = chalk_ir::FnSubst<Interner>;
91 pub use chalk_ir::FnSubst;
92 pub type ProjectionTy = chalk_ir::ProjectionTy<Interner>;
93 pub type AliasTy = chalk_ir::AliasTy<Interner>;
94 pub type OpaqueTy = chalk_ir::OpaqueTy<Interner>;
95 pub type InferenceVar = chalk_ir::InferenceVar;
96
97 pub type Lifetime = chalk_ir::Lifetime<Interner>;
98 pub type LifetimeData = chalk_ir::LifetimeData<Interner>;
99 pub type LifetimeOutlives = chalk_ir::LifetimeOutlives<Interner>;
100
101 pub type Const = chalk_ir::Const<Interner>;
102 pub type ConstData = chalk_ir::ConstData<Interner>;
103 pub type ConstValue = chalk_ir::ConstValue<Interner>;
104 pub type ConcreteConst = chalk_ir::ConcreteConst<Interner>;
105
106 pub type ChalkTraitId = chalk_ir::TraitId<Interner>;
107 pub type TraitRef = chalk_ir::TraitRef<Interner>;
108 pub type QuantifiedWhereClause = Binders<WhereClause>;
109 pub type QuantifiedWhereClauses = chalk_ir::QuantifiedWhereClauses<Interner>;
110 pub type Canonical<T> = chalk_ir::Canonical<T>;
111
112 pub type FnSig = chalk_ir::FnSig<Interner>;
113
114 pub type InEnvironment<T> = chalk_ir::InEnvironment<T>;
115 pub type DomainGoal = chalk_ir::DomainGoal<Interner>;
116 pub type AliasEq = chalk_ir::AliasEq<Interner>;
117 pub type Solution = chalk_solve::Solution<Interner>;
118 pub type ConstrainedSubst = chalk_ir::ConstrainedSubst<Interner>;
119 pub type Guidance = chalk_solve::Guidance<Interner>;
120 pub type WhereClause = chalk_ir::WhereClause<Interner>;
121
122 // FIXME: get rid of this
123 pub fn subst_prefix(s: &Substitution, n: usize) -> Substitution {
124     Substitution::from_iter(
125         &Interner,
126         s.as_slice(&Interner)[..std::cmp::min(s.len(&Interner), n)].iter().cloned(),
127     )
128 }
129
130 /// Return an index of a parameter in the generic type parameter list by it's id.
131 pub fn param_idx(db: &dyn HirDatabase, id: TypeParamId) -> Option<usize> {
132     generics(db.upcast(), id.parent).param_idx(id)
133 }
134
135 pub(crate) fn wrap_empty_binders<T>(value: T) -> Binders<T>
136 where
137     T: Fold<Interner, Result = T> + HasInterner<Interner = Interner>,
138 {
139     Binders::empty(&Interner, value.shifted_in_from(&Interner, DebruijnIndex::ONE))
140 }
141
142 pub(crate) fn make_only_type_binders<T: HasInterner<Interner = Interner>>(
143     num_vars: usize,
144     value: T,
145 ) -> Binders<T> {
146     Binders::new(
147         VariableKinds::from_iter(
148             &Interner,
149             std::iter::repeat(chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General))
150                 .take(num_vars),
151         ),
152         value,
153     )
154 }
155
156 // FIXME: get rid of this
157 pub fn make_canonical<T: HasInterner<Interner = Interner>>(
158     value: T,
159     kinds: impl IntoIterator<Item = TyVariableKind>,
160 ) -> Canonical<T> {
161     let kinds = kinds.into_iter().map(|tk| {
162         chalk_ir::CanonicalVarKind::new(
163             chalk_ir::VariableKind::Ty(tk),
164             chalk_ir::UniverseIndex::ROOT,
165         )
166     });
167     Canonical { value, binders: chalk_ir::CanonicalVarKinds::from_iter(&Interner, kinds) }
168 }
169
170 /// A function signature as seen by type inference: Several parameter types and
171 /// one return type.
172 #[derive(Clone, PartialEq, Eq, Debug)]
173 pub struct CallableSig {
174     params_and_return: Arc<[Ty]>,
175     is_varargs: bool,
176 }
177
178 has_interner!(CallableSig);
179
180 /// A polymorphic function signature.
181 pub type PolyFnSig = Binders<CallableSig>;
182
183 impl CallableSig {
184     pub fn from_params_and_return(mut params: Vec<Ty>, ret: Ty, is_varargs: bool) -> CallableSig {
185         params.push(ret);
186         CallableSig { params_and_return: params.into(), is_varargs }
187     }
188
189     pub fn from_fn_ptr(fn_ptr: &FnPointer) -> CallableSig {
190         CallableSig {
191             // FIXME: what to do about lifetime params? -> return PolyFnSig
192             params_and_return: fn_ptr
193                 .substitution
194                 .clone()
195                 .shifted_out_to(&Interner, DebruijnIndex::ONE)
196                 .expect("unexpected lifetime vars in fn ptr")
197                 .0
198                 .as_slice(&Interner)
199                 .iter()
200                 .map(|arg| arg.assert_ty_ref(&Interner).clone())
201                 .collect(),
202             is_varargs: fn_ptr.sig.variadic,
203         }
204     }
205
206     pub fn params(&self) -> &[Ty] {
207         &self.params_and_return[0..self.params_and_return.len() - 1]
208     }
209
210     pub fn ret(&self) -> &Ty {
211         &self.params_and_return[self.params_and_return.len() - 1]
212     }
213 }
214
215 impl Fold<Interner> for CallableSig {
216     type Result = CallableSig;
217
218     fn fold_with<'i>(
219         self,
220         folder: &mut dyn chalk_ir::fold::Folder<'i, Interner>,
221         outer_binder: DebruijnIndex,
222     ) -> chalk_ir::Fallible<Self::Result>
223     where
224         Interner: 'i,
225     {
226         let vec = self.params_and_return.to_vec();
227         let folded = vec.fold_with(folder, outer_binder)?;
228         Ok(CallableSig { params_and_return: folded.into(), is_varargs: self.is_varargs })
229     }
230 }
231
232 #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
233 pub enum ImplTraitId {
234     ReturnTypeImplTrait(hir_def::FunctionId, u16),
235     AsyncBlockTypeImplTrait(hir_def::DefWithBodyId, ExprId),
236 }
237
238 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
239 pub struct ReturnTypeImplTraits {
240     pub(crate) impl_traits: Vec<ReturnTypeImplTrait>,
241 }
242
243 has_interner!(ReturnTypeImplTraits);
244
245 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
246 pub(crate) struct ReturnTypeImplTrait {
247     pub(crate) bounds: Binders<Vec<QuantifiedWhereClause>>,
248 }
249
250 pub fn static_lifetime() -> Lifetime {
251     LifetimeData::Static.intern(&Interner)
252 }
253
254 pub fn dummy_usize_const() -> Const {
255     let usize_ty = chalk_ir::TyKind::Scalar(Scalar::Uint(UintTy::Usize)).intern(&Interner);
256     chalk_ir::ConstData {
257         ty: usize_ty,
258         value: chalk_ir::ConstValue::Concrete(chalk_ir::ConcreteConst {
259             interned: ConstScalar::Unknown,
260         }),
261     }
262     .intern(&Interner)
263 }
264
265 pub(crate) fn fold_free_vars<T: HasInterner<Interner = Interner> + Fold<Interner>>(
266     t: T,
267     f: impl FnMut(BoundVar, DebruijnIndex) -> Ty,
268 ) -> T::Result {
269     use chalk_ir::{fold::Folder, Fallible};
270     struct FreeVarFolder<F>(F);
271     impl<'i, F: FnMut(BoundVar, DebruijnIndex) -> Ty + 'i> Folder<'i, Interner> for FreeVarFolder<F> {
272         fn as_dyn(&mut self) -> &mut dyn Folder<'i, Interner> {
273             self
274         }
275
276         fn interner(&self) -> &'i Interner {
277             &Interner
278         }
279
280         fn fold_free_var_ty(
281             &mut self,
282             bound_var: BoundVar,
283             outer_binder: DebruijnIndex,
284         ) -> Fallible<Ty> {
285             Ok(self.0(bound_var, outer_binder))
286         }
287     }
288     t.fold_with(&mut FreeVarFolder(f), DebruijnIndex::INNERMOST).expect("fold failed unexpectedly")
289 }
290
291 pub(crate) fn fold_tys<T: HasInterner<Interner = Interner> + Fold<Interner>>(
292     t: T,
293     f: impl FnMut(Ty, DebruijnIndex) -> Ty,
294     binders: DebruijnIndex,
295 ) -> T::Result {
296     use chalk_ir::{
297         fold::{Folder, SuperFold},
298         Fallible,
299     };
300     struct TyFolder<F>(F);
301     impl<'i, F: FnMut(Ty, DebruijnIndex) -> Ty + 'i> Folder<'i, Interner> for TyFolder<F> {
302         fn as_dyn(&mut self) -> &mut dyn Folder<'i, Interner> {
303             self
304         }
305
306         fn interner(&self) -> &'i Interner {
307             &Interner
308         }
309
310         fn fold_ty(&mut self, ty: Ty, outer_binder: DebruijnIndex) -> Fallible<Ty> {
311             let ty = ty.super_fold_with(self.as_dyn(), outer_binder)?;
312             Ok(self.0(ty, outer_binder))
313         }
314     }
315     t.fold_with(&mut TyFolder(f), binders).expect("fold failed unexpectedly")
316 }