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]>,
178 legacy_const_generics_indices: Arc<[u32]>,
181 has_interner!(CallableSig);
183 /// A polymorphic function signature.
184 pub type PolyFnSig = Binders<CallableSig>;
187 pub fn from_params_and_return(mut params: Vec<Ty>, ret: Ty, is_varargs: bool) -> CallableSig {
190 params_and_return: params.into(),
192 legacy_const_generics_indices: Arc::new([]),
196 pub fn from_fn_ptr(fn_ptr: &FnPointer) -> CallableSig {
198 // FIXME: what to do about lifetime params? -> return PolyFnSig
199 params_and_return: fn_ptr
202 .shifted_out_to(Interner, DebruijnIndex::ONE)
203 .expect("unexpected lifetime vars in fn ptr")
207 .map(|arg| arg.assert_ty_ref(Interner).clone())
209 is_varargs: fn_ptr.sig.variadic,
210 legacy_const_generics_indices: Arc::new([]),
214 pub fn set_legacy_const_generics_indices(&mut self, indices: &[u32]) {
215 self.legacy_const_generics_indices = indices.into();
218 pub fn to_fn_ptr(&self) -> FnPointer {
221 sig: FnSig { abi: (), safety: Safety::Safe, variadic: self.is_varargs },
222 substitution: FnSubst(Substitution::from_iter(
224 self.params_and_return.iter().cloned(),
229 pub fn params(&self) -> &[Ty] {
230 &self.params_and_return[0..self.params_and_return.len() - 1]
233 pub fn ret(&self) -> &Ty {
234 &self.params_and_return[self.params_and_return.len() - 1]
238 impl Fold<Interner> for CallableSig {
239 type Result = CallableSig;
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)?;
249 params_and_return: folded.into(),
250 is_varargs: self.is_varargs,
251 legacy_const_generics_indices: self.legacy_const_generics_indices,
256 #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
257 pub enum ImplTraitId {
258 ReturnTypeImplTrait(hir_def::FunctionId, u16),
259 AsyncBlockTypeImplTrait(hir_def::DefWithBodyId, ExprId),
262 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
263 pub struct ReturnTypeImplTraits {
264 pub(crate) impl_traits: Vec<ReturnTypeImplTrait>,
267 has_interner!(ReturnTypeImplTraits);
269 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
270 pub(crate) struct ReturnTypeImplTrait {
271 pub(crate) bounds: Binders<Vec<QuantifiedWhereClause>>,
274 pub fn static_lifetime() -> Lifetime {
275 LifetimeData::Static.intern(Interner)
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 {
282 value: chalk_ir::ConstValue::Concrete(chalk_ir::ConcreteConst {
283 interned: ConstScalar::Unknown,
289 pub(crate) fn fold_free_vars<T: HasInterner<Interner = Interner> + Fold<Interner>>(
291 f: impl FnMut(BoundVar, DebruijnIndex) -> Ty,
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;
298 fn as_dyn(&mut self) -> &mut dyn Folder<Interner, Error = Self::Error> {
302 fn interner(&self) -> Interner {
309 outer_binder: DebruijnIndex,
311 Ok(self.0(bound_var, outer_binder))
314 t.fold_with(&mut FreeVarFolder(f), DebruijnIndex::INNERMOST).expect("fold failed unexpectedly")
317 pub(crate) fn fold_tys<T: HasInterner<Interner = Interner> + Fold<Interner>>(
319 f: impl FnMut(Ty, DebruijnIndex) -> Ty,
320 binders: DebruijnIndex,
323 fold::{Folder, SuperFold},
326 struct TyFolder<F>(F);
327 impl<'i, F: FnMut(Ty, DebruijnIndex) -> Ty + 'i> Folder<Interner> for TyFolder<F> {
328 type Error = NoSolution;
330 fn as_dyn(&mut self) -> &mut dyn Folder<Interner, Error = Self::Error> {
334 fn interner(&self) -> Interner {
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))
343 t.fold_with(&mut TyFolder(f), binders).expect("fold failed unexpectedly")
346 /// 'Canonicalizes' the `t` by replacing any errors with new variables. Also
347 /// ensures there are no unbound variables or inference variables anywhere in
349 pub fn replace_errors_with_variables<T>(t: &T) -> Canonical<T::Result>
351 T: HasInterner<Interner = Interner> + Fold<Interner> + Clone,
352 T::Result: HasInterner<Interner = Interner>,
355 fold::{Folder, SuperFold},
358 struct ErrorReplacer {
361 impl<'i> Folder<Interner> for ErrorReplacer {
362 type Error = NoSolution;
364 fn as_dyn(&mut self) -> &mut dyn Folder<Interner, Error = Self::Error> {
368 fn interner(&self) -> Interner {
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;
376 Ok(TyKind::BoundVar(BoundVar::new(outer_binder, index)).intern(Interner))
378 let ty = ty.super_fold_with(self.as_dyn(), outer_binder)?;
383 fn fold_inference_ty(
386 _kind: TyVariableKind,
387 _outer_binder: DebruijnIndex,
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
394 Ok(TyKind::Error.intern(Interner))
400 _bound_var: BoundVar,
401 _outer_binder: DebruijnIndex,
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
408 Ok(TyKind::Error.intern(Interner))
412 fn fold_inference_const(
416 _outer_binder: DebruijnIndex,
417 ) -> Fallible<Const> {
418 if cfg!(debug_assertions) {
421 Ok(dummy_usize_const())
425 fn fold_free_var_const(
428 _bound_var: BoundVar,
429 _outer_binder: DebruijnIndex,
430 ) -> Fallible<Const> {
431 if cfg!(debug_assertions) {
434 Ok(dummy_usize_const())
438 fn fold_inference_lifetime(
441 _outer_binder: DebruijnIndex,
442 ) -> Fallible<Lifetime> {
443 if cfg!(debug_assertions) {
446 Ok(static_lifetime())
450 fn fold_free_var_lifetime(
452 _bound_var: BoundVar,
453 _outer_binder: DebruijnIndex,
454 ) -> Fallible<Lifetime> {
455 if cfg!(debug_assertions) {
458 Ok(static_lifetime())
462 let mut error_replacer = ErrorReplacer { vars: 0 };
463 let value = match t.clone().fold_with(&mut error_replacer, DebruijnIndex::INNERMOST) {
465 Err(_) => panic!("Encountered unbound or inference vars in {:?}", t),
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,
473 Canonical { value, binders: chalk_ir::CanonicalVarKinds::from_iter(Interner, kinds) }