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)*) };
12 pub mod method_resolution;
36 interner::HasInterner,
40 expr::ExprId, type_ref::Rawness, ConstParamId, LifetimeParamId, TraitId, TypeAliasId,
44 use crate::{db::HirDatabase, display::HirDisplay, utils::generics};
46 pub use autoderef::autoderef;
47 pub use builder::TyBuilder;
49 pub use infer::{could_unify, InferenceResult};
51 associated_type_shorthand_candidates, callable_item_sig, CallableDefId, ImplTraitLoweringMode,
52 TyDefId, TyLoweringContext, ValueTyDefId,
54 pub use traits::{chalk::Interner, TraitEnvironment};
55 pub use walk::TypeWalk;
58 cast::Cast, AdtId, BoundVar, DebruijnIndex, Mutability, Safety, Scalar, TyVariableKind,
61 pub type ForeignDefId = chalk_ir::ForeignDefId<Interner>;
62 pub type AssocTypeId = chalk_ir::AssocTypeId<Interner>;
63 pub type FnDefId = chalk_ir::FnDefId<Interner>;
64 pub type ClosureId = chalk_ir::ClosureId<Interner>;
65 pub type OpaqueTyId = chalk_ir::OpaqueTyId<Interner>;
66 pub type PlaceholderIndex = chalk_ir::PlaceholderIndex;
68 pub type VariableKind = chalk_ir::VariableKind<Interner>;
69 pub type VariableKinds = chalk_ir::VariableKinds<Interner>;
70 pub type CanonicalVarKinds = chalk_ir::CanonicalVarKinds<Interner>;
71 pub type Binders<T> = chalk_ir::Binders<T>;
72 pub type Substitution = chalk_ir::Substitution<Interner>;
73 pub type GenericArg = chalk_ir::GenericArg<Interner>;
74 pub type GenericArgData = chalk_ir::GenericArgData<Interner>;
76 pub type Ty = chalk_ir::Ty<Interner>;
77 pub type TyKind = chalk_ir::TyKind<Interner>;
78 pub type DynTy = chalk_ir::DynTy<Interner>;
79 pub type FnPointer = chalk_ir::FnPointer<Interner>;
80 // pub type FnSubst = chalk_ir::FnSubst<Interner>;
81 pub use chalk_ir::FnSubst;
82 pub type ProjectionTy = chalk_ir::ProjectionTy<Interner>;
83 pub type AliasTy = chalk_ir::AliasTy<Interner>;
84 pub type OpaqueTy = chalk_ir::OpaqueTy<Interner>;
85 pub type InferenceVar = chalk_ir::InferenceVar;
87 pub type Lifetime = chalk_ir::Lifetime<Interner>;
88 pub type LifetimeData = chalk_ir::LifetimeData<Interner>;
89 pub type LifetimeOutlives = chalk_ir::LifetimeOutlives<Interner>;
91 pub type Const = chalk_ir::Const<Interner>;
92 pub type ConstData = chalk_ir::ConstData<Interner>;
93 pub type ConstValue = chalk_ir::ConstValue<Interner>;
94 pub type ConcreteConst = chalk_ir::ConcreteConst<Interner>;
96 pub type ChalkTraitId = chalk_ir::TraitId<Interner>;
98 pub type FnSig = chalk_ir::FnSig<Interner>;
100 pub type InEnvironment<T> = chalk_ir::InEnvironment<T>;
101 pub type DomainGoal = chalk_ir::DomainGoal<Interner>;
102 pub type AliasEq = chalk_ir::AliasEq<Interner>;
103 pub type Solution = chalk_solve::Solution<Interner>;
104 pub type ConstrainedSubst = chalk_ir::ConstrainedSubst<Interner>;
105 pub type Guidance = chalk_solve::Guidance<Interner>;
106 pub type WhereClause = chalk_ir::WhereClause<Interner>;
108 // FIXME: get rid of this
109 pub fn subst_prefix(s: &Substitution, n: usize) -> Substitution {
110 Substitution::from_iter(
112 s.interned()[..std::cmp::min(s.len(&Interner), n)].iter().cloned(),
116 /// Return an index of a parameter in the generic type parameter list by it's id.
117 pub fn param_idx(db: &dyn HirDatabase, id: TypeParamId) -> Option<usize> {
118 generics(db.upcast(), id.parent).param_idx(id)
121 pub fn wrap_empty_binders<T>(value: T) -> Binders<T>
123 T: Fold<Interner, Result = T> + HasInterner<Interner = Interner>,
125 Binders::empty(&Interner, value.shifted_in_from(&Interner, DebruijnIndex::ONE))
128 pub fn make_only_type_binders<T: HasInterner<Interner = Interner>>(
133 VariableKinds::from_iter(
135 std::iter::repeat(chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General))
142 // FIXME: get rid of this
143 pub fn make_canonical<T: HasInterner<Interner = Interner>>(
145 kinds: impl IntoIterator<Item = TyVariableKind>,
147 let kinds = kinds.into_iter().map(|tk| {
148 chalk_ir::CanonicalVarKind::new(
149 chalk_ir::VariableKind::Ty(tk),
150 chalk_ir::UniverseIndex::ROOT,
153 Canonical { value, binders: chalk_ir::CanonicalVarKinds::from_iter(&Interner, kinds) }
156 pub type TraitRef = chalk_ir::TraitRef<Interner>;
158 pub type QuantifiedWhereClause = Binders<WhereClause>;
160 pub type QuantifiedWhereClauses = chalk_ir::QuantifiedWhereClauses<Interner>;
162 pub type Canonical<T> = chalk_ir::Canonical<T>;
164 /// A function signature as seen by type inference: Several parameter types and
166 #[derive(Clone, PartialEq, Eq, Debug)]
167 pub struct CallableSig {
168 params_and_return: Arc<[Ty]>,
172 /// A polymorphic function signature.
173 pub type PolyFnSig = Binders<CallableSig>;
176 pub fn from_params_and_return(mut params: Vec<Ty>, ret: Ty, is_varargs: bool) -> CallableSig {
178 CallableSig { params_and_return: params.into(), is_varargs }
181 pub fn from_fn_ptr(fn_ptr: &FnPointer) -> CallableSig {
183 // FIXME: what to do about lifetime params? -> return PolyFnSig
184 params_and_return: fn_ptr
187 .shifted_out_to(&Interner, DebruijnIndex::ONE)
188 .expect("unexpected lifetime vars in fn ptr")
192 .map(|arg| arg.assert_ty_ref(&Interner).clone())
194 is_varargs: fn_ptr.sig.variadic,
198 pub fn params(&self) -> &[Ty] {
199 &self.params_and_return[0..self.params_and_return.len() - 1]
202 pub fn ret(&self) -> &Ty {
203 &self.params_and_return[self.params_and_return.len() - 1]
207 impl Fold<Interner> for CallableSig {
208 type Result = CallableSig;
212 folder: &mut dyn chalk_ir::fold::Folder<'i, Interner>,
213 outer_binder: DebruijnIndex,
214 ) -> chalk_ir::Fallible<Self::Result>
218 let vec = self.params_and_return.to_vec();
219 let folded = vec.fold_with(folder, outer_binder)?;
220 Ok(CallableSig { params_and_return: folded.into(), is_varargs: self.is_varargs })
224 #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
225 pub enum ImplTraitId {
226 ReturnTypeImplTrait(hir_def::FunctionId, u16),
227 AsyncBlockTypeImplTrait(hir_def::DefWithBodyId, ExprId),
230 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
231 pub struct ReturnTypeImplTraits {
232 pub(crate) impl_traits: Vec<ReturnTypeImplTrait>,
235 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
236 pub(crate) struct ReturnTypeImplTrait {
237 pub(crate) bounds: Binders<Vec<QuantifiedWhereClause>>,
240 pub fn to_foreign_def_id(id: TypeAliasId) -> ForeignDefId {
241 chalk_ir::ForeignDefId(salsa::InternKey::as_intern_id(&id))
244 pub fn from_foreign_def_id(id: ForeignDefId) -> TypeAliasId {
245 salsa::InternKey::from_intern_id(id.0)
248 pub fn to_assoc_type_id(id: TypeAliasId) -> AssocTypeId {
249 chalk_ir::AssocTypeId(salsa::InternKey::as_intern_id(&id))
252 pub fn from_assoc_type_id(id: AssocTypeId) -> TypeAliasId {
253 salsa::InternKey::from_intern_id(id.0)
256 pub fn from_placeholder_idx(db: &dyn HirDatabase, idx: PlaceholderIndex) -> TypeParamId {
257 assert_eq!(idx.ui, chalk_ir::UniverseIndex::ROOT);
258 let interned_id = salsa::InternKey::from_intern_id(salsa::InternId::from(idx.idx));
259 db.lookup_intern_type_param_id(interned_id)
262 pub fn to_placeholder_idx(db: &dyn HirDatabase, id: TypeParamId) -> PlaceholderIndex {
263 let interned_id = db.intern_type_param_id(id);
265 ui: chalk_ir::UniverseIndex::ROOT,
266 idx: salsa::InternKey::as_intern_id(&interned_id).as_usize(),
270 pub fn lt_from_placeholder_idx(db: &dyn HirDatabase, idx: PlaceholderIndex) -> LifetimeParamId {
271 assert_eq!(idx.ui, chalk_ir::UniverseIndex::ROOT);
272 let interned_id = salsa::InternKey::from_intern_id(salsa::InternId::from(idx.idx));
273 db.lookup_intern_lifetime_param_id(interned_id)
276 pub fn const_from_placeholder_idx(db: &dyn HirDatabase, idx: PlaceholderIndex) -> ConstParamId {
277 assert_eq!(idx.ui, chalk_ir::UniverseIndex::ROOT);
278 let interned_id = salsa::InternKey::from_intern_id(salsa::InternId::from(idx.idx));
279 db.lookup_intern_const_param_id(interned_id)
282 pub fn to_chalk_trait_id(id: TraitId) -> ChalkTraitId {
283 chalk_ir::TraitId(salsa::InternKey::as_intern_id(&id))
286 pub fn from_chalk_trait_id(id: ChalkTraitId) -> TraitId {
287 salsa::InternKey::from_intern_id(id.0)
290 pub fn static_lifetime() -> Lifetime {
291 LifetimeData::Static.intern(&Interner)
294 pub fn dummy_usize_const() -> Const {
295 let usize_ty = chalk_ir::TyKind::Scalar(Scalar::Uint(UintTy::Usize)).intern(&Interner);
296 chalk_ir::ConstData {
298 value: chalk_ir::ConstValue::Concrete(chalk_ir::ConcreteConst { interned: () }),
303 pub(crate) fn fold_free_vars<T: HasInterner<Interner = Interner> + Fold<Interner>>(
305 f: impl FnMut(BoundVar, DebruijnIndex) -> Ty,
307 use chalk_ir::{fold::Folder, Fallible};
308 struct FreeVarFolder<F>(F);
309 impl<'i, F: FnMut(BoundVar, DebruijnIndex) -> Ty + 'i> Folder<'i, Interner> for FreeVarFolder<F> {
310 fn as_dyn(&mut self) -> &mut dyn Folder<'i, Interner> {
314 fn interner(&self) -> &'i Interner {
321 outer_binder: DebruijnIndex,
323 Ok(self.0(bound_var, outer_binder))
326 t.fold_with(&mut FreeVarFolder(f), DebruijnIndex::INNERMOST).expect("fold failed unexpectedly")
329 pub(crate) fn fold_tys<T: HasInterner<Interner = Interner> + Fold<Interner>>(
331 f: impl FnMut(Ty, DebruijnIndex) -> Ty,
332 binders: DebruijnIndex,
335 fold::{Folder, SuperFold},
338 struct TyFolder<F>(F);
339 impl<'i, F: FnMut(Ty, DebruijnIndex) -> Ty + 'i> Folder<'i, Interner> for TyFolder<F> {
340 fn as_dyn(&mut self) -> &mut dyn Folder<'i, Interner> {
344 fn interner(&self) -> &'i Interner {
348 fn fold_ty(&mut self, ty: Ty, outer_binder: DebruijnIndex) -> Fallible<Ty> {
349 let ty = ty.super_fold_with(self.as_dyn(), outer_binder)?;
350 Ok(self.0(ty, outer_binder))
353 t.fold_with(&mut TyFolder(f), binders).expect("fold failed unexpectedly")