1 //! This module contains `TyKind` and its major components.
3 #![allow(rustc::usage_of_ty_tykind)]
5 use crate::infer::canonical::Canonical;
6 use crate::ty::subst::{GenericArg, InternalSubsts, Subst, SubstsRef};
7 use crate::ty::visit::ValidateBoundVars;
8 use crate::ty::InferTy::*;
10 self, AdtDef, DefIdTree, Discr, Term, Ty, TyCtxt, TypeFlags, TypeSuperVisitable, TypeVisitable,
13 use crate::ty::{List, ParamEnv};
14 use polonius_engine::Atom;
15 use rustc_data_structures::captures::Captures;
16 use rustc_data_structures::intern::Interned;
18 use rustc_hir::def_id::DefId;
19 use rustc_index::vec::Idx;
20 use rustc_macros::HashStable;
21 use rustc_span::symbol::{kw, Symbol};
22 use rustc_target::abi::VariantIdx;
23 use rustc_target::spec::abi;
25 use std::cmp::Ordering;
27 use std::marker::PhantomData;
28 use std::ops::{ControlFlow, Deref, Range};
29 use ty::util::IntTypeExt;
31 use rustc_type_ir::sty::TyKind::*;
32 use rustc_type_ir::RegionKind as IrRegionKind;
33 use rustc_type_ir::TyKind as IrTyKind;
35 // Re-export the `TyKind` from `rustc_type_ir` here for convenience
36 #[rustc_diagnostic_item = "TyKind"]
37 pub type TyKind<'tcx> = IrTyKind<TyCtxt<'tcx>>;
38 pub type RegionKind<'tcx> = IrRegionKind<TyCtxt<'tcx>>;
40 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
41 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
42 pub struct TypeAndMut<'tcx> {
44 pub mutbl: hir::Mutability,
47 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, TyEncodable, TyDecodable, Copy)]
49 /// A "free" region `fr` can be interpreted as "some region
50 /// at least as big as the scope `fr.scope`".
51 pub struct FreeRegion {
53 pub bound_region: BoundRegionKind,
56 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, TyEncodable, TyDecodable, Copy)]
58 pub enum BoundRegionKind {
59 /// An anonymous region parameter for a given fn (&T)
62 /// Named region parameters for functions (a in &'a T)
64 /// The `DefId` is needed to distinguish free regions in
65 /// the event of shadowing.
66 BrNamed(DefId, Symbol),
68 /// Anonymous region for the implicit env pointer parameter
73 #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, Debug, PartialOrd, Ord)]
75 pub struct BoundRegion {
77 pub kind: BoundRegionKind,
80 impl BoundRegionKind {
81 pub fn is_named(&self) -> bool {
83 BoundRegionKind::BrNamed(_, name) => name != kw::UnderscoreLifetime,
90 fn article(&self) -> &'static str;
93 impl<'tcx> Article for TyKind<'tcx> {
94 /// Get the article ("a" or "an") to use with this type.
95 fn article(&self) -> &'static str {
97 Int(_) | Float(_) | Array(_, _) => "an",
98 Adt(def, _) if def.is_enum() => "an",
99 // This should never happen, but ICEing and causing the user's code
100 // to not compile felt too harsh.
107 // `TyKind` is used a lot. Make sure it doesn't unintentionally get bigger.
108 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
109 static_assert_size!(TyKind<'_>, 32);
111 /// A closure can be modeled as a struct that looks like:
112 /// ```ignore (illustrative)
113 /// struct Closure<'l0...'li, T0...Tj, CK, CS, U>(...U);
117 /// - 'l0...'li and T0...Tj are the generic parameters
118 /// in scope on the function that defined the closure,
119 /// - CK represents the *closure kind* (Fn vs FnMut vs FnOnce). This
120 /// is rather hackily encoded via a scalar type. See
121 /// `Ty::to_opt_closure_kind` for details.
122 /// - CS represents the *closure signature*, representing as a `fn()`
123 /// type. For example, `fn(u32, u32) -> u32` would mean that the closure
124 /// implements `CK<(u32, u32), Output = u32>`, where `CK` is the trait
126 /// - U is a type parameter representing the types of its upvars, tupled up
127 /// (borrowed, if appropriate; that is, if a U field represents a by-ref upvar,
128 /// and the up-var has the type `Foo`, then that field of U will be `&Foo`).
130 /// So, for example, given this function:
131 /// ```ignore (illustrative)
132 /// fn foo<'a, T>(data: &'a mut T) {
133 /// do(|| data.count += 1)
136 /// the type of the closure would be something like:
137 /// ```ignore (illustrative)
138 /// struct Closure<'a, T, U>(...U);
140 /// Note that the type of the upvar is not specified in the struct.
141 /// You may wonder how the impl would then be able to use the upvar,
142 /// if it doesn't know it's type? The answer is that the impl is
143 /// (conceptually) not fully generic over Closure but rather tied to
144 /// instances with the expected upvar types:
145 /// ```ignore (illustrative)
146 /// impl<'b, 'a, T> FnMut() for Closure<'a, T, (&'b mut &'a mut T,)> {
150 /// You can see that the *impl* fully specified the type of the upvar
151 /// and thus knows full well that `data` has type `&'b mut &'a mut T`.
152 /// (Here, I am assuming that `data` is mut-borrowed.)
154 /// Now, the last question you may ask is: Why include the upvar types
155 /// in an extra type parameter? The reason for this design is that the
156 /// upvar types can reference lifetimes that are internal to the
157 /// creating function. In my example above, for example, the lifetime
158 /// `'b` represents the scope of the closure itself; this is some
159 /// subset of `foo`, probably just the scope of the call to the to
160 /// `do()`. If we just had the lifetime/type parameters from the
161 /// enclosing function, we couldn't name this lifetime `'b`. Note that
162 /// there can also be lifetimes in the types of the upvars themselves,
163 /// if one of them happens to be a reference to something that the
164 /// creating fn owns.
166 /// OK, you say, so why not create a more minimal set of parameters
167 /// that just includes the extra lifetime parameters? The answer is
168 /// primarily that it would be hard --- we don't know at the time when
169 /// we create the closure type what the full types of the upvars are,
170 /// nor do we know which are borrowed and which are not. In this
171 /// design, we can just supply a fresh type parameter and figure that
174 /// All right, you say, but why include the type parameters from the
175 /// original function then? The answer is that codegen may need them
176 /// when monomorphizing, and they may not appear in the upvars. A
177 /// closure could capture no variables but still make use of some
178 /// in-scope type parameter with a bound (e.g., if our example above
179 /// had an extra `U: Default`, and the closure called `U::default()`).
181 /// There is another reason. This design (implicitly) prohibits
182 /// closures from capturing themselves (except via a trait
183 /// object). This simplifies closure inference considerably, since it
184 /// means that when we infer the kind of a closure or its upvars, we
185 /// don't have to handle cycles where the decisions we make for
186 /// closure C wind up influencing the decisions we ought to make for
187 /// closure C (which would then require fixed point iteration to
188 /// handle). Plus it fixes an ICE. :P
192 /// Generators are handled similarly in `GeneratorSubsts`. The set of
193 /// type parameters is similar, but `CK` and `CS` are replaced by the
194 /// following type parameters:
196 /// * `GS`: The generator's "resume type", which is the type of the
197 /// argument passed to `resume`, and the type of `yield` expressions
198 /// inside the generator.
199 /// * `GY`: The "yield type", which is the type of values passed to
200 /// `yield` inside the generator.
201 /// * `GR`: The "return type", which is the type of value returned upon
202 /// completion of the generator.
203 /// * `GW`: The "generator witness".
204 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable)]
205 pub struct ClosureSubsts<'tcx> {
206 /// Lifetime and type parameters from the enclosing function,
207 /// concatenated with a tuple containing the types of the upvars.
209 /// These are separated out because codegen wants to pass them around
210 /// when monomorphizing.
211 pub substs: SubstsRef<'tcx>,
214 /// Struct returned by `split()`.
215 pub struct ClosureSubstsParts<'tcx, T> {
216 pub parent_substs: &'tcx [GenericArg<'tcx>],
217 pub closure_kind_ty: T,
218 pub closure_sig_as_fn_ptr_ty: T,
219 pub tupled_upvars_ty: T,
222 impl<'tcx> ClosureSubsts<'tcx> {
223 /// Construct `ClosureSubsts` from `ClosureSubstsParts`, containing `Substs`
224 /// for the closure parent, alongside additional closure-specific components.
227 parts: ClosureSubstsParts<'tcx, Ty<'tcx>>,
228 ) -> ClosureSubsts<'tcx> {
230 substs: tcx.mk_substs(
231 parts.parent_substs.iter().copied().chain(
232 [parts.closure_kind_ty, parts.closure_sig_as_fn_ptr_ty, parts.tupled_upvars_ty]
234 .map(|&ty| ty.into()),
240 /// Divides the closure substs into their respective components.
241 /// The ordering assumed here must match that used by `ClosureSubsts::new` above.
242 fn split(self) -> ClosureSubstsParts<'tcx, GenericArg<'tcx>> {
243 match self.substs[..] {
245 ref parent_substs @ ..,
247 closure_sig_as_fn_ptr_ty,
249 ] => ClosureSubstsParts {
252 closure_sig_as_fn_ptr_ty,
255 _ => bug!("closure substs missing synthetics"),
259 /// Returns `true` only if enough of the synthetic types are known to
260 /// allow using all of the methods on `ClosureSubsts` without panicking.
262 /// Used primarily by `ty::print::pretty` to be able to handle closure
263 /// types that haven't had their synthetic types substituted in.
264 pub fn is_valid(self) -> bool {
265 self.substs.len() >= 3
266 && matches!(self.split().tupled_upvars_ty.expect_ty().kind(), Tuple(_))
269 /// Returns the substitutions of the closure's parent.
270 pub fn parent_substs(self) -> &'tcx [GenericArg<'tcx>] {
271 self.split().parent_substs
274 /// Returns an iterator over the list of types of captured paths by the closure.
275 /// In case there was a type error in figuring out the types of the captured path, an
276 /// empty iterator is returned.
278 pub fn upvar_tys(self) -> impl Iterator<Item = Ty<'tcx>> + 'tcx {
279 match self.tupled_upvars_ty().kind() {
280 TyKind::Error(_) => None,
281 TyKind::Tuple(..) => Some(self.tupled_upvars_ty().tuple_fields()),
282 TyKind::Infer(_) => bug!("upvar_tys called before capture types are inferred"),
283 ty => bug!("Unexpected representation of upvar types tuple {:?}", ty),
289 /// Returns the tuple type representing the upvars for this closure.
291 pub fn tupled_upvars_ty(self) -> Ty<'tcx> {
292 self.split().tupled_upvars_ty.expect_ty()
295 /// Returns the closure kind for this closure; may return a type
296 /// variable during inference. To get the closure kind during
297 /// inference, use `infcx.closure_kind(substs)`.
298 pub fn kind_ty(self) -> Ty<'tcx> {
299 self.split().closure_kind_ty.expect_ty()
302 /// Returns the `fn` pointer type representing the closure signature for this
304 // FIXME(eddyb) this should be unnecessary, as the shallowly resolved
305 // type is known at the time of the creation of `ClosureSubsts`,
306 // see `rustc_typeck::check::closure`.
307 pub fn sig_as_fn_ptr_ty(self) -> Ty<'tcx> {
308 self.split().closure_sig_as_fn_ptr_ty.expect_ty()
311 /// Returns the closure kind for this closure; only usable outside
312 /// of an inference context, because in that context we know that
313 /// there are no type variables.
315 /// If you have an inference context, use `infcx.closure_kind()`.
316 pub fn kind(self) -> ty::ClosureKind {
317 self.kind_ty().to_opt_closure_kind().unwrap()
320 /// Extracts the signature from the closure.
321 pub fn sig(self) -> ty::PolyFnSig<'tcx> {
322 let ty = self.sig_as_fn_ptr_ty();
324 ty::FnPtr(sig) => *sig,
325 _ => bug!("closure_sig_as_fn_ptr_ty is not a fn-ptr: {:?}", ty.kind()),
329 pub fn print_as_impl_trait(self) -> ty::print::PrintClosureAsImpl<'tcx> {
330 ty::print::PrintClosureAsImpl { closure: self }
334 /// Similar to `ClosureSubsts`; see the above documentation for more.
335 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable)]
336 pub struct GeneratorSubsts<'tcx> {
337 pub substs: SubstsRef<'tcx>,
340 pub struct GeneratorSubstsParts<'tcx, T> {
341 pub parent_substs: &'tcx [GenericArg<'tcx>],
346 pub tupled_upvars_ty: T,
349 impl<'tcx> GeneratorSubsts<'tcx> {
350 /// Construct `GeneratorSubsts` from `GeneratorSubstsParts`, containing `Substs`
351 /// for the generator parent, alongside additional generator-specific components.
354 parts: GeneratorSubstsParts<'tcx, Ty<'tcx>>,
355 ) -> GeneratorSubsts<'tcx> {
357 substs: tcx.mk_substs(
358 parts.parent_substs.iter().copied().chain(
364 parts.tupled_upvars_ty,
367 .map(|&ty| ty.into()),
373 /// Divides the generator substs into their respective components.
374 /// The ordering assumed here must match that used by `GeneratorSubsts::new` above.
375 fn split(self) -> GeneratorSubstsParts<'tcx, GenericArg<'tcx>> {
376 match self.substs[..] {
377 [ref parent_substs @ .., resume_ty, yield_ty, return_ty, witness, tupled_upvars_ty] => {
378 GeneratorSubstsParts {
387 _ => bug!("generator substs missing synthetics"),
391 /// Returns `true` only if enough of the synthetic types are known to
392 /// allow using all of the methods on `GeneratorSubsts` without panicking.
394 /// Used primarily by `ty::print::pretty` to be able to handle generator
395 /// types that haven't had their synthetic types substituted in.
396 pub fn is_valid(self) -> bool {
397 self.substs.len() >= 5
398 && matches!(self.split().tupled_upvars_ty.expect_ty().kind(), Tuple(_))
401 /// Returns the substitutions of the generator's parent.
402 pub fn parent_substs(self) -> &'tcx [GenericArg<'tcx>] {
403 self.split().parent_substs
406 /// This describes the types that can be contained in a generator.
407 /// It will be a type variable initially and unified in the last stages of typeck of a body.
408 /// It contains a tuple of all the types that could end up on a generator frame.
409 /// The state transformation MIR pass may only produce layouts which mention types
410 /// in this tuple. Upvars are not counted here.
411 pub fn witness(self) -> Ty<'tcx> {
412 self.split().witness.expect_ty()
415 /// Returns an iterator over the list of types of captured paths by the generator.
416 /// In case there was a type error in figuring out the types of the captured path, an
417 /// empty iterator is returned.
419 pub fn upvar_tys(self) -> impl Iterator<Item = Ty<'tcx>> + 'tcx {
420 match self.tupled_upvars_ty().kind() {
421 TyKind::Error(_) => None,
422 TyKind::Tuple(..) => Some(self.tupled_upvars_ty().tuple_fields()),
423 TyKind::Infer(_) => bug!("upvar_tys called before capture types are inferred"),
424 ty => bug!("Unexpected representation of upvar types tuple {:?}", ty),
430 /// Returns the tuple type representing the upvars for this generator.
432 pub fn tupled_upvars_ty(self) -> Ty<'tcx> {
433 self.split().tupled_upvars_ty.expect_ty()
436 /// Returns the type representing the resume type of the generator.
437 pub fn resume_ty(self) -> Ty<'tcx> {
438 self.split().resume_ty.expect_ty()
441 /// Returns the type representing the yield type of the generator.
442 pub fn yield_ty(self) -> Ty<'tcx> {
443 self.split().yield_ty.expect_ty()
446 /// Returns the type representing the return type of the generator.
447 pub fn return_ty(self) -> Ty<'tcx> {
448 self.split().return_ty.expect_ty()
451 /// Returns the "generator signature", which consists of its yield
452 /// and return types.
454 /// N.B., some bits of the code prefers to see this wrapped in a
455 /// binder, but it never contains bound regions. Probably this
456 /// function should be removed.
457 pub fn poly_sig(self) -> PolyGenSig<'tcx> {
458 ty::Binder::dummy(self.sig())
461 /// Returns the "generator signature", which consists of its resume, yield
462 /// and return types.
463 pub fn sig(self) -> GenSig<'tcx> {
465 resume_ty: self.resume_ty(),
466 yield_ty: self.yield_ty(),
467 return_ty: self.return_ty(),
472 impl<'tcx> GeneratorSubsts<'tcx> {
473 /// Generator has not been resumed yet.
474 pub const UNRESUMED: usize = 0;
475 /// Generator has returned or is completed.
476 pub const RETURNED: usize = 1;
477 /// Generator has been poisoned.
478 pub const POISONED: usize = 2;
480 const UNRESUMED_NAME: &'static str = "Unresumed";
481 const RETURNED_NAME: &'static str = "Returned";
482 const POISONED_NAME: &'static str = "Panicked";
484 /// The valid variant indices of this generator.
486 pub fn variant_range(&self, def_id: DefId, tcx: TyCtxt<'tcx>) -> Range<VariantIdx> {
487 // FIXME requires optimized MIR
488 let num_variants = tcx.generator_layout(def_id).unwrap().variant_fields.len();
489 VariantIdx::new(0)..VariantIdx::new(num_variants)
492 /// The discriminant for the given variant. Panics if the `variant_index` is
495 pub fn discriminant_for_variant(
499 variant_index: VariantIdx,
501 // Generators don't support explicit discriminant values, so they are
502 // the same as the variant index.
503 assert!(self.variant_range(def_id, tcx).contains(&variant_index));
504 Discr { val: variant_index.as_usize() as u128, ty: self.discr_ty(tcx) }
507 /// The set of all discriminants for the generator, enumerated with their
510 pub fn discriminants(
514 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
515 self.variant_range(def_id, tcx).map(move |index| {
516 (index, Discr { val: index.as_usize() as u128, ty: self.discr_ty(tcx) })
520 /// Calls `f` with a reference to the name of the enumerator for the given
522 pub fn variant_name(v: VariantIdx) -> Cow<'static, str> {
524 Self::UNRESUMED => Cow::from(Self::UNRESUMED_NAME),
525 Self::RETURNED => Cow::from(Self::RETURNED_NAME),
526 Self::POISONED => Cow::from(Self::POISONED_NAME),
527 _ => Cow::from(format!("Suspend{}", v.as_usize() - 3)),
531 /// The type of the state discriminant used in the generator type.
533 pub fn discr_ty(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
537 /// This returns the types of the MIR locals which had to be stored across suspension points.
538 /// It is calculated in rustc_mir_transform::generator::StateTransform.
539 /// All the types here must be in the tuple in GeneratorInterior.
541 /// The locals are grouped by their variant number. Note that some locals may
542 /// be repeated in multiple variants.
548 ) -> impl Iterator<Item = impl Iterator<Item = Ty<'tcx>> + Captures<'tcx>> {
549 let layout = tcx.generator_layout(def_id).unwrap();
550 layout.variant_fields.iter().map(move |variant| {
553 .map(move |field| EarlyBinder(layout.field_tys[*field]).subst(tcx, self.substs))
557 /// This is the types of the fields of a generator which are not stored in a
560 pub fn prefix_tys(self) -> impl Iterator<Item = Ty<'tcx>> {
565 #[derive(Debug, Copy, Clone, HashStable)]
566 pub enum UpvarSubsts<'tcx> {
567 Closure(SubstsRef<'tcx>),
568 Generator(SubstsRef<'tcx>),
571 impl<'tcx> UpvarSubsts<'tcx> {
572 /// Returns an iterator over the list of types of captured paths by the closure/generator.
573 /// In case there was a type error in figuring out the types of the captured path, an
574 /// empty iterator is returned.
576 pub fn upvar_tys(self) -> impl Iterator<Item = Ty<'tcx>> + 'tcx {
577 let tupled_tys = match self {
578 UpvarSubsts::Closure(substs) => substs.as_closure().tupled_upvars_ty(),
579 UpvarSubsts::Generator(substs) => substs.as_generator().tupled_upvars_ty(),
582 match tupled_tys.kind() {
583 TyKind::Error(_) => None,
584 TyKind::Tuple(..) => Some(self.tupled_upvars_ty().tuple_fields()),
585 TyKind::Infer(_) => bug!("upvar_tys called before capture types are inferred"),
586 ty => bug!("Unexpected representation of upvar types tuple {:?}", ty),
593 pub fn tupled_upvars_ty(self) -> Ty<'tcx> {
595 UpvarSubsts::Closure(substs) => substs.as_closure().tupled_upvars_ty(),
596 UpvarSubsts::Generator(substs) => substs.as_generator().tupled_upvars_ty(),
601 /// An inline const is modeled like
602 /// ```ignore (illustrative)
603 /// const InlineConst<'l0...'li, T0...Tj, R>: R;
607 /// - 'l0...'li and T0...Tj are the generic parameters
608 /// inherited from the item that defined the inline const,
609 /// - R represents the type of the constant.
611 /// When the inline const is instantiated, `R` is substituted as the actual inferred
612 /// type of the constant. The reason that `R` is represented as an extra type parameter
613 /// is the same reason that [`ClosureSubsts`] have `CS` and `U` as type parameters:
614 /// inline const can reference lifetimes that are internal to the creating function.
615 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable)]
616 pub struct InlineConstSubsts<'tcx> {
617 /// Generic parameters from the enclosing item,
618 /// concatenated with the inferred type of the constant.
619 pub substs: SubstsRef<'tcx>,
622 /// Struct returned by `split()`.
623 pub struct InlineConstSubstsParts<'tcx, T> {
624 pub parent_substs: &'tcx [GenericArg<'tcx>],
628 impl<'tcx> InlineConstSubsts<'tcx> {
629 /// Construct `InlineConstSubsts` from `InlineConstSubstsParts`.
632 parts: InlineConstSubstsParts<'tcx, Ty<'tcx>>,
633 ) -> InlineConstSubsts<'tcx> {
635 substs: tcx.mk_substs(
636 parts.parent_substs.iter().copied().chain(std::iter::once(parts.ty.into())),
641 /// Divides the inline const substs into their respective components.
642 /// The ordering assumed here must match that used by `InlineConstSubsts::new` above.
643 fn split(self) -> InlineConstSubstsParts<'tcx, GenericArg<'tcx>> {
644 match self.substs[..] {
645 [ref parent_substs @ .., ty] => InlineConstSubstsParts { parent_substs, ty },
646 _ => bug!("inline const substs missing synthetics"),
650 /// Returns the substitutions of the inline const's parent.
651 pub fn parent_substs(self) -> &'tcx [GenericArg<'tcx>] {
652 self.split().parent_substs
655 /// Returns the type of this inline const.
656 pub fn ty(self) -> Ty<'tcx> {
657 self.split().ty.expect_ty()
661 #[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Ord, Eq, Hash, TyEncodable, TyDecodable)]
662 #[derive(HashStable, TypeFoldable, TypeVisitable)]
663 pub enum ExistentialPredicate<'tcx> {
664 /// E.g., `Iterator`.
665 Trait(ExistentialTraitRef<'tcx>),
666 /// E.g., `Iterator::Item = T`.
667 Projection(ExistentialProjection<'tcx>),
672 impl<'tcx> ExistentialPredicate<'tcx> {
673 /// Compares via an ordering that will not change if modules are reordered or other changes are
674 /// made to the tree. In particular, this ordering is preserved across incremental compilations.
675 pub fn stable_cmp(&self, tcx: TyCtxt<'tcx>, other: &Self) -> Ordering {
676 use self::ExistentialPredicate::*;
677 match (*self, *other) {
678 (Trait(_), Trait(_)) => Ordering::Equal,
679 (Projection(ref a), Projection(ref b)) => {
680 tcx.def_path_hash(a.item_def_id).cmp(&tcx.def_path_hash(b.item_def_id))
682 (AutoTrait(ref a), AutoTrait(ref b)) => {
683 tcx.def_path_hash(*a).cmp(&tcx.def_path_hash(*b))
685 (Trait(_), _) => Ordering::Less,
686 (Projection(_), Trait(_)) => Ordering::Greater,
687 (Projection(_), _) => Ordering::Less,
688 (AutoTrait(_), _) => Ordering::Greater,
693 impl<'tcx> Binder<'tcx, ExistentialPredicate<'tcx>> {
694 pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::Predicate<'tcx> {
695 use crate::ty::ToPredicate;
696 match self.skip_binder() {
697 ExistentialPredicate::Trait(tr) => {
698 self.rebind(tr).with_self_ty(tcx, self_ty).without_const().to_predicate(tcx)
700 ExistentialPredicate::Projection(p) => {
701 self.rebind(p.with_self_ty(tcx, self_ty)).to_predicate(tcx)
703 ExistentialPredicate::AutoTrait(did) => {
704 let trait_ref = self.rebind(ty::TraitRef {
706 substs: tcx.mk_substs_trait(self_ty, &[]),
708 trait_ref.without_const().to_predicate(tcx)
714 impl<'tcx> List<ty::Binder<'tcx, ExistentialPredicate<'tcx>>> {
715 /// Returns the "principal `DefId`" of this set of existential predicates.
717 /// A Rust trait object type consists (in addition to a lifetime bound)
718 /// of a set of trait bounds, which are separated into any number
719 /// of auto-trait bounds, and at most one non-auto-trait bound. The
720 /// non-auto-trait bound is called the "principal" of the trait
723 /// Only the principal can have methods or type parameters (because
724 /// auto traits can have neither of them). This is important, because
725 /// it means the auto traits can be treated as an unordered set (methods
726 /// would force an order for the vtable, while relating traits with
727 /// type parameters without knowing the order to relate them in is
728 /// a rather non-trivial task).
730 /// For example, in the trait object `dyn fmt::Debug + Sync`, the
731 /// principal bound is `Some(fmt::Debug)`, while the auto-trait bounds
732 /// are the set `{Sync}`.
734 /// It is also possible to have a "trivial" trait object that
735 /// consists only of auto traits, with no principal - for example,
736 /// `dyn Send + Sync`. In that case, the set of auto-trait bounds
737 /// is `{Send, Sync}`, while there is no principal. These trait objects
738 /// have a "trivial" vtable consisting of just the size, alignment,
740 pub fn principal(&self) -> Option<ty::Binder<'tcx, ExistentialTraitRef<'tcx>>> {
742 .map_bound(|this| match this {
743 ExistentialPredicate::Trait(tr) => Some(tr),
749 pub fn principal_def_id(&self) -> Option<DefId> {
750 self.principal().map(|trait_ref| trait_ref.skip_binder().def_id)
754 pub fn projection_bounds<'a>(
756 ) -> impl Iterator<Item = ty::Binder<'tcx, ExistentialProjection<'tcx>>> + 'a {
757 self.iter().filter_map(|predicate| {
759 .map_bound(|pred| match pred {
760 ExistentialPredicate::Projection(projection) => Some(projection),
768 pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item = DefId> + Captures<'tcx> + 'a {
769 self.iter().filter_map(|predicate| match predicate.skip_binder() {
770 ExistentialPredicate::AutoTrait(did) => Some(did),
776 /// A complete reference to a trait. These take numerous guises in syntax,
777 /// but perhaps the most recognizable form is in a where-clause:
778 /// ```ignore (illustrative)
781 /// This would be represented by a trait-reference where the `DefId` is the
782 /// `DefId` for the trait `Foo` and the substs define `T` as parameter 0,
783 /// and `U` as parameter 1.
785 /// Trait references also appear in object types like `Foo<U>`, but in
786 /// that case the `Self` parameter is absent from the substitutions.
787 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)]
788 #[derive(HashStable, TypeFoldable, TypeVisitable)]
789 pub struct TraitRef<'tcx> {
791 pub substs: SubstsRef<'tcx>,
794 impl<'tcx> TraitRef<'tcx> {
795 pub fn new(def_id: DefId, substs: SubstsRef<'tcx>) -> TraitRef<'tcx> {
796 TraitRef { def_id, substs }
799 /// Returns a `TraitRef` of the form `P0: Foo<P1..Pn>` where `Pi`
800 /// are the parameters defined on trait.
801 pub fn identity(tcx: TyCtxt<'tcx>, def_id: DefId) -> Binder<'tcx, TraitRef<'tcx>> {
802 ty::Binder::dummy(TraitRef {
804 substs: InternalSubsts::identity_for_item(tcx, def_id),
809 pub fn self_ty(&self) -> Ty<'tcx> {
810 self.substs.type_at(0)
816 substs: SubstsRef<'tcx>,
817 ) -> ty::TraitRef<'tcx> {
818 let defs = tcx.generics_of(trait_id);
819 ty::TraitRef { def_id: trait_id, substs: tcx.intern_substs(&substs[..defs.params.len()]) }
823 pub type PolyTraitRef<'tcx> = Binder<'tcx, TraitRef<'tcx>>;
825 impl<'tcx> PolyTraitRef<'tcx> {
826 pub fn self_ty(&self) -> Binder<'tcx, Ty<'tcx>> {
827 self.map_bound_ref(|tr| tr.self_ty())
830 pub fn def_id(&self) -> DefId {
831 self.skip_binder().def_id
834 pub fn to_poly_trait_predicate(&self) -> ty::PolyTraitPredicate<'tcx> {
835 self.map_bound(|trait_ref| ty::TraitPredicate {
837 constness: ty::BoundConstness::NotConst,
838 polarity: ty::ImplPolarity::Positive,
842 /// Same as [`PolyTraitRef::to_poly_trait_predicate`] but sets a negative polarity instead.
843 pub fn to_poly_trait_predicate_negative_polarity(&self) -> ty::PolyTraitPredicate<'tcx> {
844 self.map_bound(|trait_ref| ty::TraitPredicate {
846 constness: ty::BoundConstness::NotConst,
847 polarity: ty::ImplPolarity::Negative,
852 impl rustc_errors::IntoDiagnosticArg for PolyTraitRef<'_> {
853 fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue<'static> {
854 self.to_string().into_diagnostic_arg()
858 /// An existential reference to a trait, where `Self` is erased.
859 /// For example, the trait object `Trait<'a, 'b, X, Y>` is:
860 /// ```ignore (illustrative)
861 /// exists T. T: Trait<'a, 'b, X, Y>
863 /// The substitutions don't include the erased `Self`, only trait
864 /// type and lifetime parameters (`[X, Y]` and `['a, 'b]` above).
865 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)]
866 #[derive(HashStable, TypeFoldable, TypeVisitable)]
867 pub struct ExistentialTraitRef<'tcx> {
869 pub substs: SubstsRef<'tcx>,
872 impl<'tcx> ExistentialTraitRef<'tcx> {
873 pub fn erase_self_ty(
875 trait_ref: ty::TraitRef<'tcx>,
876 ) -> ty::ExistentialTraitRef<'tcx> {
877 // Assert there is a Self.
878 trait_ref.substs.type_at(0);
880 ty::ExistentialTraitRef {
881 def_id: trait_ref.def_id,
882 substs: tcx.intern_substs(&trait_ref.substs[1..]),
886 /// Object types don't have a self type specified. Therefore, when
887 /// we convert the principal trait-ref into a normal trait-ref,
888 /// you must give *some* self type. A common choice is `mk_err()`
889 /// or some placeholder type.
890 pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::TraitRef<'tcx> {
891 // otherwise the escaping vars would be captured by the binder
892 // debug_assert!(!self_ty.has_escaping_bound_vars());
894 ty::TraitRef { def_id: self.def_id, substs: tcx.mk_substs_trait(self_ty, self.substs) }
898 pub type PolyExistentialTraitRef<'tcx> = Binder<'tcx, ExistentialTraitRef<'tcx>>;
900 impl<'tcx> PolyExistentialTraitRef<'tcx> {
901 pub fn def_id(&self) -> DefId {
902 self.skip_binder().def_id
905 /// Object types don't have a self type specified. Therefore, when
906 /// we convert the principal trait-ref into a normal trait-ref,
907 /// you must give *some* self type. A common choice is `mk_err()`
908 /// or some placeholder type.
909 pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::PolyTraitRef<'tcx> {
910 self.map_bound(|trait_ref| trait_ref.with_self_ty(tcx, self_ty))
914 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
915 #[derive(Encodable, Decodable, HashStable)]
916 pub struct EarlyBinder<T>(pub T);
918 impl<T> EarlyBinder<T> {
919 pub fn as_ref(&self) -> EarlyBinder<&T> {
923 pub fn map_bound_ref<F, U>(&self, f: F) -> EarlyBinder<U>
927 self.as_ref().map_bound(f)
930 pub fn map_bound<F, U>(self, f: F) -> EarlyBinder<U>
934 let value = f(self.0);
938 pub fn try_map_bound<F, U, E>(self, f: F) -> Result<EarlyBinder<U>, E>
940 F: FnOnce(T) -> Result<U, E>,
942 let value = f(self.0)?;
943 Ok(EarlyBinder(value))
946 pub fn rebind<U>(&self, value: U) -> EarlyBinder<U> {
951 impl<T> EarlyBinder<Option<T>> {
952 pub fn transpose(self) -> Option<EarlyBinder<T>> {
953 self.0.map(|v| EarlyBinder(v))
957 impl<T, U> EarlyBinder<(T, U)> {
958 pub fn transpose_tuple2(self) -> (EarlyBinder<T>, EarlyBinder<U>) {
959 (EarlyBinder(self.0.0), EarlyBinder(self.0.1))
963 pub struct EarlyBinderIter<T> {
967 impl<T: IntoIterator> EarlyBinder<T> {
968 pub fn transpose_iter(self) -> EarlyBinderIter<T::IntoIter> {
969 EarlyBinderIter { t: self.0.into_iter() }
973 impl<T: Iterator> Iterator for EarlyBinderIter<T> {
974 type Item = EarlyBinder<T::Item>;
976 fn next(&mut self) -> Option<Self::Item> {
977 self.t.next().map(|i| EarlyBinder(i))
981 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
982 #[derive(HashStable)]
983 pub enum BoundVariableKind {
985 Region(BoundRegionKind),
989 impl BoundVariableKind {
990 pub fn expect_region(self) -> BoundRegionKind {
992 BoundVariableKind::Region(lt) => lt,
993 _ => bug!("expected a region, but found another kind"),
997 pub fn expect_ty(self) -> BoundTyKind {
999 BoundVariableKind::Ty(ty) => ty,
1000 _ => bug!("expected a type, but found another kind"),
1004 pub fn expect_const(self) {
1006 BoundVariableKind::Const => (),
1007 _ => bug!("expected a const, but found another kind"),
1012 /// Binder is a binder for higher-ranked lifetimes or types. It is part of the
1013 /// compiler's representation for things like `for<'a> Fn(&'a isize)`
1014 /// (which would be represented by the type `PolyTraitRef ==
1015 /// Binder<'tcx, TraitRef>`). Note that when we instantiate,
1016 /// erase, or otherwise "discharge" these bound vars, we change the
1017 /// type from `Binder<'tcx, T>` to just `T` (see
1018 /// e.g., `liberate_late_bound_regions`).
1020 /// `Decodable` and `Encodable` are implemented for `Binder<T>` using the `impl_binder_encode_decode!` macro.
1021 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
1022 #[derive(HashStable)]
1023 pub struct Binder<'tcx, T>(T, &'tcx List<BoundVariableKind>);
1025 impl<'tcx, T> Binder<'tcx, T>
1027 T: TypeVisitable<'tcx>,
1029 /// Wraps `value` in a binder, asserting that `value` does not
1030 /// contain any bound vars that would be bound by the
1031 /// binder. This is commonly used to 'inject' a value T into a
1032 /// different binding level.
1033 pub fn dummy(value: T) -> Binder<'tcx, T> {
1034 assert!(!value.has_escaping_bound_vars());
1035 Binder(value, ty::List::empty())
1038 pub fn bind_with_vars(value: T, vars: &'tcx List<BoundVariableKind>) -> Binder<'tcx, T> {
1039 if cfg!(debug_assertions) {
1040 let mut validator = ValidateBoundVars::new(vars);
1041 value.visit_with(&mut validator);
1047 impl<'tcx, T> Binder<'tcx, T> {
1048 /// Skips the binder and returns the "bound" value. This is a
1049 /// risky thing to do because it's easy to get confused about
1050 /// De Bruijn indices and the like. It is usually better to
1051 /// discharge the binder using `no_bound_vars` or
1052 /// `replace_late_bound_regions` or something like
1053 /// that. `skip_binder` is only valid when you are either
1054 /// extracting data that has nothing to do with bound vars, you
1055 /// are doing some sort of test that does not involve bound
1056 /// regions, or you are being very careful about your depth
1059 /// Some examples where `skip_binder` is reasonable:
1061 /// - extracting the `DefId` from a PolyTraitRef;
1062 /// - comparing the self type of a PolyTraitRef to see if it is equal to
1063 /// a type parameter `X`, since the type `X` does not reference any regions
1064 pub fn skip_binder(self) -> T {
1068 pub fn bound_vars(&self) -> &'tcx List<BoundVariableKind> {
1072 pub fn as_ref(&self) -> Binder<'tcx, &T> {
1073 Binder(&self.0, self.1)
1076 pub fn as_deref(&self) -> Binder<'tcx, &T::Target>
1080 Binder(&self.0, self.1)
1083 pub fn map_bound_ref_unchecked<F, U>(&self, f: F) -> Binder<'tcx, U>
1087 let value = f(&self.0);
1088 Binder(value, self.1)
1091 pub fn map_bound_ref<F, U: TypeVisitable<'tcx>>(&self, f: F) -> Binder<'tcx, U>
1095 self.as_ref().map_bound(f)
1098 pub fn map_bound<F, U: TypeVisitable<'tcx>>(self, f: F) -> Binder<'tcx, U>
1102 let value = f(self.0);
1103 if cfg!(debug_assertions) {
1104 let mut validator = ValidateBoundVars::new(self.1);
1105 value.visit_with(&mut validator);
1107 Binder(value, self.1)
1110 pub fn try_map_bound<F, U: TypeVisitable<'tcx>, E>(self, f: F) -> Result<Binder<'tcx, U>, E>
1112 F: FnOnce(T) -> Result<U, E>,
1114 let value = f(self.0)?;
1115 if cfg!(debug_assertions) {
1116 let mut validator = ValidateBoundVars::new(self.1);
1117 value.visit_with(&mut validator);
1119 Ok(Binder(value, self.1))
1122 /// Wraps a `value` in a binder, using the same bound variables as the
1123 /// current `Binder`. This should not be used if the new value *changes*
1124 /// the bound variables. Note: the (old or new) value itself does not
1125 /// necessarily need to *name* all the bound variables.
1127 /// This currently doesn't do anything different than `bind`, because we
1128 /// don't actually track bound vars. However, semantically, it is different
1129 /// because bound vars aren't allowed to change here, whereas they are
1130 /// in `bind`. This may be (debug) asserted in the future.
1131 pub fn rebind<U>(&self, value: U) -> Binder<'tcx, U>
1133 U: TypeVisitable<'tcx>,
1135 if cfg!(debug_assertions) {
1136 let mut validator = ValidateBoundVars::new(self.bound_vars());
1137 value.visit_with(&mut validator);
1139 Binder(value, self.1)
1142 /// Unwraps and returns the value within, but only if it contains
1143 /// no bound vars at all. (In other words, if this binder --
1144 /// and indeed any enclosing binder -- doesn't bind anything at
1145 /// all.) Otherwise, returns `None`.
1147 /// (One could imagine having a method that just unwraps a single
1148 /// binder, but permits late-bound vars bound by enclosing
1149 /// binders, but that would require adjusting the debruijn
1150 /// indices, and given the shallow binding structure we often use,
1151 /// would not be that useful.)
1152 pub fn no_bound_vars(self) -> Option<T>
1154 T: TypeVisitable<'tcx>,
1156 if self.0.has_escaping_bound_vars() { None } else { Some(self.skip_binder()) }
1159 /// Splits the contents into two things that share the same binder
1160 /// level as the original, returning two distinct binders.
1162 /// `f` should consider bound regions at depth 1 to be free, and
1163 /// anything it produces with bound regions at depth 1 will be
1164 /// bound in the resulting return values.
1165 pub fn split<U, V, F>(self, f: F) -> (Binder<'tcx, U>, Binder<'tcx, V>)
1167 F: FnOnce(T) -> (U, V),
1169 let (u, v) = f(self.0);
1170 (Binder(u, self.1), Binder(v, self.1))
1174 impl<'tcx, T> Binder<'tcx, Option<T>> {
1175 pub fn transpose(self) -> Option<Binder<'tcx, T>> {
1176 let bound_vars = self.1;
1177 self.0.map(|v| Binder(v, bound_vars))
1181 /// Represents the projection of an associated type. In explicit UFCS
1182 /// form this would be written `<T as Trait<..>>::N`.
1183 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
1184 #[derive(HashStable, TypeFoldable, TypeVisitable)]
1185 pub struct ProjectionTy<'tcx> {
1186 /// The parameters of the associated item.
1187 pub substs: SubstsRef<'tcx>,
1189 /// The `DefId` of the `TraitItem` for the associated type `N`.
1191 /// Note that this is not the `DefId` of the `TraitRef` containing this
1192 /// associated type, which is in `tcx.associated_item(item_def_id).container`,
1193 /// aka. `tcx.parent(item_def_id).unwrap()`.
1194 pub item_def_id: DefId,
1197 impl<'tcx> ProjectionTy<'tcx> {
1198 pub fn trait_def_id(&self, tcx: TyCtxt<'tcx>) -> DefId {
1199 tcx.parent(self.item_def_id)
1202 /// Extracts the underlying trait reference and own substs from this projection.
1203 /// For example, if this is a projection of `<T as StreamingIterator>::Item<'a>`,
1204 /// then this function would return a `T: Iterator` trait reference and `['a]` as the own substs
1205 pub fn trait_ref_and_own_substs(
1208 ) -> (ty::TraitRef<'tcx>, &'tcx [ty::GenericArg<'tcx>]) {
1209 let def_id = tcx.parent(self.item_def_id);
1210 let trait_generics = tcx.generics_of(def_id);
1212 ty::TraitRef { def_id, substs: self.substs.truncate_to(tcx, trait_generics) },
1213 &self.substs[trait_generics.count()..],
1217 /// Extracts the underlying trait reference from this projection.
1218 /// For example, if this is a projection of `<T as Iterator>::Item`,
1219 /// then this function would return a `T: Iterator` trait reference.
1221 /// WARNING: This will drop the substs for generic associated types
1222 /// consider calling [Self::trait_ref_and_own_substs] to get those
1224 pub fn trait_ref(&self, tcx: TyCtxt<'tcx>) -> ty::TraitRef<'tcx> {
1225 let def_id = self.trait_def_id(tcx);
1226 ty::TraitRef { def_id, substs: self.substs.truncate_to(tcx, tcx.generics_of(def_id)) }
1229 pub fn self_ty(&self) -> Ty<'tcx> {
1230 self.substs.type_at(0)
1234 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable)]
1235 pub struct GenSig<'tcx> {
1236 pub resume_ty: Ty<'tcx>,
1237 pub yield_ty: Ty<'tcx>,
1238 pub return_ty: Ty<'tcx>,
1241 pub type PolyGenSig<'tcx> = Binder<'tcx, GenSig<'tcx>>;
1243 /// Signature of a function type, which we have arbitrarily
1244 /// decided to use to refer to the input/output types.
1246 /// - `inputs`: is the list of arguments and their modes.
1247 /// - `output`: is the return type.
1248 /// - `c_variadic`: indicates whether this is a C-variadic function.
1249 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)]
1250 #[derive(HashStable, TypeFoldable, TypeVisitable)]
1251 pub struct FnSig<'tcx> {
1252 pub inputs_and_output: &'tcx List<Ty<'tcx>>,
1253 pub c_variadic: bool,
1254 pub unsafety: hir::Unsafety,
1258 impl<'tcx> FnSig<'tcx> {
1259 pub fn inputs(&self) -> &'tcx [Ty<'tcx>] {
1260 &self.inputs_and_output[..self.inputs_and_output.len() - 1]
1263 pub fn output(&self) -> Ty<'tcx> {
1264 self.inputs_and_output[self.inputs_and_output.len() - 1]
1267 // Creates a minimal `FnSig` to be used when encountering a `TyKind::Error` in a fallible
1269 fn fake() -> FnSig<'tcx> {
1271 inputs_and_output: List::empty(),
1273 unsafety: hir::Unsafety::Normal,
1274 abi: abi::Abi::Rust,
1279 pub type PolyFnSig<'tcx> = Binder<'tcx, FnSig<'tcx>>;
1281 impl<'tcx> PolyFnSig<'tcx> {
1283 pub fn inputs(&self) -> Binder<'tcx, &'tcx [Ty<'tcx>]> {
1284 self.map_bound_ref_unchecked(|fn_sig| fn_sig.inputs())
1287 pub fn input(&self, index: usize) -> ty::Binder<'tcx, Ty<'tcx>> {
1288 self.map_bound_ref(|fn_sig| fn_sig.inputs()[index])
1290 pub fn inputs_and_output(&self) -> ty::Binder<'tcx, &'tcx List<Ty<'tcx>>> {
1291 self.map_bound_ref(|fn_sig| fn_sig.inputs_and_output)
1294 pub fn output(&self) -> ty::Binder<'tcx, Ty<'tcx>> {
1295 self.map_bound_ref(|fn_sig| fn_sig.output())
1297 pub fn c_variadic(&self) -> bool {
1298 self.skip_binder().c_variadic
1300 pub fn unsafety(&self) -> hir::Unsafety {
1301 self.skip_binder().unsafety
1303 pub fn abi(&self) -> abi::Abi {
1304 self.skip_binder().abi
1308 pub type CanonicalPolyFnSig<'tcx> = Canonical<'tcx, Binder<'tcx, FnSig<'tcx>>>;
1310 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)]
1311 #[derive(HashStable)]
1312 pub struct ParamTy {
1317 impl<'tcx> ParamTy {
1318 pub fn new(index: u32, name: Symbol) -> ParamTy {
1319 ParamTy { index, name }
1322 pub fn for_def(def: &ty::GenericParamDef) -> ParamTy {
1323 ParamTy::new(def.index, def.name)
1327 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1328 tcx.mk_ty_param(self.index, self.name)
1332 #[derive(Copy, Clone, Hash, TyEncodable, TyDecodable, Eq, PartialEq, Ord, PartialOrd)]
1333 #[derive(HashStable)]
1334 pub struct ParamConst {
1340 pub fn new(index: u32, name: Symbol) -> ParamConst {
1341 ParamConst { index, name }
1344 pub fn for_def(def: &ty::GenericParamDef) -> ParamConst {
1345 ParamConst::new(def.index, def.name)
1349 /// Use this rather than `RegionKind`, whenever possible.
1350 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable)]
1351 #[rustc_pass_by_value]
1352 pub struct Region<'tcx>(pub Interned<'tcx, RegionKind<'tcx>>);
1354 impl<'tcx> Deref for Region<'tcx> {
1355 type Target = RegionKind<'tcx>;
1358 fn deref(&self) -> &RegionKind<'tcx> {
1363 impl<'tcx> fmt::Debug for Region<'tcx> {
1364 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1365 write!(f, "{:?}", self.kind())
1369 #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, PartialOrd, Ord)]
1370 #[derive(HashStable)]
1371 pub struct EarlyBoundRegion {
1377 impl fmt::Debug for EarlyBoundRegion {
1378 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1379 write!(f, "{}, {}", self.index, self.name)
1383 /// A **`const`** **v**ariable **ID**.
1384 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1385 #[derive(HashStable, TyEncodable, TyDecodable)]
1386 pub struct ConstVid<'tcx> {
1388 pub phantom: PhantomData<&'tcx ()>,
1391 rustc_index::newtype_index! {
1392 /// A **region** (lifetime) **v**ariable **ID**.
1393 #[derive(HashStable)]
1394 pub struct RegionVid {
1395 DEBUG_FORMAT = custom,
1399 impl Atom for RegionVid {
1400 fn index(self) -> usize {
1405 rustc_index::newtype_index! {
1406 #[derive(HashStable)]
1407 pub struct BoundVar { .. }
1410 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
1411 #[derive(HashStable)]
1412 pub struct BoundTy {
1414 pub kind: BoundTyKind,
1417 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
1418 #[derive(HashStable)]
1419 pub enum BoundTyKind {
1424 impl From<BoundVar> for BoundTy {
1425 fn from(var: BoundVar) -> Self {
1426 BoundTy { var, kind: BoundTyKind::Anon }
1430 /// A `ProjectionPredicate` for an `ExistentialTraitRef`.
1431 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
1432 #[derive(HashStable, TypeFoldable, TypeVisitable)]
1433 pub struct ExistentialProjection<'tcx> {
1434 pub item_def_id: DefId,
1435 pub substs: SubstsRef<'tcx>,
1436 pub term: Term<'tcx>,
1439 pub type PolyExistentialProjection<'tcx> = Binder<'tcx, ExistentialProjection<'tcx>>;
1441 impl<'tcx> ExistentialProjection<'tcx> {
1442 /// Extracts the underlying existential trait reference from this projection.
1443 /// For example, if this is a projection of `exists T. <T as Iterator>::Item == X`,
1444 /// then this function would return an `exists T. T: Iterator` existential trait
1446 pub fn trait_ref(&self, tcx: TyCtxt<'tcx>) -> ty::ExistentialTraitRef<'tcx> {
1447 let def_id = tcx.parent(self.item_def_id);
1448 let subst_count = tcx.generics_of(def_id).count() - 1;
1449 let substs = tcx.intern_substs(&self.substs[..subst_count]);
1450 ty::ExistentialTraitRef { def_id, substs }
1453 pub fn with_self_ty(
1457 ) -> ty::ProjectionPredicate<'tcx> {
1458 // otherwise the escaping regions would be captured by the binders
1459 debug_assert!(!self_ty.has_escaping_bound_vars());
1461 ty::ProjectionPredicate {
1462 projection_ty: ty::ProjectionTy {
1463 item_def_id: self.item_def_id,
1464 substs: tcx.mk_substs_trait(self_ty, self.substs),
1470 pub fn erase_self_ty(
1472 projection_predicate: ty::ProjectionPredicate<'tcx>,
1474 // Assert there is a Self.
1475 projection_predicate.projection_ty.substs.type_at(0);
1478 item_def_id: projection_predicate.projection_ty.item_def_id,
1479 substs: tcx.intern_substs(&projection_predicate.projection_ty.substs[1..]),
1480 term: projection_predicate.term,
1485 impl<'tcx> PolyExistentialProjection<'tcx> {
1486 pub fn with_self_ty(
1490 ) -> ty::PolyProjectionPredicate<'tcx> {
1491 self.map_bound(|p| p.with_self_ty(tcx, self_ty))
1494 pub fn item_def_id(&self) -> DefId {
1495 self.skip_binder().item_def_id
1499 /// Region utilities
1500 impl<'tcx> Region<'tcx> {
1501 pub fn kind(self) -> RegionKind<'tcx> {
1505 /// Is this region named by the user?
1506 pub fn has_name(self) -> bool {
1508 ty::ReEarlyBound(ebr) => ebr.has_name(),
1509 ty::ReLateBound(_, br) => br.kind.is_named(),
1510 ty::ReFree(fr) => fr.bound_region.is_named(),
1511 ty::ReStatic => true,
1512 ty::ReVar(..) => false,
1513 ty::RePlaceholder(placeholder) => placeholder.name.is_named(),
1514 ty::ReEmpty(_) => false,
1515 ty::ReErased => false,
1520 pub fn is_static(self) -> bool {
1521 matches!(*self, ty::ReStatic)
1525 pub fn is_erased(self) -> bool {
1526 matches!(*self, ty::ReErased)
1530 pub fn is_late_bound(self) -> bool {
1531 matches!(*self, ty::ReLateBound(..))
1535 pub fn is_placeholder(self) -> bool {
1536 matches!(*self, ty::RePlaceholder(..))
1540 pub fn is_empty(self) -> bool {
1541 matches!(*self, ty::ReEmpty(..))
1545 pub fn bound_at_or_above_binder(self, index: ty::DebruijnIndex) -> bool {
1547 ty::ReLateBound(debruijn, _) => debruijn >= index,
1552 pub fn type_flags(self) -> TypeFlags {
1553 let mut flags = TypeFlags::empty();
1557 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1558 flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS;
1559 flags = flags | TypeFlags::HAS_RE_INFER;
1561 ty::RePlaceholder(..) => {
1562 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1563 flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS;
1564 flags = flags | TypeFlags::HAS_RE_PLACEHOLDER;
1566 ty::ReEarlyBound(..) => {
1567 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1568 flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS;
1569 flags = flags | TypeFlags::HAS_RE_PARAM;
1571 ty::ReFree { .. } => {
1572 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1573 flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS;
1575 ty::ReEmpty(_) | ty::ReStatic => {
1576 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1578 ty::ReLateBound(..) => {
1579 flags = flags | TypeFlags::HAS_RE_LATE_BOUND;
1582 flags = flags | TypeFlags::HAS_RE_ERASED;
1586 debug!("type_flags({:?}) = {:?}", self, flags);
1591 /// Given an early-bound or free region, returns the `DefId` where it was bound.
1592 /// For example, consider the regions in this snippet of code:
1594 /// ```ignore (illustrative)
1596 /// // ^^ -- early bound, declared on an impl
1598 /// fn bar<'b, 'c>(x: &self, y: &'b u32, z: &'c u64) where 'static: 'c
1599 /// // ^^ ^^ ^ anonymous, late-bound
1600 /// // | early-bound, appears in where-clauses
1601 /// // late-bound, appears only in fn args
1606 /// Here, `free_region_binding_scope('a)` would return the `DefId`
1607 /// of the impl, and for all the other highlighted regions, it
1608 /// would return the `DefId` of the function. In other cases (not shown), this
1609 /// function might return the `DefId` of a closure.
1610 pub fn free_region_binding_scope(self, tcx: TyCtxt<'_>) -> DefId {
1612 ty::ReEarlyBound(br) => tcx.parent(br.def_id),
1613 ty::ReFree(fr) => fr.scope,
1614 _ => bug!("free_region_binding_scope invoked on inappropriate region: {:?}", self),
1618 /// True for free regions other than `'static`.
1619 pub fn is_free(self) -> bool {
1620 matches!(*self, ty::ReEarlyBound(_) | ty::ReFree(_))
1623 /// True if `self` is a free region or static.
1624 pub fn is_free_or_static(self) -> bool {
1626 ty::ReStatic => true,
1627 _ => self.is_free(),
1631 pub fn is_var(self) -> bool {
1632 matches!(self.kind(), ty::ReVar(_))
1637 impl<'tcx> Ty<'tcx> {
1639 pub fn kind(self) -> &'tcx TyKind<'tcx> {
1644 pub fn flags(self) -> TypeFlags {
1649 pub fn is_unit(self) -> bool {
1651 Tuple(ref tys) => tys.is_empty(),
1657 pub fn is_never(self) -> bool {
1658 matches!(self.kind(), Never)
1662 pub fn is_primitive(self) -> bool {
1663 self.kind().is_primitive()
1667 pub fn is_adt(self) -> bool {
1668 matches!(self.kind(), Adt(..))
1672 pub fn is_ref(self) -> bool {
1673 matches!(self.kind(), Ref(..))
1677 pub fn is_ty_var(self) -> bool {
1678 matches!(self.kind(), Infer(TyVar(_)))
1682 pub fn ty_vid(self) -> Option<ty::TyVid> {
1684 &Infer(TyVar(vid)) => Some(vid),
1690 pub fn is_ty_infer(self) -> bool {
1691 matches!(self.kind(), Infer(_))
1695 pub fn is_phantom_data(self) -> bool {
1696 if let Adt(def, _) = self.kind() { def.is_phantom_data() } else { false }
1700 pub fn is_bool(self) -> bool {
1701 *self.kind() == Bool
1704 /// Returns `true` if this type is a `str`.
1706 pub fn is_str(self) -> bool {
1711 pub fn is_param(self, index: u32) -> bool {
1713 ty::Param(ref data) => data.index == index,
1719 pub fn is_slice(self) -> bool {
1720 matches!(self.kind(), Slice(_))
1724 pub fn is_array_slice(self) -> bool {
1727 RawPtr(TypeAndMut { ty, .. }) | Ref(_, ty, _) => matches!(ty.kind(), Slice(_)),
1733 pub fn is_array(self) -> bool {
1734 matches!(self.kind(), Array(..))
1738 pub fn is_simd(self) -> bool {
1740 Adt(def, _) => def.repr().simd(),
1745 pub fn sequence_element_type(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1747 Array(ty, _) | Slice(ty) => *ty,
1748 Str => tcx.types.u8,
1749 _ => bug!("`sequence_element_type` called on non-sequence value: {}", self),
1753 pub fn simd_size_and_type(self, tcx: TyCtxt<'tcx>) -> (u64, Ty<'tcx>) {
1755 Adt(def, substs) => {
1756 assert!(def.repr().simd(), "`simd_size_and_type` called on non-SIMD type");
1757 let variant = def.non_enum_variant();
1758 let f0_ty = variant.fields[0].ty(tcx, substs);
1760 match f0_ty.kind() {
1761 // If the first field is an array, we assume it is the only field and its
1762 // elements are the SIMD components.
1763 Array(f0_elem_ty, f0_len) => {
1764 // FIXME(repr_simd): https://github.com/rust-lang/rust/pull/78863#discussion_r522784112
1765 // The way we evaluate the `N` in `[T; N]` here only works since we use
1766 // `simd_size_and_type` post-monomorphization. It will probably start to ICE
1767 // if we use it in generic code. See the `simd-array-trait` ui test.
1768 (f0_len.eval_usize(tcx, ParamEnv::empty()) as u64, *f0_elem_ty)
1770 // Otherwise, the fields of this Adt are the SIMD components (and we assume they
1771 // all have the same type).
1772 _ => (variant.fields.len() as u64, f0_ty),
1775 _ => bug!("`simd_size_and_type` called on invalid type"),
1780 pub fn is_region_ptr(self) -> bool {
1781 matches!(self.kind(), Ref(..))
1785 pub fn is_mutable_ptr(self) -> bool {
1788 RawPtr(TypeAndMut { mutbl: hir::Mutability::Mut, .. })
1789 | Ref(_, _, hir::Mutability::Mut)
1793 /// Get the mutability of the reference or `None` when not a reference
1795 pub fn ref_mutability(self) -> Option<hir::Mutability> {
1797 Ref(_, _, mutability) => Some(*mutability),
1803 pub fn is_unsafe_ptr(self) -> bool {
1804 matches!(self.kind(), RawPtr(_))
1807 /// Tests if this is any kind of primitive pointer type (reference, raw pointer, fn pointer).
1809 pub fn is_any_ptr(self) -> bool {
1810 self.is_region_ptr() || self.is_unsafe_ptr() || self.is_fn_ptr()
1814 pub fn is_box(self) -> bool {
1816 Adt(def, _) => def.is_box(),
1821 /// Panics if called on any type other than `Box<T>`.
1822 pub fn boxed_ty(self) -> Ty<'tcx> {
1824 Adt(def, substs) if def.is_box() => substs.type_at(0),
1825 _ => bug!("`boxed_ty` is called on non-box type {:?}", self),
1829 /// A scalar type is one that denotes an atomic datum, with no sub-components.
1830 /// (A RawPtr is scalar because it represents a non-managed pointer, so its
1831 /// contents are abstract to rustc.)
1833 pub fn is_scalar(self) -> bool {
1843 | Infer(IntVar(_) | FloatVar(_))
1847 /// Returns `true` if this type is a floating point type.
1849 pub fn is_floating_point(self) -> bool {
1850 matches!(self.kind(), Float(_) | Infer(FloatVar(_)))
1854 pub fn is_trait(self) -> bool {
1855 matches!(self.kind(), Dynamic(..))
1859 pub fn is_enum(self) -> bool {
1860 matches!(self.kind(), Adt(adt_def, _) if adt_def.is_enum())
1864 pub fn is_union(self) -> bool {
1865 matches!(self.kind(), Adt(adt_def, _) if adt_def.is_union())
1869 pub fn is_closure(self) -> bool {
1870 matches!(self.kind(), Closure(..))
1874 pub fn is_generator(self) -> bool {
1875 matches!(self.kind(), Generator(..))
1879 pub fn is_integral(self) -> bool {
1880 matches!(self.kind(), Infer(IntVar(_)) | Int(_) | Uint(_))
1884 pub fn is_fresh_ty(self) -> bool {
1885 matches!(self.kind(), Infer(FreshTy(_)))
1889 pub fn is_fresh(self) -> bool {
1890 matches!(self.kind(), Infer(FreshTy(_) | FreshIntTy(_) | FreshFloatTy(_)))
1894 pub fn is_char(self) -> bool {
1895 matches!(self.kind(), Char)
1899 pub fn is_numeric(self) -> bool {
1900 self.is_integral() || self.is_floating_point()
1904 pub fn is_signed(self) -> bool {
1905 matches!(self.kind(), Int(_))
1909 pub fn is_ptr_sized_integral(self) -> bool {
1910 matches!(self.kind(), Int(ty::IntTy::Isize) | Uint(ty::UintTy::Usize))
1914 pub fn has_concrete_skeleton(self) -> bool {
1915 !matches!(self.kind(), Param(_) | Infer(_) | Error(_))
1918 /// Checks whether a type recursively contains another type
1920 /// Example: `Option<()>` contains `()`
1921 pub fn contains(self, other: Ty<'tcx>) -> bool {
1922 struct ContainsTyVisitor<'tcx>(Ty<'tcx>);
1924 impl<'tcx> TypeVisitor<'tcx> for ContainsTyVisitor<'tcx> {
1927 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1928 if self.0 == t { ControlFlow::BREAK } else { t.super_visit_with(self) }
1932 let cf = self.visit_with(&mut ContainsTyVisitor(other));
1936 /// Returns the type and mutability of `*ty`.
1938 /// The parameter `explicit` indicates if this is an *explicit* dereference.
1939 /// Some types -- notably unsafe ptrs -- can only be dereferenced explicitly.
1940 pub fn builtin_deref(self, explicit: bool) -> Option<TypeAndMut<'tcx>> {
1942 Adt(def, _) if def.is_box() => {
1943 Some(TypeAndMut { ty: self.boxed_ty(), mutbl: hir::Mutability::Not })
1945 Ref(_, ty, mutbl) => Some(TypeAndMut { ty: *ty, mutbl: *mutbl }),
1946 RawPtr(mt) if explicit => Some(*mt),
1951 /// Returns the type of `ty[i]`.
1952 pub fn builtin_index(self) -> Option<Ty<'tcx>> {
1954 Array(ty, _) | Slice(ty) => Some(*ty),
1959 pub fn fn_sig(self, tcx: TyCtxt<'tcx>) -> PolyFnSig<'tcx> {
1961 FnDef(def_id, substs) => tcx.bound_fn_sig(*def_id).subst(tcx, substs),
1964 // ignore errors (#54954)
1965 ty::Binder::dummy(FnSig::fake())
1967 Closure(..) => bug!(
1968 "to get the signature of a closure, use `substs.as_closure().sig()` not `fn_sig()`",
1970 _ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self),
1975 pub fn is_fn(self) -> bool {
1976 matches!(self.kind(), FnDef(..) | FnPtr(_))
1980 pub fn is_fn_ptr(self) -> bool {
1981 matches!(self.kind(), FnPtr(_))
1985 pub fn is_impl_trait(self) -> bool {
1986 matches!(self.kind(), Opaque(..))
1990 pub fn ty_adt_def(self) -> Option<AdtDef<'tcx>> {
1992 Adt(adt, _) => Some(*adt),
1997 /// Iterates over tuple fields.
1998 /// Panics when called on anything but a tuple.
2000 pub fn tuple_fields(self) -> &'tcx List<Ty<'tcx>> {
2002 Tuple(substs) => substs,
2003 _ => bug!("tuple_fields called on non-tuple"),
2007 /// If the type contains variants, returns the valid range of variant indices.
2009 // FIXME: This requires the optimized MIR in the case of generators.
2011 pub fn variant_range(self, tcx: TyCtxt<'tcx>) -> Option<Range<VariantIdx>> {
2013 TyKind::Adt(adt, _) => Some(adt.variant_range()),
2014 TyKind::Generator(def_id, substs, _) => {
2015 Some(substs.as_generator().variant_range(*def_id, tcx))
2021 /// If the type contains variants, returns the variant for `variant_index`.
2022 /// Panics if `variant_index` is out of range.
2024 // FIXME: This requires the optimized MIR in the case of generators.
2026 pub fn discriminant_for_variant(
2029 variant_index: VariantIdx,
2030 ) -> Option<Discr<'tcx>> {
2032 TyKind::Adt(adt, _) if adt.variants().is_empty() => {
2033 // This can actually happen during CTFE, see
2034 // https://github.com/rust-lang/rust/issues/89765.
2037 TyKind::Adt(adt, _) if adt.is_enum() => {
2038 Some(adt.discriminant_for_variant(tcx, variant_index))
2040 TyKind::Generator(def_id, substs, _) => {
2041 Some(substs.as_generator().discriminant_for_variant(*def_id, tcx, variant_index))
2047 /// Returns the type of the discriminant of this type.
2048 pub fn discriminant_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
2050 ty::Adt(adt, _) if adt.is_enum() => adt.repr().discr_type().to_ty(tcx),
2051 ty::Generator(_, substs, _) => substs.as_generator().discr_ty(tcx),
2053 ty::Param(_) | ty::Projection(_) | ty::Opaque(..) | ty::Infer(ty::TyVar(_)) => {
2054 let assoc_items = tcx.associated_item_def_ids(
2055 tcx.require_lang_item(hir::LangItem::DiscriminantKind, None),
2057 tcx.mk_projection(assoc_items[0], tcx.intern_substs(&[self.into()]))
2076 | ty::GeneratorWitness(..)
2080 | ty::Infer(IntVar(_) | FloatVar(_)) => tcx.types.u8,
2083 | ty::Placeholder(_)
2084 | ty::Infer(FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2085 bug!("`discriminant_ty` applied to unexpected type: {:?}", self)
2090 /// Returns the type of metadata for (potentially fat) pointers to this type,
2091 /// and a boolean signifying if this is conditional on this type being `Sized`.
2092 pub fn ptr_metadata_ty(
2095 normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>,
2096 ) -> (Ty<'tcx>, bool) {
2097 let tail = tcx.struct_tail_with_normalize(self, normalize, || {});
2100 ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
2111 | ty::GeneratorWitness(..)
2116 // Extern types have metadata = ().
2118 // If returned by `struct_tail_without_normalization` this is a unit struct
2119 // without any fields, or not a struct, and therefore is Sized.
2121 // If returned by `struct_tail_without_normalization` this is the empty tuple,
2122 // a.k.a. unit type, which is Sized
2123 | ty::Tuple(..) => (tcx.types.unit, false),
2125 ty::Str | ty::Slice(_) => (tcx.types.usize, false),
2126 ty::Dynamic(..) => {
2127 let dyn_metadata = tcx.lang_items().dyn_metadata().unwrap();
2128 (tcx.bound_type_of(dyn_metadata).subst(tcx, &[tail.into()]), false)
2131 // type parameters only have unit metadata if they're sized, so return true
2132 // to make sure we double check this during confirmation
2133 ty::Param(_) | ty::Projection(_) | ty::Opaque(..) => (tcx.types.unit, true),
2135 ty::Infer(ty::TyVar(_))
2137 | ty::Placeholder(..)
2138 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2139 bug!("`ptr_metadata_ty` applied to unexpected type: {:?} (tail = {:?})", self, tail)
2144 /// When we create a closure, we record its kind (i.e., what trait
2145 /// it implements) into its `ClosureSubsts` using a type
2146 /// parameter. This is kind of a phantom type, except that the
2147 /// most convenient thing for us to are the integral types. This
2148 /// function converts such a special type into the closure
2149 /// kind. To go the other way, use
2150 /// `tcx.closure_kind_ty(closure_kind)`.
2152 /// Note that during type checking, we use an inference variable
2153 /// to represent the closure kind, because it has not yet been
2154 /// inferred. Once upvar inference (in `rustc_typeck/src/check/upvar.rs`)
2155 /// is complete, that type variable will be unified.
2156 pub fn to_opt_closure_kind(self) -> Option<ty::ClosureKind> {
2158 Int(int_ty) => match int_ty {
2159 ty::IntTy::I8 => Some(ty::ClosureKind::Fn),
2160 ty::IntTy::I16 => Some(ty::ClosureKind::FnMut),
2161 ty::IntTy::I32 => Some(ty::ClosureKind::FnOnce),
2162 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
2165 // "Bound" types appear in canonical queries when the
2166 // closure type is not yet known
2167 Bound(..) | Infer(_) => None,
2169 Error(_) => Some(ty::ClosureKind::Fn),
2171 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
2175 /// Fast path helper for testing if a type is `Sized`.
2177 /// Returning true means the type is known to be sized. Returning
2178 /// `false` means nothing -- could be sized, might not be.
2180 /// Note that we could never rely on the fact that a type such as `[_]` is
2181 /// trivially `!Sized` because we could be in a type environment with a
2182 /// bound such as `[_]: Copy`. A function with such a bound obviously never
2183 /// can be called, but that doesn't mean it shouldn't typecheck. This is why
2184 /// this method doesn't return `Option<bool>`.
2185 pub fn is_trivially_sized(self, tcx: TyCtxt<'tcx>) -> bool {
2187 ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
2198 | ty::GeneratorWitness(..)
2202 | ty::Error(_) => true,
2204 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => false,
2206 ty::Tuple(tys) => tys.iter().all(|ty| ty.is_trivially_sized(tcx)),
2208 ty::Adt(def, _substs) => def.sized_constraint(tcx).0.is_empty(),
2210 ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => false,
2212 ty::Infer(ty::TyVar(_)) => false,
2215 | ty::Placeholder(..)
2216 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2217 bug!("`is_trivially_sized` applied to unexpected type: {:?}", self)
2222 /// Fast path helper for primitives which are always `Copy` and which
2223 /// have a side-effect-free `Clone` impl.
2225 /// Returning true means the type is known to be pure and `Copy+Clone`.
2226 /// Returning `false` means nothing -- could be `Copy`, might not be.
2228 /// This is mostly useful for optimizations, as there are the types
2229 /// on which we can replace cloning with dereferencing.
2230 pub fn is_trivially_pure_clone_copy(self) -> bool {
2232 ty::Bool | ty::Char | ty::Never => true,
2234 // These aren't even `Clone`
2235 ty::Str | ty::Slice(..) | ty::Foreign(..) | ty::Dynamic(..) => false,
2237 ty::Int(..) | ty::Uint(..) | ty::Float(..) => true,
2239 // The voldemort ZSTs are fine.
2240 ty::FnDef(..) => true,
2242 ty::Array(element_ty, _len) => element_ty.is_trivially_pure_clone_copy(),
2244 // A 100-tuple isn't "trivial", so doing this only for reasonable sizes.
2245 ty::Tuple(field_tys) => {
2246 field_tys.len() <= 3 && field_tys.iter().all(Self::is_trivially_pure_clone_copy)
2249 // Sometimes traits aren't implemented for every ABI or arity,
2250 // because we can't be generic over everything yet.
2251 ty::FnPtr(..) => false,
2253 // Definitely absolutely not copy.
2254 ty::Ref(_, _, hir::Mutability::Mut) => false,
2256 // Thin pointers & thin shared references are pure-clone-copy, but for
2257 // anything with custom metadata it might be more complicated.
2258 ty::Ref(_, _, hir::Mutability::Not) | ty::RawPtr(..) => false,
2260 ty::Generator(..) | ty::GeneratorWitness(..) => false,
2262 // Might be, but not "trivial" so just giving the safe answer.
2263 ty::Adt(..) | ty::Closure(..) | ty::Opaque(..) => false,
2265 ty::Projection(..) | ty::Param(..) | ty::Infer(..) | ty::Error(..) => false,
2267 ty::Bound(..) | ty::Placeholder(..) => {
2268 bug!("`is_trivially_pure_clone_copy` applied to unexpected type: {:?}", self);
2274 /// Extra information about why we ended up with a particular variance.
2275 /// This is only used to add more information to error messages, and
2276 /// has no effect on soundness. While choosing the 'wrong' `VarianceDiagInfo`
2277 /// may lead to confusing notes in error messages, it will never cause
2278 /// a miscompilation or unsoundness.
2280 /// When in doubt, use `VarianceDiagInfo::default()`
2281 #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
2282 pub enum VarianceDiagInfo<'tcx> {
2283 /// No additional information - this is the default.
2284 /// We will not add any additional information to error messages.
2287 /// We switched our variance because a generic argument occurs inside
2288 /// the invariant generic argument of another type.
2290 /// The generic type containing the generic parameter
2291 /// that changes the variance (e.g. `*mut T`, `MyStruct<T>`)
2293 /// The index of the generic parameter being used
2294 /// (e.g. `0` for `*mut T`, `1` for `MyStruct<'CovariantParam, 'InvariantParam>`)
2299 impl<'tcx> VarianceDiagInfo<'tcx> {
2300 /// Mirrors `Variance::xform` - used to 'combine' the existing
2301 /// and new `VarianceDiagInfo`s when our variance changes.
2302 pub fn xform(self, other: VarianceDiagInfo<'tcx>) -> VarianceDiagInfo<'tcx> {
2303 // For now, just use the first `VarianceDiagInfo::Invariant` that we see
2305 VarianceDiagInfo::None => other,
2306 VarianceDiagInfo::Invariant { .. } => self,