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