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