]> git.lizzy.rs Git - rust.git/blob - crates/hir_ty/src/builder.rs
Merge #10420
[rust.git] / crates / hir_ty / src / builder.rs
1 //! `TyBuilder`, a helper for building instances of `Ty` and related types.
2
3 use std::iter;
4
5 use chalk_ir::{
6     cast::{Cast, CastTo, Caster},
7     fold::Fold,
8     interner::HasInterner,
9     AdtId, BoundVar, DebruijnIndex, Scalar,
10 };
11 use hir_def::{builtin_type::BuiltinType, GenericDefId, TraitId, TypeAliasId};
12 use smallvec::SmallVec;
13
14 use crate::{
15     db::HirDatabase, primitive, to_assoc_type_id, to_chalk_trait_id, utils::generics, Binders,
16     CallableSig, GenericArg, Interner, ProjectionTy, Substitution, TraitRef, Ty, TyDefId, TyExt,
17     TyKind, ValueTyDefId,
18 };
19
20 /// This is a builder for `Ty` or anything that needs a `Substitution`.
21 pub struct TyBuilder<D> {
22     /// The `data` field is used to keep track of what we're building (e.g. an
23     /// ADT, a `TraitRef`, ...).
24     data: D,
25     vec: SmallVec<[GenericArg; 2]>,
26     param_count: usize,
27 }
28
29 impl<D> TyBuilder<D> {
30     fn new(data: D, param_count: usize) -> TyBuilder<D> {
31         TyBuilder { data, param_count, vec: SmallVec::with_capacity(param_count) }
32     }
33
34     fn build_internal(self) -> (D, Substitution) {
35         assert_eq!(self.vec.len(), self.param_count);
36         let subst = Substitution::from_iter(&Interner, self.vec);
37         (self.data, subst)
38     }
39
40     pub fn push(mut self, arg: impl CastTo<GenericArg>) -> Self {
41         self.vec.push(arg.cast(&Interner));
42         self
43     }
44
45     pub fn remaining(&self) -> usize {
46         self.param_count - self.vec.len()
47     }
48
49     pub fn fill_with_bound_vars(self, debruijn: DebruijnIndex, starting_from: usize) -> Self {
50         self.fill(
51             (starting_from..)
52                 .map(|idx| TyKind::BoundVar(BoundVar::new(debruijn, idx)).intern(&Interner)),
53         )
54     }
55
56     pub fn fill_with_unknown(self) -> Self {
57         self.fill(iter::repeat(TyKind::Error.intern(&Interner)))
58     }
59
60     pub fn fill(mut self, filler: impl Iterator<Item = impl CastTo<GenericArg>>) -> Self {
61         self.vec.extend(filler.take(self.remaining()).casted(&Interner));
62         assert_eq!(self.remaining(), 0);
63         self
64     }
65
66     pub fn use_parent_substs(mut self, parent_substs: &Substitution) -> Self {
67         assert!(self.vec.is_empty());
68         assert!(parent_substs.len(&Interner) <= self.param_count);
69         self.vec.extend(parent_substs.iter(&Interner).cloned());
70         self
71     }
72 }
73
74 impl TyBuilder<()> {
75     pub fn unit() -> Ty {
76         TyKind::Tuple(0, Substitution::empty(&Interner)).intern(&Interner)
77     }
78
79     pub fn fn_ptr(sig: CallableSig) -> Ty {
80         TyKind::Function(sig.to_fn_ptr()).intern(&Interner)
81     }
82
83     pub fn builtin(builtin: BuiltinType) -> Ty {
84         match builtin {
85             BuiltinType::Char => TyKind::Scalar(Scalar::Char).intern(&Interner),
86             BuiltinType::Bool => TyKind::Scalar(Scalar::Bool).intern(&Interner),
87             BuiltinType::Str => TyKind::Str.intern(&Interner),
88             BuiltinType::Int(t) => {
89                 TyKind::Scalar(Scalar::Int(primitive::int_ty_from_builtin(t))).intern(&Interner)
90             }
91             BuiltinType::Uint(t) => {
92                 TyKind::Scalar(Scalar::Uint(primitive::uint_ty_from_builtin(t))).intern(&Interner)
93             }
94             BuiltinType::Float(t) => {
95                 TyKind::Scalar(Scalar::Float(primitive::float_ty_from_builtin(t))).intern(&Interner)
96             }
97         }
98     }
99
100     pub fn type_params_subst(db: &dyn HirDatabase, def: impl Into<GenericDefId>) -> Substitution {
101         let params = generics(db.upcast(), def.into());
102         params.type_params_subst(db)
103     }
104
105     pub fn subst_for_def(db: &dyn HirDatabase, def: impl Into<GenericDefId>) -> TyBuilder<()> {
106         let def = def.into();
107         let params = generics(db.upcast(), def);
108         let param_count = params.len();
109         TyBuilder::new((), param_count)
110     }
111
112     pub fn build(self) -> Substitution {
113         let ((), subst) = self.build_internal();
114         subst
115     }
116 }
117
118 impl TyBuilder<hir_def::AdtId> {
119     pub fn adt(db: &dyn HirDatabase, adt: hir_def::AdtId) -> TyBuilder<hir_def::AdtId> {
120         let generics = generics(db.upcast(), adt.into());
121         let param_count = generics.len();
122         TyBuilder::new(adt, param_count)
123     }
124
125     pub fn fill_with_defaults(
126         mut self,
127         db: &dyn HirDatabase,
128         mut fallback: impl FnMut() -> Ty,
129     ) -> Self {
130         let defaults = db.generic_defaults(self.data.into());
131         for default_ty in defaults.iter().skip(self.vec.len()) {
132             if default_ty.skip_binders().is_unknown() {
133                 self.vec.push(fallback().cast(&Interner));
134             } else {
135                 // each default can depend on the previous parameters
136                 let subst_so_far = Substitution::from_iter(&Interner, self.vec.clone());
137                 self.vec
138                     .push(default_ty.clone().substitute(&Interner, &subst_so_far).cast(&Interner));
139             }
140         }
141         self
142     }
143
144     pub fn build(self) -> Ty {
145         let (adt, subst) = self.build_internal();
146         TyKind::Adt(AdtId(adt), subst).intern(&Interner)
147     }
148 }
149
150 pub struct Tuple(usize);
151 impl TyBuilder<Tuple> {
152     pub fn tuple(size: usize) -> TyBuilder<Tuple> {
153         TyBuilder::new(Tuple(size), size)
154     }
155
156     pub fn build(self) -> Ty {
157         let (Tuple(size), subst) = self.build_internal();
158         TyKind::Tuple(size, subst).intern(&Interner)
159     }
160 }
161
162 impl TyBuilder<TraitId> {
163     pub fn trait_ref(db: &dyn HirDatabase, trait_id: TraitId) -> TyBuilder<TraitId> {
164         let generics = generics(db.upcast(), trait_id.into());
165         let param_count = generics.len();
166         TyBuilder::new(trait_id, param_count)
167     }
168
169     pub fn build(self) -> TraitRef {
170         let (trait_id, substitution) = self.build_internal();
171         TraitRef { trait_id: to_chalk_trait_id(trait_id), substitution }
172     }
173 }
174
175 impl TyBuilder<TypeAliasId> {
176     pub fn assoc_type_projection(
177         db: &dyn HirDatabase,
178         type_alias: TypeAliasId,
179     ) -> TyBuilder<TypeAliasId> {
180         let generics = generics(db.upcast(), type_alias.into());
181         let param_count = generics.len();
182         TyBuilder::new(type_alias, param_count)
183     }
184
185     pub fn build(self) -> ProjectionTy {
186         let (type_alias, substitution) = self.build_internal();
187         ProjectionTy { associated_ty_id: to_assoc_type_id(type_alias), substitution }
188     }
189 }
190
191 impl<T: HasInterner<Interner = Interner> + Fold<Interner>> TyBuilder<Binders<T>> {
192     fn subst_binders(b: Binders<T>) -> Self {
193         let param_count = b.binders.len(&Interner);
194         TyBuilder::new(b, param_count)
195     }
196
197     pub fn build(self) -> <T as Fold<Interner>>::Result {
198         let (b, subst) = self.build_internal();
199         b.substitute(&Interner, &subst)
200     }
201 }
202
203 impl TyBuilder<Binders<Ty>> {
204     pub fn def_ty(db: &dyn HirDatabase, def: TyDefId) -> TyBuilder<Binders<Ty>> {
205         TyBuilder::subst_binders(db.ty(def))
206     }
207
208     pub fn impl_self_ty(db: &dyn HirDatabase, def: hir_def::ImplId) -> TyBuilder<Binders<Ty>> {
209         TyBuilder::subst_binders(db.impl_self_ty(def))
210     }
211
212     pub fn value_ty(db: &dyn HirDatabase, def: ValueTyDefId) -> TyBuilder<Binders<Ty>> {
213         TyBuilder::subst_binders(db.value_ty(def))
214     }
215 }