]> git.lizzy.rs Git - rust.git/blob - crates/hir_ty/src/lib.rs
320b170ee40f7cca139e2b4a084c01e443a06aa9
[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 tls;
19 mod utils;
20 mod walk;
21 pub mod db;
22 pub mod diagnostics;
23 pub mod display;
24 pub mod method_resolution;
25 pub mod primitive;
26 pub mod traits;
27
28 #[cfg(test)]
29 mod tests;
30 #[cfg(test)]
31 mod test_db;
32
33 use std::sync::Arc;
34
35 use chalk_ir::{
36     fold::{Fold, Shift},
37     interner::HasInterner,
38     NoSolution, UintTy,
39 };
40 use hir_def::{
41     expr::ExprId,
42     type_ref::{ConstScalar, Rawness},
43     TypeParamId,
44 };
45
46 use crate::{db::HirDatabase, utils::generics};
47
48 pub use autoderef::autoderef;
49 pub use builder::TyBuilder;
50 pub use chalk_ext::*;
51 pub use infer::{could_unify, InferenceDiagnostic, InferenceResult};
52 pub use interner::Interner;
53 pub use lower::{
54     associated_type_shorthand_candidates, callable_item_sig, CallableDefId, ImplTraitLoweringMode,
55     TyDefId, TyLoweringContext, ValueTyDefId,
56 };
57 pub use mapping::{
58     const_from_placeholder_idx, from_assoc_type_id, from_chalk_trait_id, from_foreign_def_id,
59     from_placeholder_idx, lt_from_placeholder_idx, to_assoc_type_id, to_chalk_trait_id,
60     to_foreign_def_id, to_placeholder_idx,
61 };
62 pub use traits::TraitEnvironment;
63 pub use utils::all_super_traits;
64 pub use walk::TypeWalk;
65
66 pub use chalk_ir::{
67     cast::Cast, AdtId, BoundVar, DebruijnIndex, Mutability, Safety, Scalar, TyVariableKind,
68 };
69
70 pub type ForeignDefId = chalk_ir::ForeignDefId<Interner>;
71 pub type AssocTypeId = chalk_ir::AssocTypeId<Interner>;
72 pub type FnDefId = chalk_ir::FnDefId<Interner>;
73 pub type ClosureId = chalk_ir::ClosureId<Interner>;
74 pub type OpaqueTyId = chalk_ir::OpaqueTyId<Interner>;
75 pub type PlaceholderIndex = chalk_ir::PlaceholderIndex;
76
77 pub type VariableKind = chalk_ir::VariableKind<Interner>;
78 pub type VariableKinds = chalk_ir::VariableKinds<Interner>;
79 pub type CanonicalVarKinds = chalk_ir::CanonicalVarKinds<Interner>;
80 pub type Binders<T> = chalk_ir::Binders<T>;
81 pub type Substitution = chalk_ir::Substitution<Interner>;
82 pub type GenericArg = chalk_ir::GenericArg<Interner>;
83 pub type GenericArgData = chalk_ir::GenericArgData<Interner>;
84
85 pub type Ty = chalk_ir::Ty<Interner>;
86 pub type TyKind = chalk_ir::TyKind<Interner>;
87 pub type DynTy = chalk_ir::DynTy<Interner>;
88 pub type FnPointer = chalk_ir::FnPointer<Interner>;
89 // pub type FnSubst = chalk_ir::FnSubst<Interner>;
90 pub use chalk_ir::FnSubst;
91 pub type ProjectionTy = chalk_ir::ProjectionTy<Interner>;
92 pub type AliasTy = chalk_ir::AliasTy<Interner>;
93 pub type OpaqueTy = chalk_ir::OpaqueTy<Interner>;
94 pub type InferenceVar = chalk_ir::InferenceVar;
95
96 pub type Lifetime = chalk_ir::Lifetime<Interner>;
97 pub type LifetimeData = chalk_ir::LifetimeData<Interner>;
98 pub type LifetimeOutlives = chalk_ir::LifetimeOutlives<Interner>;
99
100 pub type Const = chalk_ir::Const<Interner>;
101 pub type ConstData = chalk_ir::ConstData<Interner>;
102 pub type ConstValue = chalk_ir::ConstValue<Interner>;
103 pub type ConcreteConst = chalk_ir::ConcreteConst<Interner>;
104
105 pub type ChalkTraitId = chalk_ir::TraitId<Interner>;
106 pub type TraitRef = chalk_ir::TraitRef<Interner>;
107 pub type QuantifiedWhereClause = Binders<WhereClause>;
108 pub type QuantifiedWhereClauses = chalk_ir::QuantifiedWhereClauses<Interner>;
109 pub type Canonical<T> = chalk_ir::Canonical<T>;
110
111 pub type FnSig = chalk_ir::FnSig<Interner>;
112
113 pub type InEnvironment<T> = chalk_ir::InEnvironment<T>;
114 pub type Environment = chalk_ir::Environment<Interner>;
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, E>(
232         self,
233         folder: &mut dyn chalk_ir::fold::Folder<'i, Interner, Error = E>,
234         outer_binder: DebruijnIndex,
235     ) -> Result<Self::Result, E>
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         type Error = NoSolution;
286
287         fn as_dyn(&mut self) -> &mut dyn Folder<'i, Interner, Error = Self::Error> {
288             self
289         }
290
291         fn interner(&self) -> &'i Interner {
292             &Interner
293         }
294
295         fn fold_free_var_ty(
296             &mut self,
297             bound_var: BoundVar,
298             outer_binder: DebruijnIndex,
299         ) -> Fallible<Ty> {
300             Ok(self.0(bound_var, outer_binder))
301         }
302     }
303     t.fold_with(&mut FreeVarFolder(f), DebruijnIndex::INNERMOST).expect("fold failed unexpectedly")
304 }
305
306 pub(crate) fn fold_tys<T: HasInterner<Interner = Interner> + Fold<Interner>>(
307     t: T,
308     f: impl FnMut(Ty, DebruijnIndex) -> Ty,
309     binders: DebruijnIndex,
310 ) -> T::Result {
311     use chalk_ir::{
312         fold::{Folder, SuperFold},
313         Fallible,
314     };
315     struct TyFolder<F>(F);
316     impl<'i, F: FnMut(Ty, DebruijnIndex) -> Ty + 'i> Folder<'i, Interner> for TyFolder<F> {
317         type Error = NoSolution;
318
319         fn as_dyn(&mut self) -> &mut dyn Folder<'i, Interner, Error = Self::Error> {
320             self
321         }
322
323         fn interner(&self) -> &'i Interner {
324             &Interner
325         }
326
327         fn fold_ty(&mut self, ty: Ty, outer_binder: DebruijnIndex) -> Fallible<Ty> {
328             let ty = ty.super_fold_with(self.as_dyn(), outer_binder)?;
329             Ok(self.0(ty, outer_binder))
330         }
331     }
332     t.fold_with(&mut TyFolder(f), binders).expect("fold failed unexpectedly")
333 }
334
335 /// 'Canonicalizes' the `t` by replacing any errors with new variables. Also
336 /// ensures there are no unbound variables or inference variables anywhere in
337 /// the `t`.
338 pub fn replace_errors_with_variables<T>(t: &T) -> Canonical<T::Result>
339 where
340     T: HasInterner<Interner = Interner> + Fold<Interner> + Clone,
341     T::Result: HasInterner<Interner = Interner>,
342 {
343     use chalk_ir::{
344         fold::{Folder, SuperFold},
345         Fallible,
346     };
347     struct ErrorReplacer {
348         vars: usize,
349     }
350     impl<'i> Folder<'i, Interner> for ErrorReplacer {
351         type Error = NoSolution;
352
353         fn as_dyn(&mut self) -> &mut dyn Folder<'i, Interner, Error = Self::Error> {
354             self
355         }
356
357         fn interner(&self) -> &'i Interner {
358             &Interner
359         }
360
361         fn fold_ty(&mut self, ty: Ty, outer_binder: DebruijnIndex) -> Fallible<Ty> {
362             if let TyKind::Error = ty.kind(&Interner) {
363                 let index = self.vars;
364                 self.vars += 1;
365                 Ok(TyKind::BoundVar(BoundVar::new(outer_binder, index)).intern(&Interner))
366             } else {
367                 let ty = ty.super_fold_with(self.as_dyn(), outer_binder)?;
368                 Ok(ty)
369             }
370         }
371
372         fn fold_inference_ty(
373             &mut self,
374             _var: InferenceVar,
375             _kind: TyVariableKind,
376             _outer_binder: DebruijnIndex,
377         ) -> Fallible<Ty> {
378             if cfg!(debug_assertions) {
379                 // we don't want to just panic here, because then the error message
380                 // won't contain the whole thing, which would not be very helpful
381                 Err(NoSolution)
382             } else {
383                 Ok(TyKind::Error.intern(&Interner))
384             }
385         }
386
387         fn fold_free_var_ty(
388             &mut self,
389             _bound_var: BoundVar,
390             _outer_binder: DebruijnIndex,
391         ) -> Fallible<Ty> {
392             if cfg!(debug_assertions) {
393                 // we don't want to just panic here, because then the error message
394                 // won't contain the whole thing, which would not be very helpful
395                 Err(NoSolution)
396             } else {
397                 Ok(TyKind::Error.intern(&Interner))
398             }
399         }
400
401         fn fold_inference_const(
402             &mut self,
403             _ty: Ty,
404             _var: InferenceVar,
405             _outer_binder: DebruijnIndex,
406         ) -> Fallible<Const> {
407             if cfg!(debug_assertions) {
408                 Err(NoSolution)
409             } else {
410                 Ok(dummy_usize_const())
411             }
412         }
413
414         fn fold_free_var_const(
415             &mut self,
416             _ty: Ty,
417             _bound_var: BoundVar,
418             _outer_binder: DebruijnIndex,
419         ) -> Fallible<Const> {
420             if cfg!(debug_assertions) {
421                 Err(NoSolution)
422             } else {
423                 Ok(dummy_usize_const())
424             }
425         }
426
427         fn fold_inference_lifetime(
428             &mut self,
429             _var: InferenceVar,
430             _outer_binder: DebruijnIndex,
431         ) -> Fallible<Lifetime> {
432             if cfg!(debug_assertions) {
433                 Err(NoSolution)
434             } else {
435                 Ok(static_lifetime())
436             }
437         }
438
439         fn fold_free_var_lifetime(
440             &mut self,
441             _bound_var: BoundVar,
442             _outer_binder: DebruijnIndex,
443         ) -> Fallible<Lifetime> {
444             if cfg!(debug_assertions) {
445                 Err(NoSolution)
446             } else {
447                 Ok(static_lifetime())
448             }
449         }
450     }
451     let mut error_replacer = ErrorReplacer { vars: 0 };
452     let value = match t.clone().fold_with(&mut error_replacer, DebruijnIndex::INNERMOST) {
453         Ok(t) => t,
454         Err(_) => panic!("Encountered unbound or inference vars in {:?}", t),
455     };
456     let kinds = (0..error_replacer.vars).map(|_| {
457         chalk_ir::CanonicalVarKind::new(
458             chalk_ir::VariableKind::Ty(TyVariableKind::General),
459             chalk_ir::UniverseIndex::ROOT,
460         )
461     });
462     Canonical { value, binders: chalk_ir::CanonicalVarKinds::from_iter(&Interner, kinds) }
463 }