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