]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/sty.rs
Auto merge of #100968 - cjgillot:mir-upvar-vec, r=wesleywiser
[rust.git] / compiler / rustc_middle / src / ty / sty.rs
1 //! This module contains `TyKind` and its major components.
2
3 #![allow(rustc::usage_of_ty_tykind)]
4
5 use crate::infer::canonical::Canonical;
6 use crate::ty::subst::{GenericArg, InternalSubsts, Subst, SubstsRef};
7 use crate::ty::visit::ValidateBoundVars;
8 use crate::ty::InferTy::*;
9 use crate::ty::{
10     self, AdtDef, DefIdTree, Discr, Term, Ty, TyCtxt, TypeFlags, TypeSuperVisitable, TypeVisitable,
11     TypeVisitor,
12 };
13 use crate::ty::{List, ParamEnv};
14 use hir::def::DefKind;
15 use polonius_engine::Atom;
16 use rustc_data_structures::captures::Captures;
17 use rustc_data_structures::intern::Interned;
18 use rustc_hir as hir;
19 use rustc_hir::def_id::DefId;
20 use rustc_index::vec::Idx;
21 use rustc_macros::HashStable;
22 use rustc_span::symbol::{kw, Symbol};
23 use rustc_target::abi::VariantIdx;
24 use rustc_target::spec::abi;
25 use std::borrow::Cow;
26 use std::cmp::Ordering;
27 use std::fmt;
28 use std::marker::PhantomData;
29 use std::ops::{ControlFlow, Deref, Range};
30 use ty::util::IntTypeExt;
31
32 use rustc_type_ir::sty::TyKind::*;
33 use rustc_type_ir::RegionKind as IrRegionKind;
34 use rustc_type_ir::TyKind as IrTyKind;
35
36 // Re-export the `TyKind` from `rustc_type_ir` here for convenience
37 #[rustc_diagnostic_item = "TyKind"]
38 pub type TyKind<'tcx> = IrTyKind<TyCtxt<'tcx>>;
39 pub type RegionKind<'tcx> = IrRegionKind<TyCtxt<'tcx>>;
40
41 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
42 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
43 pub struct TypeAndMut<'tcx> {
44     pub ty: Ty<'tcx>,
45     pub mutbl: hir::Mutability,
46 }
47
48 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, TyEncodable, TyDecodable, Copy)]
49 #[derive(HashStable)]
50 /// A "free" region `fr` can be interpreted as "some region
51 /// at least as big as the scope `fr.scope`".
52 pub struct FreeRegion {
53     pub scope: DefId,
54     pub bound_region: BoundRegionKind,
55 }
56
57 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, TyEncodable, TyDecodable, Copy)]
58 #[derive(HashStable)]
59 pub enum BoundRegionKind {
60     /// An anonymous region parameter for a given fn (&T)
61     BrAnon(u32),
62
63     /// Named region parameters for functions (a in &'a T)
64     ///
65     /// The `DefId` is needed to distinguish free regions in
66     /// the event of shadowing.
67     BrNamed(DefId, Symbol),
68
69     /// Anonymous region for the implicit env pointer parameter
70     /// to a closure
71     BrEnv,
72 }
73
74 #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, Debug, PartialOrd, Ord)]
75 #[derive(HashStable)]
76 pub struct BoundRegion {
77     pub var: BoundVar,
78     pub kind: BoundRegionKind,
79 }
80
81 impl BoundRegionKind {
82     pub fn is_named(&self) -> bool {
83         match *self {
84             BoundRegionKind::BrNamed(_, name) => name != kw::UnderscoreLifetime,
85             _ => false,
86         }
87     }
88 }
89
90 pub trait Article {
91     fn article(&self) -> &'static str;
92 }
93
94 impl<'tcx> Article for TyKind<'tcx> {
95     /// Get the article ("a" or "an") to use with this type.
96     fn article(&self) -> &'static str {
97         match self {
98             Int(_) | Float(_) | Array(_, _) => "an",
99             Adt(def, _) if def.is_enum() => "an",
100             // This should never happen, but ICEing and causing the user's code
101             // to not compile felt too harsh.
102             Error(_) => "a",
103             _ => "a",
104         }
105     }
106 }
107
108 // `TyKind` is used a lot. Make sure it doesn't unintentionally get bigger.
109 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
110 static_assert_size!(TyKind<'_>, 32);
111
112 /// A closure can be modeled as a struct that looks like:
113 /// ```ignore (illustrative)
114 /// struct Closure<'l0...'li, T0...Tj, CK, CS, U>(...U);
115 /// ```
116 /// where:
117 ///
118 /// - 'l0...'li and T0...Tj are the generic parameters
119 ///   in scope on the function that defined the closure,
120 /// - CK represents the *closure kind* (Fn vs FnMut vs FnOnce). This
121 ///   is rather hackily encoded via a scalar type. See
122 ///   `Ty::to_opt_closure_kind` for details.
123 /// - CS represents the *closure signature*, representing as a `fn()`
124 ///   type. For example, `fn(u32, u32) -> u32` would mean that the closure
125 ///   implements `CK<(u32, u32), Output = u32>`, where `CK` is the trait
126 ///   specified above.
127 /// - U is a type parameter representing the types of its upvars, tupled up
128 ///   (borrowed, if appropriate; that is, if a U field represents a by-ref upvar,
129 ///    and the up-var has the type `Foo`, then that field of U will be `&Foo`).
130 ///
131 /// So, for example, given this function:
132 /// ```ignore (illustrative)
133 /// fn foo<'a, T>(data: &'a mut T) {
134 ///      do(|| data.count += 1)
135 /// }
136 /// ```
137 /// the type of the closure would be something like:
138 /// ```ignore (illustrative)
139 /// struct Closure<'a, T, U>(...U);
140 /// ```
141 /// Note that the type of the upvar is not specified in the struct.
142 /// You may wonder how the impl would then be able to use the upvar,
143 /// if it doesn't know it's type? The answer is that the impl is
144 /// (conceptually) not fully generic over Closure but rather tied to
145 /// instances with the expected upvar types:
146 /// ```ignore (illustrative)
147 /// impl<'b, 'a, T> FnMut() for Closure<'a, T, (&'b mut &'a mut T,)> {
148 ///     ...
149 /// }
150 /// ```
151 /// You can see that the *impl* fully specified the type of the upvar
152 /// and thus knows full well that `data` has type `&'b mut &'a mut T`.
153 /// (Here, I am assuming that `data` is mut-borrowed.)
154 ///
155 /// Now, the last question you may ask is: Why include the upvar types
156 /// in an extra type parameter? The reason for this design is that the
157 /// upvar types can reference lifetimes that are internal to the
158 /// creating function. In my example above, for example, the lifetime
159 /// `'b` represents the scope of the closure itself; this is some
160 /// subset of `foo`, probably just the scope of the call to the to
161 /// `do()`. If we just had the lifetime/type parameters from the
162 /// enclosing function, we couldn't name this lifetime `'b`. Note that
163 /// there can also be lifetimes in the types of the upvars themselves,
164 /// if one of them happens to be a reference to something that the
165 /// creating fn owns.
166 ///
167 /// OK, you say, so why not create a more minimal set of parameters
168 /// that just includes the extra lifetime parameters? The answer is
169 /// primarily that it would be hard --- we don't know at the time when
170 /// we create the closure type what the full types of the upvars are,
171 /// nor do we know which are borrowed and which are not. In this
172 /// design, we can just supply a fresh type parameter and figure that
173 /// out later.
174 ///
175 /// All right, you say, but why include the type parameters from the
176 /// original function then? The answer is that codegen may need them
177 /// when monomorphizing, and they may not appear in the upvars. A
178 /// closure could capture no variables but still make use of some
179 /// in-scope type parameter with a bound (e.g., if our example above
180 /// had an extra `U: Default`, and the closure called `U::default()`).
181 ///
182 /// There is another reason. This design (implicitly) prohibits
183 /// closures from capturing themselves (except via a trait
184 /// object). This simplifies closure inference considerably, since it
185 /// means that when we infer the kind of a closure or its upvars, we
186 /// don't have to handle cycles where the decisions we make for
187 /// closure C wind up influencing the decisions we ought to make for
188 /// closure C (which would then require fixed point iteration to
189 /// handle). Plus it fixes an ICE. :P
190 ///
191 /// ## Generators
192 ///
193 /// Generators are handled similarly in `GeneratorSubsts`.  The set of
194 /// type parameters is similar, but `CK` and `CS` are replaced by the
195 /// following type parameters:
196 ///
197 /// * `GS`: The generator's "resume type", which is the type of the
198 ///   argument passed to `resume`, and the type of `yield` expressions
199 ///   inside the generator.
200 /// * `GY`: The "yield type", which is the type of values passed to
201 ///   `yield` inside the generator.
202 /// * `GR`: The "return type", which is the type of value returned upon
203 ///   completion of the generator.
204 /// * `GW`: The "generator witness".
205 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable)]
206 pub struct ClosureSubsts<'tcx> {
207     /// Lifetime and type parameters from the enclosing function,
208     /// concatenated with a tuple containing the types of the upvars.
209     ///
210     /// These are separated out because codegen wants to pass them around
211     /// when monomorphizing.
212     pub substs: SubstsRef<'tcx>,
213 }
214
215 /// Struct returned by `split()`.
216 pub struct ClosureSubstsParts<'tcx, T> {
217     pub parent_substs: &'tcx [GenericArg<'tcx>],
218     pub closure_kind_ty: T,
219     pub closure_sig_as_fn_ptr_ty: T,
220     pub tupled_upvars_ty: T,
221 }
222
223 impl<'tcx> ClosureSubsts<'tcx> {
224     /// Construct `ClosureSubsts` from `ClosureSubstsParts`, containing `Substs`
225     /// for the closure parent, alongside additional closure-specific components.
226     pub fn new(
227         tcx: TyCtxt<'tcx>,
228         parts: ClosureSubstsParts<'tcx, Ty<'tcx>>,
229     ) -> ClosureSubsts<'tcx> {
230         ClosureSubsts {
231             substs: tcx.mk_substs(
232                 parts.parent_substs.iter().copied().chain(
233                     [parts.closure_kind_ty, parts.closure_sig_as_fn_ptr_ty, parts.tupled_upvars_ty]
234                         .iter()
235                         .map(|&ty| ty.into()),
236                 ),
237             ),
238         }
239     }
240
241     /// Divides the closure substs into their respective components.
242     /// The ordering assumed here must match that used by `ClosureSubsts::new` above.
243     fn split(self) -> ClosureSubstsParts<'tcx, GenericArg<'tcx>> {
244         match self.substs[..] {
245             [
246                 ref parent_substs @ ..,
247                 closure_kind_ty,
248                 closure_sig_as_fn_ptr_ty,
249                 tupled_upvars_ty,
250             ] => ClosureSubstsParts {
251                 parent_substs,
252                 closure_kind_ty,
253                 closure_sig_as_fn_ptr_ty,
254                 tupled_upvars_ty,
255             },
256             _ => bug!("closure substs missing synthetics"),
257         }
258     }
259
260     /// Returns `true` only if enough of the synthetic types are known to
261     /// allow using all of the methods on `ClosureSubsts` without panicking.
262     ///
263     /// Used primarily by `ty::print::pretty` to be able to handle closure
264     /// types that haven't had their synthetic types substituted in.
265     pub fn is_valid(self) -> bool {
266         self.substs.len() >= 3
267             && matches!(self.split().tupled_upvars_ty.expect_ty().kind(), Tuple(_))
268     }
269
270     /// Returns the substitutions of the closure's parent.
271     pub fn parent_substs(self) -> &'tcx [GenericArg<'tcx>] {
272         self.split().parent_substs
273     }
274
275     /// Returns an iterator over the list of types of captured paths by the closure.
276     /// In case there was a type error in figuring out the types of the captured path, an
277     /// empty iterator is returned.
278     #[inline]
279     pub fn upvar_tys(self) -> impl Iterator<Item = Ty<'tcx>> + 'tcx {
280         match self.tupled_upvars_ty().kind() {
281             TyKind::Error(_) => None,
282             TyKind::Tuple(..) => Some(self.tupled_upvars_ty().tuple_fields()),
283             TyKind::Infer(_) => bug!("upvar_tys called before capture types are inferred"),
284             ty => bug!("Unexpected representation of upvar types tuple {:?}", ty),
285         }
286         .into_iter()
287         .flatten()
288     }
289
290     /// Returns the tuple type representing the upvars for this closure.
291     #[inline]
292     pub fn tupled_upvars_ty(self) -> Ty<'tcx> {
293         self.split().tupled_upvars_ty.expect_ty()
294     }
295
296     /// Returns the closure kind for this closure; may return a type
297     /// variable during inference. To get the closure kind during
298     /// inference, use `infcx.closure_kind(substs)`.
299     pub fn kind_ty(self) -> Ty<'tcx> {
300         self.split().closure_kind_ty.expect_ty()
301     }
302
303     /// Returns the `fn` pointer type representing the closure signature for this
304     /// closure.
305     // FIXME(eddyb) this should be unnecessary, as the shallowly resolved
306     // type is known at the time of the creation of `ClosureSubsts`,
307     // see `rustc_typeck::check::closure`.
308     pub fn sig_as_fn_ptr_ty(self) -> Ty<'tcx> {
309         self.split().closure_sig_as_fn_ptr_ty.expect_ty()
310     }
311
312     /// Returns the closure kind for this closure; only usable outside
313     /// of an inference context, because in that context we know that
314     /// there are no type variables.
315     ///
316     /// If you have an inference context, use `infcx.closure_kind()`.
317     pub fn kind(self) -> ty::ClosureKind {
318         self.kind_ty().to_opt_closure_kind().unwrap()
319     }
320
321     /// Extracts the signature from the closure.
322     pub fn sig(self) -> ty::PolyFnSig<'tcx> {
323         let ty = self.sig_as_fn_ptr_ty();
324         match ty.kind() {
325             ty::FnPtr(sig) => *sig,
326             _ => bug!("closure_sig_as_fn_ptr_ty is not a fn-ptr: {:?}", ty.kind()),
327         }
328     }
329
330     pub fn print_as_impl_trait(self) -> ty::print::PrintClosureAsImpl<'tcx> {
331         ty::print::PrintClosureAsImpl { closure: self }
332     }
333 }
334
335 /// Similar to `ClosureSubsts`; see the above documentation for more.
336 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable)]
337 pub struct GeneratorSubsts<'tcx> {
338     pub substs: SubstsRef<'tcx>,
339 }
340
341 pub struct GeneratorSubstsParts<'tcx, T> {
342     pub parent_substs: &'tcx [GenericArg<'tcx>],
343     pub resume_ty: T,
344     pub yield_ty: T,
345     pub return_ty: T,
346     pub witness: T,
347     pub tupled_upvars_ty: T,
348 }
349
350 impl<'tcx> GeneratorSubsts<'tcx> {
351     /// Construct `GeneratorSubsts` from `GeneratorSubstsParts`, containing `Substs`
352     /// for the generator parent, alongside additional generator-specific components.
353     pub fn new(
354         tcx: TyCtxt<'tcx>,
355         parts: GeneratorSubstsParts<'tcx, Ty<'tcx>>,
356     ) -> GeneratorSubsts<'tcx> {
357         GeneratorSubsts {
358             substs: tcx.mk_substs(
359                 parts.parent_substs.iter().copied().chain(
360                     [
361                         parts.resume_ty,
362                         parts.yield_ty,
363                         parts.return_ty,
364                         parts.witness,
365                         parts.tupled_upvars_ty,
366                     ]
367                     .iter()
368                     .map(|&ty| ty.into()),
369                 ),
370             ),
371         }
372     }
373
374     /// Divides the generator substs into their respective components.
375     /// The ordering assumed here must match that used by `GeneratorSubsts::new` above.
376     fn split(self) -> GeneratorSubstsParts<'tcx, GenericArg<'tcx>> {
377         match self.substs[..] {
378             [ref parent_substs @ .., resume_ty, yield_ty, return_ty, witness, tupled_upvars_ty] => {
379                 GeneratorSubstsParts {
380                     parent_substs,
381                     resume_ty,
382                     yield_ty,
383                     return_ty,
384                     witness,
385                     tupled_upvars_ty,
386                 }
387             }
388             _ => bug!("generator substs missing synthetics"),
389         }
390     }
391
392     /// Returns `true` only if enough of the synthetic types are known to
393     /// allow using all of the methods on `GeneratorSubsts` without panicking.
394     ///
395     /// Used primarily by `ty::print::pretty` to be able to handle generator
396     /// types that haven't had their synthetic types substituted in.
397     pub fn is_valid(self) -> bool {
398         self.substs.len() >= 5
399             && matches!(self.split().tupled_upvars_ty.expect_ty().kind(), Tuple(_))
400     }
401
402     /// Returns the substitutions of the generator's parent.
403     pub fn parent_substs(self) -> &'tcx [GenericArg<'tcx>] {
404         self.split().parent_substs
405     }
406
407     /// This describes the types that can be contained in a generator.
408     /// It will be a type variable initially and unified in the last stages of typeck of a body.
409     /// It contains a tuple of all the types that could end up on a generator frame.
410     /// The state transformation MIR pass may only produce layouts which mention types
411     /// in this tuple. Upvars are not counted here.
412     pub fn witness(self) -> Ty<'tcx> {
413         self.split().witness.expect_ty()
414     }
415
416     /// Returns an iterator over the list of types of captured paths by the generator.
417     /// In case there was a type error in figuring out the types of the captured path, an
418     /// empty iterator is returned.
419     #[inline]
420     pub fn upvar_tys(self) -> impl Iterator<Item = Ty<'tcx>> + 'tcx {
421         match self.tupled_upvars_ty().kind() {
422             TyKind::Error(_) => None,
423             TyKind::Tuple(..) => Some(self.tupled_upvars_ty().tuple_fields()),
424             TyKind::Infer(_) => bug!("upvar_tys called before capture types are inferred"),
425             ty => bug!("Unexpected representation of upvar types tuple {:?}", ty),
426         }
427         .into_iter()
428         .flatten()
429     }
430
431     /// Returns the tuple type representing the upvars for this generator.
432     #[inline]
433     pub fn tupled_upvars_ty(self) -> Ty<'tcx> {
434         self.split().tupled_upvars_ty.expect_ty()
435     }
436
437     /// Returns the type representing the resume type of the generator.
438     pub fn resume_ty(self) -> Ty<'tcx> {
439         self.split().resume_ty.expect_ty()
440     }
441
442     /// Returns the type representing the yield type of the generator.
443     pub fn yield_ty(self) -> Ty<'tcx> {
444         self.split().yield_ty.expect_ty()
445     }
446
447     /// Returns the type representing the return type of the generator.
448     pub fn return_ty(self) -> Ty<'tcx> {
449         self.split().return_ty.expect_ty()
450     }
451
452     /// Returns the "generator signature", which consists of its yield
453     /// and return types.
454     ///
455     /// N.B., some bits of the code prefers to see this wrapped in a
456     /// binder, but it never contains bound regions. Probably this
457     /// function should be removed.
458     pub fn poly_sig(self) -> PolyGenSig<'tcx> {
459         ty::Binder::dummy(self.sig())
460     }
461
462     /// Returns the "generator signature", which consists of its resume, yield
463     /// and return types.
464     pub fn sig(self) -> GenSig<'tcx> {
465         ty::GenSig {
466             resume_ty: self.resume_ty(),
467             yield_ty: self.yield_ty(),
468             return_ty: self.return_ty(),
469         }
470     }
471 }
472
473 impl<'tcx> GeneratorSubsts<'tcx> {
474     /// Generator has not been resumed yet.
475     pub const UNRESUMED: usize = 0;
476     /// Generator has returned or is completed.
477     pub const RETURNED: usize = 1;
478     /// Generator has been poisoned.
479     pub const POISONED: usize = 2;
480
481     const UNRESUMED_NAME: &'static str = "Unresumed";
482     const RETURNED_NAME: &'static str = "Returned";
483     const POISONED_NAME: &'static str = "Panicked";
484
485     /// The valid variant indices of this generator.
486     #[inline]
487     pub fn variant_range(&self, def_id: DefId, tcx: TyCtxt<'tcx>) -> Range<VariantIdx> {
488         // FIXME requires optimized MIR
489         let num_variants = tcx.generator_layout(def_id).unwrap().variant_fields.len();
490         VariantIdx::new(0)..VariantIdx::new(num_variants)
491     }
492
493     /// The discriminant for the given variant. Panics if the `variant_index` is
494     /// out of range.
495     #[inline]
496     pub fn discriminant_for_variant(
497         &self,
498         def_id: DefId,
499         tcx: TyCtxt<'tcx>,
500         variant_index: VariantIdx,
501     ) -> Discr<'tcx> {
502         // Generators don't support explicit discriminant values, so they are
503         // the same as the variant index.
504         assert!(self.variant_range(def_id, tcx).contains(&variant_index));
505         Discr { val: variant_index.as_usize() as u128, ty: self.discr_ty(tcx) }
506     }
507
508     /// The set of all discriminants for the generator, enumerated with their
509     /// variant indices.
510     #[inline]
511     pub fn discriminants(
512         self,
513         def_id: DefId,
514         tcx: TyCtxt<'tcx>,
515     ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
516         self.variant_range(def_id, tcx).map(move |index| {
517             (index, Discr { val: index.as_usize() as u128, ty: self.discr_ty(tcx) })
518         })
519     }
520
521     /// Calls `f` with a reference to the name of the enumerator for the given
522     /// variant `v`.
523     pub fn variant_name(v: VariantIdx) -> Cow<'static, str> {
524         match v.as_usize() {
525             Self::UNRESUMED => Cow::from(Self::UNRESUMED_NAME),
526             Self::RETURNED => Cow::from(Self::RETURNED_NAME),
527             Self::POISONED => Cow::from(Self::POISONED_NAME),
528             _ => Cow::from(format!("Suspend{}", v.as_usize() - 3)),
529         }
530     }
531
532     /// The type of the state discriminant used in the generator type.
533     #[inline]
534     pub fn discr_ty(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
535         tcx.types.u32
536     }
537
538     /// This returns the types of the MIR locals which had to be stored across suspension points.
539     /// It is calculated in rustc_mir_transform::generator::StateTransform.
540     /// All the types here must be in the tuple in GeneratorInterior.
541     ///
542     /// The locals are grouped by their variant number. Note that some locals may
543     /// be repeated in multiple variants.
544     #[inline]
545     pub fn state_tys(
546         self,
547         def_id: DefId,
548         tcx: TyCtxt<'tcx>,
549     ) -> impl Iterator<Item = impl Iterator<Item = Ty<'tcx>> + Captures<'tcx>> {
550         let layout = tcx.generator_layout(def_id).unwrap();
551         layout.variant_fields.iter().map(move |variant| {
552             variant
553                 .iter()
554                 .map(move |field| EarlyBinder(layout.field_tys[*field]).subst(tcx, self.substs))
555         })
556     }
557
558     /// This is the types of the fields of a generator which are not stored in a
559     /// variant.
560     #[inline]
561     pub fn prefix_tys(self) -> impl Iterator<Item = Ty<'tcx>> {
562         self.upvar_tys()
563     }
564 }
565
566 #[derive(Debug, Copy, Clone, HashStable)]
567 pub enum UpvarSubsts<'tcx> {
568     Closure(SubstsRef<'tcx>),
569     Generator(SubstsRef<'tcx>),
570 }
571
572 impl<'tcx> UpvarSubsts<'tcx> {
573     /// Returns an iterator over the list of types of captured paths by the closure/generator.
574     /// In case there was a type error in figuring out the types of the captured path, an
575     /// empty iterator is returned.
576     #[inline]
577     pub fn upvar_tys(self) -> impl Iterator<Item = Ty<'tcx>> + 'tcx {
578         let tupled_tys = match self {
579             UpvarSubsts::Closure(substs) => substs.as_closure().tupled_upvars_ty(),
580             UpvarSubsts::Generator(substs) => substs.as_generator().tupled_upvars_ty(),
581         };
582
583         match tupled_tys.kind() {
584             TyKind::Error(_) => None,
585             TyKind::Tuple(..) => Some(self.tupled_upvars_ty().tuple_fields()),
586             TyKind::Infer(_) => bug!("upvar_tys called before capture types are inferred"),
587             ty => bug!("Unexpected representation of upvar types tuple {:?}", ty),
588         }
589         .into_iter()
590         .flatten()
591     }
592
593     #[inline]
594     pub fn tupled_upvars_ty(self) -> Ty<'tcx> {
595         match self {
596             UpvarSubsts::Closure(substs) => substs.as_closure().tupled_upvars_ty(),
597             UpvarSubsts::Generator(substs) => substs.as_generator().tupled_upvars_ty(),
598         }
599     }
600 }
601
602 /// An inline const is modeled like
603 /// ```ignore (illustrative)
604 /// const InlineConst<'l0...'li, T0...Tj, R>: R;
605 /// ```
606 /// where:
607 ///
608 /// - 'l0...'li and T0...Tj are the generic parameters
609 ///   inherited from the item that defined the inline const,
610 /// - R represents the type of the constant.
611 ///
612 /// When the inline const is instantiated, `R` is substituted as the actual inferred
613 /// type of the constant. The reason that `R` is represented as an extra type parameter
614 /// is the same reason that [`ClosureSubsts`] have `CS` and `U` as type parameters:
615 /// inline const can reference lifetimes that are internal to the creating function.
616 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable)]
617 pub struct InlineConstSubsts<'tcx> {
618     /// Generic parameters from the enclosing item,
619     /// concatenated with the inferred type of the constant.
620     pub substs: SubstsRef<'tcx>,
621 }
622
623 /// Struct returned by `split()`.
624 pub struct InlineConstSubstsParts<'tcx, T> {
625     pub parent_substs: &'tcx [GenericArg<'tcx>],
626     pub ty: T,
627 }
628
629 impl<'tcx> InlineConstSubsts<'tcx> {
630     /// Construct `InlineConstSubsts` from `InlineConstSubstsParts`.
631     pub fn new(
632         tcx: TyCtxt<'tcx>,
633         parts: InlineConstSubstsParts<'tcx, Ty<'tcx>>,
634     ) -> InlineConstSubsts<'tcx> {
635         InlineConstSubsts {
636             substs: tcx.mk_substs(
637                 parts.parent_substs.iter().copied().chain(std::iter::once(parts.ty.into())),
638             ),
639         }
640     }
641
642     /// Divides the inline const substs into their respective components.
643     /// The ordering assumed here must match that used by `InlineConstSubsts::new` above.
644     fn split(self) -> InlineConstSubstsParts<'tcx, GenericArg<'tcx>> {
645         match self.substs[..] {
646             [ref parent_substs @ .., ty] => InlineConstSubstsParts { parent_substs, ty },
647             _ => bug!("inline const substs missing synthetics"),
648         }
649     }
650
651     /// Returns the substitutions of the inline const's parent.
652     pub fn parent_substs(self) -> &'tcx [GenericArg<'tcx>] {
653         self.split().parent_substs
654     }
655
656     /// Returns the type of this inline const.
657     pub fn ty(self) -> Ty<'tcx> {
658         self.split().ty.expect_ty()
659     }
660 }
661
662 #[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Ord, Eq, Hash, TyEncodable, TyDecodable)]
663 #[derive(HashStable, TypeFoldable, TypeVisitable)]
664 pub enum ExistentialPredicate<'tcx> {
665     /// E.g., `Iterator`.
666     Trait(ExistentialTraitRef<'tcx>),
667     /// E.g., `Iterator::Item = T`.
668     Projection(ExistentialProjection<'tcx>),
669     /// E.g., `Send`.
670     AutoTrait(DefId),
671 }
672
673 impl<'tcx> ExistentialPredicate<'tcx> {
674     /// Compares via an ordering that will not change if modules are reordered or other changes are
675     /// made to the tree. In particular, this ordering is preserved across incremental compilations.
676     pub fn stable_cmp(&self, tcx: TyCtxt<'tcx>, other: &Self) -> Ordering {
677         use self::ExistentialPredicate::*;
678         match (*self, *other) {
679             (Trait(_), Trait(_)) => Ordering::Equal,
680             (Projection(ref a), Projection(ref b)) => {
681                 tcx.def_path_hash(a.item_def_id).cmp(&tcx.def_path_hash(b.item_def_id))
682             }
683             (AutoTrait(ref a), AutoTrait(ref b)) => {
684                 tcx.def_path_hash(*a).cmp(&tcx.def_path_hash(*b))
685             }
686             (Trait(_), _) => Ordering::Less,
687             (Projection(_), Trait(_)) => Ordering::Greater,
688             (Projection(_), _) => Ordering::Less,
689             (AutoTrait(_), _) => Ordering::Greater,
690         }
691     }
692 }
693
694 impl<'tcx> Binder<'tcx, ExistentialPredicate<'tcx>> {
695     pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::Predicate<'tcx> {
696         use crate::ty::ToPredicate;
697         match self.skip_binder() {
698             ExistentialPredicate::Trait(tr) => {
699                 self.rebind(tr).with_self_ty(tcx, self_ty).without_const().to_predicate(tcx)
700             }
701             ExistentialPredicate::Projection(p) => {
702                 self.rebind(p.with_self_ty(tcx, self_ty)).to_predicate(tcx)
703             }
704             ExistentialPredicate::AutoTrait(did) => {
705                 let trait_ref = self.rebind(ty::TraitRef {
706                     def_id: did,
707                     substs: tcx.mk_substs_trait(self_ty, &[]),
708                 });
709                 trait_ref.without_const().to_predicate(tcx)
710             }
711         }
712     }
713 }
714
715 impl<'tcx> List<ty::Binder<'tcx, ExistentialPredicate<'tcx>>> {
716     /// Returns the "principal `DefId`" of this set of existential predicates.
717     ///
718     /// A Rust trait object type consists (in addition to a lifetime bound)
719     /// of a set of trait bounds, which are separated into any number
720     /// of auto-trait bounds, and at most one non-auto-trait bound. The
721     /// non-auto-trait bound is called the "principal" of the trait
722     /// object.
723     ///
724     /// Only the principal can have methods or type parameters (because
725     /// auto traits can have neither of them). This is important, because
726     /// it means the auto traits can be treated as an unordered set (methods
727     /// would force an order for the vtable, while relating traits with
728     /// type parameters without knowing the order to relate them in is
729     /// a rather non-trivial task).
730     ///
731     /// For example, in the trait object `dyn fmt::Debug + Sync`, the
732     /// principal bound is `Some(fmt::Debug)`, while the auto-trait bounds
733     /// are the set `{Sync}`.
734     ///
735     /// It is also possible to have a "trivial" trait object that
736     /// consists only of auto traits, with no principal - for example,
737     /// `dyn Send + Sync`. In that case, the set of auto-trait bounds
738     /// is `{Send, Sync}`, while there is no principal. These trait objects
739     /// have a "trivial" vtable consisting of just the size, alignment,
740     /// and destructor.
741     pub fn principal(&self) -> Option<ty::Binder<'tcx, ExistentialTraitRef<'tcx>>> {
742         self[0]
743             .map_bound(|this| match this {
744                 ExistentialPredicate::Trait(tr) => Some(tr),
745                 _ => None,
746             })
747             .transpose()
748     }
749
750     pub fn principal_def_id(&self) -> Option<DefId> {
751         self.principal().map(|trait_ref| trait_ref.skip_binder().def_id)
752     }
753
754     #[inline]
755     pub fn projection_bounds<'a>(
756         &'a self,
757     ) -> impl Iterator<Item = ty::Binder<'tcx, ExistentialProjection<'tcx>>> + 'a {
758         self.iter().filter_map(|predicate| {
759             predicate
760                 .map_bound(|pred| match pred {
761                     ExistentialPredicate::Projection(projection) => Some(projection),
762                     _ => None,
763                 })
764                 .transpose()
765         })
766     }
767
768     #[inline]
769     pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item = DefId> + Captures<'tcx> + 'a {
770         self.iter().filter_map(|predicate| match predicate.skip_binder() {
771             ExistentialPredicate::AutoTrait(did) => Some(did),
772             _ => None,
773         })
774     }
775 }
776
777 /// A complete reference to a trait. These take numerous guises in syntax,
778 /// but perhaps the most recognizable form is in a where-clause:
779 /// ```ignore (illustrative)
780 /// T: Foo<U>
781 /// ```
782 /// This would be represented by a trait-reference where the `DefId` is the
783 /// `DefId` for the trait `Foo` and the substs define `T` as parameter 0,
784 /// and `U` as parameter 1.
785 ///
786 /// Trait references also appear in object types like `Foo<U>`, but in
787 /// that case the `Self` parameter is absent from the substitutions.
788 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)]
789 #[derive(HashStable, TypeFoldable, TypeVisitable)]
790 pub struct TraitRef<'tcx> {
791     pub def_id: DefId,
792     pub substs: SubstsRef<'tcx>,
793 }
794
795 impl<'tcx> TraitRef<'tcx> {
796     pub fn new(def_id: DefId, substs: SubstsRef<'tcx>) -> TraitRef<'tcx> {
797         TraitRef { def_id, substs }
798     }
799
800     /// Returns a `TraitRef` of the form `P0: Foo<P1..Pn>` where `Pi`
801     /// are the parameters defined on trait.
802     pub fn identity(tcx: TyCtxt<'tcx>, def_id: DefId) -> Binder<'tcx, TraitRef<'tcx>> {
803         ty::Binder::dummy(TraitRef {
804             def_id,
805             substs: InternalSubsts::identity_for_item(tcx, def_id),
806         })
807     }
808
809     #[inline]
810     pub fn self_ty(&self) -> Ty<'tcx> {
811         self.substs.type_at(0)
812     }
813
814     pub fn from_method(
815         tcx: TyCtxt<'tcx>,
816         trait_id: DefId,
817         substs: SubstsRef<'tcx>,
818     ) -> ty::TraitRef<'tcx> {
819         let defs = tcx.generics_of(trait_id);
820         ty::TraitRef { def_id: trait_id, substs: tcx.intern_substs(&substs[..defs.params.len()]) }
821     }
822 }
823
824 pub type PolyTraitRef<'tcx> = Binder<'tcx, TraitRef<'tcx>>;
825
826 impl<'tcx> PolyTraitRef<'tcx> {
827     pub fn self_ty(&self) -> Binder<'tcx, Ty<'tcx>> {
828         self.map_bound_ref(|tr| tr.self_ty())
829     }
830
831     pub fn def_id(&self) -> DefId {
832         self.skip_binder().def_id
833     }
834
835     pub fn to_poly_trait_predicate(&self) -> ty::PolyTraitPredicate<'tcx> {
836         self.map_bound(|trait_ref| ty::TraitPredicate {
837             trait_ref,
838             constness: ty::BoundConstness::NotConst,
839             polarity: ty::ImplPolarity::Positive,
840         })
841     }
842
843     /// Same as [`PolyTraitRef::to_poly_trait_predicate`] but sets a negative polarity instead.
844     pub fn to_poly_trait_predicate_negative_polarity(&self) -> ty::PolyTraitPredicate<'tcx> {
845         self.map_bound(|trait_ref| ty::TraitPredicate {
846             trait_ref,
847             constness: ty::BoundConstness::NotConst,
848             polarity: ty::ImplPolarity::Negative,
849         })
850     }
851 }
852
853 impl rustc_errors::IntoDiagnosticArg for PolyTraitRef<'_> {
854     fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue<'static> {
855         self.to_string().into_diagnostic_arg()
856     }
857 }
858
859 /// An existential reference to a trait, where `Self` is erased.
860 /// For example, the trait object `Trait<'a, 'b, X, Y>` is:
861 /// ```ignore (illustrative)
862 /// exists T. T: Trait<'a, 'b, X, Y>
863 /// ```
864 /// The substitutions don't include the erased `Self`, only trait
865 /// type and lifetime parameters (`[X, Y]` and `['a, 'b]` above).
866 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)]
867 #[derive(HashStable, TypeFoldable, TypeVisitable)]
868 pub struct ExistentialTraitRef<'tcx> {
869     pub def_id: DefId,
870     pub substs: SubstsRef<'tcx>,
871 }
872
873 impl<'tcx> ExistentialTraitRef<'tcx> {
874     pub fn erase_self_ty(
875         tcx: TyCtxt<'tcx>,
876         trait_ref: ty::TraitRef<'tcx>,
877     ) -> ty::ExistentialTraitRef<'tcx> {
878         // Assert there is a Self.
879         trait_ref.substs.type_at(0);
880
881         ty::ExistentialTraitRef {
882             def_id: trait_ref.def_id,
883             substs: tcx.intern_substs(&trait_ref.substs[1..]),
884         }
885     }
886
887     /// Object types don't have a self type specified. Therefore, when
888     /// we convert the principal trait-ref into a normal trait-ref,
889     /// you must give *some* self type. A common choice is `mk_err()`
890     /// or some placeholder type.
891     pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::TraitRef<'tcx> {
892         // otherwise the escaping vars would be captured by the binder
893         // debug_assert!(!self_ty.has_escaping_bound_vars());
894
895         ty::TraitRef { def_id: self.def_id, substs: tcx.mk_substs_trait(self_ty, self.substs) }
896     }
897 }
898
899 pub type PolyExistentialTraitRef<'tcx> = Binder<'tcx, ExistentialTraitRef<'tcx>>;
900
901 impl<'tcx> PolyExistentialTraitRef<'tcx> {
902     pub fn def_id(&self) -> DefId {
903         self.skip_binder().def_id
904     }
905
906     /// Object types don't have a self type specified. Therefore, when
907     /// we convert the principal trait-ref into a normal trait-ref,
908     /// you must give *some* self type. A common choice is `mk_err()`
909     /// or some placeholder type.
910     pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::PolyTraitRef<'tcx> {
911         self.map_bound(|trait_ref| trait_ref.with_self_ty(tcx, self_ty))
912     }
913 }
914
915 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
916 #[derive(Encodable, Decodable, HashStable)]
917 pub struct EarlyBinder<T>(pub T);
918
919 impl<T> EarlyBinder<T> {
920     pub fn as_ref(&self) -> EarlyBinder<&T> {
921         EarlyBinder(&self.0)
922     }
923
924     pub fn map_bound_ref<F, U>(&self, f: F) -> EarlyBinder<U>
925     where
926         F: FnOnce(&T) -> U,
927     {
928         self.as_ref().map_bound(f)
929     }
930
931     pub fn map_bound<F, U>(self, f: F) -> EarlyBinder<U>
932     where
933         F: FnOnce(T) -> U,
934     {
935         let value = f(self.0);
936         EarlyBinder(value)
937     }
938
939     pub fn try_map_bound<F, U, E>(self, f: F) -> Result<EarlyBinder<U>, E>
940     where
941         F: FnOnce(T) -> Result<U, E>,
942     {
943         let value = f(self.0)?;
944         Ok(EarlyBinder(value))
945     }
946
947     pub fn rebind<U>(&self, value: U) -> EarlyBinder<U> {
948         EarlyBinder(value)
949     }
950 }
951
952 impl<T> EarlyBinder<Option<T>> {
953     pub fn transpose(self) -> Option<EarlyBinder<T>> {
954         self.0.map(|v| EarlyBinder(v))
955     }
956 }
957
958 impl<T, U> EarlyBinder<(T, U)> {
959     pub fn transpose_tuple2(self) -> (EarlyBinder<T>, EarlyBinder<U>) {
960         (EarlyBinder(self.0.0), EarlyBinder(self.0.1))
961     }
962 }
963
964 pub struct EarlyBinderIter<T> {
965     t: T,
966 }
967
968 impl<T: IntoIterator> EarlyBinder<T> {
969     pub fn transpose_iter(self) -> EarlyBinderIter<T::IntoIter> {
970         EarlyBinderIter { t: self.0.into_iter() }
971     }
972 }
973
974 impl<T: Iterator> Iterator for EarlyBinderIter<T> {
975     type Item = EarlyBinder<T::Item>;
976
977     fn next(&mut self) -> Option<Self::Item> {
978         self.t.next().map(|i| EarlyBinder(i))
979     }
980 }
981
982 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
983 #[derive(HashStable)]
984 pub enum BoundVariableKind {
985     Ty(BoundTyKind),
986     Region(BoundRegionKind),
987     Const,
988 }
989
990 impl BoundVariableKind {
991     pub fn expect_region(self) -> BoundRegionKind {
992         match self {
993             BoundVariableKind::Region(lt) => lt,
994             _ => bug!("expected a region, but found another kind"),
995         }
996     }
997
998     pub fn expect_ty(self) -> BoundTyKind {
999         match self {
1000             BoundVariableKind::Ty(ty) => ty,
1001             _ => bug!("expected a type, but found another kind"),
1002         }
1003     }
1004
1005     pub fn expect_const(self) {
1006         match self {
1007             BoundVariableKind::Const => (),
1008             _ => bug!("expected a const, but found another kind"),
1009         }
1010     }
1011 }
1012
1013 /// Binder is a binder for higher-ranked lifetimes or types. It is part of the
1014 /// compiler's representation for things like `for<'a> Fn(&'a isize)`
1015 /// (which would be represented by the type `PolyTraitRef ==
1016 /// Binder<'tcx, TraitRef>`). Note that when we instantiate,
1017 /// erase, or otherwise "discharge" these bound vars, we change the
1018 /// type from `Binder<'tcx, T>` to just `T` (see
1019 /// e.g., `liberate_late_bound_regions`).
1020 ///
1021 /// `Decodable` and `Encodable` are implemented for `Binder<T>` using the `impl_binder_encode_decode!` macro.
1022 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1023 #[derive(HashStable)]
1024 pub struct Binder<'tcx, T>(T, &'tcx List<BoundVariableKind>);
1025
1026 impl<'tcx, T> Binder<'tcx, T>
1027 where
1028     T: TypeVisitable<'tcx>,
1029 {
1030     /// Wraps `value` in a binder, asserting that `value` does not
1031     /// contain any bound vars that would be bound by the
1032     /// binder. This is commonly used to 'inject' a value T into a
1033     /// different binding level.
1034     pub fn dummy(value: T) -> Binder<'tcx, T> {
1035         assert!(!value.has_escaping_bound_vars());
1036         Binder(value, ty::List::empty())
1037     }
1038
1039     pub fn bind_with_vars(value: T, vars: &'tcx List<BoundVariableKind>) -> Binder<'tcx, T> {
1040         if cfg!(debug_assertions) {
1041             let mut validator = ValidateBoundVars::new(vars);
1042             value.visit_with(&mut validator);
1043         }
1044         Binder(value, vars)
1045     }
1046 }
1047
1048 impl<'tcx, T> Binder<'tcx, T> {
1049     /// Skips the binder and returns the "bound" value. This is a
1050     /// risky thing to do because it's easy to get confused about
1051     /// De Bruijn indices and the like. It is usually better to
1052     /// discharge the binder using `no_bound_vars` or
1053     /// `replace_late_bound_regions` or something like
1054     /// that. `skip_binder` is only valid when you are either
1055     /// extracting data that has nothing to do with bound vars, you
1056     /// are doing some sort of test that does not involve bound
1057     /// regions, or you are being very careful about your depth
1058     /// accounting.
1059     ///
1060     /// Some examples where `skip_binder` is reasonable:
1061     ///
1062     /// - extracting the `DefId` from a PolyTraitRef;
1063     /// - comparing the self type of a PolyTraitRef to see if it is equal to
1064     ///   a type parameter `X`, since the type `X` does not reference any regions
1065     pub fn skip_binder(self) -> T {
1066         self.0
1067     }
1068
1069     pub fn bound_vars(&self) -> &'tcx List<BoundVariableKind> {
1070         self.1
1071     }
1072
1073     pub fn as_ref(&self) -> Binder<'tcx, &T> {
1074         Binder(&self.0, self.1)
1075     }
1076
1077     pub fn as_deref(&self) -> Binder<'tcx, &T::Target>
1078     where
1079         T: Deref,
1080     {
1081         Binder(&self.0, self.1)
1082     }
1083
1084     pub fn map_bound_ref_unchecked<F, U>(&self, f: F) -> Binder<'tcx, U>
1085     where
1086         F: FnOnce(&T) -> U,
1087     {
1088         let value = f(&self.0);
1089         Binder(value, self.1)
1090     }
1091
1092     pub fn map_bound_ref<F, U: TypeVisitable<'tcx>>(&self, f: F) -> Binder<'tcx, U>
1093     where
1094         F: FnOnce(&T) -> U,
1095     {
1096         self.as_ref().map_bound(f)
1097     }
1098
1099     pub fn map_bound<F, U: TypeVisitable<'tcx>>(self, f: F) -> Binder<'tcx, U>
1100     where
1101         F: FnOnce(T) -> U,
1102     {
1103         let value = f(self.0);
1104         if cfg!(debug_assertions) {
1105             let mut validator = ValidateBoundVars::new(self.1);
1106             value.visit_with(&mut validator);
1107         }
1108         Binder(value, self.1)
1109     }
1110
1111     pub fn try_map_bound<F, U: TypeVisitable<'tcx>, E>(self, f: F) -> Result<Binder<'tcx, U>, E>
1112     where
1113         F: FnOnce(T) -> Result<U, E>,
1114     {
1115         let value = f(self.0)?;
1116         if cfg!(debug_assertions) {
1117             let mut validator = ValidateBoundVars::new(self.1);
1118             value.visit_with(&mut validator);
1119         }
1120         Ok(Binder(value, self.1))
1121     }
1122
1123     /// Wraps a `value` in a binder, using the same bound variables as the
1124     /// current `Binder`. This should not be used if the new value *changes*
1125     /// the bound variables. Note: the (old or new) value itself does not
1126     /// necessarily need to *name* all the bound variables.
1127     ///
1128     /// This currently doesn't do anything different than `bind`, because we
1129     /// don't actually track bound vars. However, semantically, it is different
1130     /// because bound vars aren't allowed to change here, whereas they are
1131     /// in `bind`. This may be (debug) asserted in the future.
1132     pub fn rebind<U>(&self, value: U) -> Binder<'tcx, U>
1133     where
1134         U: TypeVisitable<'tcx>,
1135     {
1136         if cfg!(debug_assertions) {
1137             let mut validator = ValidateBoundVars::new(self.bound_vars());
1138             value.visit_with(&mut validator);
1139         }
1140         Binder(value, self.1)
1141     }
1142
1143     /// Unwraps and returns the value within, but only if it contains
1144     /// no bound vars at all. (In other words, if this binder --
1145     /// and indeed any enclosing binder -- doesn't bind anything at
1146     /// all.) Otherwise, returns `None`.
1147     ///
1148     /// (One could imagine having a method that just unwraps a single
1149     /// binder, but permits late-bound vars bound by enclosing
1150     /// binders, but that would require adjusting the debruijn
1151     /// indices, and given the shallow binding structure we often use,
1152     /// would not be that useful.)
1153     pub fn no_bound_vars(self) -> Option<T>
1154     where
1155         T: TypeVisitable<'tcx>,
1156     {
1157         if self.0.has_escaping_bound_vars() { None } else { Some(self.skip_binder()) }
1158     }
1159
1160     /// Splits the contents into two things that share the same binder
1161     /// level as the original, returning two distinct binders.
1162     ///
1163     /// `f` should consider bound regions at depth 1 to be free, and
1164     /// anything it produces with bound regions at depth 1 will be
1165     /// bound in the resulting return values.
1166     pub fn split<U, V, F>(self, f: F) -> (Binder<'tcx, U>, Binder<'tcx, V>)
1167     where
1168         F: FnOnce(T) -> (U, V),
1169     {
1170         let (u, v) = f(self.0);
1171         (Binder(u, self.1), Binder(v, self.1))
1172     }
1173 }
1174
1175 impl<'tcx, T> Binder<'tcx, Option<T>> {
1176     pub fn transpose(self) -> Option<Binder<'tcx, T>> {
1177         let bound_vars = self.1;
1178         self.0.map(|v| Binder(v, bound_vars))
1179     }
1180 }
1181
1182 /// Represents the projection of an associated type. In explicit UFCS
1183 /// form this would be written `<T as Trait<..>>::N`.
1184 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
1185 #[derive(HashStable, TypeFoldable, TypeVisitable)]
1186 pub struct ProjectionTy<'tcx> {
1187     /// The parameters of the associated item.
1188     pub substs: SubstsRef<'tcx>,
1189
1190     /// The `DefId` of the `TraitItem` for the associated type `N`.
1191     ///
1192     /// Note that this is not the `DefId` of the `TraitRef` containing this
1193     /// associated type, which is in `tcx.associated_item(item_def_id).container`,
1194     /// aka. `tcx.parent(item_def_id).unwrap()`.
1195     pub item_def_id: DefId,
1196 }
1197
1198 impl<'tcx> ProjectionTy<'tcx> {
1199     pub fn trait_def_id(&self, tcx: TyCtxt<'tcx>) -> DefId {
1200         let parent = tcx.parent(self.item_def_id);
1201         assert_eq!(tcx.def_kind(parent), DefKind::Trait);
1202         parent
1203     }
1204
1205     /// Extracts the underlying trait reference and own substs from this projection.
1206     /// For example, if this is a projection of `<T as StreamingIterator>::Item<'a>`,
1207     /// then this function would return a `T: Iterator` trait reference and `['a]` as the own substs
1208     pub fn trait_ref_and_own_substs(
1209         &self,
1210         tcx: TyCtxt<'tcx>,
1211     ) -> (ty::TraitRef<'tcx>, &'tcx [ty::GenericArg<'tcx>]) {
1212         let def_id = tcx.parent(self.item_def_id);
1213         let trait_generics = tcx.generics_of(def_id);
1214         (
1215             ty::TraitRef { def_id, substs: self.substs.truncate_to(tcx, trait_generics) },
1216             &self.substs[trait_generics.count()..],
1217         )
1218     }
1219
1220     /// Extracts the underlying trait reference from this projection.
1221     /// For example, if this is a projection of `<T as Iterator>::Item`,
1222     /// then this function would return a `T: Iterator` trait reference.
1223     ///
1224     /// WARNING: This will drop the substs for generic associated types
1225     /// consider calling [Self::trait_ref_and_own_substs] to get those
1226     /// as well.
1227     pub fn trait_ref(&self, tcx: TyCtxt<'tcx>) -> ty::TraitRef<'tcx> {
1228         let def_id = self.trait_def_id(tcx);
1229         ty::TraitRef { def_id, substs: self.substs.truncate_to(tcx, tcx.generics_of(def_id)) }
1230     }
1231
1232     pub fn self_ty(&self) -> Ty<'tcx> {
1233         self.substs.type_at(0)
1234     }
1235 }
1236
1237 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable)]
1238 pub struct GenSig<'tcx> {
1239     pub resume_ty: Ty<'tcx>,
1240     pub yield_ty: Ty<'tcx>,
1241     pub return_ty: Ty<'tcx>,
1242 }
1243
1244 pub type PolyGenSig<'tcx> = Binder<'tcx, GenSig<'tcx>>;
1245
1246 /// Signature of a function type, which we have arbitrarily
1247 /// decided to use to refer to the input/output types.
1248 ///
1249 /// - `inputs`: is the list of arguments and their modes.
1250 /// - `output`: is the return type.
1251 /// - `c_variadic`: indicates whether this is a C-variadic function.
1252 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)]
1253 #[derive(HashStable, TypeFoldable, TypeVisitable)]
1254 pub struct FnSig<'tcx> {
1255     pub inputs_and_output: &'tcx List<Ty<'tcx>>,
1256     pub c_variadic: bool,
1257     pub unsafety: hir::Unsafety,
1258     pub abi: abi::Abi,
1259 }
1260
1261 impl<'tcx> FnSig<'tcx> {
1262     pub fn inputs(&self) -> &'tcx [Ty<'tcx>] {
1263         &self.inputs_and_output[..self.inputs_and_output.len() - 1]
1264     }
1265
1266     pub fn output(&self) -> Ty<'tcx> {
1267         self.inputs_and_output[self.inputs_and_output.len() - 1]
1268     }
1269
1270     // Creates a minimal `FnSig` to be used when encountering a `TyKind::Error` in a fallible
1271     // method.
1272     fn fake() -> FnSig<'tcx> {
1273         FnSig {
1274             inputs_and_output: List::empty(),
1275             c_variadic: false,
1276             unsafety: hir::Unsafety::Normal,
1277             abi: abi::Abi::Rust,
1278         }
1279     }
1280 }
1281
1282 pub type PolyFnSig<'tcx> = Binder<'tcx, FnSig<'tcx>>;
1283
1284 impl<'tcx> PolyFnSig<'tcx> {
1285     #[inline]
1286     pub fn inputs(&self) -> Binder<'tcx, &'tcx [Ty<'tcx>]> {
1287         self.map_bound_ref_unchecked(|fn_sig| fn_sig.inputs())
1288     }
1289     #[inline]
1290     pub fn input(&self, index: usize) -> ty::Binder<'tcx, Ty<'tcx>> {
1291         self.map_bound_ref(|fn_sig| fn_sig.inputs()[index])
1292     }
1293     pub fn inputs_and_output(&self) -> ty::Binder<'tcx, &'tcx List<Ty<'tcx>>> {
1294         self.map_bound_ref(|fn_sig| fn_sig.inputs_and_output)
1295     }
1296     #[inline]
1297     pub fn output(&self) -> ty::Binder<'tcx, Ty<'tcx>> {
1298         self.map_bound_ref(|fn_sig| fn_sig.output())
1299     }
1300     pub fn c_variadic(&self) -> bool {
1301         self.skip_binder().c_variadic
1302     }
1303     pub fn unsafety(&self) -> hir::Unsafety {
1304         self.skip_binder().unsafety
1305     }
1306     pub fn abi(&self) -> abi::Abi {
1307         self.skip_binder().abi
1308     }
1309 }
1310
1311 pub type CanonicalPolyFnSig<'tcx> = Canonical<'tcx, Binder<'tcx, FnSig<'tcx>>>;
1312
1313 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)]
1314 #[derive(HashStable)]
1315 pub struct ParamTy {
1316     pub index: u32,
1317     pub name: Symbol,
1318 }
1319
1320 impl<'tcx> ParamTy {
1321     pub fn new(index: u32, name: Symbol) -> ParamTy {
1322         ParamTy { index, name }
1323     }
1324
1325     pub fn for_def(def: &ty::GenericParamDef) -> ParamTy {
1326         ParamTy::new(def.index, def.name)
1327     }
1328
1329     #[inline]
1330     pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1331         tcx.mk_ty_param(self.index, self.name)
1332     }
1333 }
1334
1335 #[derive(Copy, Clone, Hash, TyEncodable, TyDecodable, Eq, PartialEq, Ord, PartialOrd)]
1336 #[derive(HashStable)]
1337 pub struct ParamConst {
1338     pub index: u32,
1339     pub name: Symbol,
1340 }
1341
1342 impl ParamConst {
1343     pub fn new(index: u32, name: Symbol) -> ParamConst {
1344         ParamConst { index, name }
1345     }
1346
1347     pub fn for_def(def: &ty::GenericParamDef) -> ParamConst {
1348         ParamConst::new(def.index, def.name)
1349     }
1350 }
1351
1352 /// Use this rather than `RegionKind`, whenever possible.
1353 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable)]
1354 #[rustc_pass_by_value]
1355 pub struct Region<'tcx>(pub Interned<'tcx, RegionKind<'tcx>>);
1356
1357 impl<'tcx> Deref for Region<'tcx> {
1358     type Target = RegionKind<'tcx>;
1359
1360     #[inline]
1361     fn deref(&self) -> &RegionKind<'tcx> {
1362         &self.0.0
1363     }
1364 }
1365
1366 impl<'tcx> fmt::Debug for Region<'tcx> {
1367     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1368         write!(f, "{:?}", self.kind())
1369     }
1370 }
1371
1372 #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, PartialOrd, Ord)]
1373 #[derive(HashStable)]
1374 pub struct EarlyBoundRegion {
1375     pub def_id: DefId,
1376     pub index: u32,
1377     pub name: Symbol,
1378 }
1379
1380 impl fmt::Debug for EarlyBoundRegion {
1381     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1382         write!(f, "{}, {}", self.index, self.name)
1383     }
1384 }
1385
1386 /// A **`const`** **v**ariable **ID**.
1387 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1388 #[derive(HashStable, TyEncodable, TyDecodable)]
1389 pub struct ConstVid<'tcx> {
1390     pub index: u32,
1391     pub phantom: PhantomData<&'tcx ()>,
1392 }
1393
1394 rustc_index::newtype_index! {
1395     /// A **region** (lifetime) **v**ariable **ID**.
1396     #[derive(HashStable)]
1397     pub struct RegionVid {
1398         DEBUG_FORMAT = custom,
1399     }
1400 }
1401
1402 impl Atom for RegionVid {
1403     fn index(self) -> usize {
1404         Idx::index(self)
1405     }
1406 }
1407
1408 rustc_index::newtype_index! {
1409     #[derive(HashStable)]
1410     pub struct BoundVar { .. }
1411 }
1412
1413 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
1414 #[derive(HashStable)]
1415 pub struct BoundTy {
1416     pub var: BoundVar,
1417     pub kind: BoundTyKind,
1418 }
1419
1420 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
1421 #[derive(HashStable)]
1422 pub enum BoundTyKind {
1423     Anon,
1424     Param(Symbol),
1425 }
1426
1427 impl From<BoundVar> for BoundTy {
1428     fn from(var: BoundVar) -> Self {
1429         BoundTy { var, kind: BoundTyKind::Anon }
1430     }
1431 }
1432
1433 /// A `ProjectionPredicate` for an `ExistentialTraitRef`.
1434 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
1435 #[derive(HashStable, TypeFoldable, TypeVisitable)]
1436 pub struct ExistentialProjection<'tcx> {
1437     pub item_def_id: DefId,
1438     pub substs: SubstsRef<'tcx>,
1439     pub term: Term<'tcx>,
1440 }
1441
1442 pub type PolyExistentialProjection<'tcx> = Binder<'tcx, ExistentialProjection<'tcx>>;
1443
1444 impl<'tcx> ExistentialProjection<'tcx> {
1445     /// Extracts the underlying existential trait reference from this projection.
1446     /// For example, if this is a projection of `exists T. <T as Iterator>::Item == X`,
1447     /// then this function would return an `exists T. T: Iterator` existential trait
1448     /// reference.
1449     pub fn trait_ref(&self, tcx: TyCtxt<'tcx>) -> ty::ExistentialTraitRef<'tcx> {
1450         let def_id = tcx.parent(self.item_def_id);
1451         let subst_count = tcx.generics_of(def_id).count() - 1;
1452         let substs = tcx.intern_substs(&self.substs[..subst_count]);
1453         ty::ExistentialTraitRef { def_id, substs }
1454     }
1455
1456     pub fn with_self_ty(
1457         &self,
1458         tcx: TyCtxt<'tcx>,
1459         self_ty: Ty<'tcx>,
1460     ) -> ty::ProjectionPredicate<'tcx> {
1461         // otherwise the escaping regions would be captured by the binders
1462         debug_assert!(!self_ty.has_escaping_bound_vars());
1463
1464         ty::ProjectionPredicate {
1465             projection_ty: ty::ProjectionTy {
1466                 item_def_id: self.item_def_id,
1467                 substs: tcx.mk_substs_trait(self_ty, self.substs),
1468             },
1469             term: self.term,
1470         }
1471     }
1472
1473     pub fn erase_self_ty(
1474         tcx: TyCtxt<'tcx>,
1475         projection_predicate: ty::ProjectionPredicate<'tcx>,
1476     ) -> Self {
1477         // Assert there is a Self.
1478         projection_predicate.projection_ty.substs.type_at(0);
1479
1480         Self {
1481             item_def_id: projection_predicate.projection_ty.item_def_id,
1482             substs: tcx.intern_substs(&projection_predicate.projection_ty.substs[1..]),
1483             term: projection_predicate.term,
1484         }
1485     }
1486 }
1487
1488 impl<'tcx> PolyExistentialProjection<'tcx> {
1489     pub fn with_self_ty(
1490         &self,
1491         tcx: TyCtxt<'tcx>,
1492         self_ty: Ty<'tcx>,
1493     ) -> ty::PolyProjectionPredicate<'tcx> {
1494         self.map_bound(|p| p.with_self_ty(tcx, self_ty))
1495     }
1496
1497     pub fn item_def_id(&self) -> DefId {
1498         self.skip_binder().item_def_id
1499     }
1500 }
1501
1502 /// Region utilities
1503 impl<'tcx> Region<'tcx> {
1504     pub fn kind(self) -> RegionKind<'tcx> {
1505         *self.0.0
1506     }
1507
1508     /// Is this region named by the user?
1509     pub fn has_name(self) -> bool {
1510         match *self {
1511             ty::ReEarlyBound(ebr) => ebr.has_name(),
1512             ty::ReLateBound(_, br) => br.kind.is_named(),
1513             ty::ReFree(fr) => fr.bound_region.is_named(),
1514             ty::ReStatic => true,
1515             ty::ReVar(..) => false,
1516             ty::RePlaceholder(placeholder) => placeholder.name.is_named(),
1517             ty::ReEmpty(_) => false,
1518             ty::ReErased => false,
1519         }
1520     }
1521
1522     #[inline]
1523     pub fn is_static(self) -> bool {
1524         matches!(*self, ty::ReStatic)
1525     }
1526
1527     #[inline]
1528     pub fn is_erased(self) -> bool {
1529         matches!(*self, ty::ReErased)
1530     }
1531
1532     #[inline]
1533     pub fn is_late_bound(self) -> bool {
1534         matches!(*self, ty::ReLateBound(..))
1535     }
1536
1537     #[inline]
1538     pub fn is_placeholder(self) -> bool {
1539         matches!(*self, ty::RePlaceholder(..))
1540     }
1541
1542     #[inline]
1543     pub fn is_empty(self) -> bool {
1544         matches!(*self, ty::ReEmpty(..))
1545     }
1546
1547     #[inline]
1548     pub fn bound_at_or_above_binder(self, index: ty::DebruijnIndex) -> bool {
1549         match *self {
1550             ty::ReLateBound(debruijn, _) => debruijn >= index,
1551             _ => false,
1552         }
1553     }
1554
1555     pub fn type_flags(self) -> TypeFlags {
1556         let mut flags = TypeFlags::empty();
1557
1558         match *self {
1559             ty::ReVar(..) => {
1560                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1561                 flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS;
1562                 flags = flags | TypeFlags::HAS_RE_INFER;
1563             }
1564             ty::RePlaceholder(..) => {
1565                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1566                 flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS;
1567                 flags = flags | TypeFlags::HAS_RE_PLACEHOLDER;
1568             }
1569             ty::ReEarlyBound(..) => {
1570                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1571                 flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS;
1572                 flags = flags | TypeFlags::HAS_RE_PARAM;
1573             }
1574             ty::ReFree { .. } => {
1575                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1576                 flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS;
1577             }
1578             ty::ReEmpty(_) | ty::ReStatic => {
1579                 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1580             }
1581             ty::ReLateBound(..) => {
1582                 flags = flags | TypeFlags::HAS_RE_LATE_BOUND;
1583             }
1584             ty::ReErased => {
1585                 flags = flags | TypeFlags::HAS_RE_ERASED;
1586             }
1587         }
1588
1589         debug!("type_flags({:?}) = {:?}", self, flags);
1590
1591         flags
1592     }
1593
1594     /// Given an early-bound or free region, returns the `DefId` where it was bound.
1595     /// For example, consider the regions in this snippet of code:
1596     ///
1597     /// ```ignore (illustrative)
1598     /// impl<'a> Foo {
1599     /// //   ^^ -- early bound, declared on an impl
1600     ///
1601     ///     fn bar<'b, 'c>(x: &self, y: &'b u32, z: &'c u64) where 'static: 'c
1602     /// //         ^^  ^^     ^ anonymous, late-bound
1603     /// //         |   early-bound, appears in where-clauses
1604     /// //         late-bound, appears only in fn args
1605     ///     {..}
1606     /// }
1607     /// ```
1608     ///
1609     /// Here, `free_region_binding_scope('a)` would return the `DefId`
1610     /// of the impl, and for all the other highlighted regions, it
1611     /// would return the `DefId` of the function. In other cases (not shown), this
1612     /// function might return the `DefId` of a closure.
1613     pub fn free_region_binding_scope(self, tcx: TyCtxt<'_>) -> DefId {
1614         match *self {
1615             ty::ReEarlyBound(br) => tcx.parent(br.def_id),
1616             ty::ReFree(fr) => fr.scope,
1617             _ => bug!("free_region_binding_scope invoked on inappropriate region: {:?}", self),
1618         }
1619     }
1620
1621     /// True for free regions other than `'static`.
1622     pub fn is_free(self) -> bool {
1623         matches!(*self, ty::ReEarlyBound(_) | ty::ReFree(_))
1624     }
1625
1626     /// True if `self` is a free region or static.
1627     pub fn is_free_or_static(self) -> bool {
1628         match *self {
1629             ty::ReStatic => true,
1630             _ => self.is_free(),
1631         }
1632     }
1633
1634     pub fn is_var(self) -> bool {
1635         matches!(self.kind(), ty::ReVar(_))
1636     }
1637 }
1638
1639 /// Type utilities
1640 impl<'tcx> Ty<'tcx> {
1641     #[inline(always)]
1642     pub fn kind(self) -> &'tcx TyKind<'tcx> {
1643         &self.0.0.kind
1644     }
1645
1646     #[inline(always)]
1647     pub fn flags(self) -> TypeFlags {
1648         self.0.0.flags
1649     }
1650
1651     #[inline]
1652     pub fn is_unit(self) -> bool {
1653         match self.kind() {
1654             Tuple(ref tys) => tys.is_empty(),
1655             _ => false,
1656         }
1657     }
1658
1659     #[inline]
1660     pub fn is_never(self) -> bool {
1661         matches!(self.kind(), Never)
1662     }
1663
1664     #[inline]
1665     pub fn is_primitive(self) -> bool {
1666         self.kind().is_primitive()
1667     }
1668
1669     #[inline]
1670     pub fn is_adt(self) -> bool {
1671         matches!(self.kind(), Adt(..))
1672     }
1673
1674     #[inline]
1675     pub fn is_ref(self) -> bool {
1676         matches!(self.kind(), Ref(..))
1677     }
1678
1679     #[inline]
1680     pub fn is_ty_var(self) -> bool {
1681         matches!(self.kind(), Infer(TyVar(_)))
1682     }
1683
1684     #[inline]
1685     pub fn ty_vid(self) -> Option<ty::TyVid> {
1686         match self.kind() {
1687             &Infer(TyVar(vid)) => Some(vid),
1688             _ => None,
1689         }
1690     }
1691
1692     #[inline]
1693     pub fn is_ty_infer(self) -> bool {
1694         matches!(self.kind(), Infer(_))
1695     }
1696
1697     #[inline]
1698     pub fn is_phantom_data(self) -> bool {
1699         if let Adt(def, _) = self.kind() { def.is_phantom_data() } else { false }
1700     }
1701
1702     #[inline]
1703     pub fn is_bool(self) -> bool {
1704         *self.kind() == Bool
1705     }
1706
1707     /// Returns `true` if this type is a `str`.
1708     #[inline]
1709     pub fn is_str(self) -> bool {
1710         *self.kind() == Str
1711     }
1712
1713     #[inline]
1714     pub fn is_param(self, index: u32) -> bool {
1715         match self.kind() {
1716             ty::Param(ref data) => data.index == index,
1717             _ => false,
1718         }
1719     }
1720
1721     #[inline]
1722     pub fn is_slice(self) -> bool {
1723         matches!(self.kind(), Slice(_))
1724     }
1725
1726     #[inline]
1727     pub fn is_array_slice(self) -> bool {
1728         match self.kind() {
1729             Slice(_) => true,
1730             RawPtr(TypeAndMut { ty, .. }) | Ref(_, ty, _) => matches!(ty.kind(), Slice(_)),
1731             _ => false,
1732         }
1733     }
1734
1735     #[inline]
1736     pub fn is_array(self) -> bool {
1737         matches!(self.kind(), Array(..))
1738     }
1739
1740     #[inline]
1741     pub fn is_simd(self) -> bool {
1742         match self.kind() {
1743             Adt(def, _) => def.repr().simd(),
1744             _ => false,
1745         }
1746     }
1747
1748     pub fn sequence_element_type(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1749         match self.kind() {
1750             Array(ty, _) | Slice(ty) => *ty,
1751             Str => tcx.types.u8,
1752             _ => bug!("`sequence_element_type` called on non-sequence value: {}", self),
1753         }
1754     }
1755
1756     pub fn simd_size_and_type(self, tcx: TyCtxt<'tcx>) -> (u64, Ty<'tcx>) {
1757         match self.kind() {
1758             Adt(def, substs) => {
1759                 assert!(def.repr().simd(), "`simd_size_and_type` called on non-SIMD type");
1760                 let variant = def.non_enum_variant();
1761                 let f0_ty = variant.fields[0].ty(tcx, substs);
1762
1763                 match f0_ty.kind() {
1764                     // If the first field is an array, we assume it is the only field and its
1765                     // elements are the SIMD components.
1766                     Array(f0_elem_ty, f0_len) => {
1767                         // FIXME(repr_simd): https://github.com/rust-lang/rust/pull/78863#discussion_r522784112
1768                         // The way we evaluate the `N` in `[T; N]` here only works since we use
1769                         // `simd_size_and_type` post-monomorphization. It will probably start to ICE
1770                         // if we use it in generic code. See the `simd-array-trait` ui test.
1771                         (f0_len.eval_usize(tcx, ParamEnv::empty()) as u64, *f0_elem_ty)
1772                     }
1773                     // Otherwise, the fields of this Adt are the SIMD components (and we assume they
1774                     // all have the same type).
1775                     _ => (variant.fields.len() as u64, f0_ty),
1776                 }
1777             }
1778             _ => bug!("`simd_size_and_type` called on invalid type"),
1779         }
1780     }
1781
1782     #[inline]
1783     pub fn is_region_ptr(self) -> bool {
1784         matches!(self.kind(), Ref(..))
1785     }
1786
1787     #[inline]
1788     pub fn is_mutable_ptr(self) -> bool {
1789         matches!(
1790             self.kind(),
1791             RawPtr(TypeAndMut { mutbl: hir::Mutability::Mut, .. })
1792                 | Ref(_, _, hir::Mutability::Mut)
1793         )
1794     }
1795
1796     /// Get the mutability of the reference or `None` when not a reference
1797     #[inline]
1798     pub fn ref_mutability(self) -> Option<hir::Mutability> {
1799         match self.kind() {
1800             Ref(_, _, mutability) => Some(*mutability),
1801             _ => None,
1802         }
1803     }
1804
1805     #[inline]
1806     pub fn is_unsafe_ptr(self) -> bool {
1807         matches!(self.kind(), RawPtr(_))
1808     }
1809
1810     /// Tests if this is any kind of primitive pointer type (reference, raw pointer, fn pointer).
1811     #[inline]
1812     pub fn is_any_ptr(self) -> bool {
1813         self.is_region_ptr() || self.is_unsafe_ptr() || self.is_fn_ptr()
1814     }
1815
1816     #[inline]
1817     pub fn is_box(self) -> bool {
1818         match self.kind() {
1819             Adt(def, _) => def.is_box(),
1820             _ => false,
1821         }
1822     }
1823
1824     /// Panics if called on any type other than `Box<T>`.
1825     pub fn boxed_ty(self) -> Ty<'tcx> {
1826         match self.kind() {
1827             Adt(def, substs) if def.is_box() => substs.type_at(0),
1828             _ => bug!("`boxed_ty` is called on non-box type {:?}", self),
1829         }
1830     }
1831
1832     /// A scalar type is one that denotes an atomic datum, with no sub-components.
1833     /// (A RawPtr is scalar because it represents a non-managed pointer, so its
1834     /// contents are abstract to rustc.)
1835     #[inline]
1836     pub fn is_scalar(self) -> bool {
1837         matches!(
1838             self.kind(),
1839             Bool | Char
1840                 | Int(_)
1841                 | Float(_)
1842                 | Uint(_)
1843                 | FnDef(..)
1844                 | FnPtr(_)
1845                 | RawPtr(_)
1846                 | Infer(IntVar(_) | FloatVar(_))
1847         )
1848     }
1849
1850     /// Returns `true` if this type is a floating point type.
1851     #[inline]
1852     pub fn is_floating_point(self) -> bool {
1853         matches!(self.kind(), Float(_) | Infer(FloatVar(_)))
1854     }
1855
1856     #[inline]
1857     pub fn is_trait(self) -> bool {
1858         matches!(self.kind(), Dynamic(..))
1859     }
1860
1861     #[inline]
1862     pub fn is_enum(self) -> bool {
1863         matches!(self.kind(), Adt(adt_def, _) if adt_def.is_enum())
1864     }
1865
1866     #[inline]
1867     pub fn is_union(self) -> bool {
1868         matches!(self.kind(), Adt(adt_def, _) if adt_def.is_union())
1869     }
1870
1871     #[inline]
1872     pub fn is_closure(self) -> bool {
1873         matches!(self.kind(), Closure(..))
1874     }
1875
1876     #[inline]
1877     pub fn is_generator(self) -> bool {
1878         matches!(self.kind(), Generator(..))
1879     }
1880
1881     #[inline]
1882     pub fn is_integral(self) -> bool {
1883         matches!(self.kind(), Infer(IntVar(_)) | Int(_) | Uint(_))
1884     }
1885
1886     #[inline]
1887     pub fn is_fresh_ty(self) -> bool {
1888         matches!(self.kind(), Infer(FreshTy(_)))
1889     }
1890
1891     #[inline]
1892     pub fn is_fresh(self) -> bool {
1893         matches!(self.kind(), Infer(FreshTy(_) | FreshIntTy(_) | FreshFloatTy(_)))
1894     }
1895
1896     #[inline]
1897     pub fn is_char(self) -> bool {
1898         matches!(self.kind(), Char)
1899     }
1900
1901     #[inline]
1902     pub fn is_numeric(self) -> bool {
1903         self.is_integral() || self.is_floating_point()
1904     }
1905
1906     #[inline]
1907     pub fn is_signed(self) -> bool {
1908         matches!(self.kind(), Int(_))
1909     }
1910
1911     #[inline]
1912     pub fn is_ptr_sized_integral(self) -> bool {
1913         matches!(self.kind(), Int(ty::IntTy::Isize) | Uint(ty::UintTy::Usize))
1914     }
1915
1916     #[inline]
1917     pub fn has_concrete_skeleton(self) -> bool {
1918         !matches!(self.kind(), Param(_) | Infer(_) | Error(_))
1919     }
1920
1921     /// Checks whether a type recursively contains another type
1922     ///
1923     /// Example: `Option<()>` contains `()`
1924     pub fn contains(self, other: Ty<'tcx>) -> bool {
1925         struct ContainsTyVisitor<'tcx>(Ty<'tcx>);
1926
1927         impl<'tcx> TypeVisitor<'tcx> for ContainsTyVisitor<'tcx> {
1928             type BreakTy = ();
1929
1930             fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1931                 if self.0 == t { ControlFlow::BREAK } else { t.super_visit_with(self) }
1932             }
1933         }
1934
1935         let cf = self.visit_with(&mut ContainsTyVisitor(other));
1936         cf.is_break()
1937     }
1938
1939     /// Returns the type and mutability of `*ty`.
1940     ///
1941     /// The parameter `explicit` indicates if this is an *explicit* dereference.
1942     /// Some types -- notably unsafe ptrs -- can only be dereferenced explicitly.
1943     pub fn builtin_deref(self, explicit: bool) -> Option<TypeAndMut<'tcx>> {
1944         match self.kind() {
1945             Adt(def, _) if def.is_box() => {
1946                 Some(TypeAndMut { ty: self.boxed_ty(), mutbl: hir::Mutability::Not })
1947             }
1948             Ref(_, ty, mutbl) => Some(TypeAndMut { ty: *ty, mutbl: *mutbl }),
1949             RawPtr(mt) if explicit => Some(*mt),
1950             _ => None,
1951         }
1952     }
1953
1954     /// Returns the type of `ty[i]`.
1955     pub fn builtin_index(self) -> Option<Ty<'tcx>> {
1956         match self.kind() {
1957             Array(ty, _) | Slice(ty) => Some(*ty),
1958             _ => None,
1959         }
1960     }
1961
1962     pub fn fn_sig(self, tcx: TyCtxt<'tcx>) -> PolyFnSig<'tcx> {
1963         match self.kind() {
1964             FnDef(def_id, substs) => tcx.bound_fn_sig(*def_id).subst(tcx, substs),
1965             FnPtr(f) => *f,
1966             Error(_) => {
1967                 // ignore errors (#54954)
1968                 ty::Binder::dummy(FnSig::fake())
1969             }
1970             Closure(..) => bug!(
1971                 "to get the signature of a closure, use `substs.as_closure().sig()` not `fn_sig()`",
1972             ),
1973             _ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self),
1974         }
1975     }
1976
1977     #[inline]
1978     pub fn is_fn(self) -> bool {
1979         matches!(self.kind(), FnDef(..) | FnPtr(_))
1980     }
1981
1982     #[inline]
1983     pub fn is_fn_ptr(self) -> bool {
1984         matches!(self.kind(), FnPtr(_))
1985     }
1986
1987     #[inline]
1988     pub fn is_impl_trait(self) -> bool {
1989         matches!(self.kind(), Opaque(..))
1990     }
1991
1992     #[inline]
1993     pub fn ty_adt_def(self) -> Option<AdtDef<'tcx>> {
1994         match self.kind() {
1995             Adt(adt, _) => Some(*adt),
1996             _ => None,
1997         }
1998     }
1999
2000     /// Iterates over tuple fields.
2001     /// Panics when called on anything but a tuple.
2002     #[inline]
2003     pub fn tuple_fields(self) -> &'tcx List<Ty<'tcx>> {
2004         match self.kind() {
2005             Tuple(substs) => substs,
2006             _ => bug!("tuple_fields called on non-tuple"),
2007         }
2008     }
2009
2010     /// If the type contains variants, returns the valid range of variant indices.
2011     //
2012     // FIXME: This requires the optimized MIR in the case of generators.
2013     #[inline]
2014     pub fn variant_range(self, tcx: TyCtxt<'tcx>) -> Option<Range<VariantIdx>> {
2015         match self.kind() {
2016             TyKind::Adt(adt, _) => Some(adt.variant_range()),
2017             TyKind::Generator(def_id, substs, _) => {
2018                 Some(substs.as_generator().variant_range(*def_id, tcx))
2019             }
2020             _ => None,
2021         }
2022     }
2023
2024     /// If the type contains variants, returns the variant for `variant_index`.
2025     /// Panics if `variant_index` is out of range.
2026     //
2027     // FIXME: This requires the optimized MIR in the case of generators.
2028     #[inline]
2029     pub fn discriminant_for_variant(
2030         self,
2031         tcx: TyCtxt<'tcx>,
2032         variant_index: VariantIdx,
2033     ) -> Option<Discr<'tcx>> {
2034         match self.kind() {
2035             TyKind::Adt(adt, _) if adt.variants().is_empty() => {
2036                 // This can actually happen during CTFE, see
2037                 // https://github.com/rust-lang/rust/issues/89765.
2038                 None
2039             }
2040             TyKind::Adt(adt, _) if adt.is_enum() => {
2041                 Some(adt.discriminant_for_variant(tcx, variant_index))
2042             }
2043             TyKind::Generator(def_id, substs, _) => {
2044                 Some(substs.as_generator().discriminant_for_variant(*def_id, tcx, variant_index))
2045             }
2046             _ => None,
2047         }
2048     }
2049
2050     /// Returns the type of the discriminant of this type.
2051     pub fn discriminant_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
2052         match self.kind() {
2053             ty::Adt(adt, _) if adt.is_enum() => adt.repr().discr_type().to_ty(tcx),
2054             ty::Generator(_, substs, _) => substs.as_generator().discr_ty(tcx),
2055
2056             ty::Param(_) | ty::Projection(_) | ty::Opaque(..) | ty::Infer(ty::TyVar(_)) => {
2057                 let assoc_items = tcx.associated_item_def_ids(
2058                     tcx.require_lang_item(hir::LangItem::DiscriminantKind, None),
2059                 );
2060                 tcx.mk_projection(assoc_items[0], tcx.intern_substs(&[self.into()]))
2061             }
2062
2063             ty::Bool
2064             | ty::Char
2065             | ty::Int(_)
2066             | ty::Uint(_)
2067             | ty::Float(_)
2068             | ty::Adt(..)
2069             | ty::Foreign(_)
2070             | ty::Str
2071             | ty::Array(..)
2072             | ty::Slice(_)
2073             | ty::RawPtr(_)
2074             | ty::Ref(..)
2075             | ty::FnDef(..)
2076             | ty::FnPtr(..)
2077             | ty::Dynamic(..)
2078             | ty::Closure(..)
2079             | ty::GeneratorWitness(..)
2080             | ty::Never
2081             | ty::Tuple(_)
2082             | ty::Error(_)
2083             | ty::Infer(IntVar(_) | FloatVar(_)) => tcx.types.u8,
2084
2085             ty::Bound(..)
2086             | ty::Placeholder(_)
2087             | ty::Infer(FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2088                 bug!("`discriminant_ty` applied to unexpected type: {:?}", self)
2089             }
2090         }
2091     }
2092
2093     /// Returns the type of metadata for (potentially fat) pointers to this type,
2094     /// and a boolean signifying if this is conditional on this type being `Sized`.
2095     pub fn ptr_metadata_ty(
2096         self,
2097         tcx: TyCtxt<'tcx>,
2098         normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>,
2099     ) -> (Ty<'tcx>, bool) {
2100         let tail = tcx.struct_tail_with_normalize(self, normalize, || {});
2101         match tail.kind() {
2102             // Sized types
2103             ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
2104             | ty::Uint(_)
2105             | ty::Int(_)
2106             | ty::Bool
2107             | ty::Float(_)
2108             | ty::FnDef(..)
2109             | ty::FnPtr(_)
2110             | ty::RawPtr(..)
2111             | ty::Char
2112             | ty::Ref(..)
2113             | ty::Generator(..)
2114             | ty::GeneratorWitness(..)
2115             | ty::Array(..)
2116             | ty::Closure(..)
2117             | ty::Never
2118             | ty::Error(_)
2119             // Extern types have metadata = ().
2120             | ty::Foreign(..)
2121             // If returned by `struct_tail_without_normalization` this is a unit struct
2122             // without any fields, or not a struct, and therefore is Sized.
2123             | ty::Adt(..)
2124             // If returned by `struct_tail_without_normalization` this is the empty tuple,
2125             // a.k.a. unit type, which is Sized
2126             | ty::Tuple(..) => (tcx.types.unit, false),
2127
2128             ty::Str | ty::Slice(_) => (tcx.types.usize, false),
2129             ty::Dynamic(..) => {
2130                 let dyn_metadata = tcx.lang_items().dyn_metadata().unwrap();
2131                 (tcx.bound_type_of(dyn_metadata).subst(tcx, &[tail.into()]), false)
2132             },
2133
2134             // type parameters only have unit metadata if they're sized, so return true
2135             // to make sure we double check this during confirmation
2136             ty::Param(_) |  ty::Projection(_) | ty::Opaque(..) => (tcx.types.unit, true),
2137
2138             ty::Infer(ty::TyVar(_))
2139             | ty::Bound(..)
2140             | ty::Placeholder(..)
2141             | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2142                 bug!("`ptr_metadata_ty` applied to unexpected type: {:?} (tail = {:?})", self, tail)
2143             }
2144         }
2145     }
2146
2147     /// When we create a closure, we record its kind (i.e., what trait
2148     /// it implements) into its `ClosureSubsts` using a type
2149     /// parameter. This is kind of a phantom type, except that the
2150     /// most convenient thing for us to are the integral types. This
2151     /// function converts such a special type into the closure
2152     /// kind. To go the other way, use
2153     /// `tcx.closure_kind_ty(closure_kind)`.
2154     ///
2155     /// Note that during type checking, we use an inference variable
2156     /// to represent the closure kind, because it has not yet been
2157     /// inferred. Once upvar inference (in `rustc_typeck/src/check/upvar.rs`)
2158     /// is complete, that type variable will be unified.
2159     pub fn to_opt_closure_kind(self) -> Option<ty::ClosureKind> {
2160         match self.kind() {
2161             Int(int_ty) => match int_ty {
2162                 ty::IntTy::I8 => Some(ty::ClosureKind::Fn),
2163                 ty::IntTy::I16 => Some(ty::ClosureKind::FnMut),
2164                 ty::IntTy::I32 => Some(ty::ClosureKind::FnOnce),
2165                 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
2166             },
2167
2168             // "Bound" types appear in canonical queries when the
2169             // closure type is not yet known
2170             Bound(..) | Infer(_) => None,
2171
2172             Error(_) => Some(ty::ClosureKind::Fn),
2173
2174             _ => bug!("cannot convert type `{:?}` to a closure kind", self),
2175         }
2176     }
2177
2178     /// Fast path helper for testing if a type is `Sized`.
2179     ///
2180     /// Returning true means the type is known to be sized. Returning
2181     /// `false` means nothing -- could be sized, might not be.
2182     ///
2183     /// Note that we could never rely on the fact that a type such as `[_]` is
2184     /// trivially `!Sized` because we could be in a type environment with a
2185     /// bound such as `[_]: Copy`. A function with such a bound obviously never
2186     /// can be called, but that doesn't mean it shouldn't typecheck. This is why
2187     /// this method doesn't return `Option<bool>`.
2188     pub fn is_trivially_sized(self, tcx: TyCtxt<'tcx>) -> bool {
2189         match self.kind() {
2190             ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
2191             | ty::Uint(_)
2192             | ty::Int(_)
2193             | ty::Bool
2194             | ty::Float(_)
2195             | ty::FnDef(..)
2196             | ty::FnPtr(_)
2197             | ty::RawPtr(..)
2198             | ty::Char
2199             | ty::Ref(..)
2200             | ty::Generator(..)
2201             | ty::GeneratorWitness(..)
2202             | ty::Array(..)
2203             | ty::Closure(..)
2204             | ty::Never
2205             | ty::Error(_) => true,
2206
2207             ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => false,
2208
2209             ty::Tuple(tys) => tys.iter().all(|ty| ty.is_trivially_sized(tcx)),
2210
2211             ty::Adt(def, _substs) => def.sized_constraint(tcx).0.is_empty(),
2212
2213             ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => false,
2214
2215             ty::Infer(ty::TyVar(_)) => false,
2216
2217             ty::Bound(..)
2218             | ty::Placeholder(..)
2219             | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2220                 bug!("`is_trivially_sized` applied to unexpected type: {:?}", self)
2221             }
2222         }
2223     }
2224
2225     /// Fast path helper for primitives which are always `Copy` and which
2226     /// have a side-effect-free `Clone` impl.
2227     ///
2228     /// Returning true means the type is known to be pure and `Copy+Clone`.
2229     /// Returning `false` means nothing -- could be `Copy`, might not be.
2230     ///
2231     /// This is mostly useful for optimizations, as there are the types
2232     /// on which we can replace cloning with dereferencing.
2233     pub fn is_trivially_pure_clone_copy(self) -> bool {
2234         match self.kind() {
2235             ty::Bool | ty::Char | ty::Never => true,
2236
2237             // These aren't even `Clone`
2238             ty::Str | ty::Slice(..) | ty::Foreign(..) | ty::Dynamic(..) => false,
2239
2240             ty::Int(..) | ty::Uint(..) | ty::Float(..) => true,
2241
2242             // The voldemort ZSTs are fine.
2243             ty::FnDef(..) => true,
2244
2245             ty::Array(element_ty, _len) => element_ty.is_trivially_pure_clone_copy(),
2246
2247             // A 100-tuple isn't "trivial", so doing this only for reasonable sizes.
2248             ty::Tuple(field_tys) => {
2249                 field_tys.len() <= 3 && field_tys.iter().all(Self::is_trivially_pure_clone_copy)
2250             }
2251
2252             // Sometimes traits aren't implemented for every ABI or arity,
2253             // because we can't be generic over everything yet.
2254             ty::FnPtr(..) => false,
2255
2256             // Definitely absolutely not copy.
2257             ty::Ref(_, _, hir::Mutability::Mut) => false,
2258
2259             // Thin pointers & thin shared references are pure-clone-copy, but for
2260             // anything with custom metadata it might be more complicated.
2261             ty::Ref(_, _, hir::Mutability::Not) | ty::RawPtr(..) => false,
2262
2263             ty::Generator(..) | ty::GeneratorWitness(..) => false,
2264
2265             // Might be, but not "trivial" so just giving the safe answer.
2266             ty::Adt(..) | ty::Closure(..) | ty::Opaque(..) => false,
2267
2268             ty::Projection(..) | ty::Param(..) | ty::Infer(..) | ty::Error(..) => false,
2269
2270             ty::Bound(..) | ty::Placeholder(..) => {
2271                 bug!("`is_trivially_pure_clone_copy` applied to unexpected type: {:?}", self);
2272             }
2273         }
2274     }
2275 }
2276
2277 /// Extra information about why we ended up with a particular variance.
2278 /// This is only used to add more information to error messages, and
2279 /// has no effect on soundness. While choosing the 'wrong' `VarianceDiagInfo`
2280 /// may lead to confusing notes in error messages, it will never cause
2281 /// a miscompilation or unsoundness.
2282 ///
2283 /// When in doubt, use `VarianceDiagInfo::default()`
2284 #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
2285 pub enum VarianceDiagInfo<'tcx> {
2286     /// No additional information - this is the default.
2287     /// We will not add any additional information to error messages.
2288     #[default]
2289     None,
2290     /// We switched our variance because a generic argument occurs inside
2291     /// the invariant generic argument of another type.
2292     Invariant {
2293         /// The generic type containing the generic parameter
2294         /// that changes the variance (e.g. `*mut T`, `MyStruct<T>`)
2295         ty: Ty<'tcx>,
2296         /// The index of the generic parameter being used
2297         /// (e.g. `0` for `*mut T`, `1` for `MyStruct<'CovariantParam, 'InvariantParam>`)
2298         param_index: u32,
2299     },
2300 }
2301
2302 impl<'tcx> VarianceDiagInfo<'tcx> {
2303     /// Mirrors `Variance::xform` - used to 'combine' the existing
2304     /// and new `VarianceDiagInfo`s when our variance changes.
2305     pub fn xform(self, other: VarianceDiagInfo<'tcx>) -> VarianceDiagInfo<'tcx> {
2306         // For now, just use the first `VarianceDiagInfo::Invariant` that we see
2307         match self {
2308             VarianceDiagInfo::None => other,
2309             VarianceDiagInfo::Invariant { .. } => self,
2310         }
2311     }
2312 }