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