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