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