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, SubstsRef};
7 use crate::ty::visit::ValidateBoundVars;
8 use crate::ty::InferTy::*;
10 self, AdtDef, DefIdTree, Discr, FallibleTypeFolder, Term, Ty, TyCtxt, TypeFlags, TypeFoldable,
11 TypeSuperFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitor,
13 use crate::ty::{List, ParamEnv};
14 use hir::def::DefKind;
15 use polonius_engine::Atom;
16 use rustc_data_structures::captures::Captures;
17 use rustc_data_structures::intern::Interned;
19 use rustc_hir::def_id::DefId;
20 use rustc_hir::LangItem;
21 use rustc_index::vec::Idx;
22 use rustc_macros::HashStable;
23 use rustc_span::symbol::{kw, sym, Symbol};
25 use rustc_target::abi::VariantIdx;
26 use rustc_target::spec::abi;
28 use std::cmp::Ordering;
30 use std::marker::PhantomData;
31 use std::ops::{ControlFlow, Deref, Range};
32 use ty::util::IntTypeExt;
34 use rustc_type_ir::sty::TyKind::*;
35 use rustc_type_ir::RegionKind as IrRegionKind;
36 use rustc_type_ir::TyKind as IrTyKind;
38 // Re-export the `TyKind` from `rustc_type_ir` here for convenience
39 #[rustc_diagnostic_item = "TyKind"]
40 pub type TyKind<'tcx> = IrTyKind<TyCtxt<'tcx>>;
41 pub type RegionKind<'tcx> = IrRegionKind<TyCtxt<'tcx>>;
43 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
44 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
45 pub struct TypeAndMut<'tcx> {
47 pub mutbl: hir::Mutability,
50 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, TyEncodable, TyDecodable, Copy)]
52 /// A "free" region `fr` can be interpreted as "some region
53 /// at least as big as the scope `fr.scope`".
54 pub struct FreeRegion {
56 pub bound_region: BoundRegionKind,
59 #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, TyEncodable, TyDecodable, Copy)]
61 pub enum BoundRegionKind {
62 /// An anonymous region parameter for a given fn (&T)
63 BrAnon(u32, Option<Span>),
65 /// Named region parameters for functions (a in &'a T)
67 /// The `DefId` is needed to distinguish free regions in
68 /// the event of shadowing.
69 BrNamed(DefId, Symbol),
71 /// Anonymous region for the implicit env pointer parameter
76 #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, Debug, PartialOrd, Ord)]
78 pub struct BoundRegion {
80 pub kind: BoundRegionKind,
83 impl BoundRegionKind {
84 pub fn is_named(&self) -> bool {
86 BoundRegionKind::BrNamed(_, name) => {
87 name != kw::UnderscoreLifetime && name != kw::Empty
93 pub fn get_name(&self) -> Option<Symbol> {
96 BoundRegionKind::BrNamed(_, name) => return Some(name),
104 pub fn get_id(&self) -> Option<DefId> {
106 BoundRegionKind::BrNamed(id, _) => return Some(id),
113 fn article(&self) -> &'static str;
116 impl<'tcx> Article for TyKind<'tcx> {
117 /// Get the article ("a" or "an") to use with this type.
118 fn article(&self) -> &'static str {
120 Int(_) | Float(_) | Array(_, _) => "an",
121 Adt(def, _) if def.is_enum() => "an",
122 // This should never happen, but ICEing and causing the user's code
123 // to not compile felt too harsh.
130 // `TyKind` is used a lot. Make sure it doesn't unintentionally get bigger.
131 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
132 static_assert_size!(TyKind<'_>, 32);
134 /// A closure can be modeled as a struct that looks like:
135 /// ```ignore (illustrative)
136 /// struct Closure<'l0...'li, T0...Tj, CK, CS, U>(...U);
140 /// - 'l0...'li and T0...Tj are the generic parameters
141 /// in scope on the function that defined the closure,
142 /// - CK represents the *closure kind* (Fn vs FnMut vs FnOnce). This
143 /// is rather hackily encoded via a scalar type. See
144 /// `Ty::to_opt_closure_kind` for details.
145 /// - CS represents the *closure signature*, representing as a `fn()`
146 /// type. For example, `fn(u32, u32) -> u32` would mean that the closure
147 /// implements `CK<(u32, u32), Output = u32>`, where `CK` is the trait
149 /// - U is a type parameter representing the types of its upvars, tupled up
150 /// (borrowed, if appropriate; that is, if a U field represents a by-ref upvar,
151 /// and the up-var has the type `Foo`, then that field of U will be `&Foo`).
153 /// So, for example, given this function:
154 /// ```ignore (illustrative)
155 /// fn foo<'a, T>(data: &'a mut T) {
156 /// do(|| data.count += 1)
159 /// the type of the closure would be something like:
160 /// ```ignore (illustrative)
161 /// struct Closure<'a, T, U>(...U);
163 /// Note that the type of the upvar is not specified in the struct.
164 /// You may wonder how the impl would then be able to use the upvar,
165 /// if it doesn't know it's type? The answer is that the impl is
166 /// (conceptually) not fully generic over Closure but rather tied to
167 /// instances with the expected upvar types:
168 /// ```ignore (illustrative)
169 /// impl<'b, 'a, T> FnMut() for Closure<'a, T, (&'b mut &'a mut T,)> {
173 /// You can see that the *impl* fully specified the type of the upvar
174 /// and thus knows full well that `data` has type `&'b mut &'a mut T`.
175 /// (Here, I am assuming that `data` is mut-borrowed.)
177 /// Now, the last question you may ask is: Why include the upvar types
178 /// in an extra type parameter? The reason for this design is that the
179 /// upvar types can reference lifetimes that are internal to the
180 /// creating function. In my example above, for example, the lifetime
181 /// `'b` represents the scope of the closure itself; this is some
182 /// subset of `foo`, probably just the scope of the call to the to
183 /// `do()`. If we just had the lifetime/type parameters from the
184 /// enclosing function, we couldn't name this lifetime `'b`. Note that
185 /// there can also be lifetimes in the types of the upvars themselves,
186 /// if one of them happens to be a reference to something that the
187 /// creating fn owns.
189 /// OK, you say, so why not create a more minimal set of parameters
190 /// that just includes the extra lifetime parameters? The answer is
191 /// primarily that it would be hard --- we don't know at the time when
192 /// we create the closure type what the full types of the upvars are,
193 /// nor do we know which are borrowed and which are not. In this
194 /// design, we can just supply a fresh type parameter and figure that
197 /// All right, you say, but why include the type parameters from the
198 /// original function then? The answer is that codegen may need them
199 /// when monomorphizing, and they may not appear in the upvars. A
200 /// closure could capture no variables but still make use of some
201 /// in-scope type parameter with a bound (e.g., if our example above
202 /// had an extra `U: Default`, and the closure called `U::default()`).
204 /// There is another reason. This design (implicitly) prohibits
205 /// closures from capturing themselves (except via a trait
206 /// object). This simplifies closure inference considerably, since it
207 /// means that when we infer the kind of a closure or its upvars, we
208 /// don't have to handle cycles where the decisions we make for
209 /// closure C wind up influencing the decisions we ought to make for
210 /// closure C (which would then require fixed point iteration to
211 /// handle). Plus it fixes an ICE. :P
215 /// Generators are handled similarly in `GeneratorSubsts`. The set of
216 /// type parameters is similar, but `CK` and `CS` are replaced by the
217 /// following type parameters:
219 /// * `GS`: The generator's "resume type", which is the type of the
220 /// argument passed to `resume`, and the type of `yield` expressions
221 /// inside the generator.
222 /// * `GY`: The "yield type", which is the type of values passed to
223 /// `yield` inside the generator.
224 /// * `GR`: The "return type", which is the type of value returned upon
225 /// completion of the generator.
226 /// * `GW`: The "generator witness".
227 #[derive(Copy, Clone, PartialEq, Eq, Debug, TypeFoldable, TypeVisitable, Lift)]
228 pub struct ClosureSubsts<'tcx> {
229 /// Lifetime and type parameters from the enclosing function,
230 /// concatenated with a tuple containing the types of the upvars.
232 /// These are separated out because codegen wants to pass them around
233 /// when monomorphizing.
234 pub substs: SubstsRef<'tcx>,
237 /// Struct returned by `split()`.
238 pub struct ClosureSubstsParts<'tcx, T> {
239 pub parent_substs: &'tcx [GenericArg<'tcx>],
240 pub closure_kind_ty: T,
241 pub closure_sig_as_fn_ptr_ty: T,
242 pub tupled_upvars_ty: T,
245 impl<'tcx> ClosureSubsts<'tcx> {
246 /// Construct `ClosureSubsts` from `ClosureSubstsParts`, containing `Substs`
247 /// for the closure parent, alongside additional closure-specific components.
250 parts: ClosureSubstsParts<'tcx, Ty<'tcx>>,
251 ) -> ClosureSubsts<'tcx> {
253 substs: tcx.mk_substs(
254 parts.parent_substs.iter().copied().chain(
255 [parts.closure_kind_ty, parts.closure_sig_as_fn_ptr_ty, parts.tupled_upvars_ty]
257 .map(|&ty| ty.into()),
263 /// Divides the closure substs into their respective components.
264 /// The ordering assumed here must match that used by `ClosureSubsts::new` above.
265 fn split(self) -> ClosureSubstsParts<'tcx, GenericArg<'tcx>> {
266 match self.substs[..] {
268 ref parent_substs @ ..,
270 closure_sig_as_fn_ptr_ty,
272 ] => ClosureSubstsParts {
275 closure_sig_as_fn_ptr_ty,
278 _ => bug!("closure substs missing synthetics"),
282 /// Returns `true` only if enough of the synthetic types are known to
283 /// allow using all of the methods on `ClosureSubsts` without panicking.
285 /// Used primarily by `ty::print::pretty` to be able to handle closure
286 /// types that haven't had their synthetic types substituted in.
287 pub fn is_valid(self) -> bool {
288 self.substs.len() >= 3
289 && matches!(self.split().tupled_upvars_ty.expect_ty().kind(), Tuple(_))
292 /// Returns the substitutions of the closure's parent.
293 pub fn parent_substs(self) -> &'tcx [GenericArg<'tcx>] {
294 self.split().parent_substs
297 /// Returns an iterator over the list of types of captured paths by the closure.
298 /// In case there was a type error in figuring out the types of the captured path, an
299 /// empty iterator is returned.
301 pub fn upvar_tys(self) -> impl Iterator<Item = Ty<'tcx>> + 'tcx {
302 match self.tupled_upvars_ty().kind() {
303 TyKind::Error(_) => None,
304 TyKind::Tuple(..) => Some(self.tupled_upvars_ty().tuple_fields()),
305 TyKind::Infer(_) => bug!("upvar_tys called before capture types are inferred"),
306 ty => bug!("Unexpected representation of upvar types tuple {:?}", ty),
312 /// Returns the tuple type representing the upvars for this closure.
314 pub fn tupled_upvars_ty(self) -> Ty<'tcx> {
315 self.split().tupled_upvars_ty.expect_ty()
318 /// Returns the closure kind for this closure; may return a type
319 /// variable during inference. To get the closure kind during
320 /// inference, use `infcx.closure_kind(substs)`.
321 pub fn kind_ty(self) -> Ty<'tcx> {
322 self.split().closure_kind_ty.expect_ty()
325 /// Returns the `fn` pointer type representing the closure signature for this
327 // FIXME(eddyb) this should be unnecessary, as the shallowly resolved
328 // type is known at the time of the creation of `ClosureSubsts`,
329 // see `rustc_hir_analysis::check::closure`.
330 pub fn sig_as_fn_ptr_ty(self) -> Ty<'tcx> {
331 self.split().closure_sig_as_fn_ptr_ty.expect_ty()
334 /// Returns the closure kind for this closure; only usable outside
335 /// of an inference context, because in that context we know that
336 /// there are no type variables.
338 /// If you have an inference context, use `infcx.closure_kind()`.
339 pub fn kind(self) -> ty::ClosureKind {
340 self.kind_ty().to_opt_closure_kind().unwrap()
343 /// Extracts the signature from the closure.
344 pub fn sig(self) -> ty::PolyFnSig<'tcx> {
345 let ty = self.sig_as_fn_ptr_ty();
347 ty::FnPtr(sig) => *sig,
348 _ => bug!("closure_sig_as_fn_ptr_ty is not a fn-ptr: {:?}", ty.kind()),
352 pub fn print_as_impl_trait(self) -> ty::print::PrintClosureAsImpl<'tcx> {
353 ty::print::PrintClosureAsImpl { closure: self }
357 /// Similar to `ClosureSubsts`; see the above documentation for more.
358 #[derive(Copy, Clone, PartialEq, Eq, Debug, TypeFoldable, TypeVisitable, Lift)]
359 pub struct GeneratorSubsts<'tcx> {
360 pub substs: SubstsRef<'tcx>,
363 pub struct GeneratorSubstsParts<'tcx, T> {
364 pub parent_substs: &'tcx [GenericArg<'tcx>],
369 pub tupled_upvars_ty: T,
372 impl<'tcx> GeneratorSubsts<'tcx> {
373 /// Construct `GeneratorSubsts` from `GeneratorSubstsParts`, containing `Substs`
374 /// for the generator parent, alongside additional generator-specific components.
377 parts: GeneratorSubstsParts<'tcx, Ty<'tcx>>,
378 ) -> GeneratorSubsts<'tcx> {
380 substs: tcx.mk_substs(
381 parts.parent_substs.iter().copied().chain(
387 parts.tupled_upvars_ty,
390 .map(|&ty| ty.into()),
396 /// Divides the generator substs into their respective components.
397 /// The ordering assumed here must match that used by `GeneratorSubsts::new` above.
398 fn split(self) -> GeneratorSubstsParts<'tcx, GenericArg<'tcx>> {
399 match self.substs[..] {
400 [ref parent_substs @ .., resume_ty, yield_ty, return_ty, witness, tupled_upvars_ty] => {
401 GeneratorSubstsParts {
410 _ => bug!("generator substs missing synthetics"),
414 /// Returns `true` only if enough of the synthetic types are known to
415 /// allow using all of the methods on `GeneratorSubsts` without panicking.
417 /// Used primarily by `ty::print::pretty` to be able to handle generator
418 /// types that haven't had their synthetic types substituted in.
419 pub fn is_valid(self) -> bool {
420 self.substs.len() >= 5
421 && matches!(self.split().tupled_upvars_ty.expect_ty().kind(), Tuple(_))
424 /// Returns the substitutions of the generator's parent.
425 pub fn parent_substs(self) -> &'tcx [GenericArg<'tcx>] {
426 self.split().parent_substs
429 /// This describes the types that can be contained in a generator.
430 /// It will be a type variable initially and unified in the last stages of typeck of a body.
431 /// It contains a tuple of all the types that could end up on a generator frame.
432 /// The state transformation MIR pass may only produce layouts which mention types
433 /// in this tuple. Upvars are not counted here.
434 pub fn witness(self) -> Ty<'tcx> {
435 self.split().witness.expect_ty()
438 /// Returns an iterator over the list of types of captured paths by the generator.
439 /// In case there was a type error in figuring out the types of the captured path, an
440 /// empty iterator is returned.
442 pub fn upvar_tys(self) -> impl Iterator<Item = Ty<'tcx>> + 'tcx {
443 match self.tupled_upvars_ty().kind() {
444 TyKind::Error(_) => None,
445 TyKind::Tuple(..) => Some(self.tupled_upvars_ty().tuple_fields()),
446 TyKind::Infer(_) => bug!("upvar_tys called before capture types are inferred"),
447 ty => bug!("Unexpected representation of upvar types tuple {:?}", ty),
453 /// Returns the tuple type representing the upvars for this generator.
455 pub fn tupled_upvars_ty(self) -> Ty<'tcx> {
456 self.split().tupled_upvars_ty.expect_ty()
459 /// Returns the type representing the resume type of the generator.
460 pub fn resume_ty(self) -> Ty<'tcx> {
461 self.split().resume_ty.expect_ty()
464 /// Returns the type representing the yield type of the generator.
465 pub fn yield_ty(self) -> Ty<'tcx> {
466 self.split().yield_ty.expect_ty()
469 /// Returns the type representing the return type of the generator.
470 pub fn return_ty(self) -> Ty<'tcx> {
471 self.split().return_ty.expect_ty()
474 /// Returns the "generator signature", which consists of its yield
475 /// and return types.
477 /// N.B., some bits of the code prefers to see this wrapped in a
478 /// binder, but it never contains bound regions. Probably this
479 /// function should be removed.
480 pub fn poly_sig(self) -> PolyGenSig<'tcx> {
481 ty::Binder::dummy(self.sig())
484 /// Returns the "generator signature", which consists of its resume, yield
485 /// and return types.
486 pub fn sig(self) -> GenSig<'tcx> {
488 resume_ty: self.resume_ty(),
489 yield_ty: self.yield_ty(),
490 return_ty: self.return_ty(),
495 impl<'tcx> GeneratorSubsts<'tcx> {
496 /// Generator has not been resumed yet.
497 pub const UNRESUMED: usize = 0;
498 /// Generator has returned or is completed.
499 pub const RETURNED: usize = 1;
500 /// Generator has been poisoned.
501 pub const POISONED: usize = 2;
503 const UNRESUMED_NAME: &'static str = "Unresumed";
504 const RETURNED_NAME: &'static str = "Returned";
505 const POISONED_NAME: &'static str = "Panicked";
507 /// The valid variant indices of this generator.
509 pub fn variant_range(&self, def_id: DefId, tcx: TyCtxt<'tcx>) -> Range<VariantIdx> {
510 // FIXME requires optimized MIR
511 let num_variants = tcx.generator_layout(def_id).unwrap().variant_fields.len();
512 VariantIdx::new(0)..VariantIdx::new(num_variants)
515 /// The discriminant for the given variant. Panics if the `variant_index` is
518 pub fn discriminant_for_variant(
522 variant_index: VariantIdx,
524 // Generators don't support explicit discriminant values, so they are
525 // the same as the variant index.
526 assert!(self.variant_range(def_id, tcx).contains(&variant_index));
527 Discr { val: variant_index.as_usize() as u128, ty: self.discr_ty(tcx) }
530 /// The set of all discriminants for the generator, enumerated with their
533 pub fn discriminants(
537 ) -> impl Iterator<Item = (VariantIdx, Discr<'tcx>)> + Captures<'tcx> {
538 self.variant_range(def_id, tcx).map(move |index| {
539 (index, Discr { val: index.as_usize() as u128, ty: self.discr_ty(tcx) })
543 /// Calls `f` with a reference to the name of the enumerator for the given
545 pub fn variant_name(v: VariantIdx) -> Cow<'static, str> {
547 Self::UNRESUMED => Cow::from(Self::UNRESUMED_NAME),
548 Self::RETURNED => Cow::from(Self::RETURNED_NAME),
549 Self::POISONED => Cow::from(Self::POISONED_NAME),
550 _ => Cow::from(format!("Suspend{}", v.as_usize() - 3)),
554 /// The type of the state discriminant used in the generator type.
556 pub fn discr_ty(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
560 /// This returns the types of the MIR locals which had to be stored across suspension points.
561 /// It is calculated in rustc_mir_transform::generator::StateTransform.
562 /// All the types here must be in the tuple in GeneratorInterior.
564 /// The locals are grouped by their variant number. Note that some locals may
565 /// be repeated in multiple variants.
571 ) -> impl Iterator<Item = impl Iterator<Item = Ty<'tcx>> + Captures<'tcx>> {
572 let layout = tcx.generator_layout(def_id).unwrap();
573 layout.variant_fields.iter().map(move |variant| {
576 .map(move |field| ty::EarlyBinder(layout.field_tys[*field]).subst(tcx, self.substs))
580 /// This is the types of the fields of a generator which are not stored in a
583 pub fn prefix_tys(self) -> impl Iterator<Item = Ty<'tcx>> {
588 #[derive(Debug, Copy, Clone, HashStable)]
589 pub enum UpvarSubsts<'tcx> {
590 Closure(SubstsRef<'tcx>),
591 Generator(SubstsRef<'tcx>),
594 impl<'tcx> UpvarSubsts<'tcx> {
595 /// Returns an iterator over the list of types of captured paths by the closure/generator.
596 /// In case there was a type error in figuring out the types of the captured path, an
597 /// empty iterator is returned.
599 pub fn upvar_tys(self) -> impl Iterator<Item = Ty<'tcx>> + 'tcx {
600 let tupled_tys = match self {
601 UpvarSubsts::Closure(substs) => substs.as_closure().tupled_upvars_ty(),
602 UpvarSubsts::Generator(substs) => substs.as_generator().tupled_upvars_ty(),
605 match tupled_tys.kind() {
606 TyKind::Error(_) => None,
607 TyKind::Tuple(..) => Some(self.tupled_upvars_ty().tuple_fields()),
608 TyKind::Infer(_) => bug!("upvar_tys called before capture types are inferred"),
609 ty => bug!("Unexpected representation of upvar types tuple {:?}", ty),
616 pub fn tupled_upvars_ty(self) -> Ty<'tcx> {
618 UpvarSubsts::Closure(substs) => substs.as_closure().tupled_upvars_ty(),
619 UpvarSubsts::Generator(substs) => substs.as_generator().tupled_upvars_ty(),
624 /// An inline const is modeled like
625 /// ```ignore (illustrative)
626 /// const InlineConst<'l0...'li, T0...Tj, R>: R;
630 /// - 'l0...'li and T0...Tj are the generic parameters
631 /// inherited from the item that defined the inline const,
632 /// - R represents the type of the constant.
634 /// When the inline const is instantiated, `R` is substituted as the actual inferred
635 /// type of the constant. The reason that `R` is represented as an extra type parameter
636 /// is the same reason that [`ClosureSubsts`] have `CS` and `U` as type parameters:
637 /// inline const can reference lifetimes that are internal to the creating function.
638 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable)]
639 pub struct InlineConstSubsts<'tcx> {
640 /// Generic parameters from the enclosing item,
641 /// concatenated with the inferred type of the constant.
642 pub substs: SubstsRef<'tcx>,
645 /// Struct returned by `split()`.
646 pub struct InlineConstSubstsParts<'tcx, T> {
647 pub parent_substs: &'tcx [GenericArg<'tcx>],
651 impl<'tcx> InlineConstSubsts<'tcx> {
652 /// Construct `InlineConstSubsts` from `InlineConstSubstsParts`.
655 parts: InlineConstSubstsParts<'tcx, Ty<'tcx>>,
656 ) -> InlineConstSubsts<'tcx> {
658 substs: tcx.mk_substs(
659 parts.parent_substs.iter().copied().chain(std::iter::once(parts.ty.into())),
664 /// Divides the inline const substs into their respective components.
665 /// The ordering assumed here must match that used by `InlineConstSubsts::new` above.
666 fn split(self) -> InlineConstSubstsParts<'tcx, GenericArg<'tcx>> {
667 match self.substs[..] {
668 [ref parent_substs @ .., ty] => InlineConstSubstsParts { parent_substs, ty },
669 _ => bug!("inline const substs missing synthetics"),
673 /// Returns the substitutions of the inline const's parent.
674 pub fn parent_substs(self) -> &'tcx [GenericArg<'tcx>] {
675 self.split().parent_substs
678 /// Returns the type of this inline const.
679 pub fn ty(self) -> Ty<'tcx> {
680 self.split().ty.expect_ty()
684 #[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Ord, Eq, Hash, TyEncodable, TyDecodable)]
685 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
686 pub enum ExistentialPredicate<'tcx> {
687 /// E.g., `Iterator`.
688 Trait(ExistentialTraitRef<'tcx>),
689 /// E.g., `Iterator::Item = T`.
690 Projection(ExistentialProjection<'tcx>),
695 impl<'tcx> ExistentialPredicate<'tcx> {
696 /// Compares via an ordering that will not change if modules are reordered or other changes are
697 /// made to the tree. In particular, this ordering is preserved across incremental compilations.
698 pub fn stable_cmp(&self, tcx: TyCtxt<'tcx>, other: &Self) -> Ordering {
699 use self::ExistentialPredicate::*;
700 match (*self, *other) {
701 (Trait(_), Trait(_)) => Ordering::Equal,
702 (Projection(ref a), Projection(ref b)) => {
703 tcx.def_path_hash(a.def_id).cmp(&tcx.def_path_hash(b.def_id))
705 (AutoTrait(ref a), AutoTrait(ref b)) => {
706 tcx.def_path_hash(*a).cmp(&tcx.def_path_hash(*b))
708 (Trait(_), _) => Ordering::Less,
709 (Projection(_), Trait(_)) => Ordering::Greater,
710 (Projection(_), _) => Ordering::Less,
711 (AutoTrait(_), _) => Ordering::Greater,
716 pub type PolyExistentialPredicate<'tcx> = Binder<'tcx, ExistentialPredicate<'tcx>>;
718 impl<'tcx> PolyExistentialPredicate<'tcx> {
719 /// Given an existential predicate like `?Self: PartialEq<u32>` (e.g., derived from `dyn PartialEq<u32>`),
720 /// and a concrete type `self_ty`, returns a full predicate where the existentially quantified variable `?Self`
721 /// has been replaced with `self_ty` (e.g., `self_ty: PartialEq<u32>`, in our example).
722 pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::Predicate<'tcx> {
723 use crate::ty::ToPredicate;
724 match self.skip_binder() {
725 ExistentialPredicate::Trait(tr) => {
726 self.rebind(tr).with_self_ty(tcx, self_ty).without_const().to_predicate(tcx)
728 ExistentialPredicate::Projection(p) => {
729 self.rebind(p.with_self_ty(tcx, self_ty)).to_predicate(tcx)
731 ExistentialPredicate::AutoTrait(did) => {
732 let generics = tcx.generics_of(did);
733 let trait_ref = if generics.params.len() == 1 {
734 tcx.mk_trait_ref(did, [self_ty])
736 // If this is an ill-formed auto trait, then synthesize
737 // new error substs for the missing generics.
739 ty::InternalSubsts::extend_with_error(tcx, did, &[self_ty.into()]);
740 tcx.mk_trait_ref(did, err_substs)
742 self.rebind(trait_ref).without_const().to_predicate(tcx)
748 impl<'tcx> List<ty::PolyExistentialPredicate<'tcx>> {
749 /// Returns the "principal `DefId`" of this set of existential predicates.
751 /// A Rust trait object type consists (in addition to a lifetime bound)
752 /// of a set of trait bounds, which are separated into any number
753 /// of auto-trait bounds, and at most one non-auto-trait bound. The
754 /// non-auto-trait bound is called the "principal" of the trait
757 /// Only the principal can have methods or type parameters (because
758 /// auto traits can have neither of them). This is important, because
759 /// it means the auto traits can be treated as an unordered set (methods
760 /// would force an order for the vtable, while relating traits with
761 /// type parameters without knowing the order to relate them in is
762 /// a rather non-trivial task).
764 /// For example, in the trait object `dyn fmt::Debug + Sync`, the
765 /// principal bound is `Some(fmt::Debug)`, while the auto-trait bounds
766 /// are the set `{Sync}`.
768 /// It is also possible to have a "trivial" trait object that
769 /// consists only of auto traits, with no principal - for example,
770 /// `dyn Send + Sync`. In that case, the set of auto-trait bounds
771 /// is `{Send, Sync}`, while there is no principal. These trait objects
772 /// have a "trivial" vtable consisting of just the size, alignment,
774 pub fn principal(&self) -> Option<ty::Binder<'tcx, ExistentialTraitRef<'tcx>>> {
776 .map_bound(|this| match this {
777 ExistentialPredicate::Trait(tr) => Some(tr),
783 pub fn principal_def_id(&self) -> Option<DefId> {
784 self.principal().map(|trait_ref| trait_ref.skip_binder().def_id)
788 pub fn projection_bounds<'a>(
790 ) -> impl Iterator<Item = ty::Binder<'tcx, ExistentialProjection<'tcx>>> + 'a {
791 self.iter().filter_map(|predicate| {
793 .map_bound(|pred| match pred {
794 ExistentialPredicate::Projection(projection) => Some(projection),
802 pub fn auto_traits<'a>(&'a self) -> impl Iterator<Item = DefId> + Captures<'tcx> + 'a {
803 self.iter().filter_map(|predicate| match predicate.skip_binder() {
804 ExistentialPredicate::AutoTrait(did) => Some(did),
810 /// A complete reference to a trait. These take numerous guises in syntax,
811 /// but perhaps the most recognizable form is in a where-clause:
812 /// ```ignore (illustrative)
815 /// This would be represented by a trait-reference where the `DefId` is the
816 /// `DefId` for the trait `Foo` and the substs define `T` as parameter 0,
817 /// and `U` as parameter 1.
819 /// Trait references also appear in object types like `Foo<U>`, but in
820 /// that case the `Self` parameter is absent from the substitutions.
821 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)]
822 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
823 pub struct TraitRef<'tcx> {
825 pub substs: SubstsRef<'tcx>,
826 /// This field exists to prevent the creation of `TraitRef` without
827 /// calling [TyCtxt::mk_trait_ref].
828 pub(super) _use_mk_trait_ref_instead: (),
831 impl<'tcx> TraitRef<'tcx> {
832 pub fn with_self_ty(self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> Self {
835 [self_ty.into()].into_iter().chain(self.substs.iter().skip(1)),
839 /// Returns a `TraitRef` of the form `P0: Foo<P1..Pn>` where `Pi`
840 /// are the parameters defined on trait.
841 pub fn identity(tcx: TyCtxt<'tcx>, def_id: DefId) -> Binder<'tcx, TraitRef<'tcx>> {
842 ty::Binder::dummy(tcx.mk_trait_ref(def_id, InternalSubsts::identity_for_item(tcx, def_id)))
846 pub fn self_ty(&self) -> Ty<'tcx> {
847 self.substs.type_at(0)
853 substs: SubstsRef<'tcx>,
854 ) -> ty::TraitRef<'tcx> {
855 let defs = tcx.generics_of(trait_id);
856 tcx.mk_trait_ref(trait_id, tcx.intern_substs(&substs[..defs.params.len()]))
860 pub type PolyTraitRef<'tcx> = Binder<'tcx, TraitRef<'tcx>>;
862 impl<'tcx> PolyTraitRef<'tcx> {
863 pub fn self_ty(&self) -> Binder<'tcx, Ty<'tcx>> {
864 self.map_bound_ref(|tr| tr.self_ty())
867 pub fn def_id(&self) -> DefId {
868 self.skip_binder().def_id
872 impl rustc_errors::IntoDiagnosticArg for PolyTraitRef<'_> {
873 fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue<'static> {
874 self.to_string().into_diagnostic_arg()
878 /// An existential reference to a trait, where `Self` is erased.
879 /// For example, the trait object `Trait<'a, 'b, X, Y>` is:
880 /// ```ignore (illustrative)
881 /// exists T. T: Trait<'a, 'b, X, Y>
883 /// The substitutions don't include the erased `Self`, only trait
884 /// type and lifetime parameters (`[X, Y]` and `['a, 'b]` above).
885 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)]
886 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
887 pub struct ExistentialTraitRef<'tcx> {
889 pub substs: SubstsRef<'tcx>,
892 impl<'tcx> ExistentialTraitRef<'tcx> {
893 pub fn erase_self_ty(
895 trait_ref: ty::TraitRef<'tcx>,
896 ) -> ty::ExistentialTraitRef<'tcx> {
897 // Assert there is a Self.
898 trait_ref.substs.type_at(0);
900 ty::ExistentialTraitRef {
901 def_id: trait_ref.def_id,
902 substs: tcx.intern_substs(&trait_ref.substs[1..]),
906 /// Object types don't have a self type specified. Therefore, when
907 /// we convert the principal trait-ref into a normal trait-ref,
908 /// you must give *some* self type. A common choice is `mk_err()`
909 /// or some placeholder type.
910 pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::TraitRef<'tcx> {
911 // otherwise the escaping vars would be captured by the binder
912 // debug_assert!(!self_ty.has_escaping_bound_vars());
914 tcx.mk_trait_ref(self.def_id, [self_ty.into()].into_iter().chain(self.substs.iter()))
918 pub type PolyExistentialTraitRef<'tcx> = Binder<'tcx, ExistentialTraitRef<'tcx>>;
920 impl<'tcx> PolyExistentialTraitRef<'tcx> {
921 pub fn def_id(&self) -> DefId {
922 self.skip_binder().def_id
925 /// Object types don't have a self type specified. Therefore, when
926 /// we convert the principal trait-ref into a normal trait-ref,
927 /// you must give *some* self type. A common choice is `mk_err()`
928 /// or some placeholder type.
929 pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::PolyTraitRef<'tcx> {
930 self.map_bound(|trait_ref| trait_ref.with_self_ty(tcx, self_ty))
934 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
935 #[derive(HashStable)]
936 pub enum BoundVariableKind {
938 Region(BoundRegionKind),
942 impl BoundVariableKind {
943 pub fn expect_region(self) -> BoundRegionKind {
945 BoundVariableKind::Region(lt) => lt,
946 _ => bug!("expected a region, but found another kind"),
950 pub fn expect_ty(self) -> BoundTyKind {
952 BoundVariableKind::Ty(ty) => ty,
953 _ => bug!("expected a type, but found another kind"),
957 pub fn expect_const(self) {
959 BoundVariableKind::Const => (),
960 _ => bug!("expected a const, but found another kind"),
965 /// Binder is a binder for higher-ranked lifetimes or types. It is part of the
966 /// compiler's representation for things like `for<'a> Fn(&'a isize)`
967 /// (which would be represented by the type `PolyTraitRef ==
968 /// Binder<'tcx, TraitRef>`). Note that when we instantiate,
969 /// erase, or otherwise "discharge" these bound vars, we change the
970 /// type from `Binder<'tcx, T>` to just `T` (see
971 /// e.g., `liberate_late_bound_regions`).
973 /// `Decodable` and `Encodable` are implemented for `Binder<T>` using the `impl_binder_encode_decode!` macro.
974 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
975 #[derive(HashStable, Lift)]
976 pub struct Binder<'tcx, T>(T, &'tcx List<BoundVariableKind>);
978 impl<'tcx, T> Binder<'tcx, T>
980 T: TypeVisitable<'tcx>,
982 /// Wraps `value` in a binder, asserting that `value` does not
983 /// contain any bound vars that would be bound by the
984 /// binder. This is commonly used to 'inject' a value T into a
985 /// different binding level.
987 pub fn dummy(value: T) -> Binder<'tcx, T> {
989 !value.has_escaping_bound_vars(),
990 "`{value:?}` has escaping bound vars, so it cannot be wrapped in a dummy binder."
992 Binder(value, ty::List::empty())
995 pub fn bind_with_vars(value: T, vars: &'tcx List<BoundVariableKind>) -> Binder<'tcx, T> {
996 if cfg!(debug_assertions) {
997 let mut validator = ValidateBoundVars::new(vars);
998 value.visit_with(&mut validator);
1004 impl<'tcx, T> Binder<'tcx, T> {
1005 /// Skips the binder and returns the "bound" value. This is a
1006 /// risky thing to do because it's easy to get confused about
1007 /// De Bruijn indices and the like. It is usually better to
1008 /// discharge the binder using `no_bound_vars` or
1009 /// `replace_late_bound_regions` or something like
1010 /// that. `skip_binder` is only valid when you are either
1011 /// extracting data that has nothing to do with bound vars, you
1012 /// are doing some sort of test that does not involve bound
1013 /// regions, or you are being very careful about your depth
1016 /// Some examples where `skip_binder` is reasonable:
1018 /// - extracting the `DefId` from a PolyTraitRef;
1019 /// - comparing the self type of a PolyTraitRef to see if it is equal to
1020 /// a type parameter `X`, since the type `X` does not reference any regions
1021 pub fn skip_binder(self) -> T {
1025 pub fn bound_vars(&self) -> &'tcx List<BoundVariableKind> {
1029 pub fn as_ref(&self) -> Binder<'tcx, &T> {
1030 Binder(&self.0, self.1)
1033 pub fn as_deref(&self) -> Binder<'tcx, &T::Target>
1037 Binder(&self.0, self.1)
1040 pub fn map_bound_ref_unchecked<F, U>(&self, f: F) -> Binder<'tcx, U>
1044 let value = f(&self.0);
1045 Binder(value, self.1)
1048 pub fn map_bound_ref<F, U: TypeVisitable<'tcx>>(&self, f: F) -> Binder<'tcx, U>
1052 self.as_ref().map_bound(f)
1055 pub fn map_bound<F, U: TypeVisitable<'tcx>>(self, f: F) -> Binder<'tcx, U>
1059 let value = f(self.0);
1060 if cfg!(debug_assertions) {
1061 let mut validator = ValidateBoundVars::new(self.1);
1062 value.visit_with(&mut validator);
1064 Binder(value, self.1)
1067 pub fn try_map_bound<F, U: TypeVisitable<'tcx>, E>(self, f: F) -> Result<Binder<'tcx, U>, E>
1069 F: FnOnce(T) -> Result<U, E>,
1071 let value = f(self.0)?;
1072 if cfg!(debug_assertions) {
1073 let mut validator = ValidateBoundVars::new(self.1);
1074 value.visit_with(&mut validator);
1076 Ok(Binder(value, self.1))
1079 /// Wraps a `value` in a binder, using the same bound variables as the
1080 /// current `Binder`. This should not be used if the new value *changes*
1081 /// the bound variables. Note: the (old or new) value itself does not
1082 /// necessarily need to *name* all the bound variables.
1084 /// This currently doesn't do anything different than `bind`, because we
1085 /// don't actually track bound vars. However, semantically, it is different
1086 /// because bound vars aren't allowed to change here, whereas they are
1087 /// in `bind`. This may be (debug) asserted in the future.
1088 pub fn rebind<U>(&self, value: U) -> Binder<'tcx, U>
1090 U: TypeVisitable<'tcx>,
1092 if cfg!(debug_assertions) {
1093 let mut validator = ValidateBoundVars::new(self.bound_vars());
1094 value.visit_with(&mut validator);
1096 Binder(value, self.1)
1099 /// Unwraps and returns the value within, but only if it contains
1100 /// no bound vars at all. (In other words, if this binder --
1101 /// and indeed any enclosing binder -- doesn't bind anything at
1102 /// all.) Otherwise, returns `None`.
1104 /// (One could imagine having a method that just unwraps a single
1105 /// binder, but permits late-bound vars bound by enclosing
1106 /// binders, but that would require adjusting the debruijn
1107 /// indices, and given the shallow binding structure we often use,
1108 /// would not be that useful.)
1109 pub fn no_bound_vars(self) -> Option<T>
1111 T: TypeVisitable<'tcx>,
1113 if self.0.has_escaping_bound_vars() { None } else { Some(self.skip_binder()) }
1116 /// Splits the contents into two things that share the same binder
1117 /// level as the original, returning two distinct binders.
1119 /// `f` should consider bound regions at depth 1 to be free, and
1120 /// anything it produces with bound regions at depth 1 will be
1121 /// bound in the resulting return values.
1122 pub fn split<U, V, F>(self, f: F) -> (Binder<'tcx, U>, Binder<'tcx, V>)
1124 F: FnOnce(T) -> (U, V),
1126 let (u, v) = f(self.0);
1127 (Binder(u, self.1), Binder(v, self.1))
1131 impl<'tcx, T> Binder<'tcx, Option<T>> {
1132 pub fn transpose(self) -> Option<Binder<'tcx, T>> {
1133 let bound_vars = self.1;
1134 self.0.map(|v| Binder(v, bound_vars))
1138 impl<'tcx, T: IntoIterator> Binder<'tcx, T> {
1139 pub fn iter(self) -> impl Iterator<Item = ty::Binder<'tcx, T::Item>> {
1140 let bound_vars = self.1;
1141 self.0.into_iter().map(|v| Binder(v, bound_vars))
1145 struct SkipBindersAt<'tcx> {
1147 index: ty::DebruijnIndex,
1150 impl<'tcx> FallibleTypeFolder<'tcx> for SkipBindersAt<'tcx> {
1153 fn tcx(&self) -> TyCtxt<'tcx> {
1157 fn try_fold_binder<T>(&mut self, t: Binder<'tcx, T>) -> Result<Binder<'tcx, T>, Self::Error>
1159 T: ty::TypeFoldable<'tcx>,
1161 self.index.shift_in(1);
1162 let value = t.try_map_bound(|t| t.try_fold_with(self));
1163 self.index.shift_out(1);
1167 fn try_fold_ty(&mut self, ty: Ty<'tcx>) -> Result<Ty<'tcx>, Self::Error> {
1168 if !ty.has_escaping_bound_vars() {
1170 } else if let ty::Bound(index, bv) = *ty.kind() {
1171 if index == self.index {
1174 Ok(self.tcx().mk_ty(ty::Bound(index.shifted_out(1), bv)))
1177 ty.try_super_fold_with(self)
1181 fn try_fold_region(&mut self, r: ty::Region<'tcx>) -> Result<ty::Region<'tcx>, Self::Error> {
1182 if !r.has_escaping_bound_vars() {
1184 } else if let ty::ReLateBound(index, bv) = r.kind() {
1185 if index == self.index {
1188 Ok(self.tcx().mk_region(ty::ReLateBound(index.shifted_out(1), bv)))
1191 r.try_super_fold_with(self)
1195 fn try_fold_const(&mut self, ct: ty::Const<'tcx>) -> Result<ty::Const<'tcx>, Self::Error> {
1196 if !ct.has_escaping_bound_vars() {
1198 } else if let ty::ConstKind::Bound(index, bv) = ct.kind() {
1199 if index == self.index {
1202 Ok(self.tcx().mk_const(
1203 ty::ConstKind::Bound(index.shifted_out(1), bv),
1204 ct.ty().try_fold_with(self)?,
1208 ct.try_super_fold_with(self)
1212 fn try_fold_predicate(
1214 p: ty::Predicate<'tcx>,
1215 ) -> Result<ty::Predicate<'tcx>, Self::Error> {
1216 if !p.has_escaping_bound_vars() { Ok(p) } else { p.try_super_fold_with(self) }
1220 /// Represents the projection of an associated type.
1222 /// For a projection, this would be `<Ty as Trait<...>>::N`.
1224 /// For an opaque type, there is no explicit syntax.
1225 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)]
1226 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
1227 pub struct AliasTy<'tcx> {
1228 /// The parameters of the associated or opaque item.
1230 /// For a projection, these are the substitutions for the trait and the
1231 /// GAT substitutions, if there are any.
1233 /// For RPIT the substitutions are for the generics of the function,
1234 /// while for TAIT it is used for the generic parameters of the alias.
1235 pub substs: SubstsRef<'tcx>,
1237 /// The `DefId` of the `TraitItem` for the associated type `N` if this is a projection,
1238 /// or the `OpaqueType` item if this is an opaque.
1240 /// During codegen, `tcx.type_of(def_id)` can be used to get the type of the
1241 /// underlying type if the type is an opaque.
1243 /// Note that if this is an associated type, this is not the `DefId` of the
1244 /// `TraitRef` containing this associated type, which is in `tcx.associated_item(def_id).container`,
1245 /// aka. `tcx.parent(def_id)`.
1248 /// This field exists to prevent the creation of `AliasTy` without using
1249 /// [TyCtxt::mk_alias_ty].
1250 pub(super) _use_mk_alias_ty_instead: (),
1253 impl<'tcx> AliasTy<'tcx> {
1254 pub fn kind(self, tcx: TyCtxt<'tcx>) -> ty::AliasKind {
1255 match tcx.def_kind(self.def_id) {
1256 DefKind::AssocTy | DefKind::ImplTraitPlaceholder => ty::Projection,
1257 DefKind::OpaqueTy => ty::Opaque,
1258 kind => bug!("unexpected DefKind in AliasTy: {kind:?}"),
1262 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1263 tcx.mk_ty(ty::Alias(self.kind(tcx), self))
1267 /// The following methods work only with associated type projections.
1268 impl<'tcx> AliasTy<'tcx> {
1269 pub fn trait_def_id(self, tcx: TyCtxt<'tcx>) -> DefId {
1270 match tcx.def_kind(self.def_id) {
1271 DefKind::AssocTy | DefKind::AssocConst => tcx.parent(self.def_id),
1272 DefKind::ImplTraitPlaceholder => {
1273 tcx.parent(tcx.impl_trait_in_trait_parent(self.def_id))
1275 kind => bug!("expected a projection AliasTy; found {kind:?}"),
1279 /// Extracts the underlying trait reference and own substs from this projection.
1280 /// For example, if this is a projection of `<T as StreamingIterator>::Item<'a>`,
1281 /// then this function would return a `T: Iterator` trait reference and `['a]` as the own substs
1282 pub fn trait_ref_and_own_substs(
1285 ) -> (ty::TraitRef<'tcx>, &'tcx [ty::GenericArg<'tcx>]) {
1286 debug_assert!(matches!(tcx.def_kind(self.def_id), DefKind::AssocTy | DefKind::AssocConst));
1287 let trait_def_id = self.trait_def_id(tcx);
1288 let trait_generics = tcx.generics_of(trait_def_id);
1290 tcx.mk_trait_ref(trait_def_id, self.substs.truncate_to(tcx, trait_generics)),
1291 &self.substs[trait_generics.count()..],
1295 /// Extracts the underlying trait reference from this projection.
1296 /// For example, if this is a projection of `<T as Iterator>::Item`,
1297 /// then this function would return a `T: Iterator` trait reference.
1299 /// WARNING: This will drop the substs for generic associated types
1300 /// consider calling [Self::trait_ref_and_own_substs] to get those
1302 pub fn trait_ref(self, tcx: TyCtxt<'tcx>) -> ty::TraitRef<'tcx> {
1303 let def_id = self.trait_def_id(tcx);
1304 tcx.mk_trait_ref(def_id, self.substs.truncate_to(tcx, tcx.generics_of(def_id)))
1307 pub fn self_ty(self) -> Ty<'tcx> {
1308 self.substs.type_at(0)
1311 pub fn with_self_ty(self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> Self {
1312 tcx.mk_alias_ty(self.def_id, [self_ty.into()].into_iter().chain(self.substs.iter().skip(1)))
1316 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, Lift)]
1317 pub struct GenSig<'tcx> {
1318 pub resume_ty: Ty<'tcx>,
1319 pub yield_ty: Ty<'tcx>,
1320 pub return_ty: Ty<'tcx>,
1323 pub type PolyGenSig<'tcx> = Binder<'tcx, GenSig<'tcx>>;
1325 /// Signature of a function type, which we have arbitrarily
1326 /// decided to use to refer to the input/output types.
1328 /// - `inputs`: is the list of arguments and their modes.
1329 /// - `output`: is the return type.
1330 /// - `c_variadic`: indicates whether this is a C-variadic function.
1331 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)]
1332 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
1333 pub struct FnSig<'tcx> {
1334 pub inputs_and_output: &'tcx List<Ty<'tcx>>,
1335 pub c_variadic: bool,
1336 pub unsafety: hir::Unsafety,
1340 impl<'tcx> FnSig<'tcx> {
1341 pub fn inputs(&self) -> &'tcx [Ty<'tcx>] {
1342 &self.inputs_and_output[..self.inputs_and_output.len() - 1]
1345 pub fn output(&self) -> Ty<'tcx> {
1346 self.inputs_and_output[self.inputs_and_output.len() - 1]
1349 // Creates a minimal `FnSig` to be used when encountering a `TyKind::Error` in a fallible
1351 fn fake() -> FnSig<'tcx> {
1353 inputs_and_output: List::empty(),
1355 unsafety: hir::Unsafety::Normal,
1356 abi: abi::Abi::Rust,
1361 pub type PolyFnSig<'tcx> = Binder<'tcx, FnSig<'tcx>>;
1363 impl<'tcx> PolyFnSig<'tcx> {
1365 pub fn inputs(&self) -> Binder<'tcx, &'tcx [Ty<'tcx>]> {
1366 self.map_bound_ref_unchecked(|fn_sig| fn_sig.inputs())
1369 pub fn input(&self, index: usize) -> ty::Binder<'tcx, Ty<'tcx>> {
1370 self.map_bound_ref(|fn_sig| fn_sig.inputs()[index])
1372 pub fn inputs_and_output(&self) -> ty::Binder<'tcx, &'tcx List<Ty<'tcx>>> {
1373 self.map_bound_ref(|fn_sig| fn_sig.inputs_and_output)
1376 pub fn output(&self) -> ty::Binder<'tcx, Ty<'tcx>> {
1377 self.map_bound_ref(|fn_sig| fn_sig.output())
1379 pub fn c_variadic(&self) -> bool {
1380 self.skip_binder().c_variadic
1382 pub fn unsafety(&self) -> hir::Unsafety {
1383 self.skip_binder().unsafety
1385 pub fn abi(&self) -> abi::Abi {
1386 self.skip_binder().abi
1390 pub type CanonicalPolyFnSig<'tcx> = Canonical<'tcx, Binder<'tcx, FnSig<'tcx>>>;
1392 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)]
1393 #[derive(HashStable)]
1394 pub struct ParamTy {
1399 impl<'tcx> ParamTy {
1400 pub fn new(index: u32, name: Symbol) -> ParamTy {
1401 ParamTy { index, name }
1404 pub fn for_def(def: &ty::GenericParamDef) -> ParamTy {
1405 ParamTy::new(def.index, def.name)
1409 pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1410 tcx.mk_ty_param(self.index, self.name)
1413 pub fn span_from_generics(&self, tcx: TyCtxt<'tcx>, item_with_generics: DefId) -> Span {
1414 let generics = tcx.generics_of(item_with_generics);
1415 let type_param = generics.type_param(self, tcx);
1416 tcx.def_span(type_param.def_id)
1420 #[derive(Copy, Clone, Hash, TyEncodable, TyDecodable, Eq, PartialEq, Ord, PartialOrd)]
1421 #[derive(HashStable)]
1422 pub struct ParamConst {
1428 pub fn new(index: u32, name: Symbol) -> ParamConst {
1429 ParamConst { index, name }
1432 pub fn for_def(def: &ty::GenericParamDef) -> ParamConst {
1433 ParamConst::new(def.index, def.name)
1437 /// Use this rather than `RegionKind`, whenever possible.
1438 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable)]
1439 #[rustc_pass_by_value]
1440 pub struct Region<'tcx>(pub Interned<'tcx, RegionKind<'tcx>>);
1442 impl<'tcx> Deref for Region<'tcx> {
1443 type Target = RegionKind<'tcx>;
1446 fn deref(&self) -> &RegionKind<'tcx> {
1451 impl<'tcx> fmt::Debug for Region<'tcx> {
1452 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1453 write!(f, "{:?}", self.kind())
1457 #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, PartialOrd, Ord)]
1458 #[derive(HashStable)]
1459 pub struct EarlyBoundRegion {
1465 impl fmt::Debug for EarlyBoundRegion {
1466 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1467 write!(f, "{}, {}", self.index, self.name)
1471 /// A **`const`** **v**ariable **ID**.
1472 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1473 #[derive(HashStable, TyEncodable, TyDecodable)]
1474 pub struct ConstVid<'tcx> {
1476 pub phantom: PhantomData<&'tcx ()>,
1479 rustc_index::newtype_index! {
1480 /// A **region** (lifetime) **v**ariable **ID**.
1481 #[derive(HashStable)]
1482 #[debug_format = "'_#{}r"]
1483 pub struct RegionVid {}
1486 impl Atom for RegionVid {
1487 fn index(self) -> usize {
1492 rustc_index::newtype_index! {
1493 #[derive(HashStable)]
1494 pub struct BoundVar {}
1497 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
1498 #[derive(HashStable)]
1499 pub struct BoundTy {
1501 pub kind: BoundTyKind,
1504 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
1505 #[derive(HashStable)]
1506 pub enum BoundTyKind {
1511 impl From<BoundVar> for BoundTy {
1512 fn from(var: BoundVar) -> Self {
1513 BoundTy { var, kind: BoundTyKind::Anon }
1517 /// A `ProjectionPredicate` for an `ExistentialTraitRef`.
1518 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)]
1519 #[derive(HashStable, TypeFoldable, TypeVisitable, Lift)]
1520 pub struct ExistentialProjection<'tcx> {
1522 pub substs: SubstsRef<'tcx>,
1523 pub term: Term<'tcx>,
1526 pub type PolyExistentialProjection<'tcx> = Binder<'tcx, ExistentialProjection<'tcx>>;
1528 impl<'tcx> ExistentialProjection<'tcx> {
1529 /// Extracts the underlying existential trait reference from this projection.
1530 /// For example, if this is a projection of `exists T. <T as Iterator>::Item == X`,
1531 /// then this function would return an `exists T. T: Iterator` existential trait
1533 pub fn trait_ref(&self, tcx: TyCtxt<'tcx>) -> ty::ExistentialTraitRef<'tcx> {
1534 let def_id = tcx.parent(self.def_id);
1535 let subst_count = tcx.generics_of(def_id).count() - 1;
1536 let substs = tcx.intern_substs(&self.substs[..subst_count]);
1537 ty::ExistentialTraitRef { def_id, substs }
1540 pub fn with_self_ty(
1544 ) -> ty::ProjectionPredicate<'tcx> {
1545 // otherwise the escaping regions would be captured by the binders
1546 debug_assert!(!self_ty.has_escaping_bound_vars());
1548 ty::ProjectionPredicate {
1550 .mk_alias_ty(self.def_id, [self_ty.into()].into_iter().chain(self.substs)),
1555 pub fn erase_self_ty(
1557 projection_predicate: ty::ProjectionPredicate<'tcx>,
1559 // Assert there is a Self.
1560 projection_predicate.projection_ty.substs.type_at(0);
1563 def_id: projection_predicate.projection_ty.def_id,
1564 substs: tcx.intern_substs(&projection_predicate.projection_ty.substs[1..]),
1565 term: projection_predicate.term,
1570 impl<'tcx> PolyExistentialProjection<'tcx> {
1571 pub fn with_self_ty(
1575 ) -> ty::PolyProjectionPredicate<'tcx> {
1576 self.map_bound(|p| p.with_self_ty(tcx, self_ty))
1579 pub fn item_def_id(&self) -> DefId {
1580 self.skip_binder().def_id
1584 /// Region utilities
1585 impl<'tcx> Region<'tcx> {
1586 pub fn kind(self) -> RegionKind<'tcx> {
1590 pub fn get_name(self) -> Option<Symbol> {
1591 if self.has_name() {
1592 let name = match *self {
1593 ty::ReEarlyBound(ebr) => Some(ebr.name),
1594 ty::ReLateBound(_, br) => br.kind.get_name(),
1595 ty::ReFree(fr) => fr.bound_region.get_name(),
1596 ty::ReStatic => Some(kw::StaticLifetime),
1597 ty::RePlaceholder(placeholder) => placeholder.name.get_name(),
1607 /// Is this region named by the user?
1608 pub fn has_name(self) -> bool {
1610 ty::ReEarlyBound(ebr) => ebr.has_name(),
1611 ty::ReLateBound(_, br) => br.kind.is_named(),
1612 ty::ReFree(fr) => fr.bound_region.is_named(),
1613 ty::ReStatic => true,
1614 ty::ReVar(..) => false,
1615 ty::RePlaceholder(placeholder) => placeholder.name.is_named(),
1616 ty::ReErased => false,
1621 pub fn is_static(self) -> bool {
1622 matches!(*self, ty::ReStatic)
1626 pub fn is_erased(self) -> bool {
1627 matches!(*self, ty::ReErased)
1631 pub fn is_late_bound(self) -> bool {
1632 matches!(*self, ty::ReLateBound(..))
1636 pub fn is_placeholder(self) -> bool {
1637 matches!(*self, ty::RePlaceholder(..))
1641 pub fn bound_at_or_above_binder(self, index: ty::DebruijnIndex) -> bool {
1643 ty::ReLateBound(debruijn, _) => debruijn >= index,
1648 pub fn type_flags(self) -> TypeFlags {
1649 let mut flags = TypeFlags::empty();
1653 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1654 flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS;
1655 flags = flags | TypeFlags::HAS_RE_INFER;
1657 ty::RePlaceholder(..) => {
1658 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1659 flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS;
1660 flags = flags | TypeFlags::HAS_RE_PLACEHOLDER;
1662 ty::ReEarlyBound(..) => {
1663 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1664 flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS;
1665 flags = flags | TypeFlags::HAS_RE_PARAM;
1667 ty::ReFree { .. } => {
1668 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1669 flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS;
1672 flags = flags | TypeFlags::HAS_FREE_REGIONS;
1674 ty::ReLateBound(..) => {
1675 flags = flags | TypeFlags::HAS_RE_LATE_BOUND;
1678 flags = flags | TypeFlags::HAS_RE_ERASED;
1682 debug!("type_flags({:?}) = {:?}", self, flags);
1687 /// Given an early-bound or free region, returns the `DefId` where it was bound.
1688 /// For example, consider the regions in this snippet of code:
1690 /// ```ignore (illustrative)
1692 /// // ^^ -- early bound, declared on an impl
1694 /// fn bar<'b, 'c>(x: &self, y: &'b u32, z: &'c u64) where 'static: 'c
1695 /// // ^^ ^^ ^ anonymous, late-bound
1696 /// // | early-bound, appears in where-clauses
1697 /// // late-bound, appears only in fn args
1702 /// Here, `free_region_binding_scope('a)` would return the `DefId`
1703 /// of the impl, and for all the other highlighted regions, it
1704 /// would return the `DefId` of the function. In other cases (not shown), this
1705 /// function might return the `DefId` of a closure.
1706 pub fn free_region_binding_scope(self, tcx: TyCtxt<'_>) -> DefId {
1708 ty::ReEarlyBound(br) => tcx.parent(br.def_id),
1709 ty::ReFree(fr) => fr.scope,
1710 _ => bug!("free_region_binding_scope invoked on inappropriate region: {:?}", self),
1714 /// True for free regions other than `'static`.
1715 pub fn is_free(self) -> bool {
1716 matches!(*self, ty::ReEarlyBound(_) | ty::ReFree(_))
1719 /// True if `self` is a free region or static.
1720 pub fn is_free_or_static(self) -> bool {
1722 ty::ReStatic => true,
1723 _ => self.is_free(),
1727 pub fn is_var(self) -> bool {
1728 matches!(self.kind(), ty::ReVar(_))
1733 impl<'tcx> Ty<'tcx> {
1735 pub fn kind(self) -> &'tcx TyKind<'tcx> {
1740 pub fn flags(self) -> TypeFlags {
1745 pub fn is_unit(self) -> bool {
1747 Tuple(ref tys) => tys.is_empty(),
1753 pub fn is_never(self) -> bool {
1754 matches!(self.kind(), Never)
1758 pub fn is_primitive(self) -> bool {
1759 self.kind().is_primitive()
1763 pub fn is_adt(self) -> bool {
1764 matches!(self.kind(), Adt(..))
1768 pub fn is_ref(self) -> bool {
1769 matches!(self.kind(), Ref(..))
1773 pub fn is_ty_var(self) -> bool {
1774 matches!(self.kind(), Infer(TyVar(_)))
1778 pub fn ty_vid(self) -> Option<ty::TyVid> {
1780 &Infer(TyVar(vid)) => Some(vid),
1786 pub fn is_ty_or_numeric_infer(self) -> bool {
1787 matches!(self.kind(), Infer(_))
1791 pub fn is_phantom_data(self) -> bool {
1792 if let Adt(def, _) = self.kind() { def.is_phantom_data() } else { false }
1796 pub fn is_bool(self) -> bool {
1797 *self.kind() == Bool
1800 /// Returns `true` if this type is a `str`.
1802 pub fn is_str(self) -> bool {
1807 pub fn is_param(self, index: u32) -> bool {
1809 ty::Param(ref data) => data.index == index,
1815 pub fn is_slice(self) -> bool {
1816 matches!(self.kind(), Slice(_))
1820 pub fn is_array_slice(self) -> bool {
1823 RawPtr(TypeAndMut { ty, .. }) | Ref(_, ty, _) => matches!(ty.kind(), Slice(_)),
1829 pub fn is_array(self) -> bool {
1830 matches!(self.kind(), Array(..))
1834 pub fn is_simd(self) -> bool {
1836 Adt(def, _) => def.repr().simd(),
1841 pub fn sequence_element_type(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
1843 Array(ty, _) | Slice(ty) => *ty,
1844 Str => tcx.types.u8,
1845 _ => bug!("`sequence_element_type` called on non-sequence value: {}", self),
1849 pub fn simd_size_and_type(self, tcx: TyCtxt<'tcx>) -> (u64, Ty<'tcx>) {
1851 Adt(def, substs) => {
1852 assert!(def.repr().simd(), "`simd_size_and_type` called on non-SIMD type");
1853 let variant = def.non_enum_variant();
1854 let f0_ty = variant.fields[0].ty(tcx, substs);
1856 match f0_ty.kind() {
1857 // If the first field is an array, we assume it is the only field and its
1858 // elements are the SIMD components.
1859 Array(f0_elem_ty, f0_len) => {
1860 // FIXME(repr_simd): https://github.com/rust-lang/rust/pull/78863#discussion_r522784112
1861 // The way we evaluate the `N` in `[T; N]` here only works since we use
1862 // `simd_size_and_type` post-monomorphization. It will probably start to ICE
1863 // if we use it in generic code. See the `simd-array-trait` ui test.
1864 (f0_len.eval_usize(tcx, ParamEnv::empty()) as u64, *f0_elem_ty)
1866 // Otherwise, the fields of this Adt are the SIMD components (and we assume they
1867 // all have the same type).
1868 _ => (variant.fields.len() as u64, f0_ty),
1871 _ => bug!("`simd_size_and_type` called on invalid type"),
1876 pub fn is_region_ptr(self) -> bool {
1877 matches!(self.kind(), Ref(..))
1881 pub fn is_mutable_ptr(self) -> bool {
1884 RawPtr(TypeAndMut { mutbl: hir::Mutability::Mut, .. })
1885 | Ref(_, _, hir::Mutability::Mut)
1889 /// Get the mutability of the reference or `None` when not a reference
1891 pub fn ref_mutability(self) -> Option<hir::Mutability> {
1893 Ref(_, _, mutability) => Some(*mutability),
1899 pub fn is_unsafe_ptr(self) -> bool {
1900 matches!(self.kind(), RawPtr(_))
1903 /// Tests if this is any kind of primitive pointer type (reference, raw pointer, fn pointer).
1905 pub fn is_any_ptr(self) -> bool {
1906 self.is_region_ptr() || self.is_unsafe_ptr() || self.is_fn_ptr()
1910 pub fn is_box(self) -> bool {
1912 Adt(def, _) => def.is_box(),
1917 /// Panics if called on any type other than `Box<T>`.
1918 pub fn boxed_ty(self) -> Ty<'tcx> {
1920 Adt(def, substs) if def.is_box() => substs.type_at(0),
1921 _ => bug!("`boxed_ty` is called on non-box type {:?}", self),
1925 /// A scalar type is one that denotes an atomic datum, with no sub-components.
1926 /// (A RawPtr is scalar because it represents a non-managed pointer, so its
1927 /// contents are abstract to rustc.)
1929 pub fn is_scalar(self) -> bool {
1939 | Infer(IntVar(_) | FloatVar(_))
1943 /// Returns `true` if this type is a floating point type.
1945 pub fn is_floating_point(self) -> bool {
1946 matches!(self.kind(), Float(_) | Infer(FloatVar(_)))
1950 pub fn is_trait(self) -> bool {
1951 matches!(self.kind(), Dynamic(_, _, ty::Dyn))
1955 pub fn is_dyn_star(self) -> bool {
1956 matches!(self.kind(), Dynamic(_, _, ty::DynStar))
1960 pub fn is_enum(self) -> bool {
1961 matches!(self.kind(), Adt(adt_def, _) if adt_def.is_enum())
1965 pub fn is_union(self) -> bool {
1966 matches!(self.kind(), Adt(adt_def, _) if adt_def.is_union())
1970 pub fn is_closure(self) -> bool {
1971 matches!(self.kind(), Closure(..))
1975 pub fn is_generator(self) -> bool {
1976 matches!(self.kind(), Generator(..))
1980 pub fn is_integral(self) -> bool {
1981 matches!(self.kind(), Infer(IntVar(_)) | Int(_) | Uint(_))
1985 pub fn is_fresh_ty(self) -> bool {
1986 matches!(self.kind(), Infer(FreshTy(_)))
1990 pub fn is_fresh(self) -> bool {
1991 matches!(self.kind(), Infer(FreshTy(_) | FreshIntTy(_) | FreshFloatTy(_)))
1995 pub fn is_char(self) -> bool {
1996 matches!(self.kind(), Char)
2000 pub fn is_numeric(self) -> bool {
2001 self.is_integral() || self.is_floating_point()
2005 pub fn is_signed(self) -> bool {
2006 matches!(self.kind(), Int(_))
2010 pub fn is_ptr_sized_integral(self) -> bool {
2011 matches!(self.kind(), Int(ty::IntTy::Isize) | Uint(ty::UintTy::Usize))
2015 pub fn has_concrete_skeleton(self) -> bool {
2016 !matches!(self.kind(), Param(_) | Infer(_) | Error(_))
2019 /// Checks whether a type recursively contains another type
2021 /// Example: `Option<()>` contains `()`
2022 pub fn contains(self, other: Ty<'tcx>) -> bool {
2023 struct ContainsTyVisitor<'tcx>(Ty<'tcx>);
2025 impl<'tcx> TypeVisitor<'tcx> for ContainsTyVisitor<'tcx> {
2028 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
2029 if self.0 == t { ControlFlow::Break(()) } else { t.super_visit_with(self) }
2033 let cf = self.visit_with(&mut ContainsTyVisitor(other));
2037 /// Returns the type and mutability of `*ty`.
2039 /// The parameter `explicit` indicates if this is an *explicit* dereference.
2040 /// Some types -- notably unsafe ptrs -- can only be dereferenced explicitly.
2041 pub fn builtin_deref(self, explicit: bool) -> Option<TypeAndMut<'tcx>> {
2043 Adt(def, _) if def.is_box() => {
2044 Some(TypeAndMut { ty: self.boxed_ty(), mutbl: hir::Mutability::Not })
2046 Ref(_, ty, mutbl) => Some(TypeAndMut { ty: *ty, mutbl: *mutbl }),
2047 RawPtr(mt) if explicit => Some(*mt),
2052 /// Returns the type of `ty[i]`.
2053 pub fn builtin_index(self) -> Option<Ty<'tcx>> {
2055 Array(ty, _) | Slice(ty) => Some(*ty),
2060 pub fn fn_sig(self, tcx: TyCtxt<'tcx>) -> PolyFnSig<'tcx> {
2062 FnDef(def_id, substs) => tcx.bound_fn_sig(*def_id).subst(tcx, substs),
2065 // ignore errors (#54954)
2066 ty::Binder::dummy(FnSig::fake())
2068 Closure(..) => bug!(
2069 "to get the signature of a closure, use `substs.as_closure().sig()` not `fn_sig()`",
2071 _ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self),
2076 pub fn is_fn(self) -> bool {
2077 matches!(self.kind(), FnDef(..) | FnPtr(_))
2081 pub fn is_fn_ptr(self) -> bool {
2082 matches!(self.kind(), FnPtr(_))
2086 pub fn is_impl_trait(self) -> bool {
2087 matches!(self.kind(), Alias(ty::Opaque, ..))
2091 pub fn ty_adt_def(self) -> Option<AdtDef<'tcx>> {
2093 Adt(adt, _) => Some(*adt),
2098 /// Iterates over tuple fields.
2099 /// Panics when called on anything but a tuple.
2101 pub fn tuple_fields(self) -> &'tcx List<Ty<'tcx>> {
2103 Tuple(substs) => substs,
2104 _ => bug!("tuple_fields called on non-tuple"),
2108 /// If the type contains variants, returns the valid range of variant indices.
2110 // FIXME: This requires the optimized MIR in the case of generators.
2112 pub fn variant_range(self, tcx: TyCtxt<'tcx>) -> Option<Range<VariantIdx>> {
2114 TyKind::Adt(adt, _) => Some(adt.variant_range()),
2115 TyKind::Generator(def_id, substs, _) => {
2116 Some(substs.as_generator().variant_range(*def_id, tcx))
2122 /// If the type contains variants, returns the variant for `variant_index`.
2123 /// Panics if `variant_index` is out of range.
2125 // FIXME: This requires the optimized MIR in the case of generators.
2127 pub fn discriminant_for_variant(
2130 variant_index: VariantIdx,
2131 ) -> Option<Discr<'tcx>> {
2133 TyKind::Adt(adt, _) if adt.variants().is_empty() => {
2134 // This can actually happen during CTFE, see
2135 // https://github.com/rust-lang/rust/issues/89765.
2138 TyKind::Adt(adt, _) if adt.is_enum() => {
2139 Some(adt.discriminant_for_variant(tcx, variant_index))
2141 TyKind::Generator(def_id, substs, _) => {
2142 Some(substs.as_generator().discriminant_for_variant(*def_id, tcx, variant_index))
2148 /// Returns the type of the discriminant of this type.
2149 pub fn discriminant_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> {
2151 ty::Adt(adt, _) if adt.is_enum() => adt.repr().discr_type().to_ty(tcx),
2152 ty::Generator(_, substs, _) => substs.as_generator().discr_ty(tcx),
2154 ty::Param(_) | ty::Alias(..) | ty::Infer(ty::TyVar(_)) => {
2155 let assoc_items = tcx.associated_item_def_ids(
2156 tcx.require_lang_item(hir::LangItem::DiscriminantKind, None),
2158 tcx.mk_projection(assoc_items[0], tcx.intern_substs(&[self.into()]))
2177 | ty::GeneratorWitness(..)
2181 | ty::Infer(IntVar(_) | FloatVar(_)) => tcx.types.u8,
2184 | ty::Placeholder(_)
2185 | ty::Infer(FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2186 bug!("`discriminant_ty` applied to unexpected type: {:?}", self)
2191 /// Returns the type of metadata for (potentially fat) pointers to this type,
2192 /// and a boolean signifying if this is conditional on this type being `Sized`.
2193 pub fn ptr_metadata_ty(
2196 normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>,
2197 ) -> (Ty<'tcx>, bool) {
2198 let tail = tcx.struct_tail_with_normalize(self, normalize, || {});
2201 ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
2212 | ty::GeneratorWitness(..)
2217 // Extern types have metadata = ().
2219 // If returned by `struct_tail_without_normalization` this is a unit struct
2220 // without any fields, or not a struct, and therefore is Sized.
2222 // If returned by `struct_tail_without_normalization` this is the empty tuple,
2223 // a.k.a. unit type, which is Sized
2224 | ty::Tuple(..) => (tcx.types.unit, false),
2226 ty::Str | ty::Slice(_) => (tcx.types.usize, false),
2227 ty::Dynamic(..) => {
2228 let dyn_metadata = tcx.require_lang_item(LangItem::DynMetadata, None);
2229 (tcx.bound_type_of(dyn_metadata).subst(tcx, &[tail.into()]), false)
2232 // type parameters only have unit metadata if they're sized, so return true
2233 // to make sure we double check this during confirmation
2234 ty::Param(_) | ty::Alias(..) => (tcx.types.unit, true),
2236 ty::Infer(ty::TyVar(_))
2238 | ty::Placeholder(..)
2239 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2240 bug!("`ptr_metadata_ty` applied to unexpected type: {:?} (tail = {:?})", self, tail)
2245 /// When we create a closure, we record its kind (i.e., what trait
2246 /// it implements) into its `ClosureSubsts` using a type
2247 /// parameter. This is kind of a phantom type, except that the
2248 /// most convenient thing for us to are the integral types. This
2249 /// function converts such a special type into the closure
2250 /// kind. To go the other way, use `closure_kind.to_ty(tcx)`.
2252 /// Note that during type checking, we use an inference variable
2253 /// to represent the closure kind, because it has not yet been
2254 /// inferred. Once upvar inference (in `rustc_hir_analysis/src/check/upvar.rs`)
2255 /// is complete, that type variable will be unified.
2256 pub fn to_opt_closure_kind(self) -> Option<ty::ClosureKind> {
2258 Int(int_ty) => match int_ty {
2259 ty::IntTy::I8 => Some(ty::ClosureKind::Fn),
2260 ty::IntTy::I16 => Some(ty::ClosureKind::FnMut),
2261 ty::IntTy::I32 => Some(ty::ClosureKind::FnOnce),
2262 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
2265 // "Bound" types appear in canonical queries when the
2266 // closure type is not yet known
2267 Bound(..) | Infer(_) => None,
2269 Error(_) => Some(ty::ClosureKind::Fn),
2271 _ => bug!("cannot convert type `{:?}` to a closure kind", self),
2275 /// Fast path helper for testing if a type is `Sized`.
2277 /// Returning true means the type is known to be sized. Returning
2278 /// `false` means nothing -- could be sized, might not be.
2280 /// Note that we could never rely on the fact that a type such as `[_]` is
2281 /// trivially `!Sized` because we could be in a type environment with a
2282 /// bound such as `[_]: Copy`. A function with such a bound obviously never
2283 /// can be called, but that doesn't mean it shouldn't typecheck. This is why
2284 /// this method doesn't return `Option<bool>`.
2285 pub fn is_trivially_sized(self, tcx: TyCtxt<'tcx>) -> bool {
2287 ty::Infer(ty::IntVar(_) | ty::FloatVar(_))
2298 | ty::GeneratorWitness(..)
2302 | ty::Error(_) => true,
2304 ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => false,
2306 ty::Tuple(tys) => tys.iter().all(|ty| ty.is_trivially_sized(tcx)),
2308 ty::Adt(def, _substs) => def.sized_constraint(tcx).0.is_empty(),
2310 ty::Alias(..) | ty::Param(_) => false,
2312 ty::Infer(ty::TyVar(_)) => false,
2315 | ty::Placeholder(..)
2316 | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => {
2317 bug!("`is_trivially_sized` applied to unexpected type: {:?}", self)
2322 /// Fast path helper for primitives which are always `Copy` and which
2323 /// have a side-effect-free `Clone` impl.
2325 /// Returning true means the type is known to be pure and `Copy+Clone`.
2326 /// Returning `false` means nothing -- could be `Copy`, might not be.
2328 /// This is mostly useful for optimizations, as there are the types
2329 /// on which we can replace cloning with dereferencing.
2330 pub fn is_trivially_pure_clone_copy(self) -> bool {
2332 ty::Bool | ty::Char | ty::Never => true,
2334 // These aren't even `Clone`
2335 ty::Str | ty::Slice(..) | ty::Foreign(..) | ty::Dynamic(..) => false,
2337 ty::Infer(ty::InferTy::FloatVar(_) | ty::InferTy::IntVar(_))
2340 | ty::Float(..) => true,
2342 // The voldemort ZSTs are fine.
2343 ty::FnDef(..) => true,
2345 ty::Array(element_ty, _len) => element_ty.is_trivially_pure_clone_copy(),
2347 // A 100-tuple isn't "trivial", so doing this only for reasonable sizes.
2348 ty::Tuple(field_tys) => {
2349 field_tys.len() <= 3 && field_tys.iter().all(Self::is_trivially_pure_clone_copy)
2352 // Sometimes traits aren't implemented for every ABI or arity,
2353 // because we can't be generic over everything yet.
2354 ty::FnPtr(..) => false,
2356 // Definitely absolutely not copy.
2357 ty::Ref(_, _, hir::Mutability::Mut) => false,
2359 // Thin pointers & thin shared references are pure-clone-copy, but for
2360 // anything with custom metadata it might be more complicated.
2361 ty::Ref(_, _, hir::Mutability::Not) | ty::RawPtr(..) => false,
2363 ty::Generator(..) | ty::GeneratorWitness(..) => false,
2365 // Might be, but not "trivial" so just giving the safe answer.
2366 ty::Adt(..) | ty::Closure(..) => false,
2368 // Needs normalization or revealing to determine, so no is the safe answer.
2369 ty::Alias(..) => false,
2371 ty::Param(..) | ty::Infer(..) | ty::Error(..) => false,
2373 ty::Bound(..) | ty::Placeholder(..) => {
2374 bug!("`is_trivially_pure_clone_copy` applied to unexpected type: {:?}", self);
2379 /// If `self` is a primitive, return its [`Symbol`].
2380 pub fn primitive_symbol(self) -> Option<Symbol> {
2382 ty::Bool => Some(sym::bool),
2383 ty::Char => Some(sym::char),
2384 ty::Float(f) => match f {
2385 ty::FloatTy::F32 => Some(sym::f32),
2386 ty::FloatTy::F64 => Some(sym::f64),
2388 ty::Int(f) => match f {
2389 ty::IntTy::Isize => Some(sym::isize),
2390 ty::IntTy::I8 => Some(sym::i8),
2391 ty::IntTy::I16 => Some(sym::i16),
2392 ty::IntTy::I32 => Some(sym::i32),
2393 ty::IntTy::I64 => Some(sym::i64),
2394 ty::IntTy::I128 => Some(sym::i128),
2396 ty::Uint(f) => match f {
2397 ty::UintTy::Usize => Some(sym::usize),
2398 ty::UintTy::U8 => Some(sym::u8),
2399 ty::UintTy::U16 => Some(sym::u16),
2400 ty::UintTy::U32 => Some(sym::u32),
2401 ty::UintTy::U64 => Some(sym::u64),
2402 ty::UintTy::U128 => Some(sym::u128),
2409 /// Extra information about why we ended up with a particular variance.
2410 /// This is only used to add more information to error messages, and
2411 /// has no effect on soundness. While choosing the 'wrong' `VarianceDiagInfo`
2412 /// may lead to confusing notes in error messages, it will never cause
2413 /// a miscompilation or unsoundness.
2415 /// When in doubt, use `VarianceDiagInfo::default()`
2416 #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
2417 pub enum VarianceDiagInfo<'tcx> {
2418 /// No additional information - this is the default.
2419 /// We will not add any additional information to error messages.
2422 /// We switched our variance because a generic argument occurs inside
2423 /// the invariant generic argument of another type.
2425 /// The generic type containing the generic parameter
2426 /// that changes the variance (e.g. `*mut T`, `MyStruct<T>`)
2428 /// The index of the generic parameter being used
2429 /// (e.g. `0` for `*mut T`, `1` for `MyStruct<'CovariantParam, 'InvariantParam>`)
2434 impl<'tcx> VarianceDiagInfo<'tcx> {
2435 /// Mirrors `Variance::xform` - used to 'combine' the existing
2436 /// and new `VarianceDiagInfo`s when our variance changes.
2437 pub fn xform(self, other: VarianceDiagInfo<'tcx>) -> VarianceDiagInfo<'tcx> {
2438 // For now, just use the first `VarianceDiagInfo::Invariant` that we see
2440 VarianceDiagInfo::None => other,
2441 VarianceDiagInfo::Invariant { .. } => self,