]>
Commit | Line | Data |
---|---|---|
970d7e83 LB |
1 | // Type substitutions. |
2 | ||
3dfed10e | 3 | use crate::ty::codec::{TyDecoder, TyEncoder}; |
064997fb | 4 | use crate::ty::fold::{FallibleTypeFolder, TypeFoldable, TypeFolder, TypeSuperFoldable}; |
3c0e092e | 5 | use crate::ty::sty::{ClosureSubsts, GeneratorSubsts, InlineConstSubsts}; |
9ffffee4 | 6 | use crate::ty::visit::{TypeVisitable, TypeVisitableExt, TypeVisitor}; |
923072b8 | 7 | use crate::ty::{self, Lift, List, ParamConst, Ty, TyCtxt}; |
970d7e83 | 8 | |
487cf647 | 9 | use rustc_data_structures::intern::Interned; |
9c376795 | 10 | use rustc_errors::{DiagnosticArgValue, IntoDiagnosticArg}; |
dfeec247 | 11 | use rustc_hir::def_id::DefId; |
532ac7d7 | 12 | use rustc_macros::HashStable; |
3dfed10e | 13 | use rustc_serialize::{self, Decodable, Encodable}; |
487cf647 | 14 | use rustc_type_ir::WithCachedTypeInfo; |
dfeec247 | 15 | use smallvec::SmallVec; |
1a4d82fc | 16 | |
0531ce1d | 17 | use core::intrinsics; |
532ac7d7 | 18 | use std::cmp::Ordering; |
dfeec247 | 19 | use std::fmt; |
9e0c209e SL |
20 | use std::marker::PhantomData; |
21 | use std::mem; | |
0531ce1d | 22 | use std::num::NonZeroUsize; |
487cf647 | 23 | use std::ops::{ControlFlow, Deref}; |
9e0c209e | 24 | |
a1dfa0c6 | 25 | /// An entity in the Rust type system, which can be one of |
532ac7d7 | 26 | /// several kinds (types, lifetimes, and consts). |
94222f64 | 27 | /// To reduce memory usage, a `GenericArg` is an interned pointer, |
9e0c209e | 28 | /// with the lowest 2 bits being reserved for a tag to |
532ac7d7 | 29 | /// indicate the type (`Ty`, `Region`, or `Const`) it points to. |
5099ac24 FG |
30 | /// |
31 | /// Note: the `PartialEq`, `Eq` and `Hash` derives are only valid because `Ty`, | |
32 | /// `Region` and `Const` are all interned. | |
0531ce1d | 33 | #[derive(Copy, Clone, PartialEq, Eq, Hash)] |
e74abb32 | 34 | pub struct GenericArg<'tcx> { |
0531ce1d | 35 | ptr: NonZeroUsize, |
5099ac24 | 36 | marker: PhantomData<(Ty<'tcx>, ty::Region<'tcx>, ty::Const<'tcx>)>, |
970d7e83 LB |
37 | } |
38 | ||
9c376795 FG |
39 | impl<'tcx> IntoDiagnosticArg for GenericArg<'tcx> { |
40 | fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> { | |
41 | self.to_string().into_diagnostic_arg() | |
42 | } | |
43 | } | |
44 | ||
9e0c209e SL |
45 | const TAG_MASK: usize = 0b11; |
46 | const TYPE_TAG: usize = 0b00; | |
47 | const REGION_TAG: usize = 0b01; | |
532ac7d7 | 48 | const CONST_TAG: usize = 0b10; |
9e0c209e | 49 | |
49aad941 | 50 | #[derive(Debug, TyEncodable, TyDecodable, PartialEq, Eq, PartialOrd, Ord, HashStable)] |
e74abb32 | 51 | pub enum GenericArgKind<'tcx> { |
0531ce1d XL |
52 | Lifetime(ty::Region<'tcx>), |
53 | Type(Ty<'tcx>), | |
5099ac24 | 54 | Const(ty::Const<'tcx>), |
0531ce1d XL |
55 | } |
56 | ||
e74abb32 | 57 | impl<'tcx> GenericArgKind<'tcx> { |
5099ac24 | 58 | #[inline] |
e74abb32 | 59 | fn pack(self) -> GenericArg<'tcx> { |
0531ce1d | 60 | let (tag, ptr) = match self { |
e74abb32 | 61 | GenericArgKind::Lifetime(lt) => { |
0531ce1d | 62 | // Ensure we can use the tag bits. |
923072b8 FG |
63 | assert_eq!(mem::align_of_val(&*lt.0.0) & TAG_MASK, 0); |
64 | (REGION_TAG, lt.0.0 as *const ty::RegionKind<'tcx> as usize) | |
0531ce1d | 65 | } |
e74abb32 | 66 | GenericArgKind::Type(ty) => { |
0531ce1d | 67 | // Ensure we can use the tag bits. |
923072b8 | 68 | assert_eq!(mem::align_of_val(&*ty.0.0) & TAG_MASK, 0); |
487cf647 | 69 | (TYPE_TAG, ty.0.0 as *const WithCachedTypeInfo<ty::TyKind<'tcx>> as usize) |
0531ce1d | 70 | } |
e74abb32 | 71 | GenericArgKind::Const(ct) => { |
532ac7d7 | 72 | // Ensure we can use the tag bits. |
923072b8 | 73 | assert_eq!(mem::align_of_val(&*ct.0.0) & TAG_MASK, 0); |
9c376795 | 74 | (CONST_TAG, ct.0.0 as *const ty::ConstData<'tcx> as usize) |
532ac7d7 | 75 | } |
0531ce1d | 76 | }; |
9e0c209e | 77 | |
dfeec247 | 78 | GenericArg { ptr: unsafe { NonZeroUsize::new_unchecked(ptr | tag) }, marker: PhantomData } |
1a4d82fc | 79 | } |
9cc50fc6 SL |
80 | } |
81 | ||
a2a8927a | 82 | impl<'tcx> fmt::Debug for GenericArg<'tcx> { |
532ac7d7 XL |
83 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
84 | match self.unpack() { | |
e74abb32 XL |
85 | GenericArgKind::Lifetime(lt) => lt.fmt(f), |
86 | GenericArgKind::Type(ty) => ty.fmt(f), | |
87 | GenericArgKind::Const(ct) => ct.fmt(f), | |
532ac7d7 XL |
88 | } |
89 | } | |
90 | } | |
91 | ||
e74abb32 | 92 | impl<'tcx> Ord for GenericArg<'tcx> { |
923072b8 | 93 | fn cmp(&self, other: &GenericArg<'tcx>) -> Ordering { |
b7449926 | 94 | self.unpack().cmp(&other.unpack()) |
94b46f34 XL |
95 | } |
96 | } | |
97 | ||
e74abb32 | 98 | impl<'tcx> PartialOrd for GenericArg<'tcx> { |
923072b8 | 99 | fn partial_cmp(&self, other: &GenericArg<'tcx>) -> Option<Ordering> { |
94b46f34 XL |
100 | Some(self.cmp(&other)) |
101 | } | |
102 | } | |
103 | ||
e74abb32 | 104 | impl<'tcx> From<ty::Region<'tcx>> for GenericArg<'tcx> { |
5099ac24 | 105 | #[inline] |
e74abb32 XL |
106 | fn from(r: ty::Region<'tcx>) -> GenericArg<'tcx> { |
107 | GenericArgKind::Lifetime(r).pack() | |
0531ce1d XL |
108 | } |
109 | } | |
9e0c209e | 110 | |
e74abb32 | 111 | impl<'tcx> From<Ty<'tcx>> for GenericArg<'tcx> { |
5099ac24 | 112 | #[inline] |
e74abb32 XL |
113 | fn from(ty: Ty<'tcx>) -> GenericArg<'tcx> { |
114 | GenericArgKind::Type(ty).pack() | |
970d7e83 LB |
115 | } |
116 | } | |
117 | ||
5099ac24 FG |
118 | impl<'tcx> From<ty::Const<'tcx>> for GenericArg<'tcx> { |
119 | #[inline] | |
120 | fn from(c: ty::Const<'tcx>) -> GenericArg<'tcx> { | |
e74abb32 | 121 | GenericArgKind::Const(c).pack() |
532ac7d7 XL |
122 | } |
123 | } | |
124 | ||
487cf647 FG |
125 | impl<'tcx> From<ty::Term<'tcx>> for GenericArg<'tcx> { |
126 | fn from(value: ty::Term<'tcx>) -> Self { | |
127 | match value.unpack() { | |
128 | ty::TermKind::Ty(t) => t.into(), | |
129 | ty::TermKind::Const(c) => c.into(), | |
130 | } | |
131 | } | |
132 | } | |
133 | ||
e74abb32 | 134 | impl<'tcx> GenericArg<'tcx> { |
9e0c209e | 135 | #[inline] |
e74abb32 | 136 | pub fn unpack(self) -> GenericArgKind<'tcx> { |
7cac9316 | 137 | let ptr = self.ptr.get(); |
5099ac24 FG |
138 | // SAFETY: use of `Interned::new_unchecked` here is ok because these |
139 | // pointers were originally created from `Interned` types in `pack()`, | |
140 | // and this is just going in the other direction. | |
9e0c209e | 141 | unsafe { |
0531ce1d | 142 | match ptr & TAG_MASK { |
5099ac24 | 143 | REGION_TAG => GenericArgKind::Lifetime(ty::Region(Interned::new_unchecked( |
923072b8 | 144 | &*((ptr & !TAG_MASK) as *const ty::RegionKind<'tcx>), |
5099ac24 FG |
145 | ))), |
146 | TYPE_TAG => GenericArgKind::Type(Ty(Interned::new_unchecked( | |
487cf647 | 147 | &*((ptr & !TAG_MASK) as *const WithCachedTypeInfo<ty::TyKind<'tcx>>), |
5099ac24 FG |
148 | ))), |
149 | CONST_TAG => GenericArgKind::Const(ty::Const(Interned::new_unchecked( | |
9c376795 | 150 | &*((ptr & !TAG_MASK) as *const ty::ConstData<'tcx>), |
5099ac24 | 151 | ))), |
dfeec247 | 152 | _ => intrinsics::unreachable(), |
0531ce1d | 153 | } |
1a4d82fc JJ |
154 | } |
155 | } | |
48663c56 | 156 | |
49aad941 FG |
157 | #[inline] |
158 | pub fn as_type(self) -> Option<Ty<'tcx>> { | |
064997fb | 159 | match self.unpack() { |
49aad941 FG |
160 | GenericArgKind::Type(ty) => Some(ty), |
161 | _ => None, | |
064997fb FG |
162 | } |
163 | } | |
164 | ||
49aad941 FG |
165 | #[inline] |
166 | pub fn as_region(self) -> Option<ty::Region<'tcx>> { | |
167 | match self.unpack() { | |
168 | GenericArgKind::Lifetime(re) => Some(re), | |
169 | _ => None, | |
170 | } | |
171 | } | |
172 | ||
173 | #[inline] | |
174 | pub fn as_const(self) -> Option<ty::Const<'tcx>> { | |
175 | match self.unpack() { | |
176 | GenericArgKind::Const(ct) => Some(ct), | |
177 | _ => None, | |
178 | } | |
179 | } | |
180 | ||
181 | /// Unpack the `GenericArg` as a region when it is known certainly to be a region. | |
182 | pub fn expect_region(self) -> ty::Region<'tcx> { | |
183 | self.as_region().unwrap_or_else(|| bug!("expected a region, but found another kind")) | |
184 | } | |
185 | ||
e74abb32 | 186 | /// Unpack the `GenericArg` as a type when it is known certainly to be a type. |
48663c56 XL |
187 | /// This is true in cases where `Substs` is used in places where the kinds are known |
188 | /// to be limited (e.g. in tuples, where the only parameters are type parameters). | |
189 | pub fn expect_ty(self) -> Ty<'tcx> { | |
49aad941 | 190 | self.as_type().unwrap_or_else(|| bug!("expected a type, but found another kind")) |
48663c56 | 191 | } |
ba9703b0 XL |
192 | |
193 | /// Unpack the `GenericArg` as a const when it is known certainly to be a const. | |
5099ac24 | 194 | pub fn expect_const(self) -> ty::Const<'tcx> { |
49aad941 | 195 | self.as_const().unwrap_or_else(|| bug!("expected a const, but found another kind")) |
ba9703b0 | 196 | } |
2b03887a FG |
197 | |
198 | pub fn is_non_region_infer(self) -> bool { | |
199 | match self.unpack() { | |
200 | GenericArgKind::Lifetime(_) => false, | |
9c376795 | 201 | GenericArgKind::Type(ty) => ty.is_ty_or_numeric_infer(), |
2b03887a FG |
202 | GenericArgKind::Const(ct) => ct.is_ct_infer(), |
203 | } | |
204 | } | |
9e0c209e | 205 | } |
1a4d82fc | 206 | |
e74abb32 XL |
207 | impl<'a, 'tcx> Lift<'tcx> for GenericArg<'a> { |
208 | type Lifted = GenericArg<'tcx>; | |
0531ce1d | 209 | |
29967ef6 | 210 | fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option<Self::Lifted> { |
0531ce1d | 211 | match self.unpack() { |
29967ef6 XL |
212 | GenericArgKind::Lifetime(lt) => tcx.lift(lt).map(|lt| lt.into()), |
213 | GenericArgKind::Type(ty) => tcx.lift(ty).map(|ty| ty.into()), | |
214 | GenericArgKind::Const(ct) => tcx.lift(ct).map(|ct| ct.into()), | |
abe05a73 XL |
215 | } |
216 | } | |
217 | } | |
218 | ||
9ffffee4 FG |
219 | impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for GenericArg<'tcx> { |
220 | fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>( | |
221 | self, | |
222 | folder: &mut F, | |
223 | ) -> Result<Self, F::Error> { | |
0531ce1d | 224 | match self.unpack() { |
a2a8927a XL |
225 | GenericArgKind::Lifetime(lt) => lt.try_fold_with(folder).map(Into::into), |
226 | GenericArgKind::Type(ty) => ty.try_fold_with(folder).map(Into::into), | |
227 | GenericArgKind::Const(ct) => ct.try_fold_with(folder).map(Into::into), | |
1a4d82fc | 228 | } |
1a4d82fc | 229 | } |
064997fb | 230 | } |
1a4d82fc | 231 | |
9ffffee4 FG |
232 | impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for GenericArg<'tcx> { |
233 | fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> { | |
0531ce1d | 234 | match self.unpack() { |
e74abb32 XL |
235 | GenericArgKind::Lifetime(lt) => lt.visit_with(visitor), |
236 | GenericArgKind::Type(ty) => ty.visit_with(visitor), | |
237 | GenericArgKind::Const(ct) => ct.visit_with(visitor), | |
1a4d82fc JJ |
238 | } |
239 | } | |
9e0c209e | 240 | } |
1a4d82fc | 241 | |
923072b8 FG |
242 | impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for GenericArg<'tcx> { |
243 | fn encode(&self, e: &mut E) { | |
94b46f34 | 244 | self.unpack().encode(e) |
1a4d82fc | 245 | } |
9e0c209e | 246 | } |
1a4d82fc | 247 | |
923072b8 | 248 | impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for GenericArg<'tcx> { |
5099ac24 FG |
249 | fn decode(d: &mut D) -> GenericArg<'tcx> { |
250 | GenericArgKind::decode(d).pack() | |
1a4d82fc | 251 | } |
9e0c209e | 252 | } |
1a4d82fc | 253 | |
9c376795 | 254 | /// List of generic arguments that are gonna be used to substitute generic parameters. |
e74abb32 | 255 | pub type InternalSubsts<'tcx> = List<GenericArg<'tcx>>; |
1a4d82fc | 256 | |
532ac7d7 XL |
257 | pub type SubstsRef<'tcx> = &'tcx InternalSubsts<'tcx>; |
258 | ||
923072b8 | 259 | impl<'tcx> InternalSubsts<'tcx> { |
49aad941 FG |
260 | /// Converts substs to a type list. |
261 | /// | |
262 | /// # Panics | |
263 | /// | |
264 | /// If any of the generic arguments are not types. | |
265 | pub fn into_type_list(&self, tcx: TyCtxt<'tcx>) -> &'tcx List<Ty<'tcx>> { | |
266 | tcx.mk_type_list_from_iter(self.iter().map(|arg| match arg.unpack() { | |
267 | GenericArgKind::Type(ty) => ty, | |
268 | _ => bug!("`into_type_list` called on substs with non-types"), | |
269 | })) | |
5e7ed085 FG |
270 | } |
271 | ||
e74abb32 XL |
272 | /// Interpret these substitutions as the substitutions of a closure type. |
273 | /// Closure substitutions have a particular structure controlled by the | |
274 | /// compiler that encodes information like the signature and closure kind; | |
275 | /// see `ty::ClosureSubsts` struct for more comments. | |
923072b8 | 276 | pub fn as_closure(&'tcx self) -> ClosureSubsts<'tcx> { |
dfeec247 | 277 | ClosureSubsts { substs: self } |
e74abb32 XL |
278 | } |
279 | ||
280 | /// Interpret these substitutions as the substitutions of a generator type. | |
17df50a5 | 281 | /// Generator substitutions have a particular structure controlled by the |
e74abb32 XL |
282 | /// compiler that encodes information like the signature and generator kind; |
283 | /// see `ty::GeneratorSubsts` struct for more comments. | |
284 | pub fn as_generator(&'tcx self) -> GeneratorSubsts<'tcx> { | |
285 | GeneratorSubsts { substs: self } | |
286 | } | |
287 | ||
3c0e092e XL |
288 | /// Interpret these substitutions as the substitutions of an inline const. |
289 | /// Inline const substitutions have a particular structure controlled by the | |
290 | /// compiler that encodes information like the inferred type; | |
291 | /// see `ty::InlineConstSubsts` struct for more comments. | |
292 | pub fn as_inline_const(&'tcx self) -> InlineConstSubsts<'tcx> { | |
293 | InlineConstSubsts { substs: self } | |
294 | } | |
295 | ||
94222f64 | 296 | /// Creates an `InternalSubsts` that maps each generic parameter to itself. |
353b0b11 FG |
297 | pub fn identity_for_item(tcx: TyCtxt<'tcx>, def_id: impl Into<DefId>) -> SubstsRef<'tcx> { |
298 | Self::for_item(tcx, def_id.into(), |param, _| tcx.mk_param_from_def(param)) | |
476ff2be SL |
299 | } |
300 | ||
94222f64 | 301 | /// Creates an `InternalSubsts` for generic parameter definitions, |
94b46f34 | 302 | /// by calling closures to obtain each kind. |
532ac7d7 | 303 | /// The closures get to observe the `InternalSubsts` as they're |
9e0c209e | 304 | /// being built, which can be used to correctly |
94b46f34 | 305 | /// substitute defaults of generic parameters. |
dc9dc135 XL |
306 | pub fn for_item<F>(tcx: TyCtxt<'tcx>, def_id: DefId, mut mk_kind: F) -> SubstsRef<'tcx> |
307 | where | |
e74abb32 | 308 | F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>, |
94b46f34 | 309 | { |
7cac9316 | 310 | let defs = tcx.generics_of(def_id); |
94b46f34 | 311 | let count = defs.count(); |
b7449926 | 312 | let mut substs = SmallVec::with_capacity(count); |
532ac7d7 | 313 | Self::fill_item(&mut substs, tcx, defs, &mut mk_kind); |
9ffffee4 | 314 | tcx.mk_substs(&substs) |
1a4d82fc JJ |
315 | } |
316 | ||
dc9dc135 XL |
317 | pub fn extend_to<F>(&self, tcx: TyCtxt<'tcx>, def_id: DefId, mut mk_kind: F) -> SubstsRef<'tcx> |
318 | where | |
e74abb32 | 319 | F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>, |
476ff2be | 320 | { |
532ac7d7 | 321 | Self::for_item(tcx, def_id, |param, substs| { |
dfeec247 | 322 | self.get(param.index as usize).cloned().unwrap_or_else(|| mk_kind(param, substs)) |
94b46f34 | 323 | }) |
476ff2be SL |
324 | } |
325 | ||
94222f64 | 326 | pub fn fill_item<F>( |
e74abb32 | 327 | substs: &mut SmallVec<[GenericArg<'tcx>; 8]>, |
dc9dc135 XL |
328 | tcx: TyCtxt<'tcx>, |
329 | defs: &ty::Generics, | |
330 | mk_kind: &mut F, | |
331 | ) where | |
e74abb32 | 332 | F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>, |
94b46f34 | 333 | { |
9e0c209e | 334 | if let Some(def_id) = defs.parent { |
7cac9316 | 335 | let parent_defs = tcx.generics_of(def_id); |
532ac7d7 | 336 | Self::fill_item(substs, tcx, parent_defs, mk_kind); |
9e0c209e | 337 | } |
532ac7d7 | 338 | Self::fill_single(substs, defs, mk_kind) |
94b46f34 | 339 | } |
1a4d82fc | 340 | |
94222f64 | 341 | pub fn fill_single<F>( |
dfeec247 XL |
342 | substs: &mut SmallVec<[GenericArg<'tcx>; 8]>, |
343 | defs: &ty::Generics, | |
344 | mk_kind: &mut F, | |
345 | ) where | |
346 | F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>, | |
94b46f34 | 347 | { |
0bf4aa26 | 348 | substs.reserve(defs.params.len()); |
94b46f34 XL |
349 | for param in &defs.params { |
350 | let kind = mk_kind(param, substs); | |
9c376795 | 351 | assert_eq!(param.index as usize, substs.len(), "{substs:#?}, {defs:#?}"); |
b7449926 | 352 | substs.push(kind); |
9e0c209e | 353 | } |
1a4d82fc JJ |
354 | } |
355 | ||
487cf647 FG |
356 | // Extend an `original_substs` list to the full number of substs expected by `def_id`, |
357 | // filling in the missing parameters with error ty/ct or 'static regions. | |
358 | pub fn extend_with_error( | |
359 | tcx: TyCtxt<'tcx>, | |
360 | def_id: DefId, | |
361 | original_substs: &[GenericArg<'tcx>], | |
362 | ) -> SubstsRef<'tcx> { | |
363 | ty::InternalSubsts::for_item(tcx, def_id, |def, substs| { | |
364 | if let Some(subst) = original_substs.get(def.index as usize) { | |
365 | *subst | |
366 | } else { | |
367 | def.to_error(tcx, substs) | |
368 | } | |
369 | }) | |
370 | } | |
371 | ||
9e0c209e | 372 | #[inline] |
923072b8 | 373 | pub fn types(&'tcx self) -> impl DoubleEndedIterator<Item = Ty<'tcx>> + 'tcx { |
49aad941 | 374 | self.iter().filter_map(|k| k.as_type()) |
1a4d82fc JJ |
375 | } |
376 | ||
9e0c209e | 377 | #[inline] |
923072b8 | 378 | pub fn regions(&'tcx self) -> impl DoubleEndedIterator<Item = ty::Region<'tcx>> + 'tcx { |
49aad941 | 379 | self.iter().filter_map(|k| k.as_region()) |
970d7e83 | 380 | } |
1a4d82fc | 381 | |
532ac7d7 | 382 | #[inline] |
923072b8 | 383 | pub fn consts(&'tcx self) -> impl DoubleEndedIterator<Item = ty::Const<'tcx>> + 'tcx { |
49aad941 | 384 | self.iter().filter_map(|k| k.as_const()) |
532ac7d7 XL |
385 | } |
386 | ||
387 | #[inline] | |
388 | pub fn non_erasable_generics( | |
923072b8 FG |
389 | &'tcx self, |
390 | ) -> impl DoubleEndedIterator<Item = GenericArgKind<'tcx>> + 'tcx { | |
dfeec247 XL |
391 | self.iter().filter_map(|k| match k.unpack() { |
392 | GenericArgKind::Lifetime(_) => None, | |
393 | generic => Some(generic), | |
532ac7d7 XL |
394 | }) |
395 | } | |
396 | ||
9e0c209e | 397 | #[inline] |
9c376795 | 398 | #[track_caller] |
9e0c209e | 399 | pub fn type_at(&self, i: usize) -> Ty<'tcx> { |
49aad941 | 400 | self[i].as_type().unwrap_or_else(|| bug!("expected type for param #{} in {:?}", i, self)) |
1a4d82fc | 401 | } |
1a4d82fc | 402 | |
9e0c209e | 403 | #[inline] |
9c376795 | 404 | #[track_caller] |
7cac9316 | 405 | pub fn region_at(&self, i: usize) -> ty::Region<'tcx> { |
49aad941 FG |
406 | self[i] |
407 | .as_region() | |
408 | .unwrap_or_else(|| bug!("expected region for param #{} in {:?}", i, self)) | |
1a4d82fc JJ |
409 | } |
410 | ||
532ac7d7 | 411 | #[inline] |
9c376795 | 412 | #[track_caller] |
5099ac24 | 413 | pub fn const_at(&self, i: usize) -> ty::Const<'tcx> { |
49aad941 | 414 | self[i].as_const().unwrap_or_else(|| bug!("expected const for param #{} in {:?}", i, self)) |
532ac7d7 XL |
415 | } |
416 | ||
9e0c209e | 417 | #[inline] |
9c376795 | 418 | #[track_caller] |
e74abb32 | 419 | pub fn type_for_def(&self, def: &ty::GenericParamDef) -> GenericArg<'tcx> { |
94b46f34 | 420 | self.type_at(def.index as usize).into() |
9e0c209e SL |
421 | } |
422 | ||
423 | /// Transform from substitutions for a child of `source_ancestor` | |
0731742a | 424 | /// (e.g., a trait or impl) to substitutions for the same child |
9e0c209e SL |
425 | /// in a different item, with `target_substs` as the base for |
426 | /// the target impl/trait, with the source child-specific | |
0731742a | 427 | /// parameters (e.g., method parameters) on top of that base. |
f035d41b XL |
428 | /// |
429 | /// For example given: | |
430 | /// | |
431 | /// ```no_run | |
432 | /// trait X<S> { fn f<T>(); } | |
433 | /// impl<U> X<U> for U { fn f<V>() {} } | |
434 | /// ``` | |
435 | /// | |
436 | /// * If `self` is `[Self, S, T]`: the identity substs of `f` in the trait. | |
437 | /// * If `source_ancestor` is the def_id of the trait. | |
438 | /// * If `target_substs` is `[U]`, the substs for the impl. | |
439 | /// * Then we will return `[U, T]`, the subst for `f` in the impl that | |
440 | /// are needed for it to match the trait. | |
dc9dc135 XL |
441 | pub fn rebase_onto( |
442 | &self, | |
443 | tcx: TyCtxt<'tcx>, | |
444 | source_ancestor: DefId, | |
445 | target_substs: SubstsRef<'tcx>, | |
446 | ) -> SubstsRef<'tcx> { | |
7cac9316 | 447 | let defs = tcx.generics_of(source_ancestor); |
9ffffee4 | 448 | tcx.mk_substs_from_iter(target_substs.iter().chain(self.iter().skip(defs.params.len()))) |
970d7e83 | 449 | } |
476ff2be | 450 | |
dc9dc135 | 451 | pub fn truncate_to(&self, tcx: TyCtxt<'tcx>, generics: &ty::Generics) -> SubstsRef<'tcx> { |
9ffffee4 | 452 | tcx.mk_substs_from_iter(self.iter().take(generics.count())) |
476ff2be | 453 | } |
970d7e83 LB |
454 | } |
455 | ||
9ffffee4 FG |
456 | impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for SubstsRef<'tcx> { |
457 | fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>( | |
458 | self, | |
459 | folder: &mut F, | |
460 | ) -> Result<Self, F::Error> { | |
e74abb32 XL |
461 | // This code is hot enough that it's worth specializing for the most |
462 | // common length lists, to avoid the overhead of `SmallVec` creation. | |
463 | // The match arms are in order of frequency. The 1, 2, and 0 cases are | |
464 | // typically hit in 90--99.99% of cases. When folding doesn't change | |
465 | // the substs, it's faster to reuse the existing substs rather than | |
9ffffee4 | 466 | // calling `mk_substs`. |
e74abb32 XL |
467 | match self.len() { |
468 | 1 => { | |
a2a8927a | 469 | let param0 = self[0].try_fold_with(folder)?; |
9ffffee4 FG |
470 | if param0 == self[0] { |
471 | Ok(self) | |
472 | } else { | |
473 | Ok(folder.interner().mk_substs(&[param0])) | |
474 | } | |
e74abb32 XL |
475 | } |
476 | 2 => { | |
a2a8927a XL |
477 | let param0 = self[0].try_fold_with(folder)?; |
478 | let param1 = self[1].try_fold_with(folder)?; | |
e74abb32 | 479 | if param0 == self[0] && param1 == self[1] { |
a2a8927a | 480 | Ok(self) |
e74abb32 | 481 | } else { |
9ffffee4 | 482 | Ok(folder.interner().mk_substs(&[param0, param1])) |
e74abb32 XL |
483 | } |
484 | } | |
a2a8927a | 485 | 0 => Ok(self), |
9ffffee4 | 486 | _ => ty::util::fold_list(self, folder, |tcx, v| tcx.mk_substs(v)), |
c30ab7b3 | 487 | } |
7453a54e | 488 | } |
064997fb | 489 | } |
85aaf69f | 490 | |
9ffffee4 FG |
491 | impl<'tcx> TypeFoldable<TyCtxt<'tcx>> for &'tcx ty::List<Ty<'tcx>> { |
492 | fn try_fold_with<F: FallibleTypeFolder<TyCtxt<'tcx>>>( | |
493 | self, | |
494 | folder: &mut F, | |
495 | ) -> Result<Self, F::Error> { | |
5e7ed085 FG |
496 | // This code is fairly hot, though not as hot as `SubstsRef`. |
497 | // | |
498 | // When compiling stage 2, I get the following results: | |
499 | // | |
500 | // len | total | % | |
501 | // --- | --------- | ----- | |
502 | // 2 | 15083590 | 48.1 | |
503 | // 3 | 7540067 | 24.0 | |
504 | // 1 | 5300377 | 16.9 | |
505 | // 4 | 1351897 | 4.3 | |
506 | // 0 | 1256849 | 4.0 | |
507 | // | |
508 | // I've tried it with some private repositories and got | |
509 | // close to the same result, with 4 and 0 swapping places | |
510 | // sometimes. | |
511 | match self.len() { | |
512 | 2 => { | |
513 | let param0 = self[0].try_fold_with(folder)?; | |
514 | let param1 = self[1].try_fold_with(folder)?; | |
515 | if param0 == self[0] && param1 == self[1] { | |
516 | Ok(self) | |
517 | } else { | |
9ffffee4 | 518 | Ok(folder.interner().mk_type_list(&[param0, param1])) |
5e7ed085 FG |
519 | } |
520 | } | |
9ffffee4 | 521 | _ => ty::util::fold_list(self, folder, |tcx, v| tcx.mk_type_list(v)), |
5e7ed085 FG |
522 | } |
523 | } | |
064997fb | 524 | } |
5e7ed085 | 525 | |
9ffffee4 | 526 | impl<'tcx, T: TypeVisitable<TyCtxt<'tcx>>> TypeVisitable<TyCtxt<'tcx>> for &'tcx ty::List<T> { |
2b03887a | 527 | #[inline] |
9ffffee4 | 528 | fn visit_with<V: TypeVisitor<TyCtxt<'tcx>>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> { |
5e7ed085 FG |
529 | self.iter().try_for_each(|t| t.visit_with(visitor)) |
530 | } | |
531 | } | |
532 | ||
487cf647 FG |
533 | /// Similar to [`super::Binder`] except that it tracks early bound generics, i.e. `struct Foo<T>(T)` |
534 | /// needs `T` substituted immediately. This type primarily exists to avoid forgetting to call | |
535 | /// `subst`. | |
9c376795 FG |
536 | /// |
537 | /// If you don't have anything to `subst`, you may be looking for | |
538 | /// [`subst_identity`](EarlyBinder::subst_identity) or [`skip_binder`](EarlyBinder::skip_binder). | |
2b03887a FG |
539 | #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] |
540 | #[derive(Encodable, Decodable, HashStable)] | |
541 | pub struct EarlyBinder<T>(pub T); | |
542 | ||
543 | /// For early binders, you should first call `subst` before using any visitors. | |
9ffffee4 FG |
544 | impl<'tcx, T> !TypeFoldable<TyCtxt<'tcx>> for ty::EarlyBinder<T> {} |
545 | impl<'tcx, T> !TypeVisitable<TyCtxt<'tcx>> for ty::EarlyBinder<T> {} | |
2b03887a FG |
546 | |
547 | impl<T> EarlyBinder<T> { | |
548 | pub fn as_ref(&self) -> EarlyBinder<&T> { | |
549 | EarlyBinder(&self.0) | |
550 | } | |
1a4d82fc | 551 | |
2b03887a FG |
552 | pub fn map_bound_ref<F, U>(&self, f: F) -> EarlyBinder<U> |
553 | where | |
554 | F: FnOnce(&T) -> U, | |
555 | { | |
556 | self.as_ref().map_bound(f) | |
557 | } | |
558 | ||
559 | pub fn map_bound<F, U>(self, f: F) -> EarlyBinder<U> | |
560 | where | |
561 | F: FnOnce(T) -> U, | |
562 | { | |
563 | let value = f(self.0); | |
564 | EarlyBinder(value) | |
565 | } | |
566 | ||
567 | pub fn try_map_bound<F, U, E>(self, f: F) -> Result<EarlyBinder<U>, E> | |
568 | where | |
569 | F: FnOnce(T) -> Result<U, E>, | |
570 | { | |
571 | let value = f(self.0)?; | |
572 | Ok(EarlyBinder(value)) | |
573 | } | |
574 | ||
575 | pub fn rebind<U>(&self, value: U) -> EarlyBinder<U> { | |
576 | EarlyBinder(value) | |
577 | } | |
9c376795 FG |
578 | |
579 | /// Skips the binder and returns the "bound" value. | |
580 | /// This can be used to extract data that does not depend on generic parameters | |
581 | /// (e.g., getting the `DefId` of the inner value or getting the number of | |
582 | /// arguments of an `FnSig`). Otherwise, consider using | |
583 | /// [`subst_identity`](EarlyBinder::subst_identity). | |
584 | /// | |
585 | /// See also [`Binder::skip_binder`](super::Binder::skip_binder), which is | |
586 | /// the analogous operation on [`super::Binder`]. | |
587 | pub fn skip_binder(self) -> T { | |
588 | self.0 | |
589 | } | |
1a4d82fc JJ |
590 | } |
591 | ||
2b03887a FG |
592 | impl<T> EarlyBinder<Option<T>> { |
593 | pub fn transpose(self) -> Option<EarlyBinder<T>> { | |
594 | self.0.map(|v| EarlyBinder(v)) | |
595 | } | |
596 | } | |
597 | ||
598 | impl<T, U> EarlyBinder<(T, U)> { | |
599 | pub fn transpose_tuple2(self) -> (EarlyBinder<T>, EarlyBinder<U>) { | |
600 | (EarlyBinder(self.0.0), EarlyBinder(self.0.1)) | |
601 | } | |
602 | } | |
04454e1e | 603 | |
487cf647 FG |
604 | impl<'tcx, 's, I: IntoIterator> EarlyBinder<I> |
605 | where | |
9ffffee4 | 606 | I::Item: TypeFoldable<TyCtxt<'tcx>>, |
487cf647 | 607 | { |
2b03887a FG |
608 | pub fn subst_iter( |
609 | self, | |
610 | tcx: TyCtxt<'tcx>, | |
611 | substs: &'s [GenericArg<'tcx>], | |
487cf647 FG |
612 | ) -> SubstIter<'s, 'tcx, I> { |
613 | SubstIter { it: self.0.into_iter(), tcx, substs } | |
614 | } | |
49aad941 FG |
615 | |
616 | /// Similar to [`subst_identity`](EarlyBinder::subst_identity), | |
617 | /// but on an iterator of `TypeFoldable` values. | |
618 | pub fn subst_identity_iter(self) -> I::IntoIter { | |
619 | self.0.into_iter() | |
620 | } | |
487cf647 FG |
621 | } |
622 | ||
623 | pub struct SubstIter<'s, 'tcx, I: IntoIterator> { | |
624 | it: I::IntoIter, | |
625 | tcx: TyCtxt<'tcx>, | |
626 | substs: &'s [GenericArg<'tcx>], | |
627 | } | |
628 | ||
629 | impl<'tcx, I: IntoIterator> Iterator for SubstIter<'_, 'tcx, I> | |
630 | where | |
9ffffee4 | 631 | I::Item: TypeFoldable<TyCtxt<'tcx>>, |
487cf647 FG |
632 | { |
633 | type Item = I::Item; | |
634 | ||
635 | fn next(&mut self) -> Option<Self::Item> { | |
636 | Some(EarlyBinder(self.it.next()?).subst(self.tcx, self.substs)) | |
637 | } | |
638 | ||
639 | fn size_hint(&self) -> (usize, Option<usize>) { | |
640 | self.it.size_hint() | |
2b03887a FG |
641 | } |
642 | } | |
643 | ||
487cf647 FG |
644 | impl<'tcx, I: IntoIterator> DoubleEndedIterator for SubstIter<'_, 'tcx, I> |
645 | where | |
646 | I::IntoIter: DoubleEndedIterator, | |
9ffffee4 | 647 | I::Item: TypeFoldable<TyCtxt<'tcx>>, |
487cf647 FG |
648 | { |
649 | fn next_back(&mut self) -> Option<Self::Item> { | |
650 | Some(EarlyBinder(self.it.next_back()?).subst(self.tcx, self.substs)) | |
651 | } | |
652 | } | |
653 | ||
9c376795 FG |
654 | impl<'tcx, I: IntoIterator> ExactSizeIterator for SubstIter<'_, 'tcx, I> |
655 | where | |
656 | I::IntoIter: ExactSizeIterator, | |
9ffffee4 | 657 | I::Item: TypeFoldable<TyCtxt<'tcx>>, |
9c376795 FG |
658 | { |
659 | } | |
660 | ||
487cf647 FG |
661 | impl<'tcx, 's, I: IntoIterator> EarlyBinder<I> |
662 | where | |
663 | I::Item: Deref, | |
9ffffee4 | 664 | <I::Item as Deref>::Target: Copy + TypeFoldable<TyCtxt<'tcx>>, |
2b03887a FG |
665 | { |
666 | pub fn subst_iter_copied( | |
667 | self, | |
668 | tcx: TyCtxt<'tcx>, | |
669 | substs: &'s [GenericArg<'tcx>], | |
487cf647 FG |
670 | ) -> SubstIterCopied<'s, 'tcx, I> { |
671 | SubstIterCopied { it: self.0.into_iter(), tcx, substs } | |
672 | } | |
49aad941 FG |
673 | |
674 | /// Similar to [`subst_identity`](EarlyBinder::subst_identity), | |
675 | /// but on an iterator of values that deref to a `TypeFoldable`. | |
676 | pub fn subst_identity_iter_copied(self) -> impl Iterator<Item = <I::Item as Deref>::Target> { | |
677 | self.0.into_iter().map(|v| *v) | |
678 | } | |
487cf647 FG |
679 | } |
680 | ||
681 | pub struct SubstIterCopied<'a, 'tcx, I: IntoIterator> { | |
682 | it: I::IntoIter, | |
683 | tcx: TyCtxt<'tcx>, | |
684 | substs: &'a [GenericArg<'tcx>], | |
685 | } | |
686 | ||
687 | impl<'tcx, I: IntoIterator> Iterator for SubstIterCopied<'_, 'tcx, I> | |
688 | where | |
689 | I::Item: Deref, | |
9ffffee4 | 690 | <I::Item as Deref>::Target: Copy + TypeFoldable<TyCtxt<'tcx>>, |
487cf647 FG |
691 | { |
692 | type Item = <I::Item as Deref>::Target; | |
693 | ||
694 | fn next(&mut self) -> Option<Self::Item> { | |
695 | Some(EarlyBinder(*self.it.next()?).subst(self.tcx, self.substs)) | |
696 | } | |
697 | ||
698 | fn size_hint(&self) -> (usize, Option<usize>) { | |
699 | self.it.size_hint() | |
700 | } | |
701 | } | |
702 | ||
703 | impl<'tcx, I: IntoIterator> DoubleEndedIterator for SubstIterCopied<'_, 'tcx, I> | |
704 | where | |
705 | I::IntoIter: DoubleEndedIterator, | |
706 | I::Item: Deref, | |
9ffffee4 | 707 | <I::Item as Deref>::Target: Copy + TypeFoldable<TyCtxt<'tcx>>, |
487cf647 FG |
708 | { |
709 | fn next_back(&mut self) -> Option<Self::Item> { | |
710 | Some(EarlyBinder(*self.it.next_back()?).subst(self.tcx, self.substs)) | |
2b03887a FG |
711 | } |
712 | } | |
713 | ||
9c376795 FG |
714 | impl<'tcx, I: IntoIterator> ExactSizeIterator for SubstIterCopied<'_, 'tcx, I> |
715 | where | |
716 | I::IntoIter: ExactSizeIterator, | |
717 | I::Item: Deref, | |
9ffffee4 | 718 | <I::Item as Deref>::Target: Copy + TypeFoldable<TyCtxt<'tcx>>, |
9c376795 FG |
719 | { |
720 | } | |
721 | ||
2b03887a FG |
722 | pub struct EarlyBinderIter<T> { |
723 | t: T, | |
724 | } | |
725 | ||
726 | impl<T: IntoIterator> EarlyBinder<T> { | |
727 | pub fn transpose_iter(self) -> EarlyBinderIter<T::IntoIter> { | |
728 | EarlyBinderIter { t: self.0.into_iter() } | |
729 | } | |
730 | } | |
731 | ||
732 | impl<T: Iterator> Iterator for EarlyBinderIter<T> { | |
733 | type Item = EarlyBinder<T::Item>; | |
734 | ||
735 | fn next(&mut self) -> Option<Self::Item> { | |
736 | self.t.next().map(|i| EarlyBinder(i)) | |
737 | } | |
487cf647 FG |
738 | |
739 | fn size_hint(&self) -> (usize, Option<usize>) { | |
740 | self.t.size_hint() | |
741 | } | |
2b03887a FG |
742 | } |
743 | ||
9ffffee4 | 744 | impl<'tcx, T: TypeFoldable<TyCtxt<'tcx>>> ty::EarlyBinder<T> { |
2b03887a | 745 | pub fn subst(self, tcx: TyCtxt<'tcx>, substs: &[GenericArg<'tcx>]) -> T { |
04454e1e FG |
746 | let mut folder = SubstFolder { tcx, substs, binders_passed: 0 }; |
747 | self.0.fold_with(&mut folder) | |
1a4d82fc | 748 | } |
9c376795 FG |
749 | |
750 | /// Makes the identity substitution `T0 => T0, ..., TN => TN`. | |
751 | /// Conceptually, this converts universally bound variables into placeholders | |
752 | /// when inside of a given item. | |
753 | /// | |
754 | /// For example, consider `for<T> fn foo<T>(){ .. }`: | |
755 | /// - Outside of `foo`, `T` is bound (represented by the presence of `EarlyBinder`). | |
756 | /// - Inside of the body of `foo`, we treat `T` as a placeholder by calling | |
757 | /// `subst_identity` to discharge the `EarlyBinder`. | |
758 | pub fn subst_identity(self) -> T { | |
759 | self.0 | |
760 | } | |
9ffffee4 FG |
761 | |
762 | /// Returns the inner value, but only if it contains no bound vars. | |
763 | pub fn no_bound_vars(self) -> Option<T> { | |
49aad941 | 764 | if !self.0.has_param() { Some(self.0) } else { None } |
9ffffee4 | 765 | } |
1a4d82fc JJ |
766 | } |
767 | ||
768 | /////////////////////////////////////////////////////////////////////////// | |
769 | // The actual substitution engine itself is a type folder. | |
770 | ||
dc9dc135 XL |
771 | struct SubstFolder<'a, 'tcx> { |
772 | tcx: TyCtxt<'tcx>, | |
e74abb32 | 773 | substs: &'a [GenericArg<'tcx>], |
1a4d82fc | 774 | |
48663c56 | 775 | /// Number of region binders we have passed through while doing the substitution |
a1dfa0c6 | 776 | binders_passed: u32, |
1a4d82fc JJ |
777 | } |
778 | ||
9ffffee4 | 779 | impl<'a, 'tcx> TypeFolder<TyCtxt<'tcx>> for SubstFolder<'a, 'tcx> { |
064997fb | 780 | #[inline] |
9ffffee4 | 781 | fn interner(&self) -> TyCtxt<'tcx> { |
dfeec247 XL |
782 | self.tcx |
783 | } | |
1a4d82fc | 784 | |
9ffffee4 | 785 | fn fold_binder<T: TypeFoldable<TyCtxt<'tcx>>>( |
cdc7bbd5 XL |
786 | &mut self, |
787 | t: ty::Binder<'tcx, T>, | |
788 | ) -> ty::Binder<'tcx, T> { | |
a1dfa0c6 | 789 | self.binders_passed += 1; |
54a0048b | 790 | let t = t.super_fold_with(self); |
a1dfa0c6 | 791 | self.binders_passed -= 1; |
54a0048b | 792 | t |
1a4d82fc JJ |
793 | } |
794 | ||
7cac9316 | 795 | fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { |
064997fb FG |
796 | #[cold] |
797 | #[inline(never)] | |
2b03887a | 798 | fn region_param_out_of_range(data: ty::EarlyBoundRegion, substs: &[GenericArg<'_>]) -> ! { |
064997fb | 799 | bug!( |
2b03887a FG |
800 | "Region parameter out of range when substituting in region {} (index={}, substs = {:?})", |
801 | data.name, | |
802 | data.index, | |
803 | substs, | |
804 | ) | |
805 | } | |
806 | ||
807 | #[cold] | |
808 | #[inline(never)] | |
809 | fn region_param_invalid(data: ty::EarlyBoundRegion, other: GenericArgKind<'_>) -> ! { | |
810 | bug!( | |
811 | "Unexpected parameter {:?} when substituting in region {} (index={})", | |
812 | other, | |
064997fb FG |
813 | data.name, |
814 | data.index | |
815 | ) | |
816 | } | |
817 | ||
1a4d82fc JJ |
818 | // Note: This routine only handles regions that are bound on |
819 | // type declarations and other outer declarations, not those | |
820 | // bound in *fn types*. Region substitution of the bound | |
821 | // regions that appear in a function signature is done using | |
822 | // the specialized routine `ty::replace_late_regions()`. | |
9e0c209e | 823 | match *r { |
9346a6ac | 824 | ty::ReEarlyBound(data) => { |
48663c56 XL |
825 | let rk = self.substs.get(data.index as usize).map(|k| k.unpack()); |
826 | match rk { | |
dfeec247 | 827 | Some(GenericArgKind::Lifetime(lt)) => self.shift_region_through_binders(lt), |
2b03887a FG |
828 | Some(other) => region_param_invalid(data, other), |
829 | None => region_param_out_of_range(data, self.substs), | |
970d7e83 LB |
830 | } |
831 | } | |
49aad941 FG |
832 | ty::ReLateBound(..) |
833 | | ty::ReFree(_) | |
834 | | ty::ReStatic | |
835 | | ty::RePlaceholder(_) | |
836 | | ty::ReErased | |
837 | | ty::ReError(_) => r, | |
838 | ty::ReVar(_) => bug!("unexpected region: {r:?}"), | |
970d7e83 LB |
839 | } |
840 | } | |
1a4d82fc JJ |
841 | |
842 | fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { | |
49aad941 | 843 | if !t.has_param() { |
1a4d82fc JJ |
844 | return t; |
845 | } | |
846 | ||
1b1a35ee | 847 | match *t.kind() { |
dfeec247 XL |
848 | ty::Param(p) => self.ty_for_param(p, t), |
849 | _ => t.super_fold_with(self), | |
1a4d82fc | 850 | } |
1a4d82fc | 851 | } |
532ac7d7 | 852 | |
5099ac24 | 853 | fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx> { |
923072b8 | 854 | if let ty::ConstKind::Param(p) = c.kind() { |
532ac7d7 XL |
855 | self.const_for_param(p, c) |
856 | } else { | |
857 | c.super_fold_with(self) | |
858 | } | |
859 | } | |
970d7e83 LB |
860 | } |
861 | ||
dc9dc135 | 862 | impl<'a, 'tcx> SubstFolder<'a, 'tcx> { |
1a4d82fc JJ |
863 | fn ty_for_param(&self, p: ty::ParamTy, source_ty: Ty<'tcx>) -> Ty<'tcx> { |
864 | // Look up the type in the substitutions. It really should be in there. | |
48663c56 | 865 | let opt_ty = self.substs.get(p.index as usize).map(|k| k.unpack()); |
1a4d82fc | 866 | let ty = match opt_ty { |
e74abb32 | 867 | Some(GenericArgKind::Type(ty)) => ty, |
064997fb FG |
868 | Some(kind) => self.type_param_expected(p, source_ty, kind), |
869 | None => self.type_param_out_of_range(p, source_ty), | |
1a4d82fc JJ |
870 | }; |
871 | ||
a1dfa0c6 | 872 | self.shift_vars_through_binders(ty) |
1a4d82fc JJ |
873 | } |
874 | ||
064997fb FG |
875 | #[cold] |
876 | #[inline(never)] | |
877 | fn type_param_expected(&self, p: ty::ParamTy, ty: Ty<'tcx>, kind: GenericArgKind<'tcx>) -> ! { | |
878 | bug!( | |
879 | "expected type for `{:?}` ({:?}/{}) but found {:?} when substituting, substs={:?}", | |
880 | p, | |
881 | ty, | |
882 | p.index, | |
883 | kind, | |
884 | self.substs, | |
885 | ) | |
886 | } | |
887 | ||
888 | #[cold] | |
889 | #[inline(never)] | |
890 | fn type_param_out_of_range(&self, p: ty::ParamTy, ty: Ty<'tcx>) -> ! { | |
891 | bug!( | |
892 | "type parameter `{:?}` ({:?}/{}) out of range when substituting, substs={:?}", | |
893 | p, | |
894 | ty, | |
895 | p.index, | |
896 | self.substs, | |
897 | ) | |
898 | } | |
899 | ||
5099ac24 | 900 | fn const_for_param(&self, p: ParamConst, source_ct: ty::Const<'tcx>) -> ty::Const<'tcx> { |
532ac7d7 | 901 | // Look up the const in the substitutions. It really should be in there. |
48663c56 XL |
902 | let opt_ct = self.substs.get(p.index as usize).map(|k| k.unpack()); |
903 | let ct = match opt_ct { | |
e74abb32 | 904 | Some(GenericArgKind::Const(ct)) => ct, |
064997fb FG |
905 | Some(kind) => self.const_param_expected(p, source_ct, kind), |
906 | None => self.const_param_out_of_range(p, source_ct), | |
532ac7d7 XL |
907 | }; |
908 | ||
48663c56 | 909 | self.shift_vars_through_binders(ct) |
532ac7d7 XL |
910 | } |
911 | ||
064997fb FG |
912 | #[cold] |
913 | #[inline(never)] | |
914 | fn const_param_expected( | |
915 | &self, | |
916 | p: ty::ParamConst, | |
917 | ct: ty::Const<'tcx>, | |
918 | kind: GenericArgKind<'tcx>, | |
919 | ) -> ! { | |
920 | bug!( | |
921 | "expected const for `{:?}` ({:?}/{}) but found {:?} when substituting substs={:?}", | |
922 | p, | |
923 | ct, | |
924 | p.index, | |
925 | kind, | |
926 | self.substs, | |
927 | ) | |
928 | } | |
929 | ||
930 | #[cold] | |
931 | #[inline(never)] | |
932 | fn const_param_out_of_range(&self, p: ty::ParamConst, ct: ty::Const<'tcx>) -> ! { | |
933 | bug!( | |
934 | "const parameter `{:?}` ({:?}/{}) out of range when substituting substs={:?}", | |
935 | p, | |
936 | ct, | |
937 | p.index, | |
938 | self.substs, | |
939 | ) | |
940 | } | |
941 | ||
9fa01778 | 942 | /// It is sometimes necessary to adjust the De Bruijn indices during substitution. This occurs |
a1dfa0c6 XL |
943 | /// when we are substituting a type with escaping bound vars into a context where we have |
944 | /// passed through binders. That's quite a mouthful. Let's see an example: | |
1a4d82fc JJ |
945 | /// |
946 | /// ``` | |
947 | /// type Func<A> = fn(A); | |
04454e1e | 948 | /// type MetaFunc = for<'a> fn(Func<&'a i32>); |
1a4d82fc JJ |
949 | /// ``` |
950 | /// | |
951 | /// The type `MetaFunc`, when fully expanded, will be | |
04454e1e FG |
952 | /// ```ignore (illustrative) |
953 | /// for<'a> fn(fn(&'a i32)) | |
954 | /// // ^~ ^~ ^~~ | |
955 | /// // | | | | |
956 | /// // | | DebruijnIndex of 2 | |
957 | /// // Binders | |
958 | /// ``` | |
1a4d82fc JJ |
959 | /// Here the `'a` lifetime is bound in the outer function, but appears as an argument of the |
960 | /// inner one. Therefore, that appearance will have a DebruijnIndex of 2, because we must skip | |
9fa01778 | 961 | /// over the inner binder (remember that we count De Bruijn indices from 1). However, in the |
f035d41b | 962 | /// definition of `MetaFunc`, the binder is not visible, so the type `&'a i32` will have a |
9fa01778 | 963 | /// De Bruijn index of 1. It's only during the substitution that we can see we must increase the |
1a4d82fc JJ |
964 | /// depth by 1 to account for the binder that we passed through. |
965 | /// | |
966 | /// As a second example, consider this twist: | |
967 | /// | |
968 | /// ``` | |
969 | /// type FuncTuple<A> = (A,fn(A)); | |
04454e1e | 970 | /// type MetaFuncTuple = for<'a> fn(FuncTuple<&'a i32>); |
1a4d82fc JJ |
971 | /// ``` |
972 | /// | |
973 | /// Here the final type will be: | |
04454e1e FG |
974 | /// ```ignore (illustrative) |
975 | /// for<'a> fn((&'a i32, fn(&'a i32))) | |
976 | /// // ^~~ ^~~ | |
977 | /// // | | | |
978 | /// // DebruijnIndex of 1 | | |
979 | /// // DebruijnIndex of 2 | |
980 | /// ``` | |
f035d41b | 981 | /// As indicated in the diagram, here the same type `&'a i32` is substituted once, but in the |
9fa01778 | 982 | /// first case we do not increase the De Bruijn index and in the second case we do. The reason |
1a4d82fc | 983 | /// is that only in the second case have we passed through a fn binder. |
9ffffee4 | 984 | fn shift_vars_through_binders<T: TypeFoldable<TyCtxt<'tcx>>>(&self, val: T) -> T { |
dfeec247 XL |
985 | debug!( |
986 | "shift_vars(val={:?}, binders_passed={:?}, has_escaping_bound_vars={:?})", | |
987 | val, | |
988 | self.binders_passed, | |
989 | val.has_escaping_bound_vars() | |
990 | ); | |
1a4d82fc | 991 | |
48663c56 XL |
992 | if self.binders_passed == 0 || !val.has_escaping_bound_vars() { |
993 | return val; | |
970d7e83 | 994 | } |
1a4d82fc | 995 | |
9ffffee4 | 996 | let result = ty::fold::shift_vars(TypeFolder::interner(self), val, self.binders_passed); |
a1dfa0c6 | 997 | debug!("shift_vars: shifted result = {:?}", result); |
1a4d82fc JJ |
998 | |
999 | result | |
1000 | } | |
1001 | ||
7cac9316 | 1002 | fn shift_region_through_binders(&self, region: ty::Region<'tcx>) -> ty::Region<'tcx> { |
a1dfa0c6 | 1003 | if self.binders_passed == 0 || !region.has_escaping_bound_vars() { |
cc61c64b XL |
1004 | return region; |
1005 | } | |
a1dfa0c6 | 1006 | ty::fold::shift_region(self.tcx, region, self.binders_passed) |
9e0c209e SL |
1007 | } |
1008 | } | |
0bf4aa26 | 1009 | |
0bf4aa26 XL |
1010 | /// Stores the user-given substs to reach some fully qualified path |
1011 | /// (e.g., `<T>::Item` or `<T as Trait>::Item`). | |
3dfed10e | 1012 | #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable)] |
064997fb | 1013 | #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)] |
0bf4aa26 XL |
1014 | pub struct UserSubsts<'tcx> { |
1015 | /// The substitutions for the item as given by the user. | |
532ac7d7 | 1016 | pub substs: SubstsRef<'tcx>, |
0bf4aa26 | 1017 | |
9fa01778 | 1018 | /// The self type, in the case of a `<T>::Item` path (when applied |
0bf4aa26 XL |
1019 | /// to an inherent impl). See `UserSelfTy` below. |
1020 | pub user_self_ty: Option<UserSelfTy<'tcx>>, | |
1021 | } | |
1022 | ||
9fa01778 XL |
1023 | /// Specifies the user-given self type. In the case of a path that |
1024 | /// refers to a member in an inherent impl, this self type is | |
0bf4aa26 XL |
1025 | /// sometimes needed to constrain the type parameters on the impl. For |
1026 | /// example, in this code: | |
1027 | /// | |
04454e1e | 1028 | /// ```ignore (illustrative) |
0bf4aa26 XL |
1029 | /// struct Foo<T> { } |
1030 | /// impl<A> Foo<A> { fn method() { } } | |
1031 | /// ``` | |
1032 | /// | |
1033 | /// when you then have a path like `<Foo<&'static u32>>::method`, | |
9fa01778 XL |
1034 | /// this struct would carry the `DefId` of the impl along with the |
1035 | /// self type `Foo<u32>`. Then we can instantiate the parameters of | |
0bf4aa26 | 1036 | /// the impl (with the substs from `UserSubsts`) and apply those to |
9fa01778 XL |
1037 | /// the self type, giving `Foo<?A>`. Finally, we unify that with |
1038 | /// the self type here, which contains `?A` to be `&'static u32` | |
3dfed10e | 1039 | #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable)] |
064997fb | 1040 | #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)] |
0bf4aa26 XL |
1041 | pub struct UserSelfTy<'tcx> { |
1042 | pub impl_def_id: DefId, | |
1043 | pub self_ty: Ty<'tcx>, | |
1044 | } |