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