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