]> git.lizzy.rs Git - rust.git/blob - crates/hir_ty/src/lib.rs
fix: `replace_qualified_name_with_use` does not use full item path for replacements
[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     legacy_const_generics_indices: Arc<[u32]>,
179 }
180
181 has_interner!(CallableSig);
182
183 /// A polymorphic function signature.
184 pub type PolyFnSig = Binders<CallableSig>;
185
186 impl CallableSig {
187     pub fn from_params_and_return(mut params: Vec<Ty>, ret: Ty, is_varargs: bool) -> CallableSig {
188         params.push(ret);
189         CallableSig {
190             params_and_return: params.into(),
191             is_varargs,
192             legacy_const_generics_indices: Arc::new([]),
193         }
194     }
195
196     pub fn from_fn_ptr(fn_ptr: &FnPointer) -> CallableSig {
197         CallableSig {
198             // FIXME: what to do about lifetime params? -> return PolyFnSig
199             params_and_return: fn_ptr
200                 .substitution
201                 .clone()
202                 .shifted_out_to(Interner, DebruijnIndex::ONE)
203                 .expect("unexpected lifetime vars in fn ptr")
204                 .0
205                 .as_slice(Interner)
206                 .iter()
207                 .map(|arg| arg.assert_ty_ref(Interner).clone())
208                 .collect(),
209             is_varargs: fn_ptr.sig.variadic,
210             legacy_const_generics_indices: Arc::new([]),
211         }
212     }
213
214     pub fn set_legacy_const_generics_indices(&mut self, indices: &[u32]) {
215         self.legacy_const_generics_indices = indices.into();
216     }
217
218     pub fn to_fn_ptr(&self) -> FnPointer {
219         FnPointer {
220             num_binders: 0,
221             sig: FnSig { abi: (), safety: Safety::Safe, variadic: self.is_varargs },
222             substitution: FnSubst(Substitution::from_iter(
223                 Interner,
224                 self.params_and_return.iter().cloned(),
225             )),
226         }
227     }
228
229     pub fn params(&self) -> &[Ty] {
230         &self.params_and_return[0..self.params_and_return.len() - 1]
231     }
232
233     pub fn ret(&self) -> &Ty {
234         &self.params_and_return[self.params_and_return.len() - 1]
235     }
236 }
237
238 impl Fold<Interner> for CallableSig {
239     type Result = CallableSig;
240
241     fn fold_with<E>(
242         self,
243         folder: &mut dyn chalk_ir::fold::Folder<Interner, Error = E>,
244         outer_binder: DebruijnIndex,
245     ) -> Result<Self::Result, E> {
246         let vec = self.params_and_return.to_vec();
247         let folded = vec.fold_with(folder, outer_binder)?;
248         Ok(CallableSig {
249             params_and_return: folded.into(),
250             is_varargs: self.is_varargs,
251             legacy_const_generics_indices: self.legacy_const_generics_indices,
252         })
253     }
254 }
255
256 #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
257 pub enum ImplTraitId {
258     ReturnTypeImplTrait(hir_def::FunctionId, u16),
259     AsyncBlockTypeImplTrait(hir_def::DefWithBodyId, ExprId),
260 }
261
262 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
263 pub struct ReturnTypeImplTraits {
264     pub(crate) impl_traits: Vec<ReturnTypeImplTrait>,
265 }
266
267 has_interner!(ReturnTypeImplTraits);
268
269 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
270 pub(crate) struct ReturnTypeImplTrait {
271     pub(crate) bounds: Binders<Vec<QuantifiedWhereClause>>,
272 }
273
274 pub fn static_lifetime() -> Lifetime {
275     LifetimeData::Static.intern(Interner)
276 }
277
278 pub fn dummy_usize_const() -> Const {
279     let usize_ty = chalk_ir::TyKind::Scalar(Scalar::Uint(UintTy::Usize)).intern(Interner);
280     chalk_ir::ConstData {
281         ty: usize_ty,
282         value: chalk_ir::ConstValue::Concrete(chalk_ir::ConcreteConst {
283             interned: ConstScalar::Unknown,
284         }),
285     }
286     .intern(Interner)
287 }
288
289 pub(crate) fn fold_free_vars<T: HasInterner<Interner = Interner> + Fold<Interner>>(
290     t: T,
291     f: impl FnMut(BoundVar, DebruijnIndex) -> Ty,
292 ) -> T::Result {
293     use chalk_ir::{fold::Folder, Fallible};
294     struct FreeVarFolder<F>(F);
295     impl<'i, F: FnMut(BoundVar, DebruijnIndex) -> Ty + 'i> Folder<Interner> for FreeVarFolder<F> {
296         type Error = NoSolution;
297
298         fn as_dyn(&mut self) -> &mut dyn Folder<Interner, Error = Self::Error> {
299             self
300         }
301
302         fn interner(&self) -> Interner {
303             Interner
304         }
305
306         fn fold_free_var_ty(
307             &mut self,
308             bound_var: BoundVar,
309             outer_binder: DebruijnIndex,
310         ) -> Fallible<Ty> {
311             Ok(self.0(bound_var, outer_binder))
312         }
313     }
314     t.fold_with(&mut FreeVarFolder(f), DebruijnIndex::INNERMOST).expect("fold failed unexpectedly")
315 }
316
317 pub(crate) fn fold_tys<T: HasInterner<Interner = Interner> + Fold<Interner>>(
318     t: T,
319     f: impl FnMut(Ty, DebruijnIndex) -> Ty,
320     binders: DebruijnIndex,
321 ) -> T::Result {
322     use chalk_ir::{
323         fold::{Folder, SuperFold},
324         Fallible,
325     };
326     struct TyFolder<F>(F);
327     impl<'i, F: FnMut(Ty, DebruijnIndex) -> Ty + 'i> Folder<Interner> for TyFolder<F> {
328         type Error = NoSolution;
329
330         fn as_dyn(&mut self) -> &mut dyn Folder<Interner, Error = Self::Error> {
331             self
332         }
333
334         fn interner(&self) -> Interner {
335             Interner
336         }
337
338         fn fold_ty(&mut self, ty: Ty, outer_binder: DebruijnIndex) -> Fallible<Ty> {
339             let ty = ty.super_fold_with(self.as_dyn(), outer_binder)?;
340             Ok(self.0(ty, outer_binder))
341         }
342     }
343     t.fold_with(&mut TyFolder(f), binders).expect("fold failed unexpectedly")
344 }
345
346 /// 'Canonicalizes' the `t` by replacing any errors with new variables. Also
347 /// ensures there are no unbound variables or inference variables anywhere in
348 /// the `t`.
349 pub fn replace_errors_with_variables<T>(t: &T) -> Canonical<T::Result>
350 where
351     T: HasInterner<Interner = Interner> + Fold<Interner> + Clone,
352     T::Result: HasInterner<Interner = Interner>,
353 {
354     use chalk_ir::{
355         fold::{Folder, SuperFold},
356         Fallible,
357     };
358     struct ErrorReplacer {
359         vars: usize,
360     }
361     impl<'i> Folder<Interner> for ErrorReplacer {
362         type Error = NoSolution;
363
364         fn as_dyn(&mut self) -> &mut dyn Folder<Interner, Error = Self::Error> {
365             self
366         }
367
368         fn interner(&self) -> Interner {
369             Interner
370         }
371
372         fn fold_ty(&mut self, ty: Ty, outer_binder: DebruijnIndex) -> Fallible<Ty> {
373             if let TyKind::Error = ty.kind(Interner) {
374                 let index = self.vars;
375                 self.vars += 1;
376                 Ok(TyKind::BoundVar(BoundVar::new(outer_binder, index)).intern(Interner))
377             } else {
378                 let ty = ty.super_fold_with(self.as_dyn(), outer_binder)?;
379                 Ok(ty)
380             }
381         }
382
383         fn fold_inference_ty(
384             &mut self,
385             _var: InferenceVar,
386             _kind: TyVariableKind,
387             _outer_binder: DebruijnIndex,
388         ) -> Fallible<Ty> {
389             if cfg!(debug_assertions) {
390                 // we don't want to just panic here, because then the error message
391                 // won't contain the whole thing, which would not be very helpful
392                 Err(NoSolution)
393             } else {
394                 Ok(TyKind::Error.intern(Interner))
395             }
396         }
397
398         fn fold_free_var_ty(
399             &mut self,
400             _bound_var: BoundVar,
401             _outer_binder: DebruijnIndex,
402         ) -> Fallible<Ty> {
403             if cfg!(debug_assertions) {
404                 // we don't want to just panic here, because then the error message
405                 // won't contain the whole thing, which would not be very helpful
406                 Err(NoSolution)
407             } else {
408                 Ok(TyKind::Error.intern(Interner))
409             }
410         }
411
412         fn fold_inference_const(
413             &mut self,
414             _ty: Ty,
415             _var: InferenceVar,
416             _outer_binder: DebruijnIndex,
417         ) -> Fallible<Const> {
418             if cfg!(debug_assertions) {
419                 Err(NoSolution)
420             } else {
421                 Ok(dummy_usize_const())
422             }
423         }
424
425         fn fold_free_var_const(
426             &mut self,
427             _ty: Ty,
428             _bound_var: BoundVar,
429             _outer_binder: DebruijnIndex,
430         ) -> Fallible<Const> {
431             if cfg!(debug_assertions) {
432                 Err(NoSolution)
433             } else {
434                 Ok(dummy_usize_const())
435             }
436         }
437
438         fn fold_inference_lifetime(
439             &mut self,
440             _var: InferenceVar,
441             _outer_binder: DebruijnIndex,
442         ) -> Fallible<Lifetime> {
443             if cfg!(debug_assertions) {
444                 Err(NoSolution)
445             } else {
446                 Ok(static_lifetime())
447             }
448         }
449
450         fn fold_free_var_lifetime(
451             &mut self,
452             _bound_var: BoundVar,
453             _outer_binder: DebruijnIndex,
454         ) -> Fallible<Lifetime> {
455             if cfg!(debug_assertions) {
456                 Err(NoSolution)
457             } else {
458                 Ok(static_lifetime())
459             }
460         }
461     }
462     let mut error_replacer = ErrorReplacer { vars: 0 };
463     let value = match t.clone().fold_with(&mut error_replacer, DebruijnIndex::INNERMOST) {
464         Ok(t) => t,
465         Err(_) => panic!("Encountered unbound or inference vars in {:?}", t),
466     };
467     let kinds = (0..error_replacer.vars).map(|_| {
468         chalk_ir::CanonicalVarKind::new(
469             chalk_ir::VariableKind::Ty(TyVariableKind::General),
470             chalk_ir::UniverseIndex::ROOT,
471         )
472     });
473     Canonical { value, binders: chalk_ir::CanonicalVarKinds::from_iter(Interner, kinds) }
474 }