]> git.lizzy.rs Git - rust.git/blob - crates/hir_ty/src/lib.rs
clippy::redundant_closure
[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, utils::generics};
48
49 pub use autoderef::autoderef;
50 pub use builder::TyBuilder;
51 pub use chalk_ext::*;
52 pub use infer::{could_unify, InferenceDiagnostic, 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 Goal = chalk_ir::Goal<Interner>;
117 pub type AliasEq = chalk_ir::AliasEq<Interner>;
118 pub type Solution = chalk_solve::Solution<Interner>;
119 pub type ConstrainedSubst = chalk_ir::ConstrainedSubst<Interner>;
120 pub type Guidance = chalk_solve::Guidance<Interner>;
121 pub type WhereClause = chalk_ir::WhereClause<Interner>;
122
123 // FIXME: get rid of this
124 pub fn subst_prefix(s: &Substitution, n: usize) -> Substitution {
125     Substitution::from_iter(
126         &Interner,
127         s.as_slice(&Interner)[..std::cmp::min(s.len(&Interner), n)].iter().cloned(),
128     )
129 }
130
131 /// Return an index of a parameter in the generic type parameter list by it's id.
132 pub fn param_idx(db: &dyn HirDatabase, id: TypeParamId) -> Option<usize> {
133     generics(db.upcast(), id.parent).param_idx(id)
134 }
135
136 pub(crate) fn wrap_empty_binders<T>(value: T) -> Binders<T>
137 where
138     T: Fold<Interner, Result = T> + HasInterner<Interner = Interner>,
139 {
140     Binders::empty(&Interner, value.shifted_in_from(&Interner, DebruijnIndex::ONE))
141 }
142
143 pub(crate) fn make_only_type_binders<T: HasInterner<Interner = Interner>>(
144     num_vars: usize,
145     value: T,
146 ) -> Binders<T> {
147     Binders::new(
148         VariableKinds::from_iter(
149             &Interner,
150             std::iter::repeat(chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General))
151                 .take(num_vars),
152         ),
153         value,
154     )
155 }
156
157 // FIXME: get rid of this
158 pub fn make_canonical<T: HasInterner<Interner = Interner>>(
159     value: T,
160     kinds: impl IntoIterator<Item = TyVariableKind>,
161 ) -> Canonical<T> {
162     let kinds = kinds.into_iter().map(|tk| {
163         chalk_ir::CanonicalVarKind::new(
164             chalk_ir::VariableKind::Ty(tk),
165             chalk_ir::UniverseIndex::ROOT,
166         )
167     });
168     Canonical { value, binders: chalk_ir::CanonicalVarKinds::from_iter(&Interner, kinds) }
169 }
170
171 // FIXME: get rid of this, just replace it by FnPointer
172 /// A function signature as seen by type inference: Several parameter types and
173 /// one return type.
174 #[derive(Clone, PartialEq, Eq, Debug)]
175 pub struct CallableSig {
176     params_and_return: Arc<[Ty]>,
177     is_varargs: bool,
178 }
179
180 has_interner!(CallableSig);
181
182 /// A polymorphic function signature.
183 pub type PolyFnSig = Binders<CallableSig>;
184
185 impl CallableSig {
186     pub fn from_params_and_return(mut params: Vec<Ty>, ret: Ty, is_varargs: bool) -> CallableSig {
187         params.push(ret);
188         CallableSig { params_and_return: params.into(), is_varargs }
189     }
190
191     pub fn from_fn_ptr(fn_ptr: &FnPointer) -> CallableSig {
192         CallableSig {
193             // FIXME: what to do about lifetime params? -> return PolyFnSig
194             params_and_return: fn_ptr
195                 .substitution
196                 .clone()
197                 .shifted_out_to(&Interner, DebruijnIndex::ONE)
198                 .expect("unexpected lifetime vars in fn ptr")
199                 .0
200                 .as_slice(&Interner)
201                 .iter()
202                 .map(|arg| arg.assert_ty_ref(&Interner).clone())
203                 .collect(),
204             is_varargs: fn_ptr.sig.variadic,
205         }
206     }
207
208     pub fn to_fn_ptr(&self) -> FnPointer {
209         FnPointer {
210             num_binders: 0,
211             sig: FnSig { abi: (), safety: Safety::Safe, variadic: self.is_varargs },
212             substitution: FnSubst(Substitution::from_iter(
213                 &Interner,
214                 self.params_and_return.iter().cloned(),
215             )),
216         }
217     }
218
219     pub fn params(&self) -> &[Ty] {
220         &self.params_and_return[0..self.params_and_return.len() - 1]
221     }
222
223     pub fn ret(&self) -> &Ty {
224         &self.params_and_return[self.params_and_return.len() - 1]
225     }
226 }
227
228 impl Fold<Interner> for CallableSig {
229     type Result = CallableSig;
230
231     fn fold_with<'i>(
232         self,
233         folder: &mut dyn chalk_ir::fold::Folder<'i, Interner>,
234         outer_binder: DebruijnIndex,
235     ) -> chalk_ir::Fallible<Self::Result>
236     where
237         Interner: 'i,
238     {
239         let vec = self.params_and_return.to_vec();
240         let folded = vec.fold_with(folder, outer_binder)?;
241         Ok(CallableSig { params_and_return: folded.into(), is_varargs: self.is_varargs })
242     }
243 }
244
245 #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
246 pub enum ImplTraitId {
247     ReturnTypeImplTrait(hir_def::FunctionId, u16),
248     AsyncBlockTypeImplTrait(hir_def::DefWithBodyId, ExprId),
249 }
250
251 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
252 pub struct ReturnTypeImplTraits {
253     pub(crate) impl_traits: Vec<ReturnTypeImplTrait>,
254 }
255
256 has_interner!(ReturnTypeImplTraits);
257
258 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
259 pub(crate) struct ReturnTypeImplTrait {
260     pub(crate) bounds: Binders<Vec<QuantifiedWhereClause>>,
261 }
262
263 pub fn static_lifetime() -> Lifetime {
264     LifetimeData::Static.intern(&Interner)
265 }
266
267 pub fn dummy_usize_const() -> Const {
268     let usize_ty = chalk_ir::TyKind::Scalar(Scalar::Uint(UintTy::Usize)).intern(&Interner);
269     chalk_ir::ConstData {
270         ty: usize_ty,
271         value: chalk_ir::ConstValue::Concrete(chalk_ir::ConcreteConst {
272             interned: ConstScalar::Unknown,
273         }),
274     }
275     .intern(&Interner)
276 }
277
278 pub(crate) fn fold_free_vars<T: HasInterner<Interner = Interner> + Fold<Interner>>(
279     t: T,
280     f: impl FnMut(BoundVar, DebruijnIndex) -> Ty,
281 ) -> T::Result {
282     use chalk_ir::{fold::Folder, Fallible};
283     struct FreeVarFolder<F>(F);
284     impl<'i, F: FnMut(BoundVar, DebruijnIndex) -> Ty + 'i> Folder<'i, Interner> for FreeVarFolder<F> {
285         fn as_dyn(&mut self) -> &mut dyn Folder<'i, Interner> {
286             self
287         }
288
289         fn interner(&self) -> &'i Interner {
290             &Interner
291         }
292
293         fn fold_free_var_ty(
294             &mut self,
295             bound_var: BoundVar,
296             outer_binder: DebruijnIndex,
297         ) -> Fallible<Ty> {
298             Ok(self.0(bound_var, outer_binder))
299         }
300     }
301     t.fold_with(&mut FreeVarFolder(f), DebruijnIndex::INNERMOST).expect("fold failed unexpectedly")
302 }
303
304 pub(crate) fn fold_tys<T: HasInterner<Interner = Interner> + Fold<Interner>>(
305     t: T,
306     f: impl FnMut(Ty, DebruijnIndex) -> Ty,
307     binders: DebruijnIndex,
308 ) -> T::Result {
309     use chalk_ir::{
310         fold::{Folder, SuperFold},
311         Fallible,
312     };
313     struct TyFolder<F>(F);
314     impl<'i, F: FnMut(Ty, DebruijnIndex) -> Ty + 'i> Folder<'i, Interner> for TyFolder<F> {
315         fn as_dyn(&mut self) -> &mut dyn Folder<'i, Interner> {
316             self
317         }
318
319         fn interner(&self) -> &'i Interner {
320             &Interner
321         }
322
323         fn fold_ty(&mut self, ty: Ty, outer_binder: DebruijnIndex) -> Fallible<Ty> {
324             let ty = ty.super_fold_with(self.as_dyn(), outer_binder)?;
325             Ok(self.0(ty, outer_binder))
326         }
327     }
328     t.fold_with(&mut TyFolder(f), binders).expect("fold failed unexpectedly")
329 }
330
331 /// 'Canonicalizes' the `t` by replacing any errors with new variables. Also
332 /// ensures there are no unbound variables or inference variables anywhere in
333 /// the `t`.
334 pub fn replace_errors_with_variables<T>(t: &T) -> Canonical<T::Result>
335 where
336     T: HasInterner<Interner = Interner> + Fold<Interner> + Clone,
337     T::Result: HasInterner<Interner = Interner>,
338 {
339     use chalk_ir::{
340         fold::{Folder, SuperFold},
341         Fallible, NoSolution,
342     };
343     struct ErrorReplacer {
344         vars: usize,
345     }
346     impl<'i> Folder<'i, Interner> for ErrorReplacer {
347         fn as_dyn(&mut self) -> &mut dyn Folder<'i, Interner> {
348             self
349         }
350
351         fn interner(&self) -> &'i Interner {
352             &Interner
353         }
354
355         fn fold_ty(&mut self, ty: Ty, outer_binder: DebruijnIndex) -> Fallible<Ty> {
356             if let TyKind::Error = ty.kind(&Interner) {
357                 let index = self.vars;
358                 self.vars += 1;
359                 Ok(TyKind::BoundVar(BoundVar::new(outer_binder, index)).intern(&Interner))
360             } else {
361                 let ty = ty.super_fold_with(self.as_dyn(), outer_binder)?;
362                 Ok(ty)
363             }
364         }
365
366         fn fold_inference_ty(
367             &mut self,
368             _var: InferenceVar,
369             _kind: TyVariableKind,
370             _outer_binder: DebruijnIndex,
371         ) -> Fallible<Ty> {
372             if cfg!(debug_assertions) {
373                 // we don't want to just panic here, because then the error message
374                 // won't contain the whole thing, which would not be very helpful
375                 Err(NoSolution)
376             } else {
377                 Ok(TyKind::Error.intern(&Interner))
378             }
379         }
380
381         fn fold_free_var_ty(
382             &mut self,
383             _bound_var: BoundVar,
384             _outer_binder: DebruijnIndex,
385         ) -> Fallible<Ty> {
386             if cfg!(debug_assertions) {
387                 // we don't want to just panic here, because then the error message
388                 // won't contain the whole thing, which would not be very helpful
389                 Err(NoSolution)
390             } else {
391                 Ok(TyKind::Error.intern(&Interner))
392             }
393         }
394
395         fn fold_inference_const(
396             &mut self,
397             _ty: Ty,
398             _var: InferenceVar,
399             _outer_binder: DebruijnIndex,
400         ) -> Fallible<Const> {
401             if cfg!(debug_assertions) {
402                 Err(NoSolution)
403             } else {
404                 Ok(dummy_usize_const())
405             }
406         }
407
408         fn fold_free_var_const(
409             &mut self,
410             _ty: Ty,
411             _bound_var: BoundVar,
412             _outer_binder: DebruijnIndex,
413         ) -> Fallible<Const> {
414             if cfg!(debug_assertions) {
415                 Err(NoSolution)
416             } else {
417                 Ok(dummy_usize_const())
418             }
419         }
420
421         fn fold_inference_lifetime(
422             &mut self,
423             _var: InferenceVar,
424             _outer_binder: DebruijnIndex,
425         ) -> Fallible<Lifetime> {
426             if cfg!(debug_assertions) {
427                 Err(NoSolution)
428             } else {
429                 Ok(static_lifetime())
430             }
431         }
432
433         fn fold_free_var_lifetime(
434             &mut self,
435             _bound_var: BoundVar,
436             _outer_binder: DebruijnIndex,
437         ) -> Fallible<Lifetime> {
438             if cfg!(debug_assertions) {
439                 Err(NoSolution)
440             } else {
441                 Ok(static_lifetime())
442             }
443         }
444     }
445     let mut error_replacer = ErrorReplacer { vars: 0 };
446     let value = match t.clone().fold_with(&mut error_replacer, DebruijnIndex::INNERMOST) {
447         Ok(t) => t,
448         Err(_) => panic!("Encountered unbound or inference vars in {:?}", t),
449     };
450     let kinds = (0..error_replacer.vars).map(|_| {
451         chalk_ir::CanonicalVarKind::new(
452             chalk_ir::VariableKind::Ty(TyVariableKind::General),
453             chalk_ir::UniverseIndex::ROOT,
454         )
455     });
456     Canonical { value, binders: chalk_ir::CanonicalVarKinds::from_iter(&Interner, kinds) }
457 }