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