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