1 //! The type system. We currently use this to infer types for completion, hover
2 //! information and various assists.
5 macro_rules! eprintln {
6 ($($tt:tt)*) => { stdx::eprintln!($($tt)*) };
24 pub mod method_resolution;
37 interner::HasInterner,
42 type_ref::{ConstScalar, Rawness},
46 use crate::{db::HirDatabase, utils::generics};
48 pub use autoderef::autoderef;
49 pub use builder::TyBuilder;
51 pub use infer::{could_unify, InferenceDiagnostic, InferenceResult};
52 pub use interner::Interner;
54 associated_type_shorthand_candidates, callable_item_sig, CallableDefId, ImplTraitLoweringMode,
55 TyDefId, TyLoweringContext, ValueTyDefId,
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,
62 pub use traits::TraitEnvironment;
63 pub use utils::all_super_traits;
64 pub use walk::TypeWalk;
67 cast::Cast, AdtId, BoundVar, DebruijnIndex, Mutability, Safety, Scalar, TyVariableKind,
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;
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>;
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;
96 pub type Lifetime = chalk_ir::Lifetime<Interner>;
97 pub type LifetimeData = chalk_ir::LifetimeData<Interner>;
98 pub type LifetimeOutlives = chalk_ir::LifetimeOutlives<Interner>;
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>;
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>;
111 pub type FnSig = chalk_ir::FnSig<Interner>;
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>;
123 // FIXME: get rid of this
124 pub fn subst_prefix(s: &Substitution, n: usize) -> Substitution {
125 Substitution::from_iter(
127 s.as_slice(&Interner)[..std::cmp::min(s.len(&Interner), n)].iter().cloned(),
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)
136 pub(crate) fn wrap_empty_binders<T>(value: T) -> Binders<T>
138 T: Fold<Interner, Result = T> + HasInterner<Interner = Interner>,
140 Binders::empty(&Interner, value.shifted_in_from(&Interner, DebruijnIndex::ONE))
143 pub(crate) fn make_only_type_binders<T: HasInterner<Interner = Interner>>(
148 VariableKinds::from_iter(
150 std::iter::repeat(chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General))
157 // FIXME: get rid of this
158 pub fn make_canonical<T: HasInterner<Interner = Interner>>(
160 kinds: impl IntoIterator<Item = TyVariableKind>,
162 let kinds = kinds.into_iter().map(|tk| {
163 chalk_ir::CanonicalVarKind::new(
164 chalk_ir::VariableKind::Ty(tk),
165 chalk_ir::UniverseIndex::ROOT,
168 Canonical { value, binders: chalk_ir::CanonicalVarKinds::from_iter(&Interner, kinds) }
171 // FIXME: get rid of this, just replace it by FnPointer
172 /// A function signature as seen by type inference: Several parameter types and
174 #[derive(Clone, PartialEq, Eq, Debug)]
175 pub struct CallableSig {
176 params_and_return: Arc<[Ty]>,
180 has_interner!(CallableSig);
182 /// A polymorphic function signature.
183 pub type PolyFnSig = Binders<CallableSig>;
186 pub fn from_params_and_return(mut params: Vec<Ty>, ret: Ty, is_varargs: bool) -> CallableSig {
188 CallableSig { params_and_return: params.into(), is_varargs }
191 pub fn from_fn_ptr(fn_ptr: &FnPointer) -> CallableSig {
193 // FIXME: what to do about lifetime params? -> return PolyFnSig
194 params_and_return: fn_ptr
197 .shifted_out_to(&Interner, DebruijnIndex::ONE)
198 .expect("unexpected lifetime vars in fn ptr")
202 .map(|arg| arg.assert_ty_ref(&Interner).clone())
204 is_varargs: fn_ptr.sig.variadic,
208 pub fn to_fn_ptr(&self) -> FnPointer {
211 sig: FnSig { abi: (), safety: Safety::Safe, variadic: self.is_varargs },
212 substitution: FnSubst(Substitution::from_iter(
214 self.params_and_return.iter().cloned(),
219 pub fn params(&self) -> &[Ty] {
220 &self.params_and_return[0..self.params_and_return.len() - 1]
223 pub fn ret(&self) -> &Ty {
224 &self.params_and_return[self.params_and_return.len() - 1]
228 impl Fold<Interner> for CallableSig {
229 type Result = CallableSig;
233 folder: &mut dyn chalk_ir::fold::Folder<'i, Interner>,
234 outer_binder: DebruijnIndex,
235 ) -> chalk_ir::Fallible<Self::Result>
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 })
245 #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
246 pub enum ImplTraitId {
247 ReturnTypeImplTrait(hir_def::FunctionId, u16),
248 AsyncBlockTypeImplTrait(hir_def::DefWithBodyId, ExprId),
251 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
252 pub struct ReturnTypeImplTraits {
253 pub(crate) impl_traits: Vec<ReturnTypeImplTrait>,
256 has_interner!(ReturnTypeImplTraits);
258 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
259 pub(crate) struct ReturnTypeImplTrait {
260 pub(crate) bounds: Binders<Vec<QuantifiedWhereClause>>,
263 pub fn static_lifetime() -> Lifetime {
264 LifetimeData::Static.intern(&Interner)
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 {
271 value: chalk_ir::ConstValue::Concrete(chalk_ir::ConcreteConst {
272 interned: ConstScalar::Unknown,
278 pub(crate) fn fold_free_vars<T: HasInterner<Interner = Interner> + Fold<Interner>>(
280 f: impl FnMut(BoundVar, DebruijnIndex) -> Ty,
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> {
289 fn interner(&self) -> &'i Interner {
296 outer_binder: DebruijnIndex,
298 Ok(self.0(bound_var, outer_binder))
301 t.fold_with(&mut FreeVarFolder(f), DebruijnIndex::INNERMOST).expect("fold failed unexpectedly")
304 pub(crate) fn fold_tys<T: HasInterner<Interner = Interner> + Fold<Interner>>(
306 f: impl FnMut(Ty, DebruijnIndex) -> Ty,
307 binders: DebruijnIndex,
310 fold::{Folder, SuperFold},
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> {
319 fn interner(&self) -> &'i Interner {
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))
328 t.fold_with(&mut TyFolder(f), binders).expect("fold failed unexpectedly")
331 /// 'Canonicalizes' the `t` by replacing any errors with new variables. Also
332 /// ensures there are no unbound variables or inference variables anywhere in
334 pub fn replace_errors_with_variables<T>(t: &T) -> Canonical<T::Result>
336 T: HasInterner<Interner = Interner> + Fold<Interner> + Clone,
337 T::Result: HasInterner<Interner = Interner>,
340 fold::{Folder, SuperFold},
341 Fallible, NoSolution,
343 struct ErrorReplacer {
346 impl<'i> Folder<'i, Interner> for ErrorReplacer {
347 fn as_dyn(&mut self) -> &mut dyn Folder<'i, Interner> {
351 fn interner(&self) -> &'i Interner {
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;
359 Ok(TyKind::BoundVar(BoundVar::new(outer_binder, index)).intern(&Interner))
361 let ty = ty.super_fold_with(self.as_dyn(), outer_binder)?;
366 fn fold_inference_ty(
369 _kind: TyVariableKind,
370 _outer_binder: DebruijnIndex,
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
377 Ok(TyKind::Error.intern(&Interner))
383 _bound_var: BoundVar,
384 _outer_binder: DebruijnIndex,
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
391 Ok(TyKind::Error.intern(&Interner))
395 fn fold_inference_const(
399 _outer_binder: DebruijnIndex,
400 ) -> Fallible<Const> {
401 if cfg!(debug_assertions) {
404 Ok(dummy_usize_const())
408 fn fold_free_var_const(
411 _bound_var: BoundVar,
412 _outer_binder: DebruijnIndex,
413 ) -> Fallible<Const> {
414 if cfg!(debug_assertions) {
417 Ok(dummy_usize_const())
421 fn fold_inference_lifetime(
424 _outer_binder: DebruijnIndex,
425 ) -> Fallible<Lifetime> {
426 if cfg!(debug_assertions) {
429 Ok(static_lifetime())
433 fn fold_free_var_lifetime(
435 _bound_var: BoundVar,
436 _outer_binder: DebruijnIndex,
437 ) -> Fallible<Lifetime> {
438 if cfg!(debug_assertions) {
441 Ok(static_lifetime())
445 let mut error_replacer = ErrorReplacer { vars: 0 };
446 let value = match t.clone().fold_with(&mut error_replacer, DebruijnIndex::INNERMOST) {
448 Err(_) => panic!("Encountered unbound or inference vars in {:?}", t),
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,
456 Canonical { value, binders: chalk_ir::CanonicalVarKinds::from_iter(&Interner, kinds) }