]> git.lizzy.rs Git - rust.git/blob - crates/hir_ty/src/lib.rs
Replace all the types by their Chalk versions
[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 #[allow(unused)]
4 macro_rules! eprintln {
5     ($($tt:tt)*) => { stdx::eprintln!($($tt)*) };
6 }
7
8 mod autoderef;
9 pub mod primitive;
10 pub mod traits;
11 pub mod method_resolution;
12 mod op;
13 mod lower;
14 pub(crate) mod infer;
15 pub(crate) mod utils;
16 mod chalk_cast;
17 mod chalk_ext;
18 mod builder;
19 mod walk;
20
21 pub mod display;
22 pub mod db;
23 pub mod diagnostics;
24
25 #[cfg(test)]
26 mod tests;
27 #[cfg(test)]
28 mod test_db;
29
30 use std::sync::Arc;
31
32 use base_db::salsa;
33 use chalk_ir::UintTy;
34 use hir_def::{
35     expr::ExprId, type_ref::Rawness, ConstParamId, LifetimeParamId, TraitId, TypeAliasId,
36     TypeParamId,
37 };
38
39 use crate::{db::HirDatabase, display::HirDisplay, utils::generics};
40
41 pub use autoderef::autoderef;
42 pub use builder::TyBuilder;
43 pub use chalk_ext::*;
44 pub use infer::{could_unify, InferenceResult};
45 pub use lower::{
46     associated_type_shorthand_candidates, callable_item_sig, CallableDefId, ImplTraitLoweringMode,
47     TyDefId, TyLoweringContext, ValueTyDefId,
48 };
49 pub use traits::{chalk::Interner, TraitEnvironment};
50 pub use walk::TypeWalk;
51
52 pub use chalk_ir::{
53     cast::Cast, AdtId, BoundVar, DebruijnIndex, Mutability, Safety, Scalar, TyVariableKind,
54 };
55
56 pub type ForeignDefId = chalk_ir::ForeignDefId<Interner>;
57 pub type AssocTypeId = chalk_ir::AssocTypeId<Interner>;
58 pub type FnDefId = chalk_ir::FnDefId<Interner>;
59 pub type ClosureId = chalk_ir::ClosureId<Interner>;
60 pub type OpaqueTyId = chalk_ir::OpaqueTyId<Interner>;
61 pub type PlaceholderIndex = chalk_ir::PlaceholderIndex;
62
63 pub type VariableKind = chalk_ir::VariableKind<Interner>;
64 pub type VariableKinds = chalk_ir::VariableKinds<Interner>;
65 pub type CanonicalVarKinds = chalk_ir::CanonicalVarKinds<Interner>;
66 pub type Binders<T> = chalk_ir::Binders<T>;
67 pub type Substitution = chalk_ir::Substitution<Interner>;
68 pub type GenericArg = chalk_ir::GenericArg<Interner>;
69 pub type GenericArgData = chalk_ir::GenericArgData<Interner>;
70
71 pub type Ty = chalk_ir::Ty<Interner>;
72 pub type TyKind = chalk_ir::TyKind<Interner>;
73 pub type DynTy = chalk_ir::DynTy<Interner>;
74 pub type FnPointer = chalk_ir::FnPointer<Interner>;
75 // pub type FnSubst = chalk_ir::FnSubst<Interner>;
76 pub use chalk_ir::FnSubst;
77 pub type ProjectionTy = chalk_ir::ProjectionTy<Interner>;
78 pub type AliasTy = chalk_ir::AliasTy<Interner>;
79 pub type OpaqueTy = chalk_ir::OpaqueTy<Interner>;
80 pub type InferenceVar = chalk_ir::InferenceVar;
81
82 pub type Lifetime = chalk_ir::Lifetime<Interner>;
83 pub type LifetimeData = chalk_ir::LifetimeData<Interner>;
84 pub type LifetimeOutlives = chalk_ir::LifetimeOutlives<Interner>;
85
86 pub type Const = chalk_ir::Const<Interner>;
87 pub type ConstData = chalk_ir::ConstData<Interner>;
88 pub type ConstValue = chalk_ir::ConstValue<Interner>;
89 pub type ConcreteConst = chalk_ir::ConcreteConst<Interner>;
90
91 pub type ChalkTraitId = chalk_ir::TraitId<Interner>;
92
93 pub type FnSig = chalk_ir::FnSig<Interner>;
94
95 pub type InEnvironment<T> = chalk_ir::InEnvironment<T>;
96 pub type DomainGoal = chalk_ir::DomainGoal<Interner>;
97 pub type AliasEq = chalk_ir::AliasEq<Interner>;
98 pub type Solution = chalk_solve::Solution<Interner>;
99 pub type ConstrainedSubst = chalk_ir::ConstrainedSubst<Interner>;
100 pub type Guidance = chalk_solve::Guidance<Interner>;
101 pub type WhereClause = chalk_ir::WhereClause<Interner>;
102
103 // FIXME: get rid of this
104 pub fn subst_prefix(s: &Substitution, n: usize) -> Substitution {
105     Substitution::intern(s.interned()[..std::cmp::min(s.len(&Interner), n)].into())
106 }
107
108 /// Return an index of a parameter in the generic type parameter list by it's id.
109 pub fn param_idx(db: &dyn HirDatabase, id: TypeParamId) -> Option<usize> {
110     generics(db.upcast(), id.parent).param_idx(id)
111 }
112
113 pub fn wrap_empty_binders<T>(value: T) -> Binders<T>
114 where
115     T: TypeWalk,
116 {
117     Binders::empty(&Interner, value.shifted_in_from(DebruijnIndex::ONE))
118 }
119
120 pub fn make_only_type_binders<T>(num_vars: usize, value: T) -> Binders<T> {
121     Binders::new(
122         VariableKinds::from_iter(
123             &Interner,
124             std::iter::repeat(chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General))
125                 .take(num_vars),
126         ),
127         value,
128     )
129 }
130
131 // FIXME: get rid of this
132 pub fn make_canonical<T>(
133     value: T,
134     kinds: impl IntoIterator<Item = TyVariableKind>,
135 ) -> Canonical<T> {
136     let kinds = kinds.into_iter().map(|tk| {
137         chalk_ir::CanonicalVarKind::new(
138             chalk_ir::VariableKind::Ty(tk),
139             chalk_ir::UniverseIndex::ROOT,
140         )
141     });
142     Canonical { value, binders: chalk_ir::CanonicalVarKinds::from_iter(&Interner, kinds) }
143 }
144
145 pub type TraitRef = chalk_ir::TraitRef<Interner>;
146
147 pub type QuantifiedWhereClause = Binders<WhereClause>;
148
149 pub type QuantifiedWhereClauses = chalk_ir::QuantifiedWhereClauses<Interner>;
150
151 pub type Canonical<T> = chalk_ir::Canonical<T>;
152
153 /// A function signature as seen by type inference: Several parameter types and
154 /// one return type.
155 #[derive(Clone, PartialEq, Eq, Debug)]
156 pub struct CallableSig {
157     params_and_return: Arc<[Ty]>,
158     is_varargs: bool,
159 }
160
161 /// A polymorphic function signature.
162 pub type PolyFnSig = Binders<CallableSig>;
163
164 impl CallableSig {
165     pub fn from_params_and_return(mut params: Vec<Ty>, ret: Ty, is_varargs: bool) -> CallableSig {
166         params.push(ret);
167         CallableSig { params_and_return: params.into(), is_varargs }
168     }
169
170     pub fn from_fn_ptr(fn_ptr: &FnPointer) -> CallableSig {
171         CallableSig {
172             // FIXME: what to do about lifetime params? -> return PolyFnSig
173             params_and_return: fn_ptr
174                 .substitution
175                 .clone()
176                 .shifted_out_to(DebruijnIndex::ONE)
177                 .expect("unexpected lifetime vars in fn ptr")
178                 .0
179                 .interned()
180                 .iter()
181                 .map(|arg| arg.assert_ty_ref(&Interner).clone())
182                 .collect(),
183             is_varargs: fn_ptr.sig.variadic,
184         }
185     }
186
187     pub fn params(&self) -> &[Ty] {
188         &self.params_and_return[0..self.params_and_return.len() - 1]
189     }
190
191     pub fn ret(&self) -> &Ty {
192         &self.params_and_return[self.params_and_return.len() - 1]
193     }
194 }
195
196 #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
197 pub enum ImplTraitId {
198     ReturnTypeImplTrait(hir_def::FunctionId, u16),
199     AsyncBlockTypeImplTrait(hir_def::DefWithBodyId, ExprId),
200 }
201
202 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
203 pub struct ReturnTypeImplTraits {
204     pub(crate) impl_traits: Vec<ReturnTypeImplTrait>,
205 }
206
207 #[derive(Clone, PartialEq, Eq, Debug, Hash)]
208 pub(crate) struct ReturnTypeImplTrait {
209     pub(crate) bounds: Binders<Vec<QuantifiedWhereClause>>,
210 }
211
212 pub fn to_foreign_def_id(id: TypeAliasId) -> ForeignDefId {
213     chalk_ir::ForeignDefId(salsa::InternKey::as_intern_id(&id))
214 }
215
216 pub fn from_foreign_def_id(id: ForeignDefId) -> TypeAliasId {
217     salsa::InternKey::from_intern_id(id.0)
218 }
219
220 pub fn to_assoc_type_id(id: TypeAliasId) -> AssocTypeId {
221     chalk_ir::AssocTypeId(salsa::InternKey::as_intern_id(&id))
222 }
223
224 pub fn from_assoc_type_id(id: AssocTypeId) -> TypeAliasId {
225     salsa::InternKey::from_intern_id(id.0)
226 }
227
228 pub fn from_placeholder_idx(db: &dyn HirDatabase, idx: PlaceholderIndex) -> TypeParamId {
229     assert_eq!(idx.ui, chalk_ir::UniverseIndex::ROOT);
230     let interned_id = salsa::InternKey::from_intern_id(salsa::InternId::from(idx.idx));
231     db.lookup_intern_type_param_id(interned_id)
232 }
233
234 pub fn to_placeholder_idx(db: &dyn HirDatabase, id: TypeParamId) -> PlaceholderIndex {
235     let interned_id = db.intern_type_param_id(id);
236     PlaceholderIndex {
237         ui: chalk_ir::UniverseIndex::ROOT,
238         idx: salsa::InternKey::as_intern_id(&interned_id).as_usize(),
239     }
240 }
241
242 pub fn lt_from_placeholder_idx(db: &dyn HirDatabase, idx: PlaceholderIndex) -> LifetimeParamId {
243     assert_eq!(idx.ui, chalk_ir::UniverseIndex::ROOT);
244     let interned_id = salsa::InternKey::from_intern_id(salsa::InternId::from(idx.idx));
245     db.lookup_intern_lifetime_param_id(interned_id)
246 }
247
248 pub fn const_from_placeholder_idx(db: &dyn HirDatabase, idx: PlaceholderIndex) -> ConstParamId {
249     assert_eq!(idx.ui, chalk_ir::UniverseIndex::ROOT);
250     let interned_id = salsa::InternKey::from_intern_id(salsa::InternId::from(idx.idx));
251     db.lookup_intern_const_param_id(interned_id)
252 }
253
254 pub fn to_chalk_trait_id(id: TraitId) -> ChalkTraitId {
255     chalk_ir::TraitId(salsa::InternKey::as_intern_id(&id))
256 }
257
258 pub fn from_chalk_trait_id(id: ChalkTraitId) -> TraitId {
259     salsa::InternKey::from_intern_id(id.0)
260 }
261
262 pub fn static_lifetime() -> Lifetime {
263     LifetimeData::Static.intern(&Interner)
264 }
265
266 pub fn dummy_usize_const() -> Const {
267     let usize_ty = chalk_ir::TyKind::Scalar(Scalar::Uint(UintTy::Usize)).intern(&Interner);
268     chalk_ir::ConstData {
269         ty: usize_ty,
270         value: chalk_ir::ConstValue::Concrete(chalk_ir::ConcreteConst { interned: () }),
271     }
272     .intern(&Interner)
273 }