1 //! The type system. We currently use this to infer types for completion, hover
2 //! information and various assists.
4 macro_rules! eprintln {
5 ($($tt:tt)*) => { stdx::eprintln!($($tt)*) };
11 pub mod method_resolution;
36 expr::ExprId, type_ref::Rawness, ConstParamId, LifetimeParamId, TraitId, TypeAliasId,
40 use crate::{db::HirDatabase, display::HirDisplay, utils::generics};
42 pub use autoderef::autoderef;
43 pub use builder::TyBuilder;
44 pub use chalk_ext::{ProjectionTyExt, TyExt};
45 pub use infer::{could_unify, InferenceResult, InferenceVar};
47 associated_type_shorthand_candidates, callable_item_sig, CallableDefId, ImplTraitLoweringMode,
48 TyDefId, TyLoweringContext, ValueTyDefId,
50 pub use traits::{chalk::Interner, TraitEnvironment};
52 pub use walk::TypeWalk;
55 cast::Cast, AdtId, BoundVar, DebruijnIndex, Mutability, Safety, Scalar, TyVariableKind,
58 pub type ForeignDefId = chalk_ir::ForeignDefId<Interner>;
59 pub type AssocTypeId = chalk_ir::AssocTypeId<Interner>;
60 pub type FnDefId = chalk_ir::FnDefId<Interner>;
61 pub type ClosureId = chalk_ir::ClosureId<Interner>;
62 pub type OpaqueTyId = chalk_ir::OpaqueTyId<Interner>;
63 pub type PlaceholderIndex = chalk_ir::PlaceholderIndex;
65 pub type VariableKind = chalk_ir::VariableKind<Interner>;
66 pub type VariableKinds = chalk_ir::VariableKinds<Interner>;
67 pub type CanonicalVarKinds = chalk_ir::CanonicalVarKinds<Interner>;
69 pub type Lifetime = chalk_ir::Lifetime<Interner>;
70 pub type LifetimeData = chalk_ir::LifetimeData<Interner>;
71 pub type LifetimeOutlives = chalk_ir::LifetimeOutlives<Interner>;
73 pub type Const = chalk_ir::Const<Interner>;
74 pub type ConstData = chalk_ir::ConstData<Interner>;
75 pub type ConstValue = chalk_ir::ConstValue<Interner>;
76 pub type ConcreteConst = chalk_ir::ConcreteConst<Interner>;
78 pub type ChalkTraitId = chalk_ir::TraitId<Interner>;
80 pub type FnSig = chalk_ir::FnSig<Interner>;
82 // FIXME: get rid of this
83 pub fn subst_prefix(s: &Substitution, n: usize) -> Substitution {
84 Substitution::intern(s.interned()[..std::cmp::min(s.len(&Interner), n)].into())
87 /// Return an index of a parameter in the generic type parameter list by it's id.
88 pub fn param_idx(db: &dyn HirDatabase, id: TypeParamId) -> Option<usize> {
89 generics(db.upcast(), id.parent).param_idx(id)
92 pub fn wrap_empty_binders<T>(value: T) -> Binders<T>
96 Binders::empty(&Interner, value.shifted_in_from(DebruijnIndex::ONE))
99 pub fn make_only_type_binders<T>(num_vars: usize, value: T) -> Binders<T> {
101 VariableKinds::from_iter(
103 std::iter::repeat(chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General))
111 pub fn hir_trait_id(&self) -> TraitId {
112 from_chalk_trait_id(self.trait_id)
116 impl<T> Canonical<T> {
117 pub fn new(value: T, kinds: impl IntoIterator<Item = TyVariableKind>) -> Self {
118 let kinds = kinds.into_iter().map(|tk| {
119 chalk_ir::CanonicalVarKind::new(
120 chalk_ir::VariableKind::Ty(tk),
121 chalk_ir::UniverseIndex::ROOT,
124 Self { value, binders: chalk_ir::CanonicalVarKinds::from_iter(&Interner, kinds) }
128 /// A function signature as seen by type inference: Several parameter types and
130 #[derive(Clone, PartialEq, Eq, Debug)]
131 pub struct CallableSig {
132 params_and_return: Arc<[Ty]>,
136 /// A polymorphic function signature.
137 pub type PolyFnSig = Binders<CallableSig>;
140 pub fn from_params_and_return(mut params: Vec<Ty>, ret: Ty, is_varargs: bool) -> CallableSig {
142 CallableSig { params_and_return: params.into(), is_varargs }
145 pub fn from_fn_ptr(fn_ptr: &FnPointer) -> CallableSig {
147 // FIXME: what to do about lifetime params? -> return PolyFnSig
148 params_and_return: fn_ptr
151 .shifted_out_to(DebruijnIndex::ONE)
152 .expect("unexpected lifetime vars in fn ptr")
156 .map(|arg| arg.assert_ty_ref(&Interner).clone())
158 is_varargs: fn_ptr.sig.variadic,
162 pub fn params(&self) -> &[Ty] {
163 &self.params_and_return[0..self.params_and_return.len() - 1]
166 pub fn ret(&self) -> &Ty {
167 &self.params_and_return[self.params_and_return.len() - 1]
172 pub fn equals_ctor(&self, other: &Ty) -> bool {
173 match (self.kind(&Interner), other.kind(&Interner)) {
174 (TyKind::Adt(adt, ..), TyKind::Adt(adt2, ..)) => adt == adt2,
175 (TyKind::Slice(_), TyKind::Slice(_)) | (TyKind::Array(_, _), TyKind::Array(_, _)) => {
178 (TyKind::FnDef(def_id, ..), TyKind::FnDef(def_id2, ..)) => def_id == def_id2,
179 (TyKind::OpaqueType(ty_id, ..), TyKind::OpaqueType(ty_id2, ..)) => ty_id == ty_id2,
180 (TyKind::AssociatedType(ty_id, ..), TyKind::AssociatedType(ty_id2, ..)) => {
183 (TyKind::Foreign(ty_id, ..), TyKind::Foreign(ty_id2, ..)) => ty_id == ty_id2,
184 (TyKind::Closure(id1, _), TyKind::Closure(id2, _)) => id1 == id2,
185 (TyKind::Ref(mutability, ..), TyKind::Ref(mutability2, ..))
186 | (TyKind::Raw(mutability, ..), TyKind::Raw(mutability2, ..)) => {
187 mutability == mutability2
190 TyKind::Function(FnPointer { num_binders, sig, .. }),
191 TyKind::Function(FnPointer { num_binders: num_binders2, sig: sig2, .. }),
192 ) => num_binders == num_binders2 && sig == sig2,
193 (TyKind::Tuple(cardinality, _), TyKind::Tuple(cardinality2, _)) => {
194 cardinality == cardinality2
196 (TyKind::Str, TyKind::Str) | (TyKind::Never, TyKind::Never) => true,
197 (TyKind::Scalar(scalar), TyKind::Scalar(scalar2)) => scalar == scalar2,
202 fn builtin_deref(&self) -> Option<Ty> {
203 match self.kind(&Interner) {
204 TyKind::Ref(.., ty) => Some(ty.clone()),
205 TyKind::Raw(.., ty) => Some(ty.clone()),
210 /// Returns the type parameters of this type if it has some (i.e. is an ADT
211 /// or function); so if `self` is `Option<u32>`, this returns the `u32`.
212 pub fn substs(&self) -> Option<&Substitution> {
213 match self.kind(&Interner) {
214 TyKind::Adt(_, substs)
215 | TyKind::FnDef(_, substs)
216 | TyKind::Tuple(_, substs)
217 | TyKind::OpaqueType(_, substs)
218 | TyKind::AssociatedType(_, substs)
219 | TyKind::Closure(.., substs) => Some(substs),
220 TyKind::Function(FnPointer { substitution: substs, .. }) => Some(&substs.0),
225 fn substs_mut(&mut self) -> Option<&mut Substitution> {
226 match self.interned_mut() {
227 TyKind::Adt(_, substs)
228 | TyKind::FnDef(_, substs)
229 | TyKind::Tuple(_, substs)
230 | TyKind::OpaqueType(_, substs)
231 | TyKind::AssociatedType(_, substs)
232 | TyKind::Closure(.., substs) => Some(substs),
233 TyKind::Function(FnPointer { substitution: substs, .. }) => Some(&mut substs.0),
239 #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
240 pub enum ImplTraitId {
241 ReturnTypeImplTrait(hir_def::FunctionId, u16),
242 AsyncBlockTypeImplTrait(hir_def::DefWithBodyId, ExprId),
245 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
246 pub struct ReturnTypeImplTraits {
247 pub(crate) impl_traits: Vec<ReturnTypeImplTrait>,
250 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
251 pub(crate) struct ReturnTypeImplTrait {
252 pub(crate) bounds: Binders<Vec<QuantifiedWhereClause>>,
255 pub fn to_foreign_def_id(id: TypeAliasId) -> ForeignDefId {
256 chalk_ir::ForeignDefId(salsa::InternKey::as_intern_id(&id))
259 pub fn from_foreign_def_id(id: ForeignDefId) -> TypeAliasId {
260 salsa::InternKey::from_intern_id(id.0)
263 pub fn to_assoc_type_id(id: TypeAliasId) -> AssocTypeId {
264 chalk_ir::AssocTypeId(salsa::InternKey::as_intern_id(&id))
267 pub fn from_assoc_type_id(id: AssocTypeId) -> TypeAliasId {
268 salsa::InternKey::from_intern_id(id.0)
271 pub fn from_placeholder_idx(db: &dyn HirDatabase, idx: PlaceholderIndex) -> TypeParamId {
272 assert_eq!(idx.ui, chalk_ir::UniverseIndex::ROOT);
273 let interned_id = salsa::InternKey::from_intern_id(salsa::InternId::from(idx.idx));
274 db.lookup_intern_type_param_id(interned_id)
277 pub fn to_placeholder_idx(db: &dyn HirDatabase, id: TypeParamId) -> PlaceholderIndex {
278 let interned_id = db.intern_type_param_id(id);
280 ui: chalk_ir::UniverseIndex::ROOT,
281 idx: salsa::InternKey::as_intern_id(&interned_id).as_usize(),
285 pub fn lt_from_placeholder_idx(db: &dyn HirDatabase, idx: PlaceholderIndex) -> LifetimeParamId {
286 assert_eq!(idx.ui, chalk_ir::UniverseIndex::ROOT);
287 let interned_id = salsa::InternKey::from_intern_id(salsa::InternId::from(idx.idx));
288 db.lookup_intern_lifetime_param_id(interned_id)
291 pub fn const_from_placeholder_idx(db: &dyn HirDatabase, idx: PlaceholderIndex) -> ConstParamId {
292 assert_eq!(idx.ui, chalk_ir::UniverseIndex::ROOT);
293 let interned_id = salsa::InternKey::from_intern_id(salsa::InternId::from(idx.idx));
294 db.lookup_intern_const_param_id(interned_id)
297 pub fn to_chalk_trait_id(id: TraitId) -> ChalkTraitId {
298 chalk_ir::TraitId(salsa::InternKey::as_intern_id(&id))
301 pub fn from_chalk_trait_id(id: ChalkTraitId) -> TraitId {
302 salsa::InternKey::from_intern_id(id.0)
305 pub fn static_lifetime() -> Lifetime {
306 LifetimeData::Static.intern(&Interner)
309 pub fn dummy_usize_const() -> Const {
310 let usize_ty = chalk_ir::TyKind::Scalar(Scalar::Uint(UintTy::Usize)).intern(&Interner);
311 chalk_ir::ConstData {
313 value: chalk_ir::ConstValue::Concrete(chalk_ir::ConcreteConst { interned: () }),