From a7015fe8169ebfcd6707f34bf190cb4c4ae302f7 Mon Sep 17 00:00:00 2001 From: Wilco Kusee Date: Sun, 31 Jan 2021 10:32:34 +0100 Subject: [PATCH 1/5] Move things to rustc_type_ir --- Cargo.lock | 3 + .../rustc_const_eval/src/interpret/cast.rs | 6 +- compiler/rustc_lint/src/builtin.rs | 4 +- compiler/rustc_macros/src/serialize.rs | 4 +- .../rustc_middle/src/mir/interpret/mod.rs | 14 +- compiler/rustc_middle/src/mir/mod.rs | 4 +- compiler/rustc_middle/src/ty/codec.rs | 186 +++---- compiler/rustc_middle/src/ty/consts.rs | 10 +- compiler/rustc_middle/src/ty/context.rs | 175 +++---- compiler/rustc_middle/src/ty/diagnostics.rs | 2 +- .../rustc_middle/src/ty/inhabitedness/mod.rs | 3 +- compiler/rustc_middle/src/ty/mod.rs | 12 +- compiler/rustc_middle/src/ty/sty.rs | 36 +- compiler/rustc_middle/src/ty/subst.rs | 8 +- compiler/rustc_middle/src/ty/util.rs | 5 +- compiler/rustc_query_impl/Cargo.toml | 1 + .../rustc_query_impl/src/on_disk_cache.rs | 14 +- compiler/rustc_query_system/Cargo.toml | 1 + compiler/rustc_query_system/src/ich/mod.rs | 122 +++++ compiler/rustc_ty_utils/src/ty.rs | 2 +- compiler/rustc_type_ir/Cargo.toml | 1 + compiler/rustc_type_ir/src/codec.rs | 63 +++ compiler/rustc_type_ir/src/lib.rs | 139 ++++++ compiler/rustc_type_ir/src/sty.rs | 454 ++++++++++++++++++ .../rustc_typeck/src/coherence/builtin.rs | 2 +- 25 files changed, 1030 insertions(+), 241 deletions(-) create mode 100644 compiler/rustc_type_ir/src/codec.rs create mode 100644 compiler/rustc_type_ir/src/sty.rs diff --git a/Cargo.lock b/Cargo.lock index 42bf166a71cb2..871ff8f9cdb40 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4262,6 +4262,7 @@ dependencies = [ "rustc_serialize", "rustc_session", "rustc_span", + "rustc_type_ir", "tracing", ] @@ -4283,6 +4284,7 @@ dependencies = [ "rustc_session", "rustc_span", "rustc_target", + "rustc_type_ir", "smallvec", "tracing", ] @@ -4484,6 +4486,7 @@ dependencies = [ "rustc_index", "rustc_macros", "rustc_serialize", + "smallvec", ] [[package]] diff --git a/compiler/rustc_const_eval/src/interpret/cast.rs b/compiler/rustc_const_eval/src/interpret/cast.rs index 7cd2ba34b04a7..be34a77bdba96 100644 --- a/compiler/rustc_const_eval/src/interpret/cast.rs +++ b/compiler/rustc_const_eval/src/interpret/cast.rs @@ -8,6 +8,7 @@ use rustc_middle::ty::adjustment::PointerCast; use rustc_middle::ty::layout::{IntegerExt, LayoutOf, TyAndLayout}; use rustc_middle::ty::{self, FloatTy, Ty, TypeAndMut}; use rustc_target::abi::{Integer, Variants}; +use rustc_type_ir::sty::TyKind::*; use super::{ util::ensure_monomorphic_enough, FnVal, ImmTy, Immediate, InterpCx, Machine, OpTy, PlaceTy, @@ -102,7 +103,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { src: &ImmTy<'tcx, M::PointerTag>, cast_ty: Ty<'tcx>, ) -> InterpResult<'tcx, Immediate> { - use rustc_middle::ty::TyKind::*; + use rustc_type_ir::sty::TyKind::*; trace!("Casting {:?}: {:?} to {:?}", *src, src.layout.ty, cast_ty); match src.layout.ty.kind() { @@ -205,7 +206,6 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let v = scalar.to_bits(src_layout.size)?; let v = if signed { self.sign_extend(v, src_layout) } else { v }; trace!("cast_from_scalar: {}, {} -> {}", v, src_layout.ty, cast_ty); - use rustc_middle::ty::TyKind::*; Ok(match *cast_ty.kind() { Int(_) | Uint(_) => { @@ -247,7 +247,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { where F: Float + Into> + FloatConvert + FloatConvert, { - use rustc_middle::ty::TyKind::*; + use rustc_type_ir::sty::TyKind::*; match *dest_ty.kind() { // float -> uint Uint(t) => { diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index 9317858aed909..6be78c52f99e3 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -2489,7 +2489,7 @@ impl<'tcx> LateLintPass<'tcx> for InvalidValue { ty: Ty<'tcx>, init: InitKind, ) -> Option { - use rustc_middle::ty::TyKind::*; + use rustc_type_ir::sty::TyKind::*; match ty.kind() { // Primitive types that don't like 0 as a value. Ref(..) => Some(("references must be non-null".to_string(), None)), @@ -2801,7 +2801,7 @@ impl ClashingExternDeclarations { true } else { // Do a full, depth-first comparison between the two. - use rustc_middle::ty::TyKind::*; + use rustc_type_ir::sty::TyKind::*; let a_kind = a.kind(); let b_kind = b.kind(); diff --git a/compiler/rustc_macros/src/serialize.rs b/compiler/rustc_macros/src/serialize.rs index 535158ffd8d84..653c728ee4293 100644 --- a/compiler/rustc_macros/src/serialize.rs +++ b/compiler/rustc_macros/src/serialize.rs @@ -8,7 +8,7 @@ pub fn type_decodable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2: if !s.ast().generics.lifetimes().any(|lt| lt.lifetime.ident == "tcx") { s.add_impl_generic(parse_quote! { 'tcx }); } - s.add_impl_generic(parse_quote! {#decoder_ty: ::rustc_middle::ty::codec::TyDecoder<'tcx>}); + s.add_impl_generic(parse_quote! {#decoder_ty: ::rustc_type_ir::codec::TyDecoder>}); s.add_bounds(synstructure::AddBounds::Generics); decodable_body(s, decoder_ty) @@ -95,7 +95,7 @@ pub fn type_encodable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2: s.add_impl_generic(parse_quote! {'tcx}); } let encoder_ty = quote! { __E }; - s.add_impl_generic(parse_quote! {#encoder_ty: ::rustc_middle::ty::codec::TyEncoder<'tcx>}); + s.add_impl_generic(parse_quote! {#encoder_ty: ::rustc_type_ir::codec::TyEncoder>}); s.add_bounds(synstructure::AddBounds::Generics); encodable_body(s, encoder_ty, false) diff --git a/compiler/rustc_middle/src/mir/interpret/mod.rs b/compiler/rustc_middle/src/mir/interpret/mod.rs index 16ef8d68be3a3..926afa8ccb6bb 100644 --- a/compiler/rustc_middle/src/mir/interpret/mod.rs +++ b/compiler/rustc_middle/src/mir/interpret/mod.rs @@ -115,7 +115,7 @@ use rustc_target::abi::Endian; use crate::mir; use crate::ty::codec::{TyDecoder, TyEncoder}; use crate::ty::subst::GenericArgKind; -use crate::ty::{self, Instance, Ty, TyCtxt}; +use crate::ty::{self, Instance, Ty, TyCtxt, TyInterner}; pub use self::error::{ struct_error, CheckInAllocMsg, ErrorHandled, EvalToAllocationRawResult, EvalToConstValueResult, @@ -203,7 +203,7 @@ enum AllocDiscriminant { Static, } -pub fn specialized_encode_alloc_id<'tcx, E: TyEncoder<'tcx>>( +pub fn specialized_encode_alloc_id<'tcx, E: TyEncoder>>( encoder: &mut E, tcx: TyCtxt<'tcx>, alloc_id: AllocId, @@ -277,7 +277,7 @@ impl<'s> AllocDecodingSession<'s> { /// Decodes an `AllocId` in a thread-safe way. pub fn decode_alloc_id<'tcx, D>(&self, decoder: &mut D) -> AllocId where - D: TyDecoder<'tcx>, + D: TyDecoder>, { // Read the index of the allocation. let idx = usize::try_from(decoder.read_u32()).unwrap(); @@ -305,7 +305,7 @@ impl<'s> AllocDecodingSession<'s> { AllocDiscriminant::Alloc => { // If this is an allocation, we need to reserve an // `AllocId` so we can decode cyclic graphs. - let alloc_id = decoder.tcx().reserve_alloc_id(); + let alloc_id = decoder.interner().tcx.reserve_alloc_id(); *entry = State::InProgress(TinyList::new_single(self.session_id), alloc_id); Some(alloc_id) @@ -349,7 +349,7 @@ impl<'s> AllocDecodingSession<'s> { // We already have a reserved `AllocId`. let alloc_id = alloc_id.unwrap(); trace!("decoded alloc {:?}: {:#?}", alloc_id, alloc); - decoder.tcx().set_alloc_id_same_memory(alloc_id, alloc); + decoder.interner().tcx.set_alloc_id_same_memory(alloc_id, alloc); alloc_id } AllocDiscriminant::Fn => { @@ -357,7 +357,7 @@ impl<'s> AllocDecodingSession<'s> { trace!("creating fn alloc ID"); let instance = ty::Instance::decode(decoder); trace!("decoded fn alloc instance: {:?}", instance); - let alloc_id = decoder.tcx().create_fn_alloc(instance); + let alloc_id = decoder.interner().tcx.create_fn_alloc(instance); alloc_id } AllocDiscriminant::Static => { @@ -365,7 +365,7 @@ impl<'s> AllocDecodingSession<'s> { trace!("creating extern static alloc ID"); let did = >::decode(decoder); trace!("decoded static def-ID: {:?}", did); - let alloc_id = decoder.tcx().create_static_alloc(did); + let alloc_id = decoder.interner().tcx.create_static_alloc(did); alloc_id } } diff --git a/compiler/rustc_middle/src/mir/mod.rs b/compiler/rustc_middle/src/mir/mod.rs index 9f8b22c8afc47..71cea005cf858 100644 --- a/compiler/rustc_middle/src/mir/mod.rs +++ b/compiler/rustc_middle/src/mir/mod.rs @@ -668,7 +668,7 @@ impl ClearCrossCrate { const TAG_CLEAR_CROSS_CRATE_CLEAR: u8 = 0; const TAG_CLEAR_CROSS_CRATE_SET: u8 = 1; -impl<'tcx, E: TyEncoder<'tcx>, T: Encodable> Encodable for ClearCrossCrate { +impl> Encodable for ClearCrossCrate { #[inline] fn encode(&self, e: &mut E) -> Result<(), E::Error> { if E::CLEAR_CROSS_CRATE { @@ -684,7 +684,7 @@ impl<'tcx, E: TyEncoder<'tcx>, T: Encodable> Encodable for ClearCrossCrate } } } -impl<'tcx, D: TyDecoder<'tcx>, T: Decodable> Decodable for ClearCrossCrate { +impl> Decodable for ClearCrossCrate { #[inline] fn decode(d: &mut D) -> ClearCrossCrate { if D::CLEAR_CROSS_CRATE { diff --git a/compiler/rustc_middle/src/ty/codec.rs b/compiler/rustc_middle/src/ty/codec.rs index 2a5191008a9ef..234649f1056c7 100644 --- a/compiler/rustc_middle/src/ty/codec.rs +++ b/compiler/rustc_middle/src/ty/codec.rs @@ -15,10 +15,12 @@ use crate::mir::{ use crate::thir; use crate::traits; use crate::ty::subst::SubstsRef; -use crate::ty::{self, AdtDef, Ty, TyCtxt}; +use crate::ty::{self, AdtDef, Ty}; use rustc_data_structures::fx::FxHashMap; -use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; +use rustc_serialize::{Decodable, Encodable}; +use rustc_middle::ty::TyInterner; use rustc_span::Span; +pub use rustc_type_ir::{TyDecoder, TyEncoder}; use std::hash::Hash; use std::intrinsics; use std::marker::DiscriminantKind; @@ -28,13 +30,13 @@ use std::marker::DiscriminantKind; /// This offset is also chosen so that the first byte is never < 0x80. pub const SHORTHAND_OFFSET: usize = 0x80; -pub trait EncodableWithShorthand<'tcx, E: TyEncoder<'tcx>>: Copy + Eq + Hash { +pub trait EncodableWithShorthand: Copy + Eq + Hash { type Variant: Encodable; fn variant(&self) -> &Self::Variant; } #[allow(rustc::usage_of_ty_tykind)] -impl<'tcx, E: TyEncoder<'tcx>> EncodableWithShorthand<'tcx, E> for Ty<'tcx> { +impl<'tcx, E: TyEncoder>> EncodableWithShorthand for Ty<'tcx> { type Variant = ty::TyKind<'tcx>; #[inline] @@ -43,7 +45,9 @@ impl<'tcx, E: TyEncoder<'tcx>> EncodableWithShorthand<'tcx, E> for Ty<'tcx> { } } -impl<'tcx, E: TyEncoder<'tcx>> EncodableWithShorthand<'tcx, E> for ty::PredicateKind<'tcx> { +impl<'tcx, E: TyEncoder>> EncodableWithShorthand + for ty::PredicateKind<'tcx> +{ type Variant = ty::PredicateKind<'tcx>; #[inline] @@ -52,15 +56,6 @@ impl<'tcx, E: TyEncoder<'tcx>> EncodableWithShorthand<'tcx, E> for ty::Predicate } } -pub trait TyEncoder<'tcx>: Encoder { - const CLEAR_CROSS_CRATE: bool; - - fn position(&self) -> usize; - fn type_shorthands(&mut self) -> &mut FxHashMap, usize>; - fn predicate_shorthands(&mut self) -> &mut FxHashMap, usize>; - fn encode_alloc_id(&mut self, alloc_id: &AllocId) -> Result<(), Self::Error>; -} - /// Trait for decoding to a reference. /// /// This is a separate trait from `Decodable` so that we can implement it for @@ -71,7 +66,7 @@ pub trait TyEncoder<'tcx>: Encoder { /// /// `Decodable` can still be implemented in cases where `Decodable` is required /// by a trait bound. -pub trait RefDecodable<'tcx, D: TyDecoder<'tcx>> { +pub trait RefDecodable<'tcx, D: TyDecoder>> { fn decode(d: &mut D) -> &'tcx Self; } @@ -82,9 +77,9 @@ pub fn encode_with_shorthand<'tcx, E, T, M>( cache: M, ) -> Result<(), E::Error> where - E: TyEncoder<'tcx>, + E: TyEncoder>, M: for<'b> Fn(&'b mut E) -> &'b mut FxHashMap, - T: EncodableWithShorthand<'tcx, E>, + T: EncodableWithShorthand, // The discriminant and shorthand must have the same size. T::Variant: DiscriminantKind, { @@ -119,100 +114,105 @@ where Ok(()) } -impl<'tcx, E: TyEncoder<'tcx>> Encodable for Ty<'tcx> { +impl<'tcx, E: TyEncoder>> Encodable for Ty<'tcx> { fn encode(&self, e: &mut E) -> Result<(), E::Error> { encode_with_shorthand(e, self, TyEncoder::type_shorthands) } } -impl<'tcx, E: TyEncoder<'tcx>> Encodable for ty::Binder<'tcx, ty::PredicateKind<'tcx>> { +impl<'tcx, E: TyEncoder>> Encodable + for ty::Binder<'tcx, ty::PredicateKind<'tcx>> +{ fn encode(&self, e: &mut E) -> Result<(), E::Error> { self.bound_vars().encode(e)?; encode_with_shorthand(e, &self.skip_binder(), TyEncoder::predicate_shorthands) } } -impl<'tcx, E: TyEncoder<'tcx>> Encodable for ty::Predicate<'tcx> { +impl<'tcx, E: TyEncoder>> Encodable for ty::Predicate<'tcx> { fn encode(&self, e: &mut E) -> Result<(), E::Error> { self.kind().encode(e) } } -impl<'tcx, E: TyEncoder<'tcx>> Encodable for ty::Region<'tcx> { +impl<'tcx, E: TyEncoder>> Encodable for ty::Region<'tcx> { fn encode(&self, e: &mut E) -> Result<(), E::Error> { self.kind().encode(e) } } -impl<'tcx, E: TyEncoder<'tcx>> Encodable for ty::Const<'tcx> { +impl<'tcx, E: TyEncoder>> Encodable for ty::Const<'tcx> { fn encode(&self, e: &mut E) -> Result<(), E::Error> { self.0.0.encode(e) } } -impl<'tcx, E: TyEncoder<'tcx>> Encodable for ConstAllocation<'tcx> { +impl<'tcx, E: TyEncoder>> Encodable for ConstAllocation<'tcx> { fn encode(&self, e: &mut E) -> Result<(), E::Error> { self.inner().encode(e) } } -impl<'tcx, E: TyEncoder<'tcx>> Encodable for AdtDef<'tcx> { +impl<'tcx, E: TyEncoder>> Encodable for AdtDef<'tcx> { fn encode(&self, e: &mut E) -> Result<(), E::Error> { self.0.0.encode(e) } } -impl<'tcx, E: TyEncoder<'tcx>> Encodable for AllocId { +impl<'tcx, E: TyEncoder>> Encodable for AllocId { fn encode(&self, e: &mut E) -> Result<(), E::Error> { e.encode_alloc_id(self) } } -pub trait TyDecoder<'tcx>: Decoder { - const CLEAR_CROSS_CRATE: bool; - - fn tcx(&self) -> TyCtxt<'tcx>; - - fn peek_byte(&self) -> u8; - - fn position(&self) -> usize; - - fn cached_ty_for_shorthand(&mut self, shorthand: usize, or_insert_with: F) -> Ty<'tcx> - where - F: FnOnce(&mut Self) -> Ty<'tcx>; - - fn with_position(&mut self, pos: usize, f: F) -> R - where - F: FnOnce(&mut Self) -> R; - - fn positioned_at_shorthand(&self) -> bool { - (self.peek_byte() & (SHORTHAND_OFFSET as u8)) != 0 +macro_rules! encodable_via_deref { + ($($t:ty),+) => { + $(impl<'tcx, E: TyEncoder>> Encodable for $t { + fn encode(&self, e: &mut E) -> Result<(), E::Error> { + (**self).encode(e) + } + })* } +} - fn decode_alloc_id(&mut self) -> AllocId; +encodable_via_deref! { + &'tcx ty::TypeckResults<'tcx>, + &'tcx traits::ImplSource<'tcx, ()>, + &'tcx mir::Body<'tcx>, + &'tcx mir::UnsafetyCheckResult, + &'tcx mir::BorrowCheckResult<'tcx>, + &'tcx mir::coverage::CodeRegion } #[inline] -fn decode_arena_allocable<'tcx, D, T: ArenaAllocatable<'tcx> + Decodable>( +fn decode_arena_allocable< + 'tcx, + D: TyDecoder>, + T: ArenaAllocatable<'tcx> + Decodable, +>( decoder: &mut D, ) -> &'tcx T where - D: TyDecoder<'tcx>, + D: TyDecoder, { - decoder.tcx().arena.alloc(Decodable::decode(decoder)) + decoder.interner().tcx.arena.alloc(Decodable::decode(decoder)) } #[inline] -fn decode_arena_allocable_slice<'tcx, D, T: ArenaAllocatable<'tcx> + Decodable>( +fn decode_arena_allocable_slice< + 'tcx, + D: TyDecoder>, + T: ArenaAllocatable<'tcx> + Decodable, +>( decoder: &mut D, ) -> &'tcx [T] where - D: TyDecoder<'tcx>, + D: TyDecoder, { - decoder.tcx().arena.alloc_from_iter( as Decodable>::decode(decoder)) + decoder.interner().tcx.arena.alloc_from_iter( as Decodable>::decode(decoder)) } -impl<'tcx, D: TyDecoder<'tcx>> Decodable for Ty<'tcx> { +impl<'tcx, D: TyDecoder>> Decodable for Ty<'tcx> { #[allow(rustc::usage_of_ty_tykind)] fn decode(decoder: &mut D) -> Ty<'tcx> { // Handle shorthands first, if we have a usize > 0x80. @@ -225,13 +225,13 @@ impl<'tcx, D: TyDecoder<'tcx>> Decodable for Ty<'tcx> { decoder.with_position(shorthand, Ty::decode) }) } else { - let tcx = decoder.tcx(); - tcx.mk_ty(ty::TyKind::decode(decoder)) + let tcx = decoder.interner().tcx; + tcx.mk_ty(rustc_type_ir::TyKind::decode(decoder)) } } } -impl<'tcx, D: TyDecoder<'tcx>> Decodable for ty::Binder<'tcx, ty::PredicateKind<'tcx>> { +impl<'tcx, D: TyDecoder>> Decodable for ty::Binder<'tcx, ty::PredicateKind<'tcx>> { fn decode(decoder: &mut D) -> ty::Binder<'tcx, ty::PredicateKind<'tcx>> { let bound_vars = Decodable::decode(decoder); // Handle shorthands first, if we have a usize > 0x80. @@ -250,64 +250,64 @@ impl<'tcx, D: TyDecoder<'tcx>> Decodable for ty::Binder<'tcx, ty::PredicateKi } } -impl<'tcx, D: TyDecoder<'tcx>> Decodable for ty::Predicate<'tcx> { +impl<'tcx, D: TyDecoder>> Decodable for ty::Predicate<'tcx> { fn decode(decoder: &mut D) -> ty::Predicate<'tcx> { let predicate_kind = Decodable::decode(decoder); - decoder.tcx().mk_predicate(predicate_kind) + decoder.interner().tcx.mk_predicate(predicate_kind) } } -impl<'tcx, D: TyDecoder<'tcx>> Decodable for SubstsRef<'tcx> { +impl<'tcx, D: TyDecoder>> Decodable for SubstsRef<'tcx> { fn decode(decoder: &mut D) -> Self { let len = decoder.read_usize(); - let tcx = decoder.tcx(); + let tcx = decoder.interner().tcx; tcx.mk_substs( (0..len).map::, _>(|_| Decodable::decode(decoder)), ) } } -impl<'tcx, D: TyDecoder<'tcx>> Decodable for mir::Place<'tcx> { +impl<'tcx, D: TyDecoder>> Decodable for mir::Place<'tcx> { fn decode(decoder: &mut D) -> Self { let local: mir::Local = Decodable::decode(decoder); let len = decoder.read_usize(); - let projection = decoder.tcx().mk_place_elems( + let projection = decoder.interner().tcx.mk_place_elems( (0..len).map::, _>(|_| Decodable::decode(decoder)), ); mir::Place { local, projection } } } -impl<'tcx, D: TyDecoder<'tcx>> Decodable for ty::Region<'tcx> { +impl<'tcx, D: TyDecoder>> Decodable for ty::Region<'tcx> { fn decode(decoder: &mut D) -> Self { - decoder.tcx().mk_region(Decodable::decode(decoder)) + decoder.interner().tcx.mk_region(Decodable::decode(decoder)) } } -impl<'tcx, D: TyDecoder<'tcx>> Decodable for CanonicalVarInfos<'tcx> { +impl<'tcx, D: TyDecoder>> Decodable for CanonicalVarInfos<'tcx> { fn decode(decoder: &mut D) -> Self { let len = decoder.read_usize(); let interned: Vec> = (0..len).map(|_| Decodable::decode(decoder)).collect(); - decoder.tcx().intern_canonical_var_infos(interned.as_slice()) + decoder.interner().tcx.intern_canonical_var_infos(interned.as_slice()) } } -impl<'tcx, D: TyDecoder<'tcx>> Decodable for AllocId { +impl<'tcx, D: TyDecoder>> Decodable for AllocId { fn decode(decoder: &mut D) -> Self { decoder.decode_alloc_id() } } -impl<'tcx, D: TyDecoder<'tcx>> Decodable for ty::SymbolName<'tcx> { +impl<'tcx, D: TyDecoder>> Decodable for ty::SymbolName<'tcx> { fn decode(decoder: &mut D) -> Self { - ty::SymbolName::new(decoder.tcx(), &decoder.read_str()) + ty::SymbolName::new(decoder.interner().tcx, &decoder.read_str()) } } macro_rules! impl_decodable_via_ref { ($($t:ty),+) => { - $(impl<'tcx, D: TyDecoder<'tcx>> Decodable for $t { + $(impl<'tcx, D: TyDecoder>> Decodable for $t { fn decode(decoder: &mut D) -> Self { RefDecodable::decode(decoder) } @@ -315,78 +315,78 @@ macro_rules! impl_decodable_via_ref { } } -impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::List> { +impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for ty::List> { fn decode(decoder: &mut D) -> &'tcx Self { let len = decoder.read_usize(); - decoder.tcx().mk_type_list((0..len).map::, _>(|_| Decodable::decode(decoder))) + decoder.interner().tcx.mk_type_list((0..len).map::, _>(|_| Decodable::decode(decoder))) } } -impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> +impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for ty::List>> { fn decode(decoder: &mut D) -> &'tcx Self { let len = decoder.read_usize(); - decoder.tcx().mk_poly_existential_predicates( + decoder.interner().tcx.mk_poly_existential_predicates( (0..len).map::, _>(|_| Decodable::decode(decoder)), ) } } -impl<'tcx, D: TyDecoder<'tcx>> Decodable for ty::Const<'tcx> { +impl<'tcx, D: TyDecoder>> Decodable for ty::Const<'tcx> { fn decode(decoder: &mut D) -> Self { - decoder.tcx().mk_const(Decodable::decode(decoder)) + decoder.interner().tcx.mk_const(Decodable::decode(decoder)) } } -impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [ty::ValTree<'tcx>] { +impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for [ty::ValTree<'tcx>] { fn decode(decoder: &mut D) -> &'tcx Self { - decoder.tcx().arena.alloc_from_iter( + decoder.interner().tcx.arena.alloc_from_iter( (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::>(), ) } } -impl<'tcx, D: TyDecoder<'tcx>> Decodable for ConstAllocation<'tcx> { +impl<'tcx, D: TyDecoder>> Decodable for ConstAllocation<'tcx> { fn decode(decoder: &mut D) -> Self { - decoder.tcx().intern_const_alloc(Decodable::decode(decoder)) + decoder.interner().tcx.intern_const_alloc(Decodable::decode(decoder)) } } -impl<'tcx, D: TyDecoder<'tcx>> Decodable for AdtDef<'tcx> { +impl<'tcx, D: TyDecoder>> Decodable for AdtDef<'tcx> { fn decode(decoder: &mut D) -> Self { - decoder.tcx().intern_adt_def(Decodable::decode(decoder)) + decoder.interner().tcx.intern_adt_def(Decodable::decode(decoder)) } } -impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [(ty::Predicate<'tcx>, Span)] { +impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for [(ty::Predicate<'tcx>, Span)] { fn decode(decoder: &mut D) -> &'tcx Self { - decoder.tcx().arena.alloc_from_iter( + decoder.interner().tcx.arena.alloc_from_iter( (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::>(), ) } } -impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [thir::abstract_const::Node<'tcx>] { +impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for [thir::abstract_const::Node<'tcx>] { fn decode(decoder: &mut D) -> &'tcx Self { - decoder.tcx().arena.alloc_from_iter( + decoder.interner().tcx.arena.alloc_from_iter( (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::>(), ) } } -impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [thir::abstract_const::NodeId] { +impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for [thir::abstract_const::NodeId] { fn decode(decoder: &mut D) -> &'tcx Self { - decoder.tcx().arena.alloc_from_iter( + decoder.interner().tcx.arena.alloc_from_iter( (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::>(), ) } } -impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::List { +impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for ty::List { fn decode(decoder: &mut D) -> &'tcx Self { let len = decoder.read_usize(); - decoder.tcx().mk_bound_variable_kinds( + decoder.interner().tcx.mk_bound_variable_kinds( (0..len).map::(|_| Decodable::decode(decoder)), ) } @@ -420,14 +420,14 @@ macro_rules! impl_arena_allocatable_decoder { ([]$args:tt) => {}; ([decode $(, $attrs:ident)*] [$name:ident: $ty:ty]) => { - impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for $ty { + impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for $ty { #[inline] fn decode(decoder: &mut D) -> &'tcx Self { decode_arena_allocable(decoder) } } - impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [$ty] { + impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for [$ty] { #[inline] fn decode(decoder: &mut D) -> &'tcx Self { decode_arena_allocable_slice(decoder) @@ -518,13 +518,13 @@ macro_rules! implement_ty_decoder { macro_rules! impl_binder_encode_decode { ($($t:ty),+ $(,)?) => { $( - impl<'tcx, E: TyEncoder<'tcx>> Encodable for ty::Binder<'tcx, $t> { + impl<'tcx, E: TyEncoder>> Encodable for ty::Binder<'tcx, $t> { fn encode(&self, e: &mut E) -> Result<(), E::Error> { self.bound_vars().encode(e)?; self.as_ref().skip_binder().encode(e) } } - impl<'tcx, D: TyDecoder<'tcx>> Decodable for ty::Binder<'tcx, $t> { + impl<'tcx, D: TyDecoder>> Decodable for ty::Binder<'tcx, $t> { fn decode(decoder: &mut D) -> Self { let bound_vars = Decodable::decode(decoder); ty::Binder::bind_with_vars(Decodable::decode(decoder), bound_vars) diff --git a/compiler/rustc_middle/src/ty/consts.rs b/compiler/rustc_middle/src/ty/consts.rs index 7af7eb4f5ecfd..58a237ee6f825 100644 --- a/compiler/rustc_middle/src/ty/consts.rs +++ b/compiler/rustc_middle/src/ty/consts.rs @@ -2,7 +2,7 @@ use crate::mir::interpret::ConstValue; use crate::mir::interpret::{LitToConstInput, Scalar}; use crate::ty::{ self, InlineConstSubsts, InlineConstSubstsParts, InternalSubsts, ParamEnv, ParamEnvAnd, Ty, - TyCtxt, TypeFoldable, + TyCtxt, TyInterner, TypeFoldable, }; use rustc_data_structures::intern::Interned; use rustc_errors::ErrorGuaranteed; @@ -40,6 +40,14 @@ pub struct ConstS<'tcx> { pub val: ConstKind<'tcx>, } +impl<'tcx, S: rustc_type_ir::TyEncoder>> rustc_serialize::Encodable + for &'_ Const<'_> +{ + fn encode(&self, s: &mut S) -> Result<(), S::Error> { + (*self).encode(s) + } +} + #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] static_assert_size!(ConstS<'_>, 48); diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 3c08db5dc6814..efe7a54b5bf1c 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -16,7 +16,6 @@ use crate::thir::Thir; use crate::traits; use crate::ty::query::{self, TyCtxtAt}; use crate::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, Subst, SubstsRef, UserSubsts}; -use crate::ty::TyKind::*; use crate::ty::{ self, AdtDef, AdtDefData, AdtKind, Binder, BindingMode, BoundVar, CanonicalPolyFnSig, ClosureSizeProfileData, Const, ConstS, ConstVid, DefIdTree, ExistentialPredicate, FloatTy, @@ -60,9 +59,9 @@ use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::{Span, DUMMY_SP}; use rustc_target::abi::{Layout, LayoutS, TargetDataLayout, VariantIdx}; use rustc_target::spec::abi; +use rustc_type_ir::sty::TyKind::*; +use rustc_type_ir::{InternAs, InternIteratorElement, Interner, TypeFlags}; -use rustc_type_ir::TypeFlags; -use smallvec::SmallVec; use std::any::Any; use std::borrow::Borrow; use std::cmp::Ordering; @@ -91,6 +90,70 @@ pub trait OnDiskCache<'tcx>: rustc_data_structures::sync::Sync { fn serialize(&self, tcx: TyCtxt<'tcx>, encoder: &mut FileEncoder) -> FileEncodeResult; } +pub struct TyInterner<'tcx> { + pub tcx: TyCtxt<'tcx>, +} + +/// We don't ever actually need this. It's only required for derives. +impl<'tcx> Hash for TyInterner<'tcx> { + fn hash(&self, _state: &mut H) {} +} + +/// We don't ever actually need this. It's only required for derives. +impl<'tcx> Ord for TyInterner<'tcx> { + fn cmp(&self, _other: &Self) -> Ordering { + Ordering::Equal + } +} + +/// We don't ever actually need this. It's only required for derives. +impl<'tcx> PartialOrd for TyInterner<'tcx> { + fn partial_cmp(&self, _other: &Self) -> Option { + None + } +} + +/// We don't ever actually need this. It's only required for derives. +impl<'tcx> PartialEq for TyInterner<'tcx> { + fn eq(&self, _other: &Self) -> bool { + false + } +} + +/// We don't ever actually need this. It's only required for derives. +impl<'tcx> Eq for TyInterner<'tcx> {} + +impl fmt::Debug for TyInterner<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "TyInterner") + } +} + +#[allow(rustc::usage_of_ty_tykind)] +impl<'tcx> Interner for TyInterner<'tcx> { + type AdtDef = ty::AdtDef<'tcx>; + type SubstsRef = ty::SubstsRef<'tcx>; + type DefId = DefId; + type Ty = Ty<'tcx>; + type Const = ty::Const<'tcx>; + type Region = Region<'tcx>; + type TypeAndMut = TypeAndMut<'tcx>; + type Mutability = hir::Mutability; + type Movability = hir::Movability; + type PolyFnSig = PolyFnSig<'tcx>; + type ListBinderExistentialPredicate = &'tcx List>>; + type BinderListTy = Binder<'tcx, &'tcx List>>; + type ListTy = &'tcx List>; + type ProjectionTy = ty::ProjectionTy<'tcx>; + type ParamTy = ParamTy; + type BoundTy = ty::BoundTy; + type PlaceholderType = ty::PlaceholderType; + type InferTy = InferTy; + type DelaySpanBugEmitted = DelaySpanBugEmitted; + type PredicateKind = ty::PredicateKind<'tcx>; + type AllocId = crate::mir::interpret::AllocId; +} + /// A type that is not publicly constructable. This prevents people from making [`TyKind::Error`]s /// except through the error-reporting functions on a [`tcx`][TyCtxt]. #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)] @@ -1075,6 +1138,10 @@ pub struct GlobalCtxt<'tcx> { } impl<'tcx> TyCtxt<'tcx> { + pub fn interner(self) -> TyInterner<'tcx> { + TyInterner { tcx: self } + } + /// Expects a body and returns its codegen attributes. /// /// Unlike `codegen_fn_attrs`, this returns `CodegenFnAttrs::EMPTY` for @@ -2848,108 +2915,6 @@ impl<'tcx> TyCtxtAt<'tcx> { } } -pub trait InternAs { - type Output; - fn intern_with(self, f: F) -> Self::Output - where - F: FnOnce(&T) -> R; -} - -impl InternAs<[T], R> for I -where - E: InternIteratorElement, - I: Iterator, -{ - type Output = E::Output; - fn intern_with(self, f: F) -> Self::Output - where - F: FnOnce(&[T]) -> R, - { - E::intern_with(self, f) - } -} - -pub trait InternIteratorElement: Sized { - type Output; - fn intern_with, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output; -} - -impl InternIteratorElement for T { - type Output = R; - fn intern_with, F: FnOnce(&[T]) -> R>( - mut iter: I, - f: F, - ) -> Self::Output { - // This code is hot enough that it's worth specializing for the most - // common length lists, to avoid the overhead of `SmallVec` creation. - // Lengths 0, 1, and 2 typically account for ~95% of cases. If - // `size_hint` is incorrect a panic will occur via an `unwrap` or an - // `assert`. - match iter.size_hint() { - (0, Some(0)) => { - assert!(iter.next().is_none()); - f(&[]) - } - (1, Some(1)) => { - let t0 = iter.next().unwrap(); - assert!(iter.next().is_none()); - f(&[t0]) - } - (2, Some(2)) => { - let t0 = iter.next().unwrap(); - let t1 = iter.next().unwrap(); - assert!(iter.next().is_none()); - f(&[t0, t1]) - } - _ => f(&iter.collect::>()), - } - } -} - -impl<'a, T, R> InternIteratorElement for &'a T -where - T: Clone + 'a, -{ - type Output = R; - fn intern_with, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output { - // This code isn't hot. - f(&iter.cloned().collect::>()) - } -} - -impl InternIteratorElement for Result { - type Output = Result; - fn intern_with, F: FnOnce(&[T]) -> R>( - mut iter: I, - f: F, - ) -> Self::Output { - // This code is hot enough that it's worth specializing for the most - // common length lists, to avoid the overhead of `SmallVec` creation. - // Lengths 0, 1, and 2 typically account for ~95% of cases. If - // `size_hint` is incorrect a panic will occur via an `unwrap` or an - // `assert`, unless a failure happens first, in which case the result - // will be an error anyway. - Ok(match iter.size_hint() { - (0, Some(0)) => { - assert!(iter.next().is_none()); - f(&[]) - } - (1, Some(1)) => { - let t0 = iter.next().unwrap()?; - assert!(iter.next().is_none()); - f(&[t0]) - } - (2, Some(2)) => { - let t0 = iter.next().unwrap()?; - let t1 = iter.next().unwrap()?; - assert!(iter.next().is_none()); - f(&[t0, t1]) - } - _ => f(&iter.collect::, _>>()?), - }) - } -} - // We are comparing types with different invariant lifetimes, so `ptr::eq` // won't work for us. fn ptr_eq(t: *const T, u: *const U) -> bool { diff --git a/compiler/rustc_middle/src/ty/diagnostics.rs b/compiler/rustc_middle/src/ty/diagnostics.rs index a671774697919..462fc27009de9 100644 --- a/compiler/rustc_middle/src/ty/diagnostics.rs +++ b/compiler/rustc_middle/src/ty/diagnostics.rs @@ -1,7 +1,6 @@ //! Diagnostics related methods for `Ty`. use crate::ty::subst::{GenericArg, GenericArgKind}; -use crate::ty::TyKind::*; use crate::ty::{ ConstKind, DefIdTree, ExistentialPredicate, ExistentialProjection, ExistentialTraitRef, InferTy, ProjectionTy, Term, Ty, TyCtxt, TypeAndMut, @@ -13,6 +12,7 @@ use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_hir::WherePredicate; use rustc_span::Span; +use rustc_type_ir::sty::TyKind::*; impl<'tcx> IntoDiagnosticArg for Ty<'tcx> { fn into_diagnostic_arg(self) -> DiagnosticArgValue<'static> { diff --git a/compiler/rustc_middle/src/ty/inhabitedness/mod.rs b/compiler/rustc_middle/src/ty/inhabitedness/mod.rs index b8088766cca68..3d22f5a04a2bf 100644 --- a/compiler/rustc_middle/src/ty/inhabitedness/mod.rs +++ b/compiler/rustc_middle/src/ty/inhabitedness/mod.rs @@ -2,11 +2,12 @@ pub use self::def_id_forest::DefIdForest; use crate::ty; use crate::ty::context::TyCtxt; -use crate::ty::TyKind::*; use crate::ty::{AdtDef, FieldDef, Ty, VariantDef}; use crate::ty::{AdtKind, Visibility}; use crate::ty::{DefId, SubstsRef}; +use rustc_type_ir::sty::TyKind::*; + mod def_id_forest; // The methods in this module calculate `DefIdForest`s of modules in which an diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index b61a3827602fa..2804912c9ab8a 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -51,6 +51,7 @@ use std::{fmt, str}; pub use crate::ty::diagnostics::*; pub use rustc_type_ir::InferTy::*; +pub use rustc_type_ir::TyKind::*; pub use rustc_type_ir::*; pub use self::binding::BindingMode; @@ -67,7 +68,7 @@ pub use self::consts::{ pub use self::context::{ tls, CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, CtxtInterners, DelaySpanBugEmitted, FreeRegionInfo, GeneratorDiagnosticData, - GeneratorInteriorTypeCause, GlobalCtxt, Lift, OnDiskCache, TyCtxt, TypeckResults, UserType, + GeneratorInteriorTypeCause, GlobalCtxt, Lift, OnDiskCache, TyCtxt, TyInterner, TypeckResults, UserType, UserTypeAnnotationIndex, }; pub use self::instance::{Instance, InstanceDef}; @@ -76,7 +77,6 @@ pub use self::parameterized::ParameterizedOverTcx; pub use self::rvalue_scopes::RvalueScopes; pub use self::sty::BoundRegionKind::*; pub use self::sty::RegionKind::*; -pub use self::sty::TyKind::*; pub use self::sty::{ Binder, BoundRegion, BoundRegionKind, BoundTy, BoundTyKind, BoundVar, BoundVariableKind, CanonicalPolyFnSig, ClosureSubsts, ClosureSubstsParts, ConstVid, EarlyBinder, EarlyBoundRegion, @@ -449,13 +449,13 @@ pub(crate) struct TyS<'tcx> { } // `TyS` is used a lot. Make sure it doesn't unintentionally get bigger. -#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] -static_assert_size!(TyS<'_>, 40); +//#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] +//static_assert_size!(TyS<'_>, 40); // We are actually storing a stable hash cache next to the type, so let's // also check the full size -#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] -static_assert_size!(WithStableHash>, 56); +//#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] +//static_assert_size!(WithStableHash>, 56); /// Use this rather than `TyS`, whenever possible. #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable)] diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index 2dabc69638841..314d0ef277136 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -2,16 +2,14 @@ #![allow(rustc::usage_of_ty_tykind)] -use self::TyKind::*; - use crate::infer::canonical::Canonical; use crate::ty::fold::ValidateBoundVars; use crate::ty::subst::{GenericArg, InternalSubsts, Subst, SubstsRef}; -use crate::ty::InferTy::{self, *}; +use crate::ty::InferTy::*; use crate::ty::{ self, AdtDef, DefIdTree, Discr, Term, Ty, TyCtxt, TypeFlags, TypeFoldable, TypeVisitor, }; -use crate::ty::{DelaySpanBugEmitted, List, ParamEnv}; +use crate::ty::{List, ParamEnv}; use polonius_engine::Atom; use rustc_data_structures::captures::Captures; use rustc_data_structures::intern::Interned; @@ -29,6 +27,10 @@ use std::marker::PhantomData; use std::ops::{ControlFlow, Deref, Range}; use ty::util::IntTypeExt; +use rustc_type_ir::TyKind as IrTyKind; +pub type TyKind<'tcx> = IrTyKind>; +use rustc_type_ir::sty::TyKind::*; + #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] #[derive(HashStable, TypeFoldable, Lift)] pub struct TypeAndMut<'tcx> { @@ -78,6 +80,7 @@ impl BoundRegionKind { } } +/* /// Defines the kinds of types used by the type system. /// /// Types written by the user start out as [hir::TyKind](rustc_hir::TyKind) and get @@ -253,7 +256,9 @@ pub enum TyKind<'tcx> { /// propagated to avoid useless error messages. Error(DelaySpanBugEmitted), } +*/ +/* impl<'tcx> TyKind<'tcx> { #[inline] pub fn is_primitive(&self) -> bool { @@ -272,6 +277,25 @@ impl<'tcx> TyKind<'tcx> { } } } +*/ + +pub trait Article { + fn article(&self) -> &'static str; +} + +impl<'tcx> Article for TyKind<'tcx> { + /// Get the article ("a" or "an") to use with this type. + fn article(&self) -> &'static str { + match self { + Int(_) | Float(_) | Array(_, _) => "an", + Adt(def, _) if def.is_enum() => "an", + // This should never happen, but ICEing and causing the user's code + // to not compile felt too harsh. + Error(_) => "a", + _ => "a", + } + } +} // `TyKind` is used a lot. Make sure it doesn't unintentionally get bigger. #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] @@ -930,7 +954,9 @@ impl<'tcx> List>> { } #[inline] - pub fn auto_traits<'a>(&'a self) -> impl Iterator + 'a { + pub fn auto_traits<'a>( + &'a self, + ) -> impl Iterator + rustc_data_structures::captures::Captures<'tcx> + 'a { self.iter().filter_map(|predicate| match predicate.skip_binder() { ExistentialPredicate::AutoTrait(did) => Some(did), _ => None, diff --git a/compiler/rustc_middle/src/ty/subst.rs b/compiler/rustc_middle/src/ty/subst.rs index 31a318cc68f44..e50179face0ad 100644 --- a/compiler/rustc_middle/src/ty/subst.rs +++ b/compiler/rustc_middle/src/ty/subst.rs @@ -4,7 +4,7 @@ use crate::mir; use crate::ty::codec::{TyDecoder, TyEncoder}; use crate::ty::fold::{FallibleTypeFolder, TypeFoldable, TypeFolder, TypeVisitor}; use crate::ty::sty::{ClosureSubsts, GeneratorSubsts, InlineConstSubsts}; -use crate::ty::{self, EarlyBinder, Lift, List, ParamConst, Ty, TyCtxt}; +use crate::ty::{self, Lift, List, ParamConst, Ty, TyCtxt, TyInterner}; use rustc_data_structures::intern::{Interned, WithStableHash}; use rustc_hir::def_id::DefId; @@ -216,13 +216,13 @@ impl<'tcx> TypeFoldable<'tcx> for GenericArg<'tcx> { } } -impl<'tcx, E: TyEncoder<'tcx>> Encodable for GenericArg<'tcx> { +impl<'tcx, E: TyEncoder>> Encodable for GenericArg<'tcx> { fn encode(&self, e: &mut E) -> Result<(), E::Error> { self.unpack().encode(e) } } -impl<'tcx, D: TyDecoder<'tcx>> Decodable for GenericArg<'tcx> { +impl<'tcx, D: TyDecoder>> Decodable for GenericArg<'tcx> { fn decode(d: &mut D) -> GenericArg<'tcx> { GenericArgKind::decode(d).pack() } @@ -506,7 +506,7 @@ pub trait Subst<'tcx>: Sized { fn subst(self, tcx: TyCtxt<'tcx>, substs: &[GenericArg<'tcx>]) -> Self::Inner; } -impl<'tcx, T: TypeFoldable<'tcx>> Subst<'tcx> for EarlyBinder { +impl<'tcx, T: TypeFoldable<'tcx>> Subst<'tcx> for ty::EarlyBinder { type Inner = T; fn subst(self, tcx: TyCtxt<'tcx>, substs: &[GenericArg<'tcx>]) -> Self::Inner { diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index 809e7ce2e745b..084c47a1dc4ba 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -5,7 +5,9 @@ use crate::ty::fold::{FallibleTypeFolder, TypeFolder}; use crate::ty::layout::IntegerExt; use crate::ty::query::TyCtxtAt; use crate::ty::subst::{GenericArgKind, Subst, SubstsRef}; -use crate::ty::{self, DefIdTree, Ty, TyCtxt, TypeFoldable}; +use crate::ty::{ + self, Const, DebruijnIndex, DefIdTree, List, ReEarlyBound, Ty, TyCtxt, TypeFoldable, +}; use rustc_apfloat::Float as _; use rustc_ast as ast; use rustc_attr::{self as attr, SignedInt, UnsignedInt}; @@ -20,6 +22,7 @@ use rustc_macros::HashStable; use rustc_span::{sym, DUMMY_SP}; use rustc_target::abi::{Integer, Size, TargetDataLayout}; use rustc_target::spec::abi::Abi; +use rustc_type_ir::TyKind::*; use smallvec::SmallVec; use std::{fmt, iter}; diff --git a/compiler/rustc_query_impl/Cargo.toml b/compiler/rustc_query_impl/Cargo.toml index fa05434e48b1b..bfc15f0c70b3e 100644 --- a/compiler/rustc_query_impl/Cargo.toml +++ b/compiler/rustc_query_impl/Cargo.toml @@ -20,6 +20,7 @@ rustc_query_system = { path = "../rustc_query_system" } rustc_serialize = { path = "../rustc_serialize" } rustc_session = { path = "../rustc_session" } rustc_span = { path = "../rustc_span" } +rustc_type_ir = { path = "../rustc_type_ir" } tracing = "0.1" [features] diff --git a/compiler/rustc_query_impl/src/on_disk_cache.rs b/compiler/rustc_query_impl/src/on_disk_cache.rs index c492040852763..5282c317fc4bc 100644 --- a/compiler/rustc_query_impl/src/on_disk_cache.rs +++ b/compiler/rustc_query_impl/src/on_disk_cache.rs @@ -547,12 +547,13 @@ where value } -impl<'a, 'tcx> TyDecoder<'tcx> for CacheDecoder<'a, 'tcx> { +impl<'a, 'tcx> TyDecoder for CacheDecoder<'a, 'tcx> { + type I = TyInterner<'tcx>; const CLEAR_CROSS_CRATE: bool = false; #[inline] - fn tcx(&self) -> TyCtxt<'tcx> { - self.tcx + fn interner(&self) -> TyInterner<'tcx> { + TyInterner { tcx: self.tcx } } #[inline] @@ -569,7 +570,7 @@ impl<'a, 'tcx> TyDecoder<'tcx> for CacheDecoder<'a, 'tcx> { where F: FnOnce(&mut Self) -> Ty<'tcx>, { - let tcx = self.tcx(); + let tcx = self.tcx; let cache_key = ty::CReaderCacheKey { cnum: None, pos: shorthand }; @@ -750,7 +751,7 @@ impl<'a, 'tcx> Decodable> for DefId { // If we get to this point, then all of the query inputs were green, // which means that the definition with this hash is guaranteed to // still exist in the current compilation session. - d.tcx().def_path_hash_to_def_id(def_path_hash, &mut || { + d.tcx.def_path_hash_to_def_id(def_path_hash, &mut || { panic!("Failed to convert DefPathHash {:?}", def_path_hash) }) } @@ -927,10 +928,11 @@ where } } -impl<'a, 'tcx, E> TyEncoder<'tcx> for CacheEncoder<'a, 'tcx, E> +impl<'a, 'tcx, E> TyEncoder for CacheEncoder<'a, 'tcx, E> where E: 'a + OpaqueEncoder, { + type I = TyInterner<'tcx>; const CLEAR_CROSS_CRATE: bool = false; fn position(&self) -> usize { diff --git a/compiler/rustc_query_system/Cargo.toml b/compiler/rustc_query_system/Cargo.toml index 8a35121f90cdb..0a80f014ae792 100644 --- a/compiler/rustc_query_system/Cargo.toml +++ b/compiler/rustc_query_system/Cargo.toml @@ -21,6 +21,7 @@ rustc_serialize = { path = "../rustc_serialize" } rustc_session = { path = "../rustc_session" } rustc_span = { path = "../rustc_span" } rustc_target = { path = "../rustc_target" } +rustc_type_ir = { path = "../rustc_type_ir" } parking_lot = "0.11" smallvec = { version = "1.6.1", features = ["union", "may_dangle"] } diff --git a/compiler/rustc_query_system/src/ich/mod.rs b/compiler/rustc_query_system/src/ich/mod.rs index 0a1c350b2db13..ddaac1c78a129 100644 --- a/compiler/rustc_query_system/src/ich/mod.rs +++ b/compiler/rustc_query_system/src/ich/mod.rs @@ -1,6 +1,7 @@ //! ICH - Incremental Compilation Hash pub use self::hcx::StableHashingContext; +use rustc_data_structures::stable_hasher::HashStable; use rustc_span::symbol::{sym, Symbol}; mod hcx; @@ -17,3 +18,124 @@ pub const IGNORED_ATTRIBUTES: &[Symbol] = &[ sym::rustc_partition_codegened, sym::rustc_expected_cgu_reuse, ]; + +#[allow(rustc::usage_of_ty_tykind)] +impl<'__ctx, I: rustc_type_ir::Interner> HashStable> + for rustc_type_ir::TyKind +where + I::AdtDef: HashStable>, + I::DefId: HashStable>, + I::SubstsRef: HashStable>, + I::Ty: HashStable>, + I::Const: HashStable>, + I::TypeAndMut: HashStable>, + I::PolyFnSig: HashStable>, + I::ListBinderExistentialPredicate: HashStable>, + I::Region: HashStable>, + I::Movability: HashStable>, + I::Mutability: HashStable>, + I::BinderListTy: HashStable>, + I::ListTy: HashStable>, + I::ProjectionTy: HashStable>, + I::BoundTy: HashStable>, + I::ParamTy: HashStable>, + I::PlaceholderType: HashStable>, + I::InferTy: HashStable>, + I::DelaySpanBugEmitted: HashStable>, +{ + #[inline] + fn hash_stable( + &self, + __hcx: &mut crate::ich::StableHashingContext<'__ctx>, + __hasher: &mut rustc_data_structures::stable_hasher::StableHasher, + ) { + std::mem::discriminant(self).hash_stable(__hcx, __hasher); + use rustc_type_ir::TyKind::*; + match self { + Bool => {} + Char => {} + Int(i) => { + i.hash_stable(__hcx, __hasher); + } + Uint(u) => { + u.hash_stable(__hcx, __hasher); + } + Float(f) => { + f.hash_stable(__hcx, __hasher); + } + Adt(adt, substs) => { + adt.hash_stable(__hcx, __hasher); + substs.hash_stable(__hcx, __hasher); + } + Foreign(def_id) => { + def_id.hash_stable(__hcx, __hasher); + } + Str => {} + Array(t, c) => { + t.hash_stable(__hcx, __hasher); + c.hash_stable(__hcx, __hasher); + } + Slice(t) => { + t.hash_stable(__hcx, __hasher); + } + RawPtr(tam) => { + tam.hash_stable(__hcx, __hasher); + } + Ref(r, t, m) => { + r.hash_stable(__hcx, __hasher); + t.hash_stable(__hcx, __hasher); + m.hash_stable(__hcx, __hasher); + } + FnDef(def_id, substs) => { + def_id.hash_stable(__hcx, __hasher); + substs.hash_stable(__hcx, __hasher); + } + FnPtr(polyfnsig) => { + polyfnsig.hash_stable(__hcx, __hasher); + } + Dynamic(l, r) => { + l.hash_stable(__hcx, __hasher); + r.hash_stable(__hcx, __hasher); + } + Closure(def_id, substs) => { + def_id.hash_stable(__hcx, __hasher); + substs.hash_stable(__hcx, __hasher); + } + Generator(def_id, substs, m) => { + def_id.hash_stable(__hcx, __hasher); + substs.hash_stable(__hcx, __hasher); + m.hash_stable(__hcx, __hasher); + } + GeneratorWitness(b) => { + b.hash_stable(__hcx, __hasher); + } + Never => {} + Tuple(substs) => { + substs.hash_stable(__hcx, __hasher); + } + Projection(p) => { + p.hash_stable(__hcx, __hasher); + } + Opaque(def_id, substs) => { + def_id.hash_stable(__hcx, __hasher); + substs.hash_stable(__hcx, __hasher); + } + Param(p) => { + p.hash_stable(__hcx, __hasher); + } + Bound(d, b) => { + d.hash_stable(__hcx, __hasher); + b.hash_stable(__hcx, __hasher); + } + Placeholder(p) => { + p.hash_stable(__hcx, __hasher); + } + Infer(i) => { + i.hash_stable(__hcx, __hasher); + } + Error(d) => { + d.hash_stable(__hcx, __hasher); + } + } + } +} diff --git a/compiler/rustc_ty_utils/src/ty.rs b/compiler/rustc_ty_utils/src/ty.rs index 23700e653e36a..8d04b8816ffbe 100644 --- a/compiler/rustc_ty_utils/src/ty.rs +++ b/compiler/rustc_ty_utils/src/ty.rs @@ -13,7 +13,7 @@ fn sized_constraint_for_ty<'tcx>( adtdef: ty::AdtDef<'tcx>, ty: Ty<'tcx>, ) -> Vec> { - use ty::TyKind::*; + use rustc_type_ir::sty::TyKind::*; let result = match ty.kind() { Bool | Char | Int(..) | Uint(..) | Float(..) | RawPtr(..) | Ref(..) | FnDef(..) diff --git a/compiler/rustc_type_ir/Cargo.toml b/compiler/rustc_type_ir/Cargo.toml index 439e6cdf70698..b8066f2e5d891 100644 --- a/compiler/rustc_type_ir/Cargo.toml +++ b/compiler/rustc_type_ir/Cargo.toml @@ -12,3 +12,4 @@ rustc_index = { path = "../rustc_index" } rustc_serialize = { path = "../rustc_serialize" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_macros = { path = "../rustc_macros" } +smallvec = { version = "1.0", features = ["union", "may_dangle"] } diff --git a/compiler/rustc_type_ir/src/codec.rs b/compiler/rustc_type_ir/src/codec.rs new file mode 100644 index 0000000000000..e0138f8aad92f --- /dev/null +++ b/compiler/rustc_type_ir/src/codec.rs @@ -0,0 +1,63 @@ +use crate::Interner; + +use rustc_data_structures::stable_map::FxHashMap; +use rustc_serialize::{Decoder, Encoder}; + +/// The shorthand encoding uses an enum's variant index `usize` +/// and is offset by this value so it never matches a real variant. +/// This offset is also chosen so that the first byte is never < 0x80. +pub const SHORTHAND_OFFSET: usize = 0x80; + +/// Trait for decoding to a reference. +/// +/// This is a separate trait from `Decodable` so that we can implement it for +/// upstream types, such as `FxHashSet`. +/// +/// The `TyDecodable` derive macro will use this trait for fields that are +/// references (and don't use a type alias to hide that). +/// +/// `Decodable` can still be implemented in cases where `Decodable` is required +/// by a trait bound. +pub trait RefDecodable<'tcx, D: TyDecoder> { + fn decode(d: &mut D) -> &'tcx Self; +} + +pub trait TyEncoder: Encoder { + type I: Interner; + const CLEAR_CROSS_CRATE: bool; + + fn position(&self) -> usize; + fn type_shorthands(&mut self) -> &mut FxHashMap<::Ty, usize>; + fn predicate_shorthands( + &mut self, + ) -> &mut FxHashMap<::PredicateKind, usize>; + fn encode_alloc_id( + &mut self, + alloc_id: &::AllocId, + ) -> Result<(), Self::Error>; +} + +pub trait TyDecoder: Decoder { + type I: Interner; + const CLEAR_CROSS_CRATE: bool; + + fn interner(&self) -> Self::I; + + fn peek_byte(&self) -> u8; + + fn position(&self) -> usize; + + fn cached_ty_for_shorthand(&mut self, shorthand: usize, or_insert_with: F) -> ::Ty + where + F: FnOnce(&mut Self) -> ::Ty; + + fn with_position(&mut self, pos: usize, f: F) -> R + where + F: FnOnce(&mut Self) -> R; + + fn positioned_at_shorthand(&self) -> bool { + (self.peek_byte() & (SHORTHAND_OFFSET as u8)) != 0 + } + + fn decode_alloc_id(&mut self) -> ::AllocId; +} \ No newline at end of file diff --git a/compiler/rustc_type_ir/src/lib.rs b/compiler/rustc_type_ir/src/lib.rs index c63e9c31d535c..960e42d8006ac 100644 --- a/compiler/rustc_type_ir/src/lib.rs +++ b/compiler/rustc_type_ir/src/lib.rs @@ -1,4 +1,5 @@ #![feature(min_specialization)] +#![feature(rustc_attrs)] #[macro_use] extern crate bitflags; @@ -7,9 +8,147 @@ extern crate rustc_macros; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::unify::{EqUnifyValue, UnifyKey}; +//use rustc_serialize::{Decodable, Encodable}; +use smallvec::SmallVec; use std::fmt; +use std::fmt::Debug; +use std::hash::Hash; use std::mem::discriminant; +pub mod codec; +pub mod sty; + +pub use codec::*; +pub use sty::*; + +extern crate self as rustc_type_ir; + +pub trait Interner { + type AdtDef: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord; + type SubstsRef: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord; + type DefId: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord; + type Ty: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord; + type Const: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord; + type Region: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord; + type TypeAndMut: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord; + type Mutability: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord; + type Movability: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord; + type PolyFnSig: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord; + type ListBinderExistentialPredicate: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord; + type BinderListTy: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord; + type ListTy: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord; + type ProjectionTy: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord; + type ParamTy: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord; + type BoundTy: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord; + type PlaceholderType: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord; + type InferTy: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord; + type DelaySpanBugEmitted: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord; + type PredicateKind: Clone + Debug + Hash + PartialEq + Eq; + type AllocId: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord; +} + +pub trait InternAs { + type Output; + fn intern_with(self, f: F) -> Self::Output + where + F: FnOnce(&T) -> R; +} + +impl InternAs<[T], R> for I +where + E: InternIteratorElement, + I: Iterator, +{ + type Output = E::Output; + fn intern_with(self, f: F) -> Self::Output + where + F: FnOnce(&[T]) -> R, + { + E::intern_with(self, f) + } +} + +pub trait InternIteratorElement: Sized { + type Output; + fn intern_with, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output; +} + +impl InternIteratorElement for T { + type Output = R; + fn intern_with, F: FnOnce(&[T]) -> R>( + mut iter: I, + f: F, + ) -> Self::Output { + // This code is hot enough that it's worth specializing for the most + // common length lists, to avoid the overhead of `SmallVec` creation. + // Lengths 0, 1, and 2 typically account for ~95% of cases. If + // `size_hint` is incorrect a panic will occur via an `unwrap` or an + // `assert`. + match iter.size_hint() { + (0, Some(0)) => { + assert!(iter.next().is_none()); + f(&[]) + } + (1, Some(1)) => { + let t0 = iter.next().unwrap(); + assert!(iter.next().is_none()); + f(&[t0]) + } + (2, Some(2)) => { + let t0 = iter.next().unwrap(); + let t1 = iter.next().unwrap(); + assert!(iter.next().is_none()); + f(&[t0, t1]) + } + _ => f(&iter.collect::>()), + } + } +} + +impl<'a, T, R> InternIteratorElement for &'a T +where + T: Clone + 'a, +{ + type Output = R; + fn intern_with, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output { + // This code isn't hot. + f(&iter.cloned().collect::>()) + } +} + +impl InternIteratorElement for Result { + type Output = Result; + fn intern_with, F: FnOnce(&[T]) -> R>( + mut iter: I, + f: F, + ) -> Self::Output { + // This code is hot enough that it's worth specializing for the most + // common length lists, to avoid the overhead of `SmallVec` creation. + // Lengths 0, 1, and 2 typically account for ~95% of cases. If + // `size_hint` is incorrect a panic will occur via an `unwrap` or an + // `assert`, unless a failure happens first, in which case the result + // will be an error anyway. + Ok(match iter.size_hint() { + (0, Some(0)) => { + assert!(iter.next().is_none()); + f(&[]) + } + (1, Some(1)) => { + let t0 = iter.next().unwrap()?; + assert!(iter.next().is_none()); + f(&[t0]) + } + (2, Some(2)) => { + let t0 = iter.next().unwrap()?; + let t1 = iter.next().unwrap()?; + assert!(iter.next().is_none()); + f(&[t0, t1]) + } + _ => f(&iter.collect::, _>>()?), + }) + } +} + bitflags! { /// Flags that we track on types. These flags are propagated upwards /// through the type during type construction, so that we can quickly check diff --git a/compiler/rustc_type_ir/src/sty.rs b/compiler/rustc_type_ir/src/sty.rs new file mode 100644 index 0000000000000..8f43904d96a31 --- /dev/null +++ b/compiler/rustc_type_ir/src/sty.rs @@ -0,0 +1,454 @@ +use crate::DebruijnIndex; +use crate::FloatTy; +use crate::IntTy; +use crate::Interner; +use crate::TyDecoder; +use crate::TyEncoder; +use crate::UintTy; + +use rustc_serialize::{Decodable, Encodable}; + +/// Defines the kinds of types used by the type system. +/// +/// Types written by the user start out as [hir::TyKind](rustc_hir::TyKind) and get +/// converted to this representation using `AstConv::ast_ty_to_ty`. +#[allow(rustc::usage_of_ty_tykind)] +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] +//#[derive(TyEncodable, TyDecodable)] +//#[derive(HashStable)] +#[rustc_diagnostic_item = "TyKind"] +pub enum TyKind { + /// The primitive boolean type. Written as `bool`. + Bool, + + /// The primitive character type; holds a Unicode scalar value + /// (a non-surrogate code point). Written as `char`. + Char, + + /// A primitive signed integer type. For example, `i32`. + Int(IntTy), + + /// A primitive unsigned integer type. For example, `u32`. + Uint(UintTy), + + /// A primitive floating-point type. For example, `f64`. + Float(FloatTy), + + /// Algebraic data types (ADT). For example: structures, enumerations and unions. + /// + /// For example, the type `List` would be represented using the `AdtDef` + /// for `struct List` and the substs `[i32]`. + /// + /// Note that generic parameters in fields only get lazily substituted + /// by using something like `adt_def.all_fields().map(|field| field.ty(tcx, substs))`. + Adt(I::AdtDef, I::SubstsRef), + + /// An unsized FFI type that is opaque to Rust. Written as `extern type T`. + Foreign(I::DefId), + + /// The pointee of a string slice. Written as `str`. + Str, + + /// An array with the given length. Written as `[T; N]`. + Array(I::Ty, I::Const), + + /// The pointee of an array slice. Written as `[T]`. + Slice(I::Ty), + + /// A raw pointer. Written as `*mut T` or `*const T` + RawPtr(I::TypeAndMut), + + /// A reference; a pointer with an associated lifetime. Written as + /// `&'a mut T` or `&'a T`. + Ref(I::Region, I::Ty, I::Mutability), + + /// The anonymous type of a function declaration/definition. Each + /// function has a unique type. + /// + /// For the function `fn foo() -> i32 { 3 }` this type would be + /// shown to the user as `fn() -> i32 {foo}`. + /// + /// For example the type of `bar` here: + /// ```rust + /// fn foo() -> i32 { 1 } + /// let bar = foo; // bar: fn() -> i32 {foo} + /// ``` + FnDef(I::DefId, I::SubstsRef), + + /// A pointer to a function. Written as `fn() -> i32`. + /// + /// Note that both functions and closures start out as either + /// [FnDef] or [Closure] which can be then be coerced to this variant. + /// + /// For example the type of `bar` here: + /// + /// ```rust + /// fn foo() -> i32 { 1 } + /// let bar: fn() -> i32 = foo; + /// ``` + FnPtr(I::PolyFnSig), + + /// A trait object. Written as `dyn for<'b> Trait<'b, Assoc = u32> + Send + 'a`. + Dynamic(I::ListBinderExistentialPredicate, I::Region), + + /// The anonymous type of a closure. Used to represent the type of `|a| a`. + /// + /// Closure substs contain both the - potentially substituted - generic parameters + /// of its parent and some synthetic parameters. See the documentation for + /// [ClosureSubsts] for more details. + Closure(I::DefId, I::SubstsRef), + + /// The anonymous type of a generator. Used to represent the type of + /// `|a| yield a`. + /// + /// For more info about generator substs, visit the documentation for + /// [GeneratorSubsts]. + Generator(I::DefId, I::SubstsRef, I::Movability), + + /// A type representing the types stored inside a generator. + /// This should only appear as part of the [GeneratorSubsts]. + /// + /// Note that the captured variables for generators are stored separately + /// using a tuple in the same way as for closures. + /// + /// Unlike upvars, the witness can reference lifetimes from + /// inside of the generator itself. To deal with them in + /// the type of the generator, we convert them to higher ranked + /// lifetimes bound by the witness itself. + /// + /// Looking at the following example, the witness for this generator + /// may end up as something like `for<'a> [Vec, &'a Vec]`: + /// + /// ```ignore UNSOLVED (ask @compiler-errors, should this error? can we just swap the yields?) + /// #![feature(generators)] + /// |a| { + /// let x = &vec![3]; + /// yield a; + /// yield x[0]; + /// } + /// # ; + /// ``` + GeneratorWitness(I::BinderListTy), + + /// The never type `!`. + Never, + + /// A tuple type. For example, `(i32, bool)`. + Tuple(I::ListTy), + + /// The projection of an associated type. For example, + /// `>::N`. + Projection(I::ProjectionTy), + + /// Opaque (`impl Trait`) type found in a return type. + /// + /// The `DefId` comes either from + /// * the `impl Trait` ast::Ty node, + /// * or the `type Foo = impl Trait` declaration + /// + /// For RPIT the substitutions are for the generics of the function, + /// while for TAIT it is used for the generic parameters of the alias. + /// + /// During codegen, `tcx.type_of(def_id)` can be used to get the underlying type. + Opaque(I::DefId, I::SubstsRef), + + /// A type parameter; for example, `T` in `fn f(x: T) {}`. + Param(I::ParamTy), + + /// Bound type variable, used to represent the `'a` in `for<'a> fn(&'a ())`. + /// + /// For canonical queries, we replace inference variables with bound variables, + /// so e.g. when checking whether `&'_ (): Trait<_>` holds, we canonicalize that to + /// `for<'a, T> &'a (): Trait` and then convert the introduced bound variables + /// back to inference variables in a new inference context when inside of the query. + /// + /// See the `rustc-dev-guide` for more details about + /// [higher-ranked trait bounds][1] and [canonical queries][2]. + /// + /// [1]: https://rustc-dev-guide.rust-lang.org/traits/hrtb.html + /// [2]: https://rustc-dev-guide.rust-lang.org/traits/canonical-queries.html + Bound(DebruijnIndex, I::BoundTy), + + /// A placeholder type, used during higher ranked subtyping to instantiate + /// bound variables. + Placeholder(I::PlaceholderType), + + /// A type variable used during type checking. + /// + /// Similar to placeholders, inference variables also live in a universe to + /// correctly deal with higher ranked types. Though unlike placeholders, + /// that universe is stored in the `InferCtxt` instead of directly + /// inside of the type. + Infer(I::InferTy), + + /// A placeholder for a type which could not be computed; this is + /// propagated to avoid useless error messages. + Error(I::DelaySpanBugEmitted), +} + +#[allow(rustc::usage_of_ty_tykind)] +impl TyKind { + #[inline] + pub fn is_primitive(&self) -> bool { + use crate::TyKind::*; + matches!(self, Bool | Char | Int(_) | Uint(_) | Float(_)) + } +} + +#[allow(rustc::usage_of_ty_tykind)] +impl<__I: Interner, __E: TyEncoder> Encodable<__E> for TyKind<__I> +where + __I::DelaySpanBugEmitted: Encodable<__E>, + __I::AdtDef: Encodable<__E>, + __I::SubstsRef: Encodable<__E>, + __I::DefId: Encodable<__E>, + __I::Ty: Encodable<__E>, + __I::Const: Encodable<__E>, + __I::Region: Encodable<__E>, + __I::TypeAndMut: Encodable<__E>, + __I::Mutability: Encodable<__E>, + __I::Movability: Encodable<__E>, + __I::PolyFnSig: Encodable<__E>, + __I::ListBinderExistentialPredicate: Encodable<__E>, + __I::BinderListTy: Encodable<__E>, + __I::ListTy: Encodable<__E>, + __I::ProjectionTy: Encodable<__E>, + __I::ParamTy: Encodable<__E>, + __I::BoundTy: Encodable<__E>, + __I::PlaceholderType: Encodable<__E>, + __I::InferTy: Encodable<__E>, + __I::DelaySpanBugEmitted: Encodable<__E>, + __I::PredicateKind: Encodable<__E>, + __I::AllocId: Encodable<__E>, +{ + fn encode(&self, e: &mut __E) -> Result<(), <__E as rustc_serialize::Encoder>::Error> { + rustc_serialize::Encoder::emit_enum(e, |e| { + use rustc_type_ir::TyKind::*; + match self { + Bool => e.emit_enum_variant("Bool", 0, 0, |_| Ok(())), + Char => e.emit_enum_variant("Char", 1, 0, |_| Ok(())), + Int(i) => e.emit_enum_variant("Int", 2, 1, |e| { + e.emit_enum_variant_arg(true, |e| i.encode(e))?; + Ok(()) + }), + Uint(u) => e.emit_enum_variant("Uint", 3, 1, |e| { + e.emit_enum_variant_arg(true, |e| u.encode(e))?; + Ok(()) + }), + Float(f) => e.emit_enum_variant("Float", 4, 1, |e| { + e.emit_enum_variant_arg(true, |e| f.encode(e))?; + Ok(()) + }), + Adt(adt, substs) => e.emit_enum_variant("Adt", 5, 2, |e| { + e.emit_enum_variant_arg(true, |e| adt.encode(e))?; + e.emit_enum_variant_arg(false, |e| substs.encode(e))?; + Ok(()) + }), + Foreign(def_id) => e.emit_enum_variant("Foreign", 6, 1, |e| { + e.emit_enum_variant_arg(true, |e| def_id.encode(e))?; + Ok(()) + }), + Str => e.emit_enum_variant("Str", 7, 0, |_| Ok(())), + Array(t, c) => e.emit_enum_variant("Array", 8, 2, |e| { + e.emit_enum_variant_arg(true, |e| t.encode(e))?; + e.emit_enum_variant_arg(false, |e| c.encode(e))?; + Ok(()) + }), + Slice(t) => e.emit_enum_variant("Slice", 9, 1, |e| { + e.emit_enum_variant_arg(true, |e| t.encode(e))?; + Ok(()) + }), + RawPtr(tam) => e.emit_enum_variant("RawPtr", 10, 1, |e| { + e.emit_enum_variant_arg(true, |e| tam.encode(e))?; + Ok(()) + }), + Ref(r, t, m) => e.emit_enum_variant("Ref", 11, 3, |e| { + e.emit_enum_variant_arg(true, |e| r.encode(e))?; + e.emit_enum_variant_arg(false, |e| t.encode(e))?; + e.emit_enum_variant_arg(false, |e| m.encode(e))?; + Ok(()) + }), + FnDef(def_id, substs) => e.emit_enum_variant("FnDef", 12, 2, |e| { + e.emit_enum_variant_arg(true, |e| def_id.encode(e))?; + e.emit_enum_variant_arg(false, |e| substs.encode(e))?; + Ok(()) + }), + FnPtr(polyfnsig) => e.emit_enum_variant("FnPtr", 13, 1, |e| { + e.emit_enum_variant_arg(true, |e| polyfnsig.encode(e))?; + Ok(()) + }), + Dynamic(l, r) => e.emit_enum_variant("Dynamic", 14, 2, |e| { + e.emit_enum_variant_arg(true, |e| l.encode(e))?; + e.emit_enum_variant_arg(false, |e| r.encode(e))?; + Ok(()) + }), + Closure(def_id, substs) => e.emit_enum_variant("Closure", 15, 2, |e| { + e.emit_enum_variant_arg(true, |e| def_id.encode(e))?; + e.emit_enum_variant_arg(false, |e| substs.encode(e))?; + Ok(()) + }), + Generator(def_id, substs, m) => e.emit_enum_variant("Generator", 16, 3, |e| { + e.emit_enum_variant_arg(true, |e| def_id.encode(e))?; + e.emit_enum_variant_arg(false, |e| substs.encode(e))?; + e.emit_enum_variant_arg(false, |e| m.encode(e))?; + Ok(()) + }), + GeneratorWitness(b) => e.emit_enum_variant("GeneratorWitness", 17, 1, |e| { + e.emit_enum_variant_arg(true, |e| b.encode(e))?; + Ok(()) + }), + Never => e.emit_enum_variant("Never", 18, 0, |_| Ok(())), + Tuple(substs) => e.emit_enum_variant("Tuple", 19, 1, |e| { + e.emit_enum_variant_arg(true, |e| substs.encode(e))?; + Ok(()) + }), + Projection(p) => e.emit_enum_variant("Projection", 20, 1, |e| { + e.emit_enum_variant_arg(true, |e| p.encode(e))?; + Ok(()) + }), + Opaque(def_id, substs) => e.emit_enum_variant("Opaque", 21, 2, |e| { + e.emit_enum_variant_arg(true, |e| def_id.encode(e))?; + e.emit_enum_variant_arg(false, |e| substs.encode(e))?; + Ok(()) + }), + Param(p) => e.emit_enum_variant("Param", 22, 1, |e| { + e.emit_enum_variant_arg(true, |e| p.encode(e))?; + Ok(()) + }), + Bound(d, b) => e.emit_enum_variant("Bound", 23, 2, |e| { + e.emit_enum_variant_arg(true, |e| d.encode(e))?; + e.emit_enum_variant_arg(false, |e| b.encode(e))?; + Ok(()) + }), + Placeholder(p) => e.emit_enum_variant("Placeholder", 24, 1, |e| { + e.emit_enum_variant_arg(true, |e| p.encode(e))?; + Ok(()) + }), + Infer(i) => e.emit_enum_variant("Infer", 25, 1, |e| { + e.emit_enum_variant_arg(true, |e| i.encode(e))?; + Ok(()) + }), + Error(d) => e.emit_enum_variant("Error", 26, 1, |e| { + e.emit_enum_variant_arg(true, |e| d.encode(e))?; + Ok(()) + }), + } + }) + } +} + +#[allow(rustc::usage_of_ty_tykind)] +impl<__I: Interner, __D: TyDecoder> Decodable<__D> for TyKind<__I> +where + __I::DelaySpanBugEmitted: Decodable<__D>, + __I::AdtDef: Decodable<__D>, + __I::SubstsRef: Decodable<__D>, + __I::DefId: Decodable<__D>, + __I::Ty: Decodable<__D>, + __I::Const: Decodable<__D>, + __I::Region: Decodable<__D>, + __I::TypeAndMut: Decodable<__D>, + __I::Mutability: Decodable<__D>, + __I::Movability: Decodable<__D>, + __I::PolyFnSig: Decodable<__D>, + __I::ListBinderExistentialPredicate: Decodable<__D>, + __I::BinderListTy: Decodable<__D>, + __I::ListTy: Decodable<__D>, + __I::ProjectionTy: Decodable<__D>, + __I::ParamTy: Decodable<__D>, + __I::BoundTy: Decodable<__D>, + __I::PlaceholderType: Decodable<__D>, + __I::InferTy: Decodable<__D>, + __I::DelaySpanBugEmitted: Decodable<__D>, + __I::PredicateKind: Decodable<__D>, + __I::AllocId: Decodable<__D>, +{ + fn decode(__decoder: &mut __D) -> Self { + use TyKind::*; + + match rustc_serialize::Decoder::read_usize(__decoder) { + 0 => Bool, + 1 => Char, + 2 => Int(rustc_serialize::Decodable::decode(__decoder)), + 3 => Uint(rustc_serialize::Decodable::decode(__decoder)), + 4 => Float(rustc_serialize::Decodable::decode(__decoder)), + 5 => Adt( + rustc_serialize::Decodable::decode(__decoder), + rustc_serialize::Decodable::decode(__decoder), + ), + 6 => Foreign(rustc_serialize::Decodable::decode(__decoder)), + 7 => Str, + 8 => Array( + rustc_serialize::Decodable::decode(__decoder), + rustc_serialize::Decodable::decode(__decoder), + ), + 9 => Slice(rustc_serialize::Decodable::decode(__decoder)), + 10 => RawPtr( + rustc_serialize::Decodable::decode(__decoder), + ), + 11 => Ref( + rustc_serialize::Decodable::decode(__decoder), + rustc_serialize::Decodable::decode(__decoder), + rustc_serialize::Decodable::decode(__decoder), + ), + 12 => FnDef( + rustc_serialize::Decodable::decode(__decoder), + rustc_serialize::Decodable::decode(__decoder), + ), + 13 => FnPtr( + rustc_serialize::Decodable::decode(__decoder), + ), + 14 => Dynamic( + rustc_serialize::Decodable::decode(__decoder), + rustc_serialize::Decodable::decode(__decoder), + ), + 15 => Closure( + rustc_serialize::Decodable::decode(__decoder), + rustc_serialize::Decodable::decode(__decoder), + ), + 16 => Generator( + rustc_serialize::Decodable::decode(__decoder), + rustc_serialize::Decodable::decode(__decoder), + rustc_serialize::Decodable::decode(__decoder), + ), + 17 => GeneratorWitness( + rustc_serialize::Decodable::decode(__decoder), + ), + 18 => Never, + 19 => Tuple( + rustc_serialize::Decodable::decode(__decoder), + ), + 20 => Projection( + rustc_serialize::Decodable::decode(__decoder), + ), + 21 => Opaque( + rustc_serialize::Decodable::decode(__decoder), + rustc_serialize::Decodable::decode(__decoder), + ), + 22 => Param( + rustc_serialize::Decodable::decode(__decoder), + ), + 23 => Bound( + rustc_serialize::Decodable::decode(__decoder), + rustc_serialize::Decodable::decode(__decoder), + ), + 24 => Placeholder( + rustc_serialize::Decodable::decode(__decoder), + ), + 25 => Infer( + rustc_serialize::Decodable::decode(__decoder), + ), + 26 => Error( + rustc_serialize::Decodable::decode(__decoder), + ), + _ => + panic!( + "{}", + format!( + "invalid enum variant tag while decoding `{}`, expected 0..{}", + "TyKind", 27, + ) + ), + } + } +} diff --git a/compiler/rustc_typeck/src/coherence/builtin.rs b/compiler/rustc_typeck/src/coherence/builtin.rs index 3135e9996ab8b..d08d9938708c9 100644 --- a/compiler/rustc_typeck/src/coherence/builtin.rs +++ b/compiler/rustc_typeck/src/coherence/builtin.rs @@ -177,7 +177,7 @@ fn visit_implementation_of_dispatch_from_dyn<'tcx>(tcx: TyCtxt<'tcx>, impl_did: tcx.infer_ctxt().enter(|infcx| { let cause = ObligationCause::misc(span, impl_hir_id); - use ty::TyKind::*; + use rustc_type_ir::sty::TyKind::*; match (source.kind(), target.kind()) { (&Ref(r_a, _, mutbl_a), Ref(r_b, _, mutbl_b)) if infcx.at(&cause, param_env).eq(r_a, *r_b).is_ok() && mutbl_a == *mutbl_b => {} From a056a953f00d7b78d12dc192b34c47cca6fa7b6b Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sun, 22 May 2022 12:57:46 -0700 Subject: [PATCH 2/5] Initial fixes on top of type interner commit --- Cargo.lock | 5 ++ compiler/rustc_borrowck/src/lib.rs | 6 +- .../src/debuginfo/metadata.rs | 4 +- compiler/rustc_const_eval/Cargo.toml | 1 + .../rustc_const_eval/src/interpret/traits.rs | 8 +- compiler/rustc_lint/Cargo.toml | 1 + compiler/rustc_metadata/Cargo.toml | 1 + compiler/rustc_metadata/src/rmeta/decoder.rs | 11 +-- compiler/rustc_metadata/src/rmeta/encoder.rs | 6 +- compiler/rustc_middle/src/ty/codec.rs | 54 +++++------- compiler/rustc_middle/src/ty/consts.rs | 10 +-- compiler/rustc_middle/src/ty/context.rs | 2 +- compiler/rustc_middle/src/ty/mod.rs | 53 +++++++---- compiler/rustc_middle/src/ty/sty.rs | 4 +- compiler/rustc_middle/src/ty/subst.rs | 6 +- compiler/rustc_middle/src/ty/util.rs | 5 +- compiler/rustc_middle/src/ty/vtable.rs | 7 +- .../rustc_mir_transform/src/coverage/tests.rs | 6 +- .../rustc_query_impl/src/on_disk_cache.rs | 2 +- .../rustc_trait_selection/src/traits/mod.rs | 6 +- .../src/traits/select/confirmation.rs | 2 +- compiler/rustc_ty_utils/Cargo.toml | 1 + compiler/rustc_type_ir/src/codec.rs | 8 +- compiler/rustc_type_ir/src/sty.rs | 87 +++++++++++-------- compiler/rustc_typeck/Cargo.toml | 1 + compiler/rustc_typeck/src/check/demand.rs | 2 +- .../rustc_typeck/src/check/intrinsicck.rs | 2 +- compiler/rustc_typeck/src/check/op.rs | 4 +- 28 files changed, 171 insertions(+), 134 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 871ff8f9cdb40..3f17f24875d92 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3676,6 +3676,7 @@ dependencies = [ "rustc_span", "rustc_target", "rustc_trait_selection", + "rustc_type_ir", "tracing", ] @@ -3969,6 +3970,7 @@ dependencies = [ "rustc_span", "rustc_target", "rustc_trait_selection", + "rustc_type_ir", "tracing", "unicode-security", ] @@ -4041,6 +4043,7 @@ dependencies = [ "rustc_session", "rustc_span", "rustc_target", + "rustc_type_ir", "smallvec", "snap", "tracing", @@ -4474,6 +4477,7 @@ dependencies = [ "rustc_span", "rustc_target", "rustc_trait_selection", + "rustc_type_ir", "tracing", ] @@ -4512,6 +4516,7 @@ dependencies = [ "rustc_target", "rustc_trait_selection", "rustc_ty_utils", + "rustc_type_ir", "smallvec", "tracing", ] diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs index d3aea1fd61c63..93c7a832afd51 100644 --- a/compiler/rustc_borrowck/src/lib.rs +++ b/compiler/rustc_borrowck/src/lib.rs @@ -98,7 +98,9 @@ struct Upvar<'tcx> { by_ref: bool, } -const DEREF_PROJECTION: &[PlaceElem<'_>; 1] = &[ProjectionElem::Deref]; +const fn deref_projection<'tcx>() -> &'tcx [PlaceElem<'tcx>; 1] { + &[ProjectionElem::Deref] +} pub fn provide(providers: &mut Providers) { *providers = Providers { @@ -1443,7 +1445,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { // Thread-locals might be dropped after the function exits // We have to dereference the outer reference because // borrows don't conflict behind shared references. - root_place.projection = DEREF_PROJECTION; + root_place.projection = deref_projection(); (true, true) } else { (false, self.locals_are_invalidated_at_exit) diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs index 97d3acb34ce75..bbbd1e945148e 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs @@ -33,7 +33,7 @@ use rustc_middle::mir::{self, GeneratorLayout}; use rustc_middle::ty::layout::LayoutOf; use rustc_middle::ty::layout::TyAndLayout; use rustc_middle::ty::subst::GenericArgKind; -use rustc_middle::ty::{self, AdtKind, Instance, ParamEnv, Ty, TyCtxt, COMMON_VTABLE_ENTRIES}; +use rustc_middle::ty::{self, common_vtable_entries, AdtKind, Instance, ParamEnv, Ty, TyCtxt}; use rustc_session::config::{self, DebugInfo}; use rustc_span::symbol::Symbol; use rustc_span::FileName; @@ -1392,7 +1392,7 @@ fn build_vtable_type_di_node<'ll, 'tcx>( tcx.vtable_entries(trait_ref) } else { - COMMON_VTABLE_ENTRIES + common_vtable_entries() }; // All function pointers are described as opaque pointers. This could be improved in the future diff --git a/compiler/rustc_const_eval/Cargo.toml b/compiler/rustc_const_eval/Cargo.toml index 4ed908a383332..32e8233a0415f 100644 --- a/compiler/rustc_const_eval/Cargo.toml +++ b/compiler/rustc_const_eval/Cargo.toml @@ -24,3 +24,4 @@ rustc_session = { path = "../rustc_session" } rustc_target = { path = "../rustc_target" } rustc_trait_selection = { path = "../rustc_trait_selection" } rustc_span = { path = "../rustc_span" } +rustc_type_ir = { path = "../rustc_type_ir" } diff --git a/compiler/rustc_const_eval/src/interpret/traits.rs b/compiler/rustc_const_eval/src/interpret/traits.rs index 235938422a893..d5a448a8963a3 100644 --- a/compiler/rustc_const_eval/src/interpret/traits.rs +++ b/compiler/rustc_const_eval/src/interpret/traits.rs @@ -2,7 +2,7 @@ use std::convert::TryFrom; use rustc_middle::mir::interpret::{InterpResult, Pointer, PointerArithmetic}; use rustc_middle::ty::{ - self, Ty, COMMON_VTABLE_ENTRIES, COMMON_VTABLE_ENTRIES_ALIGN, + self, common_vtable_entries, Ty, COMMON_VTABLE_ENTRIES_ALIGN, COMMON_VTABLE_ENTRIES_DROPINPLACE, COMMON_VTABLE_ENTRIES_SIZE, }; use rustc_target::abi::{Align, Size}; @@ -38,7 +38,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { } /// Resolves the function at the specified slot in the provided - /// vtable. Currently an index of '3' (`COMMON_VTABLE_ENTRIES.len()`) + /// vtable. Currently an index of '3' (`common_vtable_entries().len()`) /// corresponds to the first method declared in the trait of the provided vtable. pub fn get_vtable_slot( &self, @@ -64,7 +64,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let vtable = self .get_ptr_alloc( vtable, - pointer_size * u64::try_from(COMMON_VTABLE_ENTRIES.len()).unwrap(), + pointer_size * u64::try_from(common_vtable_entries().len()).unwrap(), self.tcx.data_layout.pointer_align.abi, )? .expect("cannot be a ZST"); @@ -99,7 +99,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let vtable = self .get_ptr_alloc( vtable, - pointer_size * u64::try_from(COMMON_VTABLE_ENTRIES.len()).unwrap(), + pointer_size * u64::try_from(common_vtable_entries().len()).unwrap(), self.tcx.data_layout.pointer_align.abi, )? .expect("cannot be a ZST"); diff --git a/compiler/rustc_lint/Cargo.toml b/compiler/rustc_lint/Cargo.toml index 02f747eeccc3e..fab60b6f6096c 100644 --- a/compiler/rustc_lint/Cargo.toml +++ b/compiler/rustc_lint/Cargo.toml @@ -21,3 +21,4 @@ rustc_session = { path = "../rustc_session" } rustc_trait_selection = { path = "../rustc_trait_selection" } rustc_parse_format = { path = "../rustc_parse_format" } rustc_infer = { path = "../rustc_infer" } +rustc_type_ir = { path = "../rustc_type_ir" } diff --git a/compiler/rustc_metadata/Cargo.toml b/compiler/rustc_metadata/Cargo.toml index 59796dd652943..41224e3346177 100644 --- a/compiler/rustc_metadata/Cargo.toml +++ b/compiler/rustc_metadata/Cargo.toml @@ -27,3 +27,4 @@ rustc_ast = { path = "../rustc_ast" } rustc_expand = { path = "../rustc_expand" } rustc_span = { path = "../rustc_span" } rustc_session = { path = "../rustc_session" } +rustc_type_ir = { path = "../rustc_type_ir" } diff --git a/compiler/rustc_metadata/src/rmeta/decoder.rs b/compiler/rustc_metadata/src/rmeta/decoder.rs index 7f0b595347f49..806db61471ada 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder.rs @@ -24,8 +24,8 @@ use rustc_middle::mir::interpret::{AllocDecodingSession, AllocDecodingState}; use rustc_middle::thir; use rustc_middle::ty::codec::TyDecoder; use rustc_middle::ty::fast_reject::SimplifiedType; -use rustc_middle::ty::GeneratorDiagnosticData; use rustc_middle::ty::{self, ParameterizedOverTcx, Ty, TyCtxt, Visibility}; +use rustc_middle::ty::{GeneratorDiagnosticData, TyInterner}; use rustc_serialize::{opaque, Decodable, Decoder}; use rustc_session::cstore::{ CrateSource, ExternCrate, ForeignModule, LinkagePreference, NativeLib, @@ -377,12 +377,13 @@ impl<'a, 'tcx> DecodeContext<'a, 'tcx> { } } -impl<'a, 'tcx> TyDecoder<'tcx> for DecodeContext<'a, 'tcx> { +impl<'a, 'tcx> TyDecoder for DecodeContext<'a, 'tcx> { const CLEAR_CROSS_CRATE: bool = true; - #[inline] - fn tcx(&self) -> TyCtxt<'tcx> { - self.tcx.expect("missing TyCtxt in DecodeContext") + type I = TyInterner<'tcx>; + + fn interner(&self) -> Self::I { + TyInterner { tcx: self.tcx() } } #[inline] diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 339d2fc0867ae..2a862502f38ac 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -26,7 +26,7 @@ use rustc_middle::traits::specialization_graph; use rustc_middle::ty::codec::TyEncoder; use rustc_middle::ty::fast_reject::{self, SimplifiedType, TreatParams}; use rustc_middle::ty::query::Providers; -use rustc_middle::ty::{self, SymbolName, Ty, TyCtxt}; +use rustc_middle::ty::{self, SymbolName, Ty, TyCtxt, TyInterner}; use rustc_serialize::{opaque, Encodable, Encoder}; use rustc_session::config::CrateType; use rustc_session::cstore::{ForeignModule, LinkagePreference, NativeLib}; @@ -313,9 +313,11 @@ impl<'a, 'tcx> Encodable> for Span { } } -impl<'a, 'tcx> TyEncoder<'tcx> for EncodeContext<'a, 'tcx> { +impl<'a, 'tcx> TyEncoder for EncodeContext<'a, 'tcx> { const CLEAR_CROSS_CRATE: bool = true; + type I = TyInterner<'tcx>; + fn position(&self) -> usize { self.opaque.position() } diff --git a/compiler/rustc_middle/src/ty/codec.rs b/compiler/rustc_middle/src/ty/codec.rs index 234649f1056c7..2298cb4098b76 100644 --- a/compiler/rustc_middle/src/ty/codec.rs +++ b/compiler/rustc_middle/src/ty/codec.rs @@ -17,8 +17,8 @@ use crate::traits; use crate::ty::subst::SubstsRef; use crate::ty::{self, AdtDef, Ty}; use rustc_data_structures::fx::FxHashMap; -use rustc_serialize::{Decodable, Encodable}; use rustc_middle::ty::TyInterner; +use rustc_serialize::{Decodable, Encodable}; use rustc_span::Span; pub use rustc_type_ir::{TyDecoder, TyEncoder}; use std::hash::Hash; @@ -165,25 +165,6 @@ impl<'tcx, E: TyEncoder>> Encodable for AllocId { } } -macro_rules! encodable_via_deref { - ($($t:ty),+) => { - $(impl<'tcx, E: TyEncoder>> Encodable for $t { - fn encode(&self, e: &mut E) -> Result<(), E::Error> { - (**self).encode(e) - } - })* - } -} - -encodable_via_deref! { - &'tcx ty::TypeckResults<'tcx>, - &'tcx traits::ImplSource<'tcx, ()>, - &'tcx mir::Body<'tcx>, - &'tcx mir::UnsafetyCheckResult, - &'tcx mir::BorrowCheckResult<'tcx>, - &'tcx mir::coverage::CodeRegion -} - #[inline] fn decode_arena_allocable< 'tcx, @@ -231,7 +212,9 @@ impl<'tcx, D: TyDecoder>> Decodable for Ty<'tcx> { } } -impl<'tcx, D: TyDecoder>> Decodable for ty::Binder<'tcx, ty::PredicateKind<'tcx>> { +impl<'tcx, D: TyDecoder>> Decodable + for ty::Binder<'tcx, ty::PredicateKind<'tcx>> +{ fn decode(decoder: &mut D) -> ty::Binder<'tcx, ty::PredicateKind<'tcx>> { let bound_vars = Decodable::decode(decoder); // Handle shorthands first, if we have a usize > 0x80. @@ -318,7 +301,10 @@ macro_rules! impl_decodable_via_ref { impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for ty::List> { fn decode(decoder: &mut D) -> &'tcx Self { let len = decoder.read_usize(); - decoder.interner().tcx.mk_type_list((0..len).map::, _>(|_| Decodable::decode(decoder))) + decoder + .interner() + .tcx + .mk_type_list((0..len).map::, _>(|_| Decodable::decode(decoder))) } } @@ -359,7 +345,9 @@ impl<'tcx, D: TyDecoder>> Decodable for AdtDef<'tcx> { } } -impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for [(ty::Predicate<'tcx>, Span)] { +impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> + for [(ty::Predicate<'tcx>, Span)] +{ fn decode(decoder: &mut D) -> &'tcx Self { decoder.interner().tcx.arena.alloc_from_iter( (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::>(), @@ -367,7 +355,9 @@ impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for [(ty::P } } -impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for [thir::abstract_const::Node<'tcx>] { +impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> + for [thir::abstract_const::Node<'tcx>] +{ fn decode(decoder: &mut D) -> &'tcx Self { decoder.interner().tcx.arena.alloc_from_iter( (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::>(), @@ -375,7 +365,9 @@ impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for [thir:: } } -impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for [thir::abstract_const::NodeId] { +impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> + for [thir::abstract_const::NodeId] +{ fn decode(decoder: &mut D) -> &'tcx Self { decoder.interner().tcx.arena.alloc_from_iter( (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::>(), @@ -383,7 +375,9 @@ impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for [thir:: } } -impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for ty::List { +impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> + for ty::List +{ fn decode(decoder: &mut D) -> &'tcx Self { let len = decoder.read_usize(); decoder.interner().tcx.mk_bound_variable_kinds( @@ -449,17 +443,17 @@ arena_types!(impl_arena_allocatable_decoders); macro_rules! impl_arena_copy_decoder { (<$tcx:tt> $($ty:ty,)*) => { - $(impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for $ty { + $(impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for $ty { #[inline] fn decode(decoder: &mut D) -> &'tcx Self { - decoder.tcx().arena.alloc(Decodable::decode(decoder)) + decoder.interner().tcx.arena.alloc(Decodable::decode(decoder)) } } - impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [$ty] { + impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for [$ty] { #[inline] fn decode(decoder: &mut D) -> &'tcx Self { - decoder.tcx().arena.alloc_from_iter( as Decodable>::decode(decoder)) + decoder.interner().tcx.arena.alloc_from_iter( as Decodable>::decode(decoder)) } })* }; diff --git a/compiler/rustc_middle/src/ty/consts.rs b/compiler/rustc_middle/src/ty/consts.rs index 58a237ee6f825..7af7eb4f5ecfd 100644 --- a/compiler/rustc_middle/src/ty/consts.rs +++ b/compiler/rustc_middle/src/ty/consts.rs @@ -2,7 +2,7 @@ use crate::mir::interpret::ConstValue; use crate::mir::interpret::{LitToConstInput, Scalar}; use crate::ty::{ self, InlineConstSubsts, InlineConstSubstsParts, InternalSubsts, ParamEnv, ParamEnvAnd, Ty, - TyCtxt, TyInterner, TypeFoldable, + TyCtxt, TypeFoldable, }; use rustc_data_structures::intern::Interned; use rustc_errors::ErrorGuaranteed; @@ -40,14 +40,6 @@ pub struct ConstS<'tcx> { pub val: ConstKind<'tcx>, } -impl<'tcx, S: rustc_type_ir::TyEncoder>> rustc_serialize::Encodable - for &'_ Const<'_> -{ - fn encode(&self, s: &mut S) -> Result<(), S::Error> { - (*self).encode(s) - } -} - #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] static_assert_size!(ConstS<'_>, 48); diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index efe7a54b5bf1c..a5e6a1b97dddc 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -1744,7 +1744,7 @@ macro_rules! nop_lift { impl<'a, 'tcx> Lift<'tcx> for $ty { type Lifted = $lifted; fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option { - if tcx.interners.$set.contains_pointer_to(&InternedInSet(self.0.0)) { + if tcx.interners.$set.contains_pointer_to(&InternedInSet(&*self.0.0)) { // SAFETY: `self` is interned and therefore valid // for the entire lifetime of the `TyCtxt`. Some(unsafe { mem::transmute(self) }) diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 2804912c9ab8a..a7ecbdff5aee9 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -68,8 +68,8 @@ pub use self::consts::{ pub use self::context::{ tls, CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, CtxtInterners, DelaySpanBugEmitted, FreeRegionInfo, GeneratorDiagnosticData, - GeneratorInteriorTypeCause, GlobalCtxt, Lift, OnDiskCache, TyCtxt, TyInterner, TypeckResults, UserType, - UserTypeAnnotationIndex, + GeneratorInteriorTypeCause, GlobalCtxt, Lift, OnDiskCache, TyCtxt, TyInterner, TypeckResults, + UserType, UserTypeAnnotationIndex, }; pub use self::instance::{Instance, InstanceDef}; pub use self::list::List; @@ -78,13 +78,13 @@ pub use self::rvalue_scopes::RvalueScopes; pub use self::sty::BoundRegionKind::*; pub use self::sty::RegionKind::*; pub use self::sty::{ - Binder, BoundRegion, BoundRegionKind, BoundTy, BoundTyKind, BoundVar, BoundVariableKind, - CanonicalPolyFnSig, ClosureSubsts, ClosureSubstsParts, ConstVid, EarlyBinder, EarlyBoundRegion, - ExistentialPredicate, ExistentialProjection, ExistentialTraitRef, FnSig, FreeRegion, GenSig, - GeneratorSubsts, GeneratorSubstsParts, InlineConstSubsts, InlineConstSubstsParts, ParamConst, - ParamTy, PolyExistentialProjection, PolyExistentialTraitRef, PolyFnSig, PolyGenSig, - PolyTraitRef, ProjectionTy, Region, RegionKind, RegionVid, TraitRef, TyKind, TypeAndMut, - UpvarSubsts, VarianceDiagInfo, + Article, Binder, BoundRegion, BoundRegionKind, BoundTy, BoundTyKind, BoundVar, + BoundVariableKind, CanonicalPolyFnSig, ClosureSubsts, ClosureSubstsParts, ConstVid, + EarlyBinder, EarlyBoundRegion, ExistentialPredicate, ExistentialProjection, + ExistentialTraitRef, FnSig, FreeRegion, GenSig, GeneratorSubsts, GeneratorSubstsParts, + InlineConstSubsts, InlineConstSubstsParts, ParamConst, ParamTy, PolyExistentialProjection, + PolyExistentialTraitRef, PolyFnSig, PolyGenSig, PolyTraitRef, ProjectionTy, Region, RegionKind, + RegionVid, TraitRef, TyKind, TypeAndMut, UpvarSubsts, VarianceDiagInfo, }; pub use self::trait_def::TraitDef; @@ -463,16 +463,31 @@ pub(crate) struct TyS<'tcx> { #[rustc_pass_by_value] pub struct Ty<'tcx>(Interned<'tcx, WithStableHash>>); -// Statics only used for internal testing. -pub static BOOL_TY: Ty<'static> = Ty(Interned::new_unchecked(&WithStableHash { - internee: BOOL_TYS, - stable_hash: Fingerprint::ZERO, -})); -const BOOL_TYS: TyS<'static> = TyS { - kind: ty::Bool, - flags: TypeFlags::empty(), - outer_exclusive_binder: DebruijnIndex::from_usize(0), -}; +const LEAKED_BOOL_TY_ALREADY: std::sync::atomic::AtomicBool = + std::sync::atomic::AtomicBool::new(false); + +/// "Static" bool only used for internal testing. +/// +/// FIXME(rustc_type_ir): This really should be replaced with something that doesn't leak. +/// however, since it's used for testing, it's not _that_ bad. +pub fn leak_bool_ty_for_unit_testing<'tcx>() -> Ty<'tcx> { + use std::sync::atomic::*; + + if LEAKED_BOOL_TY_ALREADY.load(Ordering::Acquire) { + panic!("Can only leak one bool type, since its equality depends on its address"); + } else { + LEAKED_BOOL_TY_ALREADY.store(true, Ordering::Release); + } + + Ty(Interned::new_unchecked(Box::leak(Box::new(WithStableHash { + internee: TyS { + kind: ty::Bool, + flags: TypeFlags::empty(), + outer_exclusive_binder: DebruijnIndex::from_usize(0), + }, + stable_hash: Fingerprint::ZERO, + })))) +} impl<'a, 'tcx> HashStable> for TyS<'tcx> { #[inline] diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index 314d0ef277136..4edad27ee7a77 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -954,9 +954,7 @@ impl<'tcx> List>> { } #[inline] - pub fn auto_traits<'a>( - &'a self, - ) -> impl Iterator + rustc_data_structures::captures::Captures<'tcx> + 'a { + pub fn auto_traits<'a>(&'a self) -> impl Iterator + Captures<'tcx> + 'a { self.iter().filter_map(|predicate| match predicate.skip_binder() { ExistentialPredicate::AutoTrait(did) => Some(did), _ => None, diff --git a/compiler/rustc_middle/src/ty/subst.rs b/compiler/rustc_middle/src/ty/subst.rs index e50179face0ad..8494d5c71fe42 100644 --- a/compiler/rustc_middle/src/ty/subst.rs +++ b/compiler/rustc_middle/src/ty/subst.rs @@ -79,17 +79,17 @@ impl<'tcx> GenericArgKind<'tcx> { let (tag, ptr) = match self { GenericArgKind::Lifetime(lt) => { // Ensure we can use the tag bits. - assert_eq!(mem::align_of_val(lt.0.0) & TAG_MASK, 0); + assert_eq!(mem::align_of_val(&*lt.0.0) & TAG_MASK, 0); (REGION_TAG, lt.0.0 as *const ty::RegionKind as usize) } GenericArgKind::Type(ty) => { // Ensure we can use the tag bits. - assert_eq!(mem::align_of_val(ty.0.0) & TAG_MASK, 0); + assert_eq!(mem::align_of_val(&*ty.0.0) & TAG_MASK, 0); (TYPE_TAG, ty.0.0 as *const WithStableHash> as usize) } GenericArgKind::Const(ct) => { // Ensure we can use the tag bits. - assert_eq!(mem::align_of_val(ct.0.0) & TAG_MASK, 0); + assert_eq!(mem::align_of_val(&*ct.0.0) & TAG_MASK, 0); (CONST_TAG, ct.0.0 as *const ty::ConstS<'tcx> as usize) } }; diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index 084c47a1dc4ba..809e7ce2e745b 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -5,9 +5,7 @@ use crate::ty::fold::{FallibleTypeFolder, TypeFolder}; use crate::ty::layout::IntegerExt; use crate::ty::query::TyCtxtAt; use crate::ty::subst::{GenericArgKind, Subst, SubstsRef}; -use crate::ty::{ - self, Const, DebruijnIndex, DefIdTree, List, ReEarlyBound, Ty, TyCtxt, TypeFoldable, -}; +use crate::ty::{self, DefIdTree, Ty, TyCtxt, TypeFoldable}; use rustc_apfloat::Float as _; use rustc_ast as ast; use rustc_attr::{self as attr, SignedInt, UnsignedInt}; @@ -22,7 +20,6 @@ use rustc_macros::HashStable; use rustc_span::{sym, DUMMY_SP}; use rustc_target::abi::{Integer, Size, TargetDataLayout}; use rustc_target::spec::abi::Abi; -use rustc_type_ir::TyKind::*; use smallvec::SmallVec; use std::{fmt, iter}; diff --git a/compiler/rustc_middle/src/ty/vtable.rs b/compiler/rustc_middle/src/ty/vtable.rs index f766cad2b3d21..793b5768ad1b1 100644 --- a/compiler/rustc_middle/src/ty/vtable.rs +++ b/compiler/rustc_middle/src/ty/vtable.rs @@ -36,8 +36,9 @@ impl<'tcx> fmt::Debug for VtblEntry<'tcx> { } } -pub const COMMON_VTABLE_ENTRIES: &[VtblEntry<'_>] = - &[VtblEntry::MetadataDropInPlace, VtblEntry::MetadataSize, VtblEntry::MetadataAlign]; +pub const fn common_vtable_entries<'tcx>() -> &'tcx [VtblEntry<'tcx>] { + &[VtblEntry::MetadataDropInPlace, VtblEntry::MetadataSize, VtblEntry::MetadataAlign] +} pub const COMMON_VTABLE_ENTRIES_DROPINPLACE: usize = 0; pub const COMMON_VTABLE_ENTRIES_SIZE: usize = 1; @@ -57,7 +58,7 @@ pub(super) fn vtable_allocation_provider<'tcx>( tcx.vtable_entries(trait_ref) } else { - COMMON_VTABLE_ENTRIES + common_vtable_entries() }; let layout = tcx diff --git a/compiler/rustc_mir_transform/src/coverage/tests.rs b/compiler/rustc_mir_transform/src/coverage/tests.rs index 4615f9be33fac..41f004b0c0043 100644 --- a/compiler/rustc_mir_transform/src/coverage/tests.rs +++ b/compiler/rustc_mir_transform/src/coverage/tests.rs @@ -37,7 +37,7 @@ use rustc_data_structures::graph::WithSuccessors; use rustc_index::vec::{Idx, IndexVec}; use rustc_middle::mir::coverage::CoverageKind; use rustc_middle::mir::*; -use rustc_middle::ty::{self, BOOL_TY}; +use rustc_middle::ty::{self, Ty}; use rustc_span::{self, BytePos, Pos, Span, DUMMY_SP}; // All `TEMP_BLOCK` targets should be replaced before calling `to_body() -> mir::Body`. @@ -47,6 +47,7 @@ struct MockBlocks<'tcx> { blocks: IndexVec>, dummy_place: Place<'tcx>, next_local: usize, + bool_ty: Ty<'tcx>, } impl<'tcx> MockBlocks<'tcx> { @@ -55,6 +56,7 @@ impl<'tcx> MockBlocks<'tcx> { blocks: IndexVec::new(), dummy_place: Place { local: RETURN_PLACE, projection: ty::List::empty() }, next_local: 0, + bool_ty: ty::leak_bool_ty_for_unit_testing(), } } @@ -155,7 +157,7 @@ impl<'tcx> MockBlocks<'tcx> { fn switchint(&mut self, some_from_block: Option) -> BasicBlock { let switchint_kind = TerminatorKind::SwitchInt { discr: Operand::Move(Place::from(self.new_temp())), - switch_ty: BOOL_TY, // just a dummy value + switch_ty: self.bool_ty, // just a dummy value targets: SwitchTargets::static_if(0, TEMP_BLOCK, TEMP_BLOCK), }; self.add_block_from(some_from_block, switchint_kind) diff --git a/compiler/rustc_query_impl/src/on_disk_cache.rs b/compiler/rustc_query_impl/src/on_disk_cache.rs index 5282c317fc4bc..7dc6921a569fd 100644 --- a/compiler/rustc_query_impl/src/on_disk_cache.rs +++ b/compiler/rustc_query_impl/src/on_disk_cache.rs @@ -11,7 +11,7 @@ use rustc_middle::mir::interpret::{AllocDecodingSession, AllocDecodingState}; use rustc_middle::mir::{self, interpret}; use rustc_middle::thir; use rustc_middle::ty::codec::{RefDecodable, TyDecoder, TyEncoder}; -use rustc_middle::ty::{self, Ty, TyCtxt}; +use rustc_middle::ty::{self, Ty, TyCtxt, TyInterner}; use rustc_query_system::dep_graph::DepContext; use rustc_query_system::query::{QueryCache, QueryContext, QuerySideEffects}; use rustc_serialize::{ diff --git a/compiler/rustc_trait_selection/src/traits/mod.rs b/compiler/rustc_trait_selection/src/traits/mod.rs index dcfdff68640dd..0a0a1296aae29 100644 --- a/compiler/rustc_trait_selection/src/traits/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/mod.rs @@ -33,7 +33,7 @@ use rustc_hir::lang_items::LangItem; use rustc_middle::ty::fold::TypeFoldable; use rustc_middle::ty::subst::{InternalSubsts, SubstsRef}; use rustc_middle::ty::{ - self, GenericParamDefKind, ToPredicate, Ty, TyCtxt, VtblEntry, COMMON_VTABLE_ENTRIES, + self, common_vtable_entries, GenericParamDefKind, ToPredicate, Ty, TyCtxt, VtblEntry, }; use rustc_span::{sym, Span}; use smallvec::SmallVec; @@ -695,7 +695,7 @@ fn vtable_entries<'tcx>( let vtable_segment_callback = |segment| -> ControlFlow<()> { match segment { VtblSegment::MetadataDSA => { - entries.extend(COMMON_VTABLE_ENTRIES); + entries.extend(common_vtable_entries()); } VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => { let existential_trait_ref = trait_ref @@ -785,7 +785,7 @@ fn vtable_trait_first_method_offset<'tcx>( move |segment| { match segment { VtblSegment::MetadataDSA => { - vtable_base += COMMON_VTABLE_ENTRIES.len(); + vtable_base += common_vtable_entries().len(); } VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => { if tcx.erase_regions(trait_ref) == trait_to_be_found_erased { diff --git a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs index d607f4e7642b6..548b60d74bac0 100644 --- a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs +++ b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs @@ -834,7 +834,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { move |segment| { match segment { VtblSegment::MetadataDSA => { - vptr_offset += ty::COMMON_VTABLE_ENTRIES.len(); + vptr_offset += ty::common_vtable_entries().len(); } VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => { vptr_offset += util::count_own_vtable_entries(tcx, trait_ref); diff --git a/compiler/rustc_ty_utils/Cargo.toml b/compiler/rustc_ty_utils/Cargo.toml index 78df95e680e00..d03d675bfd231 100644 --- a/compiler/rustc_ty_utils/Cargo.toml +++ b/compiler/rustc_ty_utils/Cargo.toml @@ -14,3 +14,4 @@ rustc_span = { path = "../rustc_span" } rustc_session = { path = "../rustc_session" } rustc_target = { path = "../rustc_target" } rustc_trait_selection = { path = "../rustc_trait_selection" } +rustc_type_ir = { path = "../rustc_type_ir" } diff --git a/compiler/rustc_type_ir/src/codec.rs b/compiler/rustc_type_ir/src/codec.rs index e0138f8aad92f..09f781fae75bd 100644 --- a/compiler/rustc_type_ir/src/codec.rs +++ b/compiler/rustc_type_ir/src/codec.rs @@ -47,7 +47,11 @@ pub trait TyDecoder: Decoder { fn position(&self) -> usize; - fn cached_ty_for_shorthand(&mut self, shorthand: usize, or_insert_with: F) -> ::Ty + fn cached_ty_for_shorthand( + &mut self, + shorthand: usize, + or_insert_with: F, + ) -> ::Ty where F: FnOnce(&mut Self) -> ::Ty; @@ -60,4 +64,4 @@ pub trait TyDecoder: Decoder { } fn decode_alloc_id(&mut self) -> ::AllocId; -} \ No newline at end of file +} diff --git a/compiler/rustc_type_ir/src/sty.rs b/compiler/rustc_type_ir/src/sty.rs index 8f43904d96a31..0f614967defcb 100644 --- a/compiler/rustc_type_ir/src/sty.rs +++ b/compiler/rustc_type_ir/src/sty.rs @@ -13,7 +13,7 @@ use rustc_serialize::{Decodable, Encodable}; /// Types written by the user start out as [hir::TyKind](rustc_hir::TyKind) and get /// converted to this representation using `AstConv::ast_ty_to_ty`. #[allow(rustc::usage_of_ty_tykind)] -#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] +#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] //#[derive(TyEncodable, TyDecodable)] //#[derive(HashStable)] #[rustc_diagnostic_item = "TyKind"] @@ -186,6 +186,42 @@ pub enum TyKind { Error(I::DelaySpanBugEmitted), } +#[allow(rustc::usage_of_ty_tykind)] +impl Clone for TyKind { + fn clone(&self) -> Self { + use crate::TyKind::*; + match self { + Bool => Bool, + Char => Char, + Int(i) => Int(i.clone()), + Uint(u) => Uint(u.clone()), + Float(f) => Float(f.clone()), + Adt(d, s) => Adt(d.clone(), s.clone()), + Foreign(d) => Foreign(d.clone()), + Str => Str, + Array(t, c) => Array(t.clone(), c.clone()), + Slice(t) => Slice(t.clone()), + RawPtr(t) => RawPtr(t.clone()), + Ref(r, t, m) => Ref(r.clone(), t.clone(), m.clone()), + FnDef(d, s) => FnDef(d.clone(), s.clone()), + FnPtr(s) => FnPtr(s.clone()), + Dynamic(p, r) => Dynamic(p.clone(), r.clone()), + Closure(d, s) => Closure(d.clone(), s.clone()), + Generator(d, s, m) => Generator(d.clone(), s.clone(), m.clone()), + GeneratorWitness(g) => GeneratorWitness(g.clone()), + Never => Never, + Tuple(t) => Tuple(t.clone()), + Projection(p) => Projection(p.clone()), + Opaque(d, s) => Opaque(d.clone(), s.clone()), + Param(p) => Param(p.clone()), + Bound(d, b) => Bound(d.clone(), b.clone()), + Placeholder(p) => Placeholder(p.clone()), + Infer(t) => Infer(t.clone()), + Error(e) => Error(e.clone()), + } + } +} + #[allow(rustc::usage_of_ty_tykind)] impl TyKind { #[inline] @@ -383,9 +419,7 @@ where rustc_serialize::Decodable::decode(__decoder), ), 9 => Slice(rustc_serialize::Decodable::decode(__decoder)), - 10 => RawPtr( - rustc_serialize::Decodable::decode(__decoder), - ), + 10 => RawPtr(rustc_serialize::Decodable::decode(__decoder)), 11 => Ref( rustc_serialize::Decodable::decode(__decoder), rustc_serialize::Decodable::decode(__decoder), @@ -395,9 +429,7 @@ where rustc_serialize::Decodable::decode(__decoder), rustc_serialize::Decodable::decode(__decoder), ), - 13 => FnPtr( - rustc_serialize::Decodable::decode(__decoder), - ), + 13 => FnPtr(rustc_serialize::Decodable::decode(__decoder)), 14 => Dynamic( rustc_serialize::Decodable::decode(__decoder), rustc_serialize::Decodable::decode(__decoder), @@ -411,44 +443,29 @@ where rustc_serialize::Decodable::decode(__decoder), rustc_serialize::Decodable::decode(__decoder), ), - 17 => GeneratorWitness( - rustc_serialize::Decodable::decode(__decoder), - ), + 17 => GeneratorWitness(rustc_serialize::Decodable::decode(__decoder)), 18 => Never, - 19 => Tuple( - rustc_serialize::Decodable::decode(__decoder), - ), - 20 => Projection( - rustc_serialize::Decodable::decode(__decoder), - ), + 19 => Tuple(rustc_serialize::Decodable::decode(__decoder)), + 20 => Projection(rustc_serialize::Decodable::decode(__decoder)), 21 => Opaque( rustc_serialize::Decodable::decode(__decoder), rustc_serialize::Decodable::decode(__decoder), ), - 22 => Param( - rustc_serialize::Decodable::decode(__decoder), - ), + 22 => Param(rustc_serialize::Decodable::decode(__decoder)), 23 => Bound( rustc_serialize::Decodable::decode(__decoder), rustc_serialize::Decodable::decode(__decoder), ), - 24 => Placeholder( - rustc_serialize::Decodable::decode(__decoder), - ), - 25 => Infer( - rustc_serialize::Decodable::decode(__decoder), - ), - 26 => Error( - rustc_serialize::Decodable::decode(__decoder), + 24 => Placeholder(rustc_serialize::Decodable::decode(__decoder)), + 25 => Infer(rustc_serialize::Decodable::decode(__decoder)), + 26 => Error(rustc_serialize::Decodable::decode(__decoder)), + _ => panic!( + "{}", + format!( + "invalid enum variant tag while decoding `{}`, expected 0..{}", + "TyKind", 27, + ) ), - _ => - panic!( - "{}", - format!( - "invalid enum variant tag while decoding `{}`, expected 0..{}", - "TyKind", 27, - ) - ), } } } diff --git a/compiler/rustc_typeck/Cargo.toml b/compiler/rustc_typeck/Cargo.toml index 57930a28a35a1..c08023ee6a70a 100644 --- a/compiler/rustc_typeck/Cargo.toml +++ b/compiler/rustc_typeck/Cargo.toml @@ -29,3 +29,4 @@ rustc_trait_selection = { path = "../rustc_trait_selection" } rustc_ty_utils = { path = "../rustc_ty_utils" } rustc_lint = { path = "../rustc_lint" } rustc_serialize = { path = "../rustc_serialize" } +rustc_type_ir = { path = "../rustc_type_ir" } diff --git a/compiler/rustc_typeck/src/check/demand.rs b/compiler/rustc_typeck/src/check/demand.rs index d0d2841209a6e..419ccb5a73aac 100644 --- a/compiler/rustc_typeck/src/check/demand.rs +++ b/compiler/rustc_typeck/src/check/demand.rs @@ -12,7 +12,7 @@ use rustc_middle::lint::in_external_macro; use rustc_middle::ty::adjustment::AllowTwoPhase; use rustc_middle::ty::error::{ExpectedFound, TypeError}; use rustc_middle::ty::print::with_no_trimmed_paths; -use rustc_middle::ty::{self, AssocItem, Ty, TypeAndMut}; +use rustc_middle::ty::{self, Article, AssocItem, Ty, TypeAndMut}; use rustc_span::symbol::{sym, Symbol}; use rustc_span::{BytePos, Span}; diff --git a/compiler/rustc_typeck/src/check/intrinsicck.rs b/compiler/rustc_typeck/src/check/intrinsicck.rs index 027868be8bb0d..75508009ad825 100644 --- a/compiler/rustc_typeck/src/check/intrinsicck.rs +++ b/compiler/rustc_typeck/src/check/intrinsicck.rs @@ -4,7 +4,7 @@ use rustc_errors::struct_span_err; use rustc_hir as hir; use rustc_index::vec::Idx; use rustc_middle::ty::layout::{LayoutError, SizeSkeleton}; -use rustc_middle::ty::{self, FloatTy, InferTy, IntTy, Ty, TyCtxt, TypeFoldable, UintTy}; +use rustc_middle::ty::{self, FloatTy, InferTy, IntTy, Ty, TyCtxt, TypeFoldable, UintTy, Article}; use rustc_session::lint; use rustc_span::{Span, Symbol, DUMMY_SP}; use rustc_target::abi::{Pointer, VariantIdx}; diff --git a/compiler/rustc_typeck/src/check/op.rs b/compiler/rustc_typeck/src/check/op.rs index 637f6459525a2..6df9ac5f0a430 100644 --- a/compiler/rustc_typeck/src/check/op.rs +++ b/compiler/rustc_typeck/src/check/op.rs @@ -10,7 +10,6 @@ use rustc_middle::ty::adjustment::{ Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, }; use rustc_middle::ty::fold::TypeFolder; -use rustc_middle::ty::TyKind::{Adt, Array, Char, FnDef, Never, Ref, Str, Tuple, Uint}; use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable, TypeVisitor}; use rustc_span::source_map::Spanned; use rustc_span::symbol::{sym, Ident}; @@ -18,6 +17,7 @@ use rustc_span::Span; use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits::error_reporting::suggestions::InferCtxtExt as _; use rustc_trait_selection::traits::{FulfillmentError, TraitEngine, TraitEngineExt}; +use rustc_type_ir::sty::TyKind::*; use std::ops::ControlFlow; @@ -677,6 +677,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { operand_ty: Ty<'tcx>, op: hir::UnOp, ) -> Ty<'tcx> { + use rustc_type_ir::sty::TyKind::*; + assert!(op.is_by_value()); match self.lookup_op_method(operand_ty, None, None, Op::Unary(op, ex.span)) { Ok(method) => { From 34e05812e029206add91fa39df86765fcb3f8b5a Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Thu, 26 May 2022 20:22:28 -0700 Subject: [PATCH 3/5] Fix TyKind lint, make consts no longer fn, etc --- compiler/rustc_borrowck/src/lib.rs | 8 +- .../src/debuginfo/metadata.rs | 4 +- .../rustc_const_eval/src/interpret/traits.rs | 10 +- compiler/rustc_lint/src/internal.rs | 191 +++-- compiler/rustc_middle/src/ty/context.rs | 2 + compiler/rustc_middle/src/ty/fast_reject.rs | 8 +- compiler/rustc_middle/src/ty/mod.rs | 8 +- compiler/rustc_middle/src/ty/sty.rs | 204 +---- compiler/rustc_middle/src/ty/vtable.rs | 8 +- compiler/rustc_span/src/symbol.rs | 1 + .../rustc_trait_selection/src/traits/mod.rs | 8 +- .../src/traits/select/confirmation.rs | 4 +- compiler/rustc_type_ir/src/lib.rs | 2 - compiler/rustc_type_ir/src/sty.rs | 718 ++++++++++++++---- .../obtain-borrowck/driver.rs | 2 +- .../internal-lints/ty_tykind_usage.rs | 60 +- .../internal-lints/ty_tykind_usage.stderr | 146 ++-- 17 files changed, 857 insertions(+), 527 deletions(-) diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs index 93c7a832afd51..bf38ca19484c9 100644 --- a/compiler/rustc_borrowck/src/lib.rs +++ b/compiler/rustc_borrowck/src/lib.rs @@ -98,8 +98,10 @@ struct Upvar<'tcx> { by_ref: bool, } -const fn deref_projection<'tcx>() -> &'tcx [PlaceElem<'tcx>; 1] { - &[ProjectionElem::Deref] +/// Associate some local constants with the `'tcx` lifetime +struct TyCtxtConsts<'tcx>(TyCtxt<'tcx>); +impl<'tcx> TyCtxtConsts<'tcx> { + const DEREF_PROJECTION: &'tcx [PlaceElem<'tcx>; 1] = &[ProjectionElem::Deref]; } pub fn provide(providers: &mut Providers) { @@ -1445,7 +1447,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { // Thread-locals might be dropped after the function exits // We have to dereference the outer reference because // borrows don't conflict behind shared references. - root_place.projection = deref_projection(); + root_place.projection = TyCtxtConsts::DEREF_PROJECTION; (true, true) } else { (false, self.locals_are_invalidated_at_exit) diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs index bbbd1e945148e..dd3adbf70a62f 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs @@ -33,7 +33,7 @@ use rustc_middle::mir::{self, GeneratorLayout}; use rustc_middle::ty::layout::LayoutOf; use rustc_middle::ty::layout::TyAndLayout; use rustc_middle::ty::subst::GenericArgKind; -use rustc_middle::ty::{self, common_vtable_entries, AdtKind, Instance, ParamEnv, Ty, TyCtxt}; +use rustc_middle::ty::{self, AdtKind, Instance, ParamEnv, Ty, TyCtxt}; use rustc_session::config::{self, DebugInfo}; use rustc_span::symbol::Symbol; use rustc_span::FileName; @@ -1392,7 +1392,7 @@ fn build_vtable_type_di_node<'ll, 'tcx>( tcx.vtable_entries(trait_ref) } else { - common_vtable_entries() + TyCtxt::COMMON_VTABLE_ENTRIES }; // All function pointers are described as opaque pointers. This could be improved in the future diff --git a/compiler/rustc_const_eval/src/interpret/traits.rs b/compiler/rustc_const_eval/src/interpret/traits.rs index d5a448a8963a3..c4d1074e4379c 100644 --- a/compiler/rustc_const_eval/src/interpret/traits.rs +++ b/compiler/rustc_const_eval/src/interpret/traits.rs @@ -2,8 +2,8 @@ use std::convert::TryFrom; use rustc_middle::mir::interpret::{InterpResult, Pointer, PointerArithmetic}; use rustc_middle::ty::{ - self, common_vtable_entries, Ty, COMMON_VTABLE_ENTRIES_ALIGN, - COMMON_VTABLE_ENTRIES_DROPINPLACE, COMMON_VTABLE_ENTRIES_SIZE, + self, Ty, TyCtxt, COMMON_VTABLE_ENTRIES_ALIGN, COMMON_VTABLE_ENTRIES_DROPINPLACE, + COMMON_VTABLE_ENTRIES_SIZE, }; use rustc_target::abi::{Align, Size}; @@ -38,7 +38,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { } /// Resolves the function at the specified slot in the provided - /// vtable. Currently an index of '3' (`common_vtable_entries().len()`) + /// vtable. Currently an index of '3' (`TyCtxt::COMMON_VTABLE_ENTRIES.len()`) /// corresponds to the first method declared in the trait of the provided vtable. pub fn get_vtable_slot( &self, @@ -64,7 +64,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let vtable = self .get_ptr_alloc( vtable, - pointer_size * u64::try_from(common_vtable_entries().len()).unwrap(), + pointer_size * u64::try_from(TyCtxt::COMMON_VTABLE_ENTRIES.len()).unwrap(), self.tcx.data_layout.pointer_align.abi, )? .expect("cannot be a ZST"); @@ -99,7 +99,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { let vtable = self .get_ptr_alloc( vtable, - pointer_size * u64::try_from(common_vtable_entries().len()).unwrap(), + pointer_size * u64::try_from(TyCtxt::COMMON_VTABLE_ENTRIES.len()).unwrap(), self.tcx.data_layout.pointer_align.abi, )? .expect("cannot be a ZST"); diff --git a/compiler/rustc_lint/src/internal.rs b/compiler/rustc_lint/src/internal.rs index 27d44da6dfc38..b83d63e0da086 100644 --- a/compiler/rustc_lint/src/internal.rs +++ b/compiler/rustc_lint/src/internal.rs @@ -5,8 +5,8 @@ use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext} use rustc_ast as ast; use rustc_errors::Applicability; use rustc_hir::def::Res; -use rustc_hir::{Expr, ExprKind, GenericArg, Path, PathSegment, QPath}; -use rustc_hir::{HirId, Item, ItemKind, Node, Ty, TyKind}; +use rustc_hir::{Expr, ExprKind, GenericArg, PatKind, Path, PathSegment, QPath}; +use rustc_hir::{HirId, Item, ItemKind, Node, Pat, Ty, TyKind}; use rustc_middle::ty; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::hygiene::{ExpnKind, MacroKind}; @@ -123,55 +123,115 @@ declare_lint_pass!(TyTyKind => [ ]); impl<'tcx> LateLintPass<'tcx> for TyTyKind { - fn check_path(&mut self, cx: &LateContext<'_>, path: &'tcx Path<'tcx>, _: HirId) { - let segments = path.segments.iter().rev().skip(1).rev(); - - if let Some(last) = segments.last() { - let span = path.span.with_hi(last.ident.span.hi()); - if lint_ty_kind_usage(cx, last) { - cx.struct_span_lint(USAGE_OF_TY_TYKIND, span, |lint| { - lint.build("usage of `ty::TyKind::`") - .span_suggestion( - span, - "try using ty:: directly", - "ty".to_string(), - Applicability::MaybeIncorrect, // ty maybe needs an import - ) - .emit(); - }) - } + fn check_path( + &mut self, + cx: &LateContext<'tcx>, + path: &'tcx rustc_hir::Path<'tcx>, + _: rustc_hir::HirId, + ) { + if let Some(segment) = path.segments.iter().nth_back(1) + && let Some(res) = &segment.res + && lint_ty_kind_usage(cx, res) + { + let span = path.span.with_hi( + segment.args.map_or(segment.ident.span, |a| a.span_ext).hi() + ); + cx.struct_span_lint(USAGE_OF_TY_TYKIND, path.span, |lint| { + lint.build("usage of `ty::TyKind::`") + .span_suggestion( + span, + "try using `ty::` directly", + "ty".to_string(), + Applicability::MaybeIncorrect, // ty maybe needs an import + ) + .emit(); + }); } } fn check_ty(&mut self, cx: &LateContext<'_>, ty: &'tcx Ty<'tcx>) { match &ty.kind { TyKind::Path(QPath::Resolved(_, path)) => { - if let Some(last) = path.segments.iter().last() { - if lint_ty_kind_usage(cx, last) { - cx.struct_span_lint(USAGE_OF_TY_TYKIND, path.span, |lint| { - lint.build("usage of `ty::TyKind`") - .help("try using `Ty` instead") - .emit(); - }) - } else { - if ty.span.from_expansion() { - return; - } - if let Some(t) = is_ty_or_ty_ctxt(cx, ty) { - if path.segments.len() > 1 { - cx.struct_span_lint(USAGE_OF_QUALIFIED_TY, path.span, |lint| { - lint.build(&format!("usage of qualified `ty::{}`", t)) + if lint_ty_kind_usage(cx, &path.res) { + cx.struct_span_lint(USAGE_OF_TY_TYKIND, path.span, |lint| { + let hir = cx.tcx.hir(); + match hir.find(hir.get_parent_node(ty.hir_id)) { + Some(Node::Pat(Pat { + kind: + PatKind::Path(qpath) + | PatKind::TupleStruct(qpath, ..) + | PatKind::Struct(qpath, ..), + .. + })) => { + if let QPath::TypeRelative(qpath_ty, ..) = qpath + && qpath_ty.hir_id == ty.hir_id + { + lint.build("usage of `ty::TyKind::`") + .span_suggestion( + path.span, + "try using `ty::` directly", + "ty".to_string(), + Applicability::MaybeIncorrect, // ty maybe needs an import + ) + .emit(); + return; + } + } + Some(Node::Expr(Expr { + kind: ExprKind::Path(qpath), + .. + })) => { + if let QPath::TypeRelative(qpath_ty, ..) = qpath + && qpath_ty.hir_id == ty.hir_id + { + lint.build("usage of `ty::TyKind::`") .span_suggestion( path.span, - "try importing it and using it unqualified", - t, - // The import probably needs to be changed - Applicability::MaybeIncorrect, + "try using `ty::` directly", + "ty".to_string(), + Applicability::MaybeIncorrect, // ty maybe needs an import ) .emit(); - }) + return; + } } + // Can't unify these two branches because qpath below is `&&` and above is `&` + // and `A | B` paths don't play well together with adjustments, apparently. + Some(Node::Expr(Expr { + kind: ExprKind::Struct(qpath, ..), + .. + })) => { + if let QPath::TypeRelative(qpath_ty, ..) = qpath + && qpath_ty.hir_id == ty.hir_id + { + lint.build("usage of `ty::TyKind::`") + .span_suggestion( + path.span, + "try using `ty::` directly", + "ty".to_string(), + Applicability::MaybeIncorrect, // ty maybe needs an import + ) + .emit(); + return; + } + } + _ => {} } + lint.build("usage of `ty::TyKind`").help("try using `Ty` instead").emit(); + }) + } else if !ty.span.from_expansion() && let Some(t) = is_ty_or_ty_ctxt(cx, &path) { + if path.segments.len() > 1 { + cx.struct_span_lint(USAGE_OF_QUALIFIED_TY, path.span, |lint| { + lint.build(&format!("usage of qualified `ty::{}`", t)) + .span_suggestion( + path.span, + "try importing it and using it unqualified", + t, + // The import probably needs to be changed + Applicability::MaybeIncorrect, + ) + .emit(); + }) } } } @@ -180,42 +240,37 @@ impl<'tcx> LateLintPass<'tcx> for TyTyKind { } } -fn lint_ty_kind_usage(cx: &LateContext<'_>, segment: &PathSegment<'_>) -> bool { - if let Some(res) = segment.res { - if let Some(did) = res.opt_def_id() { - return cx.tcx.is_diagnostic_item(sym::TyKind, did); - } +fn lint_ty_kind_usage(cx: &LateContext<'_>, res: &Res) -> bool { + if let Some(did) = res.opt_def_id() { + cx.tcx.is_diagnostic_item(sym::TyKind, did) || cx.tcx.is_diagnostic_item(sym::IrTyKind, did) + } else { + false } - - false } -fn is_ty_or_ty_ctxt(cx: &LateContext<'_>, ty: &Ty<'_>) -> Option { - if let TyKind::Path(QPath::Resolved(_, path)) = &ty.kind { - match path.res { - Res::Def(_, def_id) => { - if let Some(name @ (sym::Ty | sym::TyCtxt)) = cx.tcx.get_diagnostic_name(def_id) { - return Some(format!("{}{}", name, gen_args(path.segments.last().unwrap()))); - } +fn is_ty_or_ty_ctxt(cx: &LateContext<'_>, path: &Path<'_>) -> Option { + match &path.res { + Res::Def(_, def_id) => { + if let Some(name @ (sym::Ty | sym::TyCtxt)) = cx.tcx.get_diagnostic_name(*def_id) { + return Some(format!("{}{}", name, gen_args(path.segments.last().unwrap()))); } - // Only lint on `&Ty` and `&TyCtxt` if it is used outside of a trait. - Res::SelfTy { trait_: None, alias_to: Some((did, _)) } => { - if let ty::Adt(adt, substs) = cx.tcx.type_of(did).kind() { - if let Some(name @ (sym::Ty | sym::TyCtxt)) = - cx.tcx.get_diagnostic_name(adt.did()) - { - // NOTE: This path is currently unreachable as `Ty<'tcx>` is - // defined as a type alias meaning that `impl<'tcx> Ty<'tcx>` - // is not actually allowed. - // - // I(@lcnr) still kept this branch in so we don't miss this - // if we ever change it in the future. - return Some(format!("{}<{}>", name, substs[0])); - } + } + // Only lint on `&Ty` and `&TyCtxt` if it is used outside of a trait. + Res::SelfTy { trait_: None, alias_to: Some((did, _)) } => { + if let ty::Adt(adt, substs) = cx.tcx.type_of(did).kind() { + if let Some(name @ (sym::Ty | sym::TyCtxt)) = cx.tcx.get_diagnostic_name(adt.did()) + { + // NOTE: This path is currently unreachable as `Ty<'tcx>` is + // defined as a type alias meaning that `impl<'tcx> Ty<'tcx>` + // is not actually allowed. + // + // I(@lcnr) still kept this branch in so we don't miss this + // if we ever change it in the future. + return Some(format!("{}<{}>", name, substs[0])); } } - _ => (), } + _ => (), } None diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index a5e6a1b97dddc..6f548658ef33d 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -94,6 +94,7 @@ pub struct TyInterner<'tcx> { pub tcx: TyCtxt<'tcx>, } +/* /// We don't ever actually need this. It's only required for derives. impl<'tcx> Hash for TyInterner<'tcx> { fn hash(&self, _state: &mut H) {} @@ -128,6 +129,7 @@ impl fmt::Debug for TyInterner<'_> { write!(f, "TyInterner") } } +*/ #[allow(rustc::usage_of_ty_tykind)] impl<'tcx> Interner for TyInterner<'tcx> { diff --git a/compiler/rustc_middle/src/ty/fast_reject.rs b/compiler/rustc_middle/src/ty/fast_reject.rs index f7ced066062ad..208cd9ba16a08 100644 --- a/compiler/rustc_middle/src/ty/fast_reject.rs +++ b/compiler/rustc_middle/src/ty/fast_reject.rs @@ -207,10 +207,10 @@ pub struct DeepRejectCtxt { } impl DeepRejectCtxt { - pub fn generic_args_may_unify( + pub fn generic_args_may_unify<'tcx>( self, - obligation_arg: ty::GenericArg<'_>, - impl_arg: ty::GenericArg<'_>, + obligation_arg: ty::GenericArg<'tcx>, + impl_arg: ty::GenericArg<'tcx>, ) -> bool { match (obligation_arg.unpack(), impl_arg.unpack()) { // We don't fast reject based on regions for now. @@ -225,7 +225,7 @@ impl DeepRejectCtxt { } } - pub fn types_may_unify(self, obligation_ty: Ty<'_>, impl_ty: Ty<'_>) -> bool { + pub fn types_may_unify<'tcx>(self, obligation_ty: Ty<'tcx>, impl_ty: Ty<'tcx>) -> bool { match impl_ty.kind() { // Start by checking whether the type in the impl may unify with // pretty much everything. Just return `true` in that case. diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index a7ecbdff5aee9..25305804d3a71 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -449,13 +449,13 @@ pub(crate) struct TyS<'tcx> { } // `TyS` is used a lot. Make sure it doesn't unintentionally get bigger. -//#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] -//static_assert_size!(TyS<'_>, 40); +#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] +static_assert_size!(TyS<'_>, 40); // We are actually storing a stable hash cache next to the type, so let's // also check the full size -//#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] -//static_assert_size!(WithStableHash>, 56); +#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] +static_assert_size!(WithStableHash>, 56); /// Use this rather than `TyS`, whenever possible. #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, HashStable)] diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index 4edad27ee7a77..9410166ac2013 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -27,9 +27,12 @@ use std::marker::PhantomData; use std::ops::{ControlFlow, Deref, Range}; use ty::util::IntTypeExt; +use rustc_type_ir::sty::TyKind::*; use rustc_type_ir::TyKind as IrTyKind; + +// Re-export the `TyKind` from `rustc_type_ir` here for convenience +#[rustc_diagnostic_item = "TyKind"] pub type TyKind<'tcx> = IrTyKind>; -use rustc_type_ir::sty::TyKind::*; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] #[derive(HashStable, TypeFoldable, Lift)] @@ -80,205 +83,6 @@ impl BoundRegionKind { } } -/* -/// Defines the kinds of types used by the type system. -/// -/// Types written by the user start out as [hir::TyKind](rustc_hir::TyKind) and get -/// converted to this representation using `AstConv::ast_ty_to_ty`. -#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable, Debug)] -#[derive(HashStable)] -#[rustc_diagnostic_item = "TyKind"] -pub enum TyKind<'tcx> { - /// The primitive boolean type. Written as `bool`. - Bool, - - /// The primitive character type; holds a Unicode scalar value - /// (a non-surrogate code point). Written as `char`. - Char, - - /// A primitive signed integer type. For example, `i32`. - Int(ty::IntTy), - - /// A primitive unsigned integer type. For example, `u32`. - Uint(ty::UintTy), - - /// A primitive floating-point type. For example, `f64`. - Float(ty::FloatTy), - - /// Algebraic data types (ADT). For example: structures, enumerations and unions. - /// - /// For example, the type `List` would be represented using the `AdtDef` - /// for `struct List` and the substs `[i32]`. - /// - /// Note that generic parameters in fields only get lazily substituted - /// by using something like `adt_def.all_fields().map(|field| field.ty(tcx, substs))`. - Adt(AdtDef<'tcx>, SubstsRef<'tcx>), - - /// An unsized FFI type that is opaque to Rust. Written as `extern type T`. - Foreign(DefId), - - /// The pointee of a string slice. Written as `str`. - Str, - - /// An array with the given length. Written as `[T; N]`. - Array(Ty<'tcx>, ty::Const<'tcx>), - - /// The pointee of an array slice. Written as `[T]`. - Slice(Ty<'tcx>), - - /// A raw pointer. Written as `*mut T` or `*const T` - RawPtr(TypeAndMut<'tcx>), - - /// A reference; a pointer with an associated lifetime. Written as - /// `&'a mut T` or `&'a T`. - Ref(Region<'tcx>, Ty<'tcx>, hir::Mutability), - - /// The anonymous type of a function declaration/definition. Each - /// function has a unique type. - /// - /// For the function `fn foo() -> i32 { 3 }` this type would be - /// shown to the user as `fn() -> i32 {foo}`. - /// - /// For example the type of `bar` here: - /// ```rust - /// fn foo() -> i32 { 1 } - /// let bar = foo; // bar: fn() -> i32 {foo} - /// ``` - FnDef(DefId, SubstsRef<'tcx>), - - /// A pointer to a function. Written as `fn() -> i32`. - /// - /// Note that both functions and closures start out as either - /// [FnDef] or [Closure] which can be then be coerced to this variant. - /// - /// For example the type of `bar` here: - /// - /// ```rust - /// fn foo() -> i32 { 1 } - /// let bar: fn() -> i32 = foo; - /// ``` - FnPtr(PolyFnSig<'tcx>), - - /// A trait object. Written as `dyn for<'b> Trait<'b, Assoc = u32> + Send + 'a`. - Dynamic(&'tcx List>>, ty::Region<'tcx>), - - /// The anonymous type of a closure. Used to represent the type of `|a| a`. - /// - /// Closure substs contain both the - potentially substituted - generic parameters - /// of its parent and some synthetic parameters. See the documentation for - /// [ClosureSubsts] for more details. - Closure(DefId, SubstsRef<'tcx>), - - /// The anonymous type of a generator. Used to represent the type of - /// `|a| yield a`. - /// - /// For more info about generator substs, visit the documentation for - /// [GeneratorSubsts]. - Generator(DefId, SubstsRef<'tcx>, hir::Movability), - - /// A type representing the types stored inside a generator. - /// This should only appear as part of the [GeneratorSubsts]. - /// - /// Note that the captured variables for generators are stored separately - /// using a tuple in the same way as for closures. - /// - /// Unlike upvars, the witness can reference lifetimes from - /// inside of the generator itself. To deal with them in - /// the type of the generator, we convert them to higher ranked - /// lifetimes bound by the witness itself. - /// - /// Looking at the following example, the witness for this generator - /// may end up as something like `for<'a> [Vec, &'a Vec]`: - /// - /// ```ignore UNSOLVED (ask @compiler-errors, should this error? can we just swap the yields?) - /// #![feature(generators)] - /// |a| { - /// let x = &vec![3]; - /// yield a; - /// yield x[0]; - /// } - /// # ; - /// ``` - GeneratorWitness(Binder<'tcx, &'tcx List>>), - - /// The never type `!`. - Never, - - /// A tuple type. For example, `(i32, bool)`. - Tuple(&'tcx List>), - - /// The projection of an associated type. For example, - /// `>::N`. - Projection(ProjectionTy<'tcx>), - - /// Opaque (`impl Trait`) type found in a return type. - /// - /// The `DefId` comes either from - /// * the `impl Trait` ast::Ty node, - /// * or the `type Foo = impl Trait` declaration - /// - /// For RPIT the substitutions are for the generics of the function, - /// while for TAIT it is used for the generic parameters of the alias. - /// - /// During codegen, `tcx.type_of(def_id)` can be used to get the underlying type. - Opaque(DefId, SubstsRef<'tcx>), - - /// A type parameter; for example, `T` in `fn f(x: T) {}`. - Param(ParamTy), - - /// Bound type variable, used to represent the `'a` in `for<'a> fn(&'a ())`. - /// - /// For canonical queries, we replace inference variables with bound variables, - /// so e.g. when checking whether `&'_ (): Trait<_>` holds, we canonicalize that to - /// `for<'a, T> &'a (): Trait` and then convert the introduced bound variables - /// back to inference variables in a new inference context when inside of the query. - /// - /// See the `rustc-dev-guide` for more details about - /// [higher-ranked trait bounds][1] and [canonical queries][2]. - /// - /// [1]: https://rustc-dev-guide.rust-lang.org/traits/hrtb.html - /// [2]: https://rustc-dev-guide.rust-lang.org/traits/canonical-queries.html - Bound(ty::DebruijnIndex, BoundTy), - - /// A placeholder type, used during higher ranked subtyping to instantiate - /// bound variables. - Placeholder(ty::PlaceholderType), - - /// A type variable used during type checking. - /// - /// Similar to placeholders, inference variables also live in a universe to - /// correctly deal with higher ranked types. Though unlike placeholders, - /// that universe is stored in the `InferCtxt` instead of directly - /// inside of the type. - Infer(InferTy), - - /// A placeholder for a type which could not be computed; this is - /// propagated to avoid useless error messages. - Error(DelaySpanBugEmitted), -} -*/ - -/* -impl<'tcx> TyKind<'tcx> { - #[inline] - pub fn is_primitive(&self) -> bool { - matches!(self, Bool | Char | Int(_) | Uint(_) | Float(_)) - } - - /// Get the article ("a" or "an") to use with this type. - pub fn article(&self) -> &'static str { - match self { - Int(_) | Float(_) | Array(_, _) => "an", - Adt(def, _) if def.is_enum() => "an", - // This should never happen, but ICEing and causing the user's code - // to not compile felt too harsh. - Error(_) => "a", - _ => "a", - } - } -} -*/ - pub trait Article { fn article(&self) -> &'static str; } diff --git a/compiler/rustc_middle/src/ty/vtable.rs b/compiler/rustc_middle/src/ty/vtable.rs index 793b5768ad1b1..04a9fd1f71308 100644 --- a/compiler/rustc_middle/src/ty/vtable.rs +++ b/compiler/rustc_middle/src/ty/vtable.rs @@ -36,8 +36,10 @@ impl<'tcx> fmt::Debug for VtblEntry<'tcx> { } } -pub const fn common_vtable_entries<'tcx>() -> &'tcx [VtblEntry<'tcx>] { - &[VtblEntry::MetadataDropInPlace, VtblEntry::MetadataSize, VtblEntry::MetadataAlign] +// Needs to be associated with the `'tcx` lifetime +impl<'tcx> TyCtxt<'tcx> { + pub const COMMON_VTABLE_ENTRIES: &'tcx [VtblEntry<'tcx>] = + &[VtblEntry::MetadataDropInPlace, VtblEntry::MetadataSize, VtblEntry::MetadataAlign]; } pub const COMMON_VTABLE_ENTRIES_DROPINPLACE: usize = 0; @@ -58,7 +60,7 @@ pub(super) fn vtable_allocation_provider<'tcx>( tcx.vtable_entries(trait_ref) } else { - common_vtable_entries() + TyCtxt::COMMON_VTABLE_ENTRIES }; let layout = tcx diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 406e9a4113ef3..6aeedc49adf55 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -205,6 +205,7 @@ symbols! { IntoIterator, IoRead, IoWrite, + IrTyKind, Is, ItemContext, Iterator, diff --git a/compiler/rustc_trait_selection/src/traits/mod.rs b/compiler/rustc_trait_selection/src/traits/mod.rs index 0a0a1296aae29..03757b5447eea 100644 --- a/compiler/rustc_trait_selection/src/traits/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/mod.rs @@ -32,9 +32,7 @@ use rustc_hir::def_id::DefId; use rustc_hir::lang_items::LangItem; use rustc_middle::ty::fold::TypeFoldable; use rustc_middle::ty::subst::{InternalSubsts, SubstsRef}; -use rustc_middle::ty::{ - self, common_vtable_entries, GenericParamDefKind, ToPredicate, Ty, TyCtxt, VtblEntry, -}; +use rustc_middle::ty::{self, GenericParamDefKind, ToPredicate, Ty, TyCtxt, VtblEntry}; use rustc_span::{sym, Span}; use smallvec::SmallVec; @@ -695,7 +693,7 @@ fn vtable_entries<'tcx>( let vtable_segment_callback = |segment| -> ControlFlow<()> { match segment { VtblSegment::MetadataDSA => { - entries.extend(common_vtable_entries()); + entries.extend(TyCtxt::COMMON_VTABLE_ENTRIES); } VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => { let existential_trait_ref = trait_ref @@ -785,7 +783,7 @@ fn vtable_trait_first_method_offset<'tcx>( move |segment| { match segment { VtblSegment::MetadataDSA => { - vtable_base += common_vtable_entries().len(); + vtable_base += TyCtxt::COMMON_VTABLE_ENTRIES.len(); } VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => { if tcx.erase_regions(trait_ref) == trait_to_be_found_erased { diff --git a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs index 548b60d74bac0..34dc81b14d29e 100644 --- a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs +++ b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs @@ -12,7 +12,7 @@ use rustc_index::bit_set::GrowableBitSet; use rustc_infer::infer::InferOk; use rustc_infer::infer::LateBoundRegionConversionTime::HigherRankedType; use rustc_middle::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, Subst, SubstsRef}; -use rustc_middle::ty::{self, EarlyBinder, GenericParamDefKind, Ty}; +use rustc_middle::ty::{self, EarlyBinder, GenericParamDefKind, Ty, TyCtxt}; use rustc_middle::ty::{ToPolyTraitRef, ToPredicate}; use rustc_span::def_id::DefId; @@ -834,7 +834,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { move |segment| { match segment { VtblSegment::MetadataDSA => { - vptr_offset += ty::common_vtable_entries().len(); + vptr_offset += TyCtxt::COMMON_VTABLE_ENTRIES.len(); } VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => { vptr_offset += util::count_own_vtable_entries(tcx, trait_ref); diff --git a/compiler/rustc_type_ir/src/lib.rs b/compiler/rustc_type_ir/src/lib.rs index 960e42d8006ac..766875dd82bdf 100644 --- a/compiler/rustc_type_ir/src/lib.rs +++ b/compiler/rustc_type_ir/src/lib.rs @@ -21,8 +21,6 @@ pub mod sty; pub use codec::*; pub use sty::*; -extern crate self as rustc_type_ir; - pub trait Interner { type AdtDef: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord; type SubstsRef: Clone + Debug + Hash + PartialEq + Eq + PartialOrd + Ord; diff --git a/compiler/rustc_type_ir/src/sty.rs b/compiler/rustc_type_ir/src/sty.rs index 0f614967defcb..33b3a273f44cc 100644 --- a/compiler/rustc_type_ir/src/sty.rs +++ b/compiler/rustc_type_ir/src/sty.rs @@ -1,3 +1,8 @@ +#![allow(rustc::usage_of_ty_tykind)] + +use std::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}; +use std::{fmt, hash}; + use crate::DebruijnIndex; use crate::FloatTy; use crate::IntTy; @@ -6,17 +11,17 @@ use crate::TyDecoder; use crate::TyEncoder; use crate::UintTy; +use self::TyKind::*; + use rustc_serialize::{Decodable, Encodable}; /// Defines the kinds of types used by the type system. /// -/// Types written by the user start out as [hir::TyKind](rustc_hir::TyKind) and get +/// Types written by the user start out as `hir::TyKind` and get /// converted to this representation using `AstConv::ast_ty_to_ty`. -#[allow(rustc::usage_of_ty_tykind)] -#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] -//#[derive(TyEncodable, TyDecodable)] -//#[derive(HashStable)] -#[rustc_diagnostic_item = "TyKind"] +/// +/// The `HashStable` implementation for this type is defined in `rustc_query_system::ich`. +#[rustc_diagnostic_item = "IrTyKind"] pub enum TyKind { /// The primitive boolean type. Written as `bool`. Bool, @@ -95,18 +100,18 @@ pub enum TyKind { /// /// Closure substs contain both the - potentially substituted - generic parameters /// of its parent and some synthetic parameters. See the documentation for - /// [ClosureSubsts] for more details. + /// `ClosureSubsts` for more details. Closure(I::DefId, I::SubstsRef), /// The anonymous type of a generator. Used to represent the type of /// `|a| yield a`. /// /// For more info about generator substs, visit the documentation for - /// [GeneratorSubsts]. + /// `GeneratorSubsts`. Generator(I::DefId, I::SubstsRef, I::Movability), /// A type representing the types stored inside a generator. - /// This should only appear as part of the [GeneratorSubsts]. + /// This should only appear as part of the `GeneratorSubsts`. /// /// Note that the captured variables for generators are stored separately /// using a tuple in the same way as for closures. @@ -186,10 +191,47 @@ pub enum TyKind { Error(I::DelaySpanBugEmitted), } -#[allow(rustc::usage_of_ty_tykind)] +impl TyKind { + #[inline] + pub fn is_primitive(&self) -> bool { + matches!(self, Bool | Char | Int(_) | Uint(_) | Float(_)) + } +} + +fn discriminant(value: &TyKind) -> usize { + match value { + Bool => 0, + Char => 1, + Int(_) => 2, + Uint(_) => 3, + Float(_) => 4, + Adt(_, _) => 5, + Foreign(_) => 6, + Str => 7, + Array(_, _) => 8, + Slice(_) => 9, + RawPtr(_) => 10, + Ref(_, _, _) => 11, + FnDef(_, _) => 12, + FnPtr(_) => 13, + Dynamic(_, _) => 14, + Closure(_, _) => 15, + Generator(_, _, _) => 16, + GeneratorWitness(_) => 17, + Never => 18, + Tuple(_) => 19, + Projection(_) => 20, + Opaque(_, _) => 21, + Param(_) => 22, + Bound(_, _) => 23, + Placeholder(_) => 24, + Infer(_) => 25, + Error(_) => 26, + } +} + impl Clone for TyKind { fn clone(&self) -> Self { - use crate::TyKind::*; match self { Bool => Bool, Char => Char, @@ -222,149 +264,553 @@ impl Clone for TyKind { } } -#[allow(rustc::usage_of_ty_tykind)] -impl TyKind { +impl PartialEq for TyKind { #[inline] - pub fn is_primitive(&self) -> bool { - use crate::TyKind::*; - matches!(self, Bool | Char | Int(_) | Uint(_) | Float(_)) + fn eq(&self, other: &TyKind) -> bool { + let __self_vi = discriminant(self); + let __arg_1_vi = discriminant(other); + if __self_vi == __arg_1_vi { + match (&*self, &*other) { + (&Int(ref __self_0), &Int(ref __arg_1_0)) => __self_0 == __arg_1_0, + (&Uint(ref __self_0), &Uint(ref __arg_1_0)) => __self_0 == __arg_1_0, + (&Float(ref __self_0), &Float(ref __arg_1_0)) => __self_0 == __arg_1_0, + (&Adt(ref __self_0, ref __self_1), &Adt(ref __arg_1_0, ref __arg_1_1)) => { + __self_0 == __arg_1_0 && __self_1 == __arg_1_1 + } + (&Foreign(ref __self_0), &Foreign(ref __arg_1_0)) => __self_0 == __arg_1_0, + (&Array(ref __self_0, ref __self_1), &Array(ref __arg_1_0, ref __arg_1_1)) => { + __self_0 == __arg_1_0 && __self_1 == __arg_1_1 + } + (&Slice(ref __self_0), &Slice(ref __arg_1_0)) => __self_0 == __arg_1_0, + (&RawPtr(ref __self_0), &RawPtr(ref __arg_1_0)) => __self_0 == __arg_1_0, + ( + &Ref(ref __self_0, ref __self_1, ref __self_2), + &Ref(ref __arg_1_0, ref __arg_1_1, ref __arg_1_2), + ) => __self_0 == __arg_1_0 && __self_1 == __arg_1_1 && __self_2 == __arg_1_2, + (&FnDef(ref __self_0, ref __self_1), &FnDef(ref __arg_1_0, ref __arg_1_1)) => { + __self_0 == __arg_1_0 && __self_1 == __arg_1_1 + } + (&FnPtr(ref __self_0), &FnPtr(ref __arg_1_0)) => __self_0 == __arg_1_0, + (&Dynamic(ref __self_0, ref __self_1), &Dynamic(ref __arg_1_0, ref __arg_1_1)) => { + __self_0 == __arg_1_0 && __self_1 == __arg_1_1 + } + (&Closure(ref __self_0, ref __self_1), &Closure(ref __arg_1_0, ref __arg_1_1)) => { + __self_0 == __arg_1_0 && __self_1 == __arg_1_1 + } + ( + &Generator(ref __self_0, ref __self_1, ref __self_2), + &Generator(ref __arg_1_0, ref __arg_1_1, ref __arg_1_2), + ) => __self_0 == __arg_1_0 && __self_1 == __arg_1_1 && __self_2 == __arg_1_2, + (&GeneratorWitness(ref __self_0), &GeneratorWitness(ref __arg_1_0)) => { + __self_0 == __arg_1_0 + } + (&Tuple(ref __self_0), &Tuple(ref __arg_1_0)) => __self_0 == __arg_1_0, + (&Projection(ref __self_0), &Projection(ref __arg_1_0)) => __self_0 == __arg_1_0, + (&Opaque(ref __self_0, ref __self_1), &Opaque(ref __arg_1_0, ref __arg_1_1)) => { + __self_0 == __arg_1_0 && __self_1 == __arg_1_1 + } + (&Param(ref __self_0), &Param(ref __arg_1_0)) => __self_0 == __arg_1_0, + (&Bound(ref __self_0, ref __self_1), &Bound(ref __arg_1_0, ref __arg_1_1)) => { + __self_0 == __arg_1_0 && __self_1 == __arg_1_1 + } + (&Placeholder(ref __self_0), &Placeholder(ref __arg_1_0)) => __self_0 == __arg_1_0, + (&Infer(ref __self_0), &Infer(ref __arg_1_0)) => __self_0 == __arg_1_0, + (&Error(ref __self_0), &Error(ref __arg_1_0)) => __self_0 == __arg_1_0, + _ => true, + } + } else { + false + } + } +} + +impl Eq for TyKind {} + +impl PartialOrd for TyKind { + #[inline] + fn partial_cmp(&self, other: &TyKind) -> Option { + Some(Ord::cmp(self, other)) + } +} + +impl Ord for TyKind { + #[inline] + fn cmp(&self, other: &TyKind) -> Ordering { + let __self_vi = discriminant(self); + let __arg_1_vi = discriminant(other); + if __self_vi == __arg_1_vi { + match (&*self, &*other) { + (&Int(ref __self_0), &Int(ref __arg_1_0)) => Ord::cmp(__self_0, __arg_1_0), + (&Uint(ref __self_0), &Uint(ref __arg_1_0)) => Ord::cmp(__self_0, __arg_1_0), + (&Float(ref __self_0), &Float(ref __arg_1_0)) => Ord::cmp(__self_0, __arg_1_0), + (&Adt(ref __self_0, ref __self_1), &Adt(ref __arg_1_0, ref __arg_1_1)) => { + match Ord::cmp(__self_0, __arg_1_0) { + Ordering::Equal => Ord::cmp(__self_1, __arg_1_1), + cmp => cmp, + } + } + (&Foreign(ref __self_0), &Foreign(ref __arg_1_0)) => Ord::cmp(__self_0, __arg_1_0), + (&Array(ref __self_0, ref __self_1), &Array(ref __arg_1_0, ref __arg_1_1)) => { + match Ord::cmp(__self_0, __arg_1_0) { + Ordering::Equal => Ord::cmp(__self_1, __arg_1_1), + cmp => cmp, + } + } + (&Slice(ref __self_0), &Slice(ref __arg_1_0)) => Ord::cmp(__self_0, __arg_1_0), + (&RawPtr(ref __self_0), &RawPtr(ref __arg_1_0)) => Ord::cmp(__self_0, __arg_1_0), + ( + &Ref(ref __self_0, ref __self_1, ref __self_2), + &Ref(ref __arg_1_0, ref __arg_1_1, ref __arg_1_2), + ) => match Ord::cmp(__self_0, __arg_1_0) { + Ordering::Equal => match Ord::cmp(__self_1, __arg_1_1) { + Ordering::Equal => Ord::cmp(__self_2, __arg_1_2), + cmp => cmp, + }, + cmp => cmp, + }, + (&FnDef(ref __self_0, ref __self_1), &FnDef(ref __arg_1_0, ref __arg_1_1)) => { + match Ord::cmp(__self_0, __arg_1_0) { + Ordering::Equal => Ord::cmp(__self_1, __arg_1_1), + cmp => cmp, + } + } + (&FnPtr(ref __self_0), &FnPtr(ref __arg_1_0)) => Ord::cmp(__self_0, __arg_1_0), + (&Dynamic(ref __self_0, ref __self_1), &Dynamic(ref __arg_1_0, ref __arg_1_1)) => { + match Ord::cmp(__self_0, __arg_1_0) { + Ordering::Equal => Ord::cmp(__self_1, __arg_1_1), + cmp => cmp, + } + } + (&Closure(ref __self_0, ref __self_1), &Closure(ref __arg_1_0, ref __arg_1_1)) => { + match Ord::cmp(__self_0, __arg_1_0) { + Ordering::Equal => Ord::cmp(__self_1, __arg_1_1), + cmp => cmp, + } + } + ( + &Generator(ref __self_0, ref __self_1, ref __self_2), + &Generator(ref __arg_1_0, ref __arg_1_1, ref __arg_1_2), + ) => match Ord::cmp(__self_0, __arg_1_0) { + Ordering::Equal => match Ord::cmp(__self_1, __arg_1_1) { + Ordering::Equal => Ord::cmp(__self_2, __arg_1_2), + cmp => cmp, + }, + cmp => cmp, + }, + (&GeneratorWitness(ref __self_0), &GeneratorWitness(ref __arg_1_0)) => { + Ord::cmp(__self_0, __arg_1_0) + } + (&Tuple(ref __self_0), &Tuple(ref __arg_1_0)) => Ord::cmp(__self_0, __arg_1_0), + (&Projection(ref __self_0), &Projection(ref __arg_1_0)) => { + Ord::cmp(__self_0, __arg_1_0) + } + (&Opaque(ref __self_0, ref __self_1), &Opaque(ref __arg_1_0, ref __arg_1_1)) => { + match Ord::cmp(__self_0, __arg_1_0) { + Ordering::Equal => Ord::cmp(__self_1, __arg_1_1), + cmp => cmp, + } + } + (&Param(ref __self_0), &Param(ref __arg_1_0)) => Ord::cmp(__self_0, __arg_1_0), + (&Bound(ref __self_0, ref __self_1), &Bound(ref __arg_1_0, ref __arg_1_1)) => { + match Ord::cmp(__self_0, __arg_1_0) { + Ordering::Equal => Ord::cmp(__self_1, __arg_1_1), + cmp => cmp, + } + } + (&Placeholder(ref __self_0), &Placeholder(ref __arg_1_0)) => { + Ord::cmp(__self_0, __arg_1_0) + } + (&Infer(ref __self_0), &Infer(ref __arg_1_0)) => Ord::cmp(__self_0, __arg_1_0), + (&Error(ref __self_0), &Error(ref __arg_1_0)) => Ord::cmp(__self_0, __arg_1_0), + _ => Ordering::Equal, + } + } else { + Ord::cmp(&__self_vi, &__arg_1_vi) + } + } +} + +impl hash::Hash for TyKind { + fn hash<__H: hash::Hasher>(&self, state: &mut __H) -> () { + match (&*self,) { + (&Int(ref __self_0),) => { + hash::Hash::hash(&discriminant(self), state); + hash::Hash::hash(__self_0, state) + } + (&Uint(ref __self_0),) => { + hash::Hash::hash(&discriminant(self), state); + hash::Hash::hash(__self_0, state) + } + (&Float(ref __self_0),) => { + hash::Hash::hash(&discriminant(self), state); + hash::Hash::hash(__self_0, state) + } + (&Adt(ref __self_0, ref __self_1),) => { + hash::Hash::hash(&discriminant(self), state); + hash::Hash::hash(__self_0, state); + hash::Hash::hash(__self_1, state) + } + (&Foreign(ref __self_0),) => { + hash::Hash::hash(&discriminant(self), state); + hash::Hash::hash(__self_0, state) + } + (&Array(ref __self_0, ref __self_1),) => { + hash::Hash::hash(&discriminant(self), state); + hash::Hash::hash(__self_0, state); + hash::Hash::hash(__self_1, state) + } + (&Slice(ref __self_0),) => { + hash::Hash::hash(&discriminant(self), state); + hash::Hash::hash(__self_0, state) + } + (&RawPtr(ref __self_0),) => { + hash::Hash::hash(&discriminant(self), state); + hash::Hash::hash(__self_0, state) + } + (&Ref(ref __self_0, ref __self_1, ref __self_2),) => { + hash::Hash::hash(&discriminant(self), state); + hash::Hash::hash(__self_0, state); + hash::Hash::hash(__self_1, state); + hash::Hash::hash(__self_2, state) + } + (&FnDef(ref __self_0, ref __self_1),) => { + hash::Hash::hash(&discriminant(self), state); + hash::Hash::hash(__self_0, state); + hash::Hash::hash(__self_1, state) + } + (&FnPtr(ref __self_0),) => { + hash::Hash::hash(&discriminant(self), state); + hash::Hash::hash(__self_0, state) + } + (&Dynamic(ref __self_0, ref __self_1),) => { + hash::Hash::hash(&discriminant(self), state); + hash::Hash::hash(__self_0, state); + hash::Hash::hash(__self_1, state) + } + (&Closure(ref __self_0, ref __self_1),) => { + hash::Hash::hash(&discriminant(self), state); + hash::Hash::hash(__self_0, state); + hash::Hash::hash(__self_1, state) + } + (&Generator(ref __self_0, ref __self_1, ref __self_2),) => { + hash::Hash::hash(&discriminant(self), state); + hash::Hash::hash(__self_0, state); + hash::Hash::hash(__self_1, state); + hash::Hash::hash(__self_2, state) + } + (&GeneratorWitness(ref __self_0),) => { + hash::Hash::hash(&discriminant(self), state); + hash::Hash::hash(__self_0, state) + } + (&Tuple(ref __self_0),) => { + hash::Hash::hash(&discriminant(self), state); + hash::Hash::hash(__self_0, state) + } + (&Projection(ref __self_0),) => { + hash::Hash::hash(&discriminant(self), state); + hash::Hash::hash(__self_0, state) + } + (&Opaque(ref __self_0, ref __self_1),) => { + hash::Hash::hash(&discriminant(self), state); + hash::Hash::hash(__self_0, state); + hash::Hash::hash(__self_1, state) + } + (&Param(ref __self_0),) => { + hash::Hash::hash(&discriminant(self), state); + hash::Hash::hash(__self_0, state) + } + (&Bound(ref __self_0, ref __self_1),) => { + hash::Hash::hash(&discriminant(self), state); + hash::Hash::hash(__self_0, state); + hash::Hash::hash(__self_1, state) + } + (&Placeholder(ref __self_0),) => { + hash::Hash::hash(&discriminant(self), state); + hash::Hash::hash(__self_0, state) + } + (&Infer(ref __self_0),) => { + hash::Hash::hash(&discriminant(self), state); + hash::Hash::hash(__self_0, state) + } + (&Error(ref __self_0),) => { + hash::Hash::hash(&discriminant(self), state); + hash::Hash::hash(__self_0, state) + } + _ => hash::Hash::hash(&discriminant(self), state), + } } } -#[allow(rustc::usage_of_ty_tykind)] -impl<__I: Interner, __E: TyEncoder> Encodable<__E> for TyKind<__I> +impl fmt::Debug for TyKind { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match (&*self,) { + (&Bool,) => fmt::Formatter::write_str(f, "Bool"), + (&Char,) => fmt::Formatter::write_str(f, "Char"), + (&Int(ref __self_0),) => { + let debug_trait_builder = &mut fmt::Formatter::debug_tuple(f, "Int"); + let _ = fmt::DebugTuple::field(debug_trait_builder, &__self_0); + fmt::DebugTuple::finish(debug_trait_builder) + } + (&Uint(ref __self_0),) => { + let debug_trait_builder = &mut fmt::Formatter::debug_tuple(f, "Uint"); + let _ = fmt::DebugTuple::field(debug_trait_builder, &__self_0); + fmt::DebugTuple::finish(debug_trait_builder) + } + (&Float(ref __self_0),) => { + let debug_trait_builder = &mut fmt::Formatter::debug_tuple(f, "Float"); + let _ = fmt::DebugTuple::field(debug_trait_builder, &__self_0); + fmt::DebugTuple::finish(debug_trait_builder) + } + (&Adt(ref __self_0, ref __self_1),) => { + let debug_trait_builder = &mut fmt::Formatter::debug_tuple(f, "Adt"); + let _ = fmt::DebugTuple::field(debug_trait_builder, &__self_0); + let _ = fmt::DebugTuple::field(debug_trait_builder, &__self_1); + fmt::DebugTuple::finish(debug_trait_builder) + } + (&Foreign(ref __self_0),) => { + let debug_trait_builder = &mut fmt::Formatter::debug_tuple(f, "Foreign"); + let _ = fmt::DebugTuple::field(debug_trait_builder, &__self_0); + fmt::DebugTuple::finish(debug_trait_builder) + } + (&Str,) => fmt::Formatter::write_str(f, "Str"), + (&Array(ref __self_0, ref __self_1),) => { + let debug_trait_builder = &mut fmt::Formatter::debug_tuple(f, "Array"); + let _ = fmt::DebugTuple::field(debug_trait_builder, &__self_0); + let _ = fmt::DebugTuple::field(debug_trait_builder, &__self_1); + fmt::DebugTuple::finish(debug_trait_builder) + } + (&Slice(ref __self_0),) => { + let debug_trait_builder = &mut fmt::Formatter::debug_tuple(f, "Slice"); + let _ = fmt::DebugTuple::field(debug_trait_builder, &__self_0); + fmt::DebugTuple::finish(debug_trait_builder) + } + (&RawPtr(ref __self_0),) => { + let debug_trait_builder = &mut fmt::Formatter::debug_tuple(f, "RawPtr"); + let _ = fmt::DebugTuple::field(debug_trait_builder, &__self_0); + fmt::DebugTuple::finish(debug_trait_builder) + } + (&Ref(ref __self_0, ref __self_1, ref __self_2),) => { + let debug_trait_builder = &mut fmt::Formatter::debug_tuple(f, "Ref"); + let _ = fmt::DebugTuple::field(debug_trait_builder, &__self_0); + let _ = fmt::DebugTuple::field(debug_trait_builder, &__self_1); + let _ = fmt::DebugTuple::field(debug_trait_builder, &__self_2); + fmt::DebugTuple::finish(debug_trait_builder) + } + (&FnDef(ref __self_0, ref __self_1),) => { + let debug_trait_builder = &mut fmt::Formatter::debug_tuple(f, "FnDef"); + let _ = fmt::DebugTuple::field(debug_trait_builder, &__self_0); + let _ = fmt::DebugTuple::field(debug_trait_builder, &__self_1); + fmt::DebugTuple::finish(debug_trait_builder) + } + (&FnPtr(ref __self_0),) => { + let debug_trait_builder = &mut fmt::Formatter::debug_tuple(f, "FnPtr"); + let _ = fmt::DebugTuple::field(debug_trait_builder, &__self_0); + fmt::DebugTuple::finish(debug_trait_builder) + } + (&Dynamic(ref __self_0, ref __self_1),) => { + let debug_trait_builder = &mut fmt::Formatter::debug_tuple(f, "Dynamic"); + let _ = fmt::DebugTuple::field(debug_trait_builder, &__self_0); + let _ = fmt::DebugTuple::field(debug_trait_builder, &__self_1); + fmt::DebugTuple::finish(debug_trait_builder) + } + (&Closure(ref __self_0, ref __self_1),) => { + let debug_trait_builder = &mut fmt::Formatter::debug_tuple(f, "Closure"); + let _ = fmt::DebugTuple::field(debug_trait_builder, &__self_0); + let _ = fmt::DebugTuple::field(debug_trait_builder, &__self_1); + fmt::DebugTuple::finish(debug_trait_builder) + } + (&Generator(ref __self_0, ref __self_1, ref __self_2),) => { + let debug_trait_builder = &mut fmt::Formatter::debug_tuple(f, "Generator"); + let _ = fmt::DebugTuple::field(debug_trait_builder, &__self_0); + let _ = fmt::DebugTuple::field(debug_trait_builder, &__self_1); + let _ = fmt::DebugTuple::field(debug_trait_builder, &__self_2); + fmt::DebugTuple::finish(debug_trait_builder) + } + (&GeneratorWitness(ref __self_0),) => { + let debug_trait_builder = &mut fmt::Formatter::debug_tuple(f, "GeneratorWitness"); + let _ = fmt::DebugTuple::field(debug_trait_builder, &__self_0); + fmt::DebugTuple::finish(debug_trait_builder) + } + (&Never,) => fmt::Formatter::write_str(f, "Never"), + (&Tuple(ref __self_0),) => { + let debug_trait_builder = &mut fmt::Formatter::debug_tuple(f, "Tuple"); + let _ = fmt::DebugTuple::field(debug_trait_builder, &__self_0); + fmt::DebugTuple::finish(debug_trait_builder) + } + (&Projection(ref __self_0),) => { + let debug_trait_builder = &mut fmt::Formatter::debug_tuple(f, "Projection"); + let _ = fmt::DebugTuple::field(debug_trait_builder, &__self_0); + fmt::DebugTuple::finish(debug_trait_builder) + } + (&Opaque(ref __self_0, ref __self_1),) => { + let debug_trait_builder = &mut fmt::Formatter::debug_tuple(f, "Opaque"); + let _ = fmt::DebugTuple::field(debug_trait_builder, &__self_0); + let _ = fmt::DebugTuple::field(debug_trait_builder, &__self_1); + fmt::DebugTuple::finish(debug_trait_builder) + } + (&Param(ref __self_0),) => { + let debug_trait_builder = &mut fmt::Formatter::debug_tuple(f, "Param"); + let _ = fmt::DebugTuple::field(debug_trait_builder, &__self_0); + fmt::DebugTuple::finish(debug_trait_builder) + } + (&Bound(ref __self_0, ref __self_1),) => { + let debug_trait_builder = &mut fmt::Formatter::debug_tuple(f, "Bound"); + let _ = fmt::DebugTuple::field(debug_trait_builder, &__self_0); + let _ = fmt::DebugTuple::field(debug_trait_builder, &__self_1); + fmt::DebugTuple::finish(debug_trait_builder) + } + (&Placeholder(ref __self_0),) => { + let debug_trait_builder = &mut fmt::Formatter::debug_tuple(f, "Placeholder"); + let _ = fmt::DebugTuple::field(debug_trait_builder, &__self_0); + fmt::DebugTuple::finish(debug_trait_builder) + } + (&Infer(ref __self_0),) => { + let debug_trait_builder = &mut fmt::Formatter::debug_tuple(f, "Infer"); + let _ = fmt::DebugTuple::field(debug_trait_builder, &__self_0); + fmt::DebugTuple::finish(debug_trait_builder) + } + (&Error(ref __self_0),) => { + let debug_trait_builder = &mut fmt::Formatter::debug_tuple(f, "Error"); + let _ = fmt::DebugTuple::field(debug_trait_builder, &__self_0); + fmt::DebugTuple::finish(debug_trait_builder) + } + } + } +} + +impl Encodable for TyKind where - __I::DelaySpanBugEmitted: Encodable<__E>, - __I::AdtDef: Encodable<__E>, - __I::SubstsRef: Encodable<__E>, - __I::DefId: Encodable<__E>, - __I::Ty: Encodable<__E>, - __I::Const: Encodable<__E>, - __I::Region: Encodable<__E>, - __I::TypeAndMut: Encodable<__E>, - __I::Mutability: Encodable<__E>, - __I::Movability: Encodable<__E>, - __I::PolyFnSig: Encodable<__E>, - __I::ListBinderExistentialPredicate: Encodable<__E>, - __I::BinderListTy: Encodable<__E>, - __I::ListTy: Encodable<__E>, - __I::ProjectionTy: Encodable<__E>, - __I::ParamTy: Encodable<__E>, - __I::BoundTy: Encodable<__E>, - __I::PlaceholderType: Encodable<__E>, - __I::InferTy: Encodable<__E>, - __I::DelaySpanBugEmitted: Encodable<__E>, - __I::PredicateKind: Encodable<__E>, - __I::AllocId: Encodable<__E>, + I::DelaySpanBugEmitted: Encodable, + I::AdtDef: Encodable, + I::SubstsRef: Encodable, + I::DefId: Encodable, + I::Ty: Encodable, + I::Const: Encodable, + I::Region: Encodable, + I::TypeAndMut: Encodable, + I::Mutability: Encodable, + I::Movability: Encodable, + I::PolyFnSig: Encodable, + I::ListBinderExistentialPredicate: Encodable, + I::BinderListTy: Encodable, + I::ListTy: Encodable, + I::ProjectionTy: Encodable, + I::ParamTy: Encodable, + I::BoundTy: Encodable, + I::PlaceholderType: Encodable, + I::InferTy: Encodable, + I::DelaySpanBugEmitted: Encodable, + I::PredicateKind: Encodable, + I::AllocId: Encodable, { - fn encode(&self, e: &mut __E) -> Result<(), <__E as rustc_serialize::Encoder>::Error> { + fn encode(&self, e: &mut E) -> Result<(), ::Error> { rustc_serialize::Encoder::emit_enum(e, |e| { - use rustc_type_ir::TyKind::*; + let disc = discriminant(self); match self { - Bool => e.emit_enum_variant("Bool", 0, 0, |_| Ok(())), - Char => e.emit_enum_variant("Char", 1, 0, |_| Ok(())), - Int(i) => e.emit_enum_variant("Int", 2, 1, |e| { + Bool => e.emit_enum_variant("Bool", disc, 0, |_| Ok(())), + Char => e.emit_enum_variant("Char", disc, 0, |_| Ok(())), + Int(i) => e.emit_enum_variant("Int", disc, 1, |e| { e.emit_enum_variant_arg(true, |e| i.encode(e))?; Ok(()) }), - Uint(u) => e.emit_enum_variant("Uint", 3, 1, |e| { + Uint(u) => e.emit_enum_variant("Uint", disc, 1, |e| { e.emit_enum_variant_arg(true, |e| u.encode(e))?; Ok(()) }), - Float(f) => e.emit_enum_variant("Float", 4, 1, |e| { + Float(f) => e.emit_enum_variant("Float", disc, 1, |e| { e.emit_enum_variant_arg(true, |e| f.encode(e))?; Ok(()) }), - Adt(adt, substs) => e.emit_enum_variant("Adt", 5, 2, |e| { + Adt(adt, substs) => e.emit_enum_variant("Adt", disc, 2, |e| { e.emit_enum_variant_arg(true, |e| adt.encode(e))?; e.emit_enum_variant_arg(false, |e| substs.encode(e))?; Ok(()) }), - Foreign(def_id) => e.emit_enum_variant("Foreign", 6, 1, |e| { + Foreign(def_id) => e.emit_enum_variant("Foreign", disc, 1, |e| { e.emit_enum_variant_arg(true, |e| def_id.encode(e))?; Ok(()) }), - Str => e.emit_enum_variant("Str", 7, 0, |_| Ok(())), - Array(t, c) => e.emit_enum_variant("Array", 8, 2, |e| { + Str => e.emit_enum_variant("Str", disc, 0, |_| Ok(())), + Array(t, c) => e.emit_enum_variant("Array", disc, 2, |e| { e.emit_enum_variant_arg(true, |e| t.encode(e))?; e.emit_enum_variant_arg(false, |e| c.encode(e))?; Ok(()) }), - Slice(t) => e.emit_enum_variant("Slice", 9, 1, |e| { + Slice(t) => e.emit_enum_variant("Slice", disc, 1, |e| { e.emit_enum_variant_arg(true, |e| t.encode(e))?; Ok(()) }), - RawPtr(tam) => e.emit_enum_variant("RawPtr", 10, 1, |e| { + RawPtr(tam) => e.emit_enum_variant("RawPtr", disc, 1, |e| { e.emit_enum_variant_arg(true, |e| tam.encode(e))?; Ok(()) }), - Ref(r, t, m) => e.emit_enum_variant("Ref", 11, 3, |e| { + Ref(r, t, m) => e.emit_enum_variant("Ref", disc, 3, |e| { e.emit_enum_variant_arg(true, |e| r.encode(e))?; e.emit_enum_variant_arg(false, |e| t.encode(e))?; e.emit_enum_variant_arg(false, |e| m.encode(e))?; Ok(()) }), - FnDef(def_id, substs) => e.emit_enum_variant("FnDef", 12, 2, |e| { + FnDef(def_id, substs) => e.emit_enum_variant("FnDef", disc, 2, |e| { e.emit_enum_variant_arg(true, |e| def_id.encode(e))?; e.emit_enum_variant_arg(false, |e| substs.encode(e))?; Ok(()) }), - FnPtr(polyfnsig) => e.emit_enum_variant("FnPtr", 13, 1, |e| { + FnPtr(polyfnsig) => e.emit_enum_variant("FnPtr", disc, 1, |e| { e.emit_enum_variant_arg(true, |e| polyfnsig.encode(e))?; Ok(()) }), - Dynamic(l, r) => e.emit_enum_variant("Dynamic", 14, 2, |e| { + Dynamic(l, r) => e.emit_enum_variant("Dynamic", disc, 2, |e| { e.emit_enum_variant_arg(true, |e| l.encode(e))?; e.emit_enum_variant_arg(false, |e| r.encode(e))?; Ok(()) }), - Closure(def_id, substs) => e.emit_enum_variant("Closure", 15, 2, |e| { + Closure(def_id, substs) => e.emit_enum_variant("Closure", disc, 2, |e| { e.emit_enum_variant_arg(true, |e| def_id.encode(e))?; e.emit_enum_variant_arg(false, |e| substs.encode(e))?; Ok(()) }), - Generator(def_id, substs, m) => e.emit_enum_variant("Generator", 16, 3, |e| { + Generator(def_id, substs, m) => e.emit_enum_variant("Generator", disc, 3, |e| { e.emit_enum_variant_arg(true, |e| def_id.encode(e))?; e.emit_enum_variant_arg(false, |e| substs.encode(e))?; e.emit_enum_variant_arg(false, |e| m.encode(e))?; Ok(()) }), - GeneratorWitness(b) => e.emit_enum_variant("GeneratorWitness", 17, 1, |e| { + GeneratorWitness(b) => e.emit_enum_variant("GeneratorWitness", disc, 1, |e| { e.emit_enum_variant_arg(true, |e| b.encode(e))?; Ok(()) }), - Never => e.emit_enum_variant("Never", 18, 0, |_| Ok(())), - Tuple(substs) => e.emit_enum_variant("Tuple", 19, 1, |e| { + Never => e.emit_enum_variant("Never", disc, 0, |_| Ok(())), + Tuple(substs) => e.emit_enum_variant("Tuple", disc, 1, |e| { e.emit_enum_variant_arg(true, |e| substs.encode(e))?; Ok(()) }), - Projection(p) => e.emit_enum_variant("Projection", 20, 1, |e| { + Projection(p) => e.emit_enum_variant("Projection", disc, 1, |e| { e.emit_enum_variant_arg(true, |e| p.encode(e))?; Ok(()) }), - Opaque(def_id, substs) => e.emit_enum_variant("Opaque", 21, 2, |e| { + Opaque(def_id, substs) => e.emit_enum_variant("Opaque", disc, 2, |e| { e.emit_enum_variant_arg(true, |e| def_id.encode(e))?; e.emit_enum_variant_arg(false, |e| substs.encode(e))?; Ok(()) }), - Param(p) => e.emit_enum_variant("Param", 22, 1, |e| { + Param(p) => e.emit_enum_variant("Param", disc, 1, |e| { e.emit_enum_variant_arg(true, |e| p.encode(e))?; Ok(()) }), - Bound(d, b) => e.emit_enum_variant("Bound", 23, 2, |e| { + Bound(d, b) => e.emit_enum_variant("Bound", disc, 2, |e| { e.emit_enum_variant_arg(true, |e| d.encode(e))?; e.emit_enum_variant_arg(false, |e| b.encode(e))?; Ok(()) }), - Placeholder(p) => e.emit_enum_variant("Placeholder", 24, 1, |e| { + Placeholder(p) => e.emit_enum_variant("Placeholder", disc, 1, |e| { e.emit_enum_variant_arg(true, |e| p.encode(e))?; Ok(()) }), - Infer(i) => e.emit_enum_variant("Infer", 25, 1, |e| { + Infer(i) => e.emit_enum_variant("Infer", disc, 1, |e| { e.emit_enum_variant_arg(true, |e| i.encode(e))?; Ok(()) }), - Error(d) => e.emit_enum_variant("Error", 26, 1, |e| { + Error(d) => e.emit_enum_variant("Error", disc, 1, |e| { e.emit_enum_variant_arg(true, |e| d.encode(e))?; Ok(()) }), @@ -373,92 +819,82 @@ where } } -#[allow(rustc::usage_of_ty_tykind)] -impl<__I: Interner, __D: TyDecoder> Decodable<__D> for TyKind<__I> +impl> Decodable for TyKind where - __I::DelaySpanBugEmitted: Decodable<__D>, - __I::AdtDef: Decodable<__D>, - __I::SubstsRef: Decodable<__D>, - __I::DefId: Decodable<__D>, - __I::Ty: Decodable<__D>, - __I::Const: Decodable<__D>, - __I::Region: Decodable<__D>, - __I::TypeAndMut: Decodable<__D>, - __I::Mutability: Decodable<__D>, - __I::Movability: Decodable<__D>, - __I::PolyFnSig: Decodable<__D>, - __I::ListBinderExistentialPredicate: Decodable<__D>, - __I::BinderListTy: Decodable<__D>, - __I::ListTy: Decodable<__D>, - __I::ProjectionTy: Decodable<__D>, - __I::ParamTy: Decodable<__D>, - __I::BoundTy: Decodable<__D>, - __I::PlaceholderType: Decodable<__D>, - __I::InferTy: Decodable<__D>, - __I::DelaySpanBugEmitted: Decodable<__D>, - __I::PredicateKind: Decodable<__D>, - __I::AllocId: Decodable<__D>, + I::DelaySpanBugEmitted: Decodable, + I::AdtDef: Decodable, + I::SubstsRef: Decodable, + I::DefId: Decodable, + I::Ty: Decodable, + I::Const: Decodable, + I::Region: Decodable, + I::TypeAndMut: Decodable, + I::Mutability: Decodable, + I::Movability: Decodable, + I::PolyFnSig: Decodable, + I::ListBinderExistentialPredicate: Decodable, + I::BinderListTy: Decodable, + I::ListTy: Decodable, + I::ProjectionTy: Decodable, + I::ParamTy: Decodable, + I::BoundTy: Decodable, + I::PlaceholderType: Decodable, + I::InferTy: Decodable, + I::DelaySpanBugEmitted: Decodable, + I::PredicateKind: Decodable, + I::AllocId: Decodable, { - fn decode(__decoder: &mut __D) -> Self { - use TyKind::*; - - match rustc_serialize::Decoder::read_usize(__decoder) { + fn decode(d: &mut D) -> Self { + match rustc_serialize::Decoder::read_usize(d) { 0 => Bool, 1 => Char, - 2 => Int(rustc_serialize::Decodable::decode(__decoder)), - 3 => Uint(rustc_serialize::Decodable::decode(__decoder)), - 4 => Float(rustc_serialize::Decodable::decode(__decoder)), - 5 => Adt( - rustc_serialize::Decodable::decode(__decoder), - rustc_serialize::Decodable::decode(__decoder), - ), - 6 => Foreign(rustc_serialize::Decodable::decode(__decoder)), + 2 => Int(rustc_serialize::Decodable::decode(d)), + 3 => Uint(rustc_serialize::Decodable::decode(d)), + 4 => Float(rustc_serialize::Decodable::decode(d)), + 5 => Adt(rustc_serialize::Decodable::decode(d), rustc_serialize::Decodable::decode(d)), + 6 => Foreign(rustc_serialize::Decodable::decode(d)), 7 => Str, - 8 => Array( - rustc_serialize::Decodable::decode(__decoder), - rustc_serialize::Decodable::decode(__decoder), - ), - 9 => Slice(rustc_serialize::Decodable::decode(__decoder)), - 10 => RawPtr(rustc_serialize::Decodable::decode(__decoder)), + 8 => { + Array(rustc_serialize::Decodable::decode(d), rustc_serialize::Decodable::decode(d)) + } + 9 => Slice(rustc_serialize::Decodable::decode(d)), + 10 => RawPtr(rustc_serialize::Decodable::decode(d)), 11 => Ref( - rustc_serialize::Decodable::decode(__decoder), - rustc_serialize::Decodable::decode(__decoder), - rustc_serialize::Decodable::decode(__decoder), - ), - 12 => FnDef( - rustc_serialize::Decodable::decode(__decoder), - rustc_serialize::Decodable::decode(__decoder), + rustc_serialize::Decodable::decode(d), + rustc_serialize::Decodable::decode(d), + rustc_serialize::Decodable::decode(d), ), - 13 => FnPtr(rustc_serialize::Decodable::decode(__decoder)), + 12 => { + FnDef(rustc_serialize::Decodable::decode(d), rustc_serialize::Decodable::decode(d)) + } + 13 => FnPtr(rustc_serialize::Decodable::decode(d)), 14 => Dynamic( - rustc_serialize::Decodable::decode(__decoder), - rustc_serialize::Decodable::decode(__decoder), + rustc_serialize::Decodable::decode(d), + rustc_serialize::Decodable::decode(d), ), 15 => Closure( - rustc_serialize::Decodable::decode(__decoder), - rustc_serialize::Decodable::decode(__decoder), + rustc_serialize::Decodable::decode(d), + rustc_serialize::Decodable::decode(d), ), 16 => Generator( - rustc_serialize::Decodable::decode(__decoder), - rustc_serialize::Decodable::decode(__decoder), - rustc_serialize::Decodable::decode(__decoder), + rustc_serialize::Decodable::decode(d), + rustc_serialize::Decodable::decode(d), + rustc_serialize::Decodable::decode(d), ), - 17 => GeneratorWitness(rustc_serialize::Decodable::decode(__decoder)), + 17 => GeneratorWitness(rustc_serialize::Decodable::decode(d)), 18 => Never, - 19 => Tuple(rustc_serialize::Decodable::decode(__decoder)), - 20 => Projection(rustc_serialize::Decodable::decode(__decoder)), - 21 => Opaque( - rustc_serialize::Decodable::decode(__decoder), - rustc_serialize::Decodable::decode(__decoder), - ), - 22 => Param(rustc_serialize::Decodable::decode(__decoder)), - 23 => Bound( - rustc_serialize::Decodable::decode(__decoder), - rustc_serialize::Decodable::decode(__decoder), - ), - 24 => Placeholder(rustc_serialize::Decodable::decode(__decoder)), - 25 => Infer(rustc_serialize::Decodable::decode(__decoder)), - 26 => Error(rustc_serialize::Decodable::decode(__decoder)), + 19 => Tuple(rustc_serialize::Decodable::decode(d)), + 20 => Projection(rustc_serialize::Decodable::decode(d)), + 21 => { + Opaque(rustc_serialize::Decodable::decode(d), rustc_serialize::Decodable::decode(d)) + } + 22 => Param(rustc_serialize::Decodable::decode(d)), + 23 => { + Bound(rustc_serialize::Decodable::decode(d), rustc_serialize::Decodable::decode(d)) + } + 24 => Placeholder(rustc_serialize::Decodable::decode(d)), + 25 => Infer(rustc_serialize::Decodable::decode(d)), + 26 => Error(rustc_serialize::Decodable::decode(d)), _ => panic!( "{}", format!( diff --git a/src/test/run-make-fulldeps/obtain-borrowck/driver.rs b/src/test/run-make-fulldeps/obtain-borrowck/driver.rs index c3b82aa853c78..8f78bda033ec1 100644 --- a/src/test/run-make-fulldeps/obtain-borrowck/driver.rs +++ b/src/test/run-make-fulldeps/obtain-borrowck/driver.rs @@ -154,7 +154,7 @@ fn get_bodies<'tcx>(tcx: TyCtxt<'tcx>) -> Vec<(String, BodyWithBorrowckFacts<'tc // SAFETY: For soundness we need to ensure that the bodies have // the same lifetime (`'tcx`), which they had before they were // stored in the thread local. - (def_path.to_string_no_crate_verbose(), body) + (def_path.to_string_no_crate_verbose(), unsafe { std::mem::transmute(body) }) }) .collect() }) diff --git a/src/test/ui-fulldeps/internal-lints/ty_tykind_usage.rs b/src/test/ui-fulldeps/internal-lints/ty_tykind_usage.rs index 973294e985f7a..2cb1ed6fcb76b 100644 --- a/src/test/ui-fulldeps/internal-lints/ty_tykind_usage.rs +++ b/src/test/ui-fulldeps/internal-lints/ty_tykind_usage.rs @@ -3,41 +3,43 @@ #![feature(rustc_private)] extern crate rustc_middle; +extern crate rustc_type_ir; use rustc_middle::ty::{self, Ty, TyKind}; +use rustc_type_ir::{Interner, TyKind as IrTyKind}; #[deny(rustc::usage_of_ty_tykind)] fn main() { let kind = TyKind::Bool; //~ ERROR usage of `ty::TyKind::` match kind { - TyKind::Bool => (), //~ ERROR usage of `ty::TyKind::` - TyKind::Char => (), //~ ERROR usage of `ty::TyKind::` - TyKind::Int(..) => (), //~ ERROR usage of `ty::TyKind::` - TyKind::Uint(..) => (), //~ ERROR usage of `ty::TyKind::` - TyKind::Float(..) => (), //~ ERROR usage of `ty::TyKind::` - TyKind::Adt(..) => (), //~ ERROR usage of `ty::TyKind::` - TyKind::Foreign(..) => (), //~ ERROR usage of `ty::TyKind::` - TyKind::Str => (), //~ ERROR usage of `ty::TyKind::` - TyKind::Array(..) => (), //~ ERROR usage of `ty::TyKind::` - TyKind::Slice(..) => (), //~ ERROR usage of `ty::TyKind::` - TyKind::RawPtr(..) => (), //~ ERROR usage of `ty::TyKind::` - TyKind::Ref(..) => (), //~ ERROR usage of `ty::TyKind::` - TyKind::FnDef(..) => (), //~ ERROR usage of `ty::TyKind::` - TyKind::FnPtr(..) => (), //~ ERROR usage of `ty::TyKind::` - TyKind::Dynamic(..) => (), //~ ERROR usage of `ty::TyKind::` - TyKind::Closure(..) => (), //~ ERROR usage of `ty::TyKind::` - TyKind::Generator(..) => (), //~ ERROR usage of `ty::TyKind::` + TyKind::Bool => (), //~ ERROR usage of `ty::TyKind::` + TyKind::Char => (), //~ ERROR usage of `ty::TyKind::` + TyKind::Int(..) => (), //~ ERROR usage of `ty::TyKind::` + TyKind::Uint(..) => (), //~ ERROR usage of `ty::TyKind::` + TyKind::Float(..) => (), //~ ERROR usage of `ty::TyKind::` + TyKind::Adt(..) => (), //~ ERROR usage of `ty::TyKind::` + TyKind::Foreign(..) => (), //~ ERROR usage of `ty::TyKind::` + TyKind::Str => (), //~ ERROR usage of `ty::TyKind::` + TyKind::Array(..) => (), //~ ERROR usage of `ty::TyKind::` + TyKind::Slice(..) => (), //~ ERROR usage of `ty::TyKind::` + TyKind::RawPtr(..) => (), //~ ERROR usage of `ty::TyKind::` + TyKind::Ref(..) => (), //~ ERROR usage of `ty::TyKind::` + TyKind::FnDef(..) => (), //~ ERROR usage of `ty::TyKind::` + TyKind::FnPtr(..) => (), //~ ERROR usage of `ty::TyKind::` + TyKind::Dynamic(..) => (), //~ ERROR usage of `ty::TyKind::` + TyKind::Closure(..) => (), //~ ERROR usage of `ty::TyKind::` + TyKind::Generator(..) => (), //~ ERROR usage of `ty::TyKind::` TyKind::GeneratorWitness(..) => (), //~ ERROR usage of `ty::TyKind::` - TyKind::Never => (), //~ ERROR usage of `ty::TyKind::` - TyKind::Tuple(..) => (), //~ ERROR usage of `ty::TyKind::` - TyKind::Projection(..) => (), //~ ERROR usage of `ty::TyKind::` - TyKind::Opaque(..) => (), //~ ERROR usage of `ty::TyKind::` - TyKind::Param(..) => (), //~ ERROR usage of `ty::TyKind::` - TyKind::Bound(..) => (), //~ ERROR usage of `ty::TyKind::` - TyKind::Placeholder(..) => (), //~ ERROR usage of `ty::TyKind::` - TyKind::Infer(..) => (), //~ ERROR usage of `ty::TyKind::` - TyKind::Error(_) => (), //~ ERROR usage of `ty::TyKind::` + TyKind::Never => (), //~ ERROR usage of `ty::TyKind::` + TyKind::Tuple(..) => (), //~ ERROR usage of `ty::TyKind::` + TyKind::Projection(..) => (), //~ ERROR usage of `ty::TyKind::` + TyKind::Opaque(..) => (), //~ ERROR usage of `ty::TyKind::` + TyKind::Param(..) => (), //~ ERROR usage of `ty::TyKind::` + TyKind::Bound(..) => (), //~ ERROR usage of `ty::TyKind::` + TyKind::Placeholder(..) => (), //~ ERROR usage of `ty::TyKind::` + TyKind::Infer(..) => (), //~ ERROR usage of `ty::TyKind::` + TyKind::Error(_) => (), //~ ERROR usage of `ty::TyKind::` } if let ty::Int(int_ty) = kind {} @@ -45,4 +47,10 @@ fn main() { if let TyKind::Int(int_ty) = kind {} //~ ERROR usage of `ty::TyKind::` fn ty_kind(ty_bad: TyKind<'_>, ty_good: Ty<'_>) {} //~ ERROR usage of `ty::TyKind` + + fn ir_ty_kind(bad: IrTyKind) -> IrTyKind { + //~^ ERROR usage of `ty::TyKind` + //~| ERROR usage of `ty::TyKind` + IrTyKind::Bool //~ ERROR usage of `ty::TyKind::` + } } diff --git a/src/test/ui-fulldeps/internal-lints/ty_tykind_usage.stderr b/src/test/ui-fulldeps/internal-lints/ty_tykind_usage.stderr index d6e4c85c190d5..171f49087d695 100644 --- a/src/test/ui-fulldeps/internal-lints/ty_tykind_usage.stderr +++ b/src/test/ui-fulldeps/internal-lints/ty_tykind_usage.stderr @@ -1,190 +1,214 @@ error: usage of `ty::TyKind::` - --> $DIR/ty_tykind_usage.rs:11:16 + --> $DIR/ty_tykind_usage.rs:13:16 | LL | let kind = TyKind::Bool; - | ^^^^^^ help: try using ty:: directly: `ty` + | ^^^^^^ help: try using `ty::` directly: `ty` | note: the lint level is defined here - --> $DIR/ty_tykind_usage.rs:9:8 + --> $DIR/ty_tykind_usage.rs:11:8 | LL | #[deny(rustc::usage_of_ty_tykind)] | ^^^^^^^^^^^^^^^^^^^^^^^^^ error: usage of `ty::TyKind::` - --> $DIR/ty_tykind_usage.rs:14:9 + --> $DIR/ty_tykind_usage.rs:16:9 | LL | TyKind::Bool => (), - | ^^^^^^ help: try using ty:: directly: `ty` + | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` - --> $DIR/ty_tykind_usage.rs:15:9 + --> $DIR/ty_tykind_usage.rs:17:9 | LL | TyKind::Char => (), - | ^^^^^^ help: try using ty:: directly: `ty` + | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` - --> $DIR/ty_tykind_usage.rs:16:9 + --> $DIR/ty_tykind_usage.rs:18:9 | LL | TyKind::Int(..) => (), - | ^^^^^^ help: try using ty:: directly: `ty` + | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` - --> $DIR/ty_tykind_usage.rs:17:9 + --> $DIR/ty_tykind_usage.rs:19:9 | LL | TyKind::Uint(..) => (), - | ^^^^^^ help: try using ty:: directly: `ty` + | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` - --> $DIR/ty_tykind_usage.rs:18:9 + --> $DIR/ty_tykind_usage.rs:20:9 | LL | TyKind::Float(..) => (), - | ^^^^^^ help: try using ty:: directly: `ty` + | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` - --> $DIR/ty_tykind_usage.rs:19:9 + --> $DIR/ty_tykind_usage.rs:21:9 | LL | TyKind::Adt(..) => (), - | ^^^^^^ help: try using ty:: directly: `ty` + | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` - --> $DIR/ty_tykind_usage.rs:20:9 + --> $DIR/ty_tykind_usage.rs:22:9 | LL | TyKind::Foreign(..) => (), - | ^^^^^^ help: try using ty:: directly: `ty` + | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` - --> $DIR/ty_tykind_usage.rs:21:9 + --> $DIR/ty_tykind_usage.rs:23:9 | LL | TyKind::Str => (), - | ^^^^^^ help: try using ty:: directly: `ty` + | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` - --> $DIR/ty_tykind_usage.rs:22:9 + --> $DIR/ty_tykind_usage.rs:24:9 | LL | TyKind::Array(..) => (), - | ^^^^^^ help: try using ty:: directly: `ty` + | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` - --> $DIR/ty_tykind_usage.rs:23:9 + --> $DIR/ty_tykind_usage.rs:25:9 | LL | TyKind::Slice(..) => (), - | ^^^^^^ help: try using ty:: directly: `ty` + | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` - --> $DIR/ty_tykind_usage.rs:24:9 + --> $DIR/ty_tykind_usage.rs:26:9 | LL | TyKind::RawPtr(..) => (), - | ^^^^^^ help: try using ty:: directly: `ty` + | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` - --> $DIR/ty_tykind_usage.rs:25:9 + --> $DIR/ty_tykind_usage.rs:27:9 | LL | TyKind::Ref(..) => (), - | ^^^^^^ help: try using ty:: directly: `ty` + | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` - --> $DIR/ty_tykind_usage.rs:26:9 + --> $DIR/ty_tykind_usage.rs:28:9 | LL | TyKind::FnDef(..) => (), - | ^^^^^^ help: try using ty:: directly: `ty` + | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` - --> $DIR/ty_tykind_usage.rs:27:9 + --> $DIR/ty_tykind_usage.rs:29:9 | LL | TyKind::FnPtr(..) => (), - | ^^^^^^ help: try using ty:: directly: `ty` + | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` - --> $DIR/ty_tykind_usage.rs:28:9 + --> $DIR/ty_tykind_usage.rs:30:9 | LL | TyKind::Dynamic(..) => (), - | ^^^^^^ help: try using ty:: directly: `ty` + | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` - --> $DIR/ty_tykind_usage.rs:29:9 + --> $DIR/ty_tykind_usage.rs:31:9 | LL | TyKind::Closure(..) => (), - | ^^^^^^ help: try using ty:: directly: `ty` + | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` - --> $DIR/ty_tykind_usage.rs:30:9 + --> $DIR/ty_tykind_usage.rs:32:9 | LL | TyKind::Generator(..) => (), - | ^^^^^^ help: try using ty:: directly: `ty` + | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` - --> $DIR/ty_tykind_usage.rs:31:9 + --> $DIR/ty_tykind_usage.rs:33:9 | LL | TyKind::GeneratorWitness(..) => (), - | ^^^^^^ help: try using ty:: directly: `ty` + | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` - --> $DIR/ty_tykind_usage.rs:32:9 + --> $DIR/ty_tykind_usage.rs:34:9 | LL | TyKind::Never => (), - | ^^^^^^ help: try using ty:: directly: `ty` + | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` - --> $DIR/ty_tykind_usage.rs:33:9 + --> $DIR/ty_tykind_usage.rs:35:9 | LL | TyKind::Tuple(..) => (), - | ^^^^^^ help: try using ty:: directly: `ty` + | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` - --> $DIR/ty_tykind_usage.rs:34:9 + --> $DIR/ty_tykind_usage.rs:36:9 | LL | TyKind::Projection(..) => (), - | ^^^^^^ help: try using ty:: directly: `ty` + | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` - --> $DIR/ty_tykind_usage.rs:35:9 + --> $DIR/ty_tykind_usage.rs:37:9 | LL | TyKind::Opaque(..) => (), - | ^^^^^^ help: try using ty:: directly: `ty` + | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` - --> $DIR/ty_tykind_usage.rs:36:9 + --> $DIR/ty_tykind_usage.rs:38:9 | LL | TyKind::Param(..) => (), - | ^^^^^^ help: try using ty:: directly: `ty` + | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` - --> $DIR/ty_tykind_usage.rs:37:9 + --> $DIR/ty_tykind_usage.rs:39:9 | LL | TyKind::Bound(..) => (), - | ^^^^^^ help: try using ty:: directly: `ty` + | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` - --> $DIR/ty_tykind_usage.rs:38:9 + --> $DIR/ty_tykind_usage.rs:40:9 | LL | TyKind::Placeholder(..) => (), - | ^^^^^^ help: try using ty:: directly: `ty` + | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` - --> $DIR/ty_tykind_usage.rs:39:9 + --> $DIR/ty_tykind_usage.rs:41:9 | LL | TyKind::Infer(..) => (), - | ^^^^^^ help: try using ty:: directly: `ty` + | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` - --> $DIR/ty_tykind_usage.rs:40:9 + --> $DIR/ty_tykind_usage.rs:42:9 | LL | TyKind::Error(_) => (), - | ^^^^^^ help: try using ty:: directly: `ty` + | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind::` - --> $DIR/ty_tykind_usage.rs:45:12 + --> $DIR/ty_tykind_usage.rs:47:12 | LL | if let TyKind::Int(int_ty) = kind {} - | ^^^^^^ help: try using ty:: directly: `ty` + | ^^^^^^ help: try using `ty::` directly: `ty` error: usage of `ty::TyKind` - --> $DIR/ty_tykind_usage.rs:47:24 + --> $DIR/ty_tykind_usage.rs:49:24 | LL | fn ty_kind(ty_bad: TyKind<'_>, ty_good: Ty<'_>) {} | ^^^^^^^^^^ | = help: try using `Ty` instead -error: aborting due to 30 previous errors +error: usage of `ty::TyKind` + --> $DIR/ty_tykind_usage.rs:51:37 + | +LL | fn ir_ty_kind(bad: IrTyKind) -> IrTyKind { + | ^^^^^^^^^^^ + | + = help: try using `Ty` instead + +error: usage of `ty::TyKind` + --> $DIR/ty_tykind_usage.rs:51:53 + | +LL | fn ir_ty_kind(bad: IrTyKind) -> IrTyKind { + | ^^^^^^^^^^^ + | + = help: try using `Ty` instead + +error: usage of `ty::TyKind::` + --> $DIR/ty_tykind_usage.rs:54:9 + | +LL | IrTyKind::Bool + | --------^^^^^^ + | | + | help: try using `ty::` directly: `ty` + +error: aborting due to 33 previous errors From f05a92d15896604faf30d33e73c7d40b98b2ec9c Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Fri, 27 May 2022 07:52:56 -0700 Subject: [PATCH 4/5] Remove some comments, inline interner fn --- compiler/rustc_metadata/src/rmeta/decoder.rs | 1 + compiler/rustc_middle/src/ty/context.rs | 38 +------------------ compiler/rustc_middle/src/ty/mod.rs | 2 +- .../rustc_typeck/src/check/intrinsicck.rs | 2 +- 4 files changed, 4 insertions(+), 39 deletions(-) diff --git a/compiler/rustc_metadata/src/rmeta/decoder.rs b/compiler/rustc_metadata/src/rmeta/decoder.rs index 806db61471ada..d9f21fa9bb9ad 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder.rs @@ -382,6 +382,7 @@ impl<'a, 'tcx> TyDecoder for DecodeContext<'a, 'tcx> { type I = TyInterner<'tcx>; + #[inline] fn interner(&self) -> Self::I { TyInterner { tcx: self.tcx() } } diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 6f548658ef33d..c1c7e1389cb53 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -94,43 +94,6 @@ pub struct TyInterner<'tcx> { pub tcx: TyCtxt<'tcx>, } -/* -/// We don't ever actually need this. It's only required for derives. -impl<'tcx> Hash for TyInterner<'tcx> { - fn hash(&self, _state: &mut H) {} -} - -/// We don't ever actually need this. It's only required for derives. -impl<'tcx> Ord for TyInterner<'tcx> { - fn cmp(&self, _other: &Self) -> Ordering { - Ordering::Equal - } -} - -/// We don't ever actually need this. It's only required for derives. -impl<'tcx> PartialOrd for TyInterner<'tcx> { - fn partial_cmp(&self, _other: &Self) -> Option { - None - } -} - -/// We don't ever actually need this. It's only required for derives. -impl<'tcx> PartialEq for TyInterner<'tcx> { - fn eq(&self, _other: &Self) -> bool { - false - } -} - -/// We don't ever actually need this. It's only required for derives. -impl<'tcx> Eq for TyInterner<'tcx> {} - -impl fmt::Debug for TyInterner<'_> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "TyInterner") - } -} -*/ - #[allow(rustc::usage_of_ty_tykind)] impl<'tcx> Interner for TyInterner<'tcx> { type AdtDef = ty::AdtDef<'tcx>; @@ -1140,6 +1103,7 @@ pub struct GlobalCtxt<'tcx> { } impl<'tcx> TyCtxt<'tcx> { + #[inline] pub fn interner(self) -> TyInterner<'tcx> { TyInterner { tcx: self } } diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 25305804d3a71..03e8a9cb96cc6 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -463,7 +463,7 @@ static_assert_size!(WithStableHash>, 56); #[rustc_pass_by_value] pub struct Ty<'tcx>(Interned<'tcx, WithStableHash>>); -const LEAKED_BOOL_TY_ALREADY: std::sync::atomic::AtomicBool = +static LEAKED_BOOL_TY_ALREADY: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); /// "Static" bool only used for internal testing. diff --git a/compiler/rustc_typeck/src/check/intrinsicck.rs b/compiler/rustc_typeck/src/check/intrinsicck.rs index 75508009ad825..9cb57759b86c1 100644 --- a/compiler/rustc_typeck/src/check/intrinsicck.rs +++ b/compiler/rustc_typeck/src/check/intrinsicck.rs @@ -4,7 +4,7 @@ use rustc_errors::struct_span_err; use rustc_hir as hir; use rustc_index::vec::Idx; use rustc_middle::ty::layout::{LayoutError, SizeSkeleton}; -use rustc_middle::ty::{self, FloatTy, InferTy, IntTy, Ty, TyCtxt, TypeFoldable, UintTy, Article}; +use rustc_middle::ty::{self, Article, FloatTy, InferTy, IntTy, Ty, TyCtxt, TypeFoldable, UintTy}; use rustc_session::lint; use rustc_span::{Span, Symbol, DUMMY_SP}; use rustc_target::abi::{Pointer, VariantIdx}; From 46389159403ca0973bf88a4c153a2707cdb257d2 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Fri, 27 May 2022 20:03:57 -0700 Subject: [PATCH 5/5] Make TyCtxt implement Interner, make HashStable generic and move to rustc_type_ir --- compiler/rustc_macros/src/serialize.rs | 4 +- compiler/rustc_metadata/src/rmeta/decoder.rs | 6 +- compiler/rustc_metadata/src/rmeta/encoder.rs | 4 +- .../rustc_middle/src/mir/interpret/mod.rs | 14 +- compiler/rustc_middle/src/ty/codec.rs | 129 ++++++++--------- compiler/rustc_middle/src/ty/context.rs | 11 +- compiler/rustc_middle/src/ty/mod.rs | 27 +--- compiler/rustc_middle/src/ty/sty.rs | 2 +- compiler/rustc_middle/src/ty/subst.rs | 6 +- .../rustc_mir_transform/src/coverage/tests.rs | 4 +- .../rustc_query_impl/src/on_disk_cache.rs | 10 +- compiler/rustc_query_system/src/ich/mod.rs | 122 ---------------- compiler/rustc_type_ir/src/lib.rs | 1 - compiler/rustc_type_ir/src/sty.rs | 135 +++++++++++++++++- compiler/rustc_typeck/src/check/op.rs | 2 - 15 files changed, 229 insertions(+), 248 deletions(-) diff --git a/compiler/rustc_macros/src/serialize.rs b/compiler/rustc_macros/src/serialize.rs index 653c728ee4293..a39b44139811e 100644 --- a/compiler/rustc_macros/src/serialize.rs +++ b/compiler/rustc_macros/src/serialize.rs @@ -8,7 +8,7 @@ pub fn type_decodable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2: if !s.ast().generics.lifetimes().any(|lt| lt.lifetime.ident == "tcx") { s.add_impl_generic(parse_quote! { 'tcx }); } - s.add_impl_generic(parse_quote! {#decoder_ty: ::rustc_type_ir::codec::TyDecoder>}); + s.add_impl_generic(parse_quote! {#decoder_ty: ::rustc_type_ir::codec::TyDecoder>}); s.add_bounds(synstructure::AddBounds::Generics); decodable_body(s, decoder_ty) @@ -95,7 +95,7 @@ pub fn type_encodable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2: s.add_impl_generic(parse_quote! {'tcx}); } let encoder_ty = quote! { __E }; - s.add_impl_generic(parse_quote! {#encoder_ty: ::rustc_type_ir::codec::TyEncoder>}); + s.add_impl_generic(parse_quote! {#encoder_ty: ::rustc_type_ir::codec::TyEncoder>}); s.add_bounds(synstructure::AddBounds::Generics); encodable_body(s, encoder_ty, false) diff --git a/compiler/rustc_metadata/src/rmeta/decoder.rs b/compiler/rustc_metadata/src/rmeta/decoder.rs index d9f21fa9bb9ad..775ebb48402aa 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder.rs @@ -24,8 +24,8 @@ use rustc_middle::mir::interpret::{AllocDecodingSession, AllocDecodingState}; use rustc_middle::thir; use rustc_middle::ty::codec::TyDecoder; use rustc_middle::ty::fast_reject::SimplifiedType; +use rustc_middle::ty::GeneratorDiagnosticData; use rustc_middle::ty::{self, ParameterizedOverTcx, Ty, TyCtxt, Visibility}; -use rustc_middle::ty::{GeneratorDiagnosticData, TyInterner}; use rustc_serialize::{opaque, Decodable, Decoder}; use rustc_session::cstore::{ CrateSource, ExternCrate, ForeignModule, LinkagePreference, NativeLib, @@ -380,11 +380,11 @@ impl<'a, 'tcx> DecodeContext<'a, 'tcx> { impl<'a, 'tcx> TyDecoder for DecodeContext<'a, 'tcx> { const CLEAR_CROSS_CRATE: bool = true; - type I = TyInterner<'tcx>; + type I = TyCtxt<'tcx>; #[inline] fn interner(&self) -> Self::I { - TyInterner { tcx: self.tcx() } + self.tcx() } #[inline] diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 2a862502f38ac..5a40986307c7f 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -26,7 +26,7 @@ use rustc_middle::traits::specialization_graph; use rustc_middle::ty::codec::TyEncoder; use rustc_middle::ty::fast_reject::{self, SimplifiedType, TreatParams}; use rustc_middle::ty::query::Providers; -use rustc_middle::ty::{self, SymbolName, Ty, TyCtxt, TyInterner}; +use rustc_middle::ty::{self, SymbolName, Ty, TyCtxt}; use rustc_serialize::{opaque, Encodable, Encoder}; use rustc_session::config::CrateType; use rustc_session::cstore::{ForeignModule, LinkagePreference, NativeLib}; @@ -316,7 +316,7 @@ impl<'a, 'tcx> Encodable> for Span { impl<'a, 'tcx> TyEncoder for EncodeContext<'a, 'tcx> { const CLEAR_CROSS_CRATE: bool = true; - type I = TyInterner<'tcx>; + type I = TyCtxt<'tcx>; fn position(&self) -> usize { self.opaque.position() diff --git a/compiler/rustc_middle/src/mir/interpret/mod.rs b/compiler/rustc_middle/src/mir/interpret/mod.rs index 926afa8ccb6bb..06cd6a66e39f5 100644 --- a/compiler/rustc_middle/src/mir/interpret/mod.rs +++ b/compiler/rustc_middle/src/mir/interpret/mod.rs @@ -115,7 +115,7 @@ use rustc_target::abi::Endian; use crate::mir; use crate::ty::codec::{TyDecoder, TyEncoder}; use crate::ty::subst::GenericArgKind; -use crate::ty::{self, Instance, Ty, TyCtxt, TyInterner}; +use crate::ty::{self, Instance, Ty, TyCtxt}; pub use self::error::{ struct_error, CheckInAllocMsg, ErrorHandled, EvalToAllocationRawResult, EvalToConstValueResult, @@ -203,7 +203,7 @@ enum AllocDiscriminant { Static, } -pub fn specialized_encode_alloc_id<'tcx, E: TyEncoder>>( +pub fn specialized_encode_alloc_id<'tcx, E: TyEncoder>>( encoder: &mut E, tcx: TyCtxt<'tcx>, alloc_id: AllocId, @@ -277,7 +277,7 @@ impl<'s> AllocDecodingSession<'s> { /// Decodes an `AllocId` in a thread-safe way. pub fn decode_alloc_id<'tcx, D>(&self, decoder: &mut D) -> AllocId where - D: TyDecoder>, + D: TyDecoder>, { // Read the index of the allocation. let idx = usize::try_from(decoder.read_u32()).unwrap(); @@ -305,7 +305,7 @@ impl<'s> AllocDecodingSession<'s> { AllocDiscriminant::Alloc => { // If this is an allocation, we need to reserve an // `AllocId` so we can decode cyclic graphs. - let alloc_id = decoder.interner().tcx.reserve_alloc_id(); + let alloc_id = decoder.interner().reserve_alloc_id(); *entry = State::InProgress(TinyList::new_single(self.session_id), alloc_id); Some(alloc_id) @@ -349,7 +349,7 @@ impl<'s> AllocDecodingSession<'s> { // We already have a reserved `AllocId`. let alloc_id = alloc_id.unwrap(); trace!("decoded alloc {:?}: {:#?}", alloc_id, alloc); - decoder.interner().tcx.set_alloc_id_same_memory(alloc_id, alloc); + decoder.interner().set_alloc_id_same_memory(alloc_id, alloc); alloc_id } AllocDiscriminant::Fn => { @@ -357,7 +357,7 @@ impl<'s> AllocDecodingSession<'s> { trace!("creating fn alloc ID"); let instance = ty::Instance::decode(decoder); trace!("decoded fn alloc instance: {:?}", instance); - let alloc_id = decoder.interner().tcx.create_fn_alloc(instance); + let alloc_id = decoder.interner().create_fn_alloc(instance); alloc_id } AllocDiscriminant::Static => { @@ -365,7 +365,7 @@ impl<'s> AllocDecodingSession<'s> { trace!("creating extern static alloc ID"); let did = >::decode(decoder); trace!("decoded static def-ID: {:?}", did); - let alloc_id = decoder.interner().tcx.create_static_alloc(did); + let alloc_id = decoder.interner().create_static_alloc(did); alloc_id } } diff --git a/compiler/rustc_middle/src/ty/codec.rs b/compiler/rustc_middle/src/ty/codec.rs index 2298cb4098b76..1e2d1fbeb4bf6 100644 --- a/compiler/rustc_middle/src/ty/codec.rs +++ b/compiler/rustc_middle/src/ty/codec.rs @@ -17,7 +17,7 @@ use crate::traits; use crate::ty::subst::SubstsRef; use crate::ty::{self, AdtDef, Ty}; use rustc_data_structures::fx::FxHashMap; -use rustc_middle::ty::TyInterner; +use rustc_middle::ty::TyCtxt; use rustc_serialize::{Decodable, Encodable}; use rustc_span::Span; pub use rustc_type_ir::{TyDecoder, TyEncoder}; @@ -36,7 +36,7 @@ pub trait EncodableWithShorthand: Copy + Eq + Hash { } #[allow(rustc::usage_of_ty_tykind)] -impl<'tcx, E: TyEncoder>> EncodableWithShorthand for Ty<'tcx> { +impl<'tcx, E: TyEncoder>> EncodableWithShorthand for Ty<'tcx> { type Variant = ty::TyKind<'tcx>; #[inline] @@ -45,9 +45,7 @@ impl<'tcx, E: TyEncoder>> EncodableWithShorthand for Ty< } } -impl<'tcx, E: TyEncoder>> EncodableWithShorthand - for ty::PredicateKind<'tcx> -{ +impl<'tcx, E: TyEncoder>> EncodableWithShorthand for ty::PredicateKind<'tcx> { type Variant = ty::PredicateKind<'tcx>; #[inline] @@ -66,7 +64,7 @@ impl<'tcx, E: TyEncoder>> EncodableWithShorthand /// /// `Decodable` can still be implemented in cases where `Decodable` is required /// by a trait bound. -pub trait RefDecodable<'tcx, D: TyDecoder>> { +pub trait RefDecodable<'tcx, D: TyDecoder>> { fn decode(d: &mut D) -> &'tcx Self; } @@ -77,7 +75,7 @@ pub fn encode_with_shorthand<'tcx, E, T, M>( cache: M, ) -> Result<(), E::Error> where - E: TyEncoder>, + E: TyEncoder>, M: for<'b> Fn(&'b mut E) -> &'b mut FxHashMap, T: EncodableWithShorthand, // The discriminant and shorthand must have the same size. @@ -114,13 +112,13 @@ where Ok(()) } -impl<'tcx, E: TyEncoder>> Encodable for Ty<'tcx> { +impl<'tcx, E: TyEncoder>> Encodable for Ty<'tcx> { fn encode(&self, e: &mut E) -> Result<(), E::Error> { encode_with_shorthand(e, self, TyEncoder::type_shorthands) } } -impl<'tcx, E: TyEncoder>> Encodable +impl<'tcx, E: TyEncoder>> Encodable for ty::Binder<'tcx, ty::PredicateKind<'tcx>> { fn encode(&self, e: &mut E) -> Result<(), E::Error> { @@ -129,37 +127,37 @@ impl<'tcx, E: TyEncoder>> Encodable } } -impl<'tcx, E: TyEncoder>> Encodable for ty::Predicate<'tcx> { +impl<'tcx, E: TyEncoder>> Encodable for ty::Predicate<'tcx> { fn encode(&self, e: &mut E) -> Result<(), E::Error> { self.kind().encode(e) } } -impl<'tcx, E: TyEncoder>> Encodable for ty::Region<'tcx> { +impl<'tcx, E: TyEncoder>> Encodable for ty::Region<'tcx> { fn encode(&self, e: &mut E) -> Result<(), E::Error> { self.kind().encode(e) } } -impl<'tcx, E: TyEncoder>> Encodable for ty::Const<'tcx> { +impl<'tcx, E: TyEncoder>> Encodable for ty::Const<'tcx> { fn encode(&self, e: &mut E) -> Result<(), E::Error> { self.0.0.encode(e) } } -impl<'tcx, E: TyEncoder>> Encodable for ConstAllocation<'tcx> { +impl<'tcx, E: TyEncoder>> Encodable for ConstAllocation<'tcx> { fn encode(&self, e: &mut E) -> Result<(), E::Error> { self.inner().encode(e) } } -impl<'tcx, E: TyEncoder>> Encodable for AdtDef<'tcx> { +impl<'tcx, E: TyEncoder>> Encodable for AdtDef<'tcx> { fn encode(&self, e: &mut E) -> Result<(), E::Error> { self.0.0.encode(e) } } -impl<'tcx, E: TyEncoder>> Encodable for AllocId { +impl<'tcx, E: TyEncoder>> Encodable for AllocId { fn encode(&self, e: &mut E) -> Result<(), E::Error> { e.encode_alloc_id(self) } @@ -168,7 +166,7 @@ impl<'tcx, E: TyEncoder>> Encodable for AllocId { #[inline] fn decode_arena_allocable< 'tcx, - D: TyDecoder>, + D: TyDecoder>, T: ArenaAllocatable<'tcx> + Decodable, >( decoder: &mut D, @@ -176,13 +174,13 @@ fn decode_arena_allocable< where D: TyDecoder, { - decoder.interner().tcx.arena.alloc(Decodable::decode(decoder)) + decoder.interner().arena.alloc(Decodable::decode(decoder)) } #[inline] fn decode_arena_allocable_slice< 'tcx, - D: TyDecoder>, + D: TyDecoder>, T: ArenaAllocatable<'tcx> + Decodable, >( decoder: &mut D, @@ -190,10 +188,10 @@ fn decode_arena_allocable_slice< where D: TyDecoder, { - decoder.interner().tcx.arena.alloc_from_iter( as Decodable>::decode(decoder)) + decoder.interner().arena.alloc_from_iter( as Decodable>::decode(decoder)) } -impl<'tcx, D: TyDecoder>> Decodable for Ty<'tcx> { +impl<'tcx, D: TyDecoder>> Decodable for Ty<'tcx> { #[allow(rustc::usage_of_ty_tykind)] fn decode(decoder: &mut D) -> Ty<'tcx> { // Handle shorthands first, if we have a usize > 0x80. @@ -206,13 +204,13 @@ impl<'tcx, D: TyDecoder>> Decodable for Ty<'tcx> { decoder.with_position(shorthand, Ty::decode) }) } else { - let tcx = decoder.interner().tcx; + let tcx = decoder.interner(); tcx.mk_ty(rustc_type_ir::TyKind::decode(decoder)) } } } -impl<'tcx, D: TyDecoder>> Decodable +impl<'tcx, D: TyDecoder>> Decodable for ty::Binder<'tcx, ty::PredicateKind<'tcx>> { fn decode(decoder: &mut D) -> ty::Binder<'tcx, ty::PredicateKind<'tcx>> { @@ -233,64 +231,64 @@ impl<'tcx, D: TyDecoder>> Decodable } } -impl<'tcx, D: TyDecoder>> Decodable for ty::Predicate<'tcx> { +impl<'tcx, D: TyDecoder>> Decodable for ty::Predicate<'tcx> { fn decode(decoder: &mut D) -> ty::Predicate<'tcx> { let predicate_kind = Decodable::decode(decoder); - decoder.interner().tcx.mk_predicate(predicate_kind) + decoder.interner().mk_predicate(predicate_kind) } } -impl<'tcx, D: TyDecoder>> Decodable for SubstsRef<'tcx> { +impl<'tcx, D: TyDecoder>> Decodable for SubstsRef<'tcx> { fn decode(decoder: &mut D) -> Self { let len = decoder.read_usize(); - let tcx = decoder.interner().tcx; + let tcx = decoder.interner(); tcx.mk_substs( (0..len).map::, _>(|_| Decodable::decode(decoder)), ) } } -impl<'tcx, D: TyDecoder>> Decodable for mir::Place<'tcx> { +impl<'tcx, D: TyDecoder>> Decodable for mir::Place<'tcx> { fn decode(decoder: &mut D) -> Self { let local: mir::Local = Decodable::decode(decoder); let len = decoder.read_usize(); - let projection = decoder.interner().tcx.mk_place_elems( + let projection = decoder.interner().mk_place_elems( (0..len).map::, _>(|_| Decodable::decode(decoder)), ); mir::Place { local, projection } } } -impl<'tcx, D: TyDecoder>> Decodable for ty::Region<'tcx> { +impl<'tcx, D: TyDecoder>> Decodable for ty::Region<'tcx> { fn decode(decoder: &mut D) -> Self { - decoder.interner().tcx.mk_region(Decodable::decode(decoder)) + decoder.interner().mk_region(Decodable::decode(decoder)) } } -impl<'tcx, D: TyDecoder>> Decodable for CanonicalVarInfos<'tcx> { +impl<'tcx, D: TyDecoder>> Decodable for CanonicalVarInfos<'tcx> { fn decode(decoder: &mut D) -> Self { let len = decoder.read_usize(); let interned: Vec> = (0..len).map(|_| Decodable::decode(decoder)).collect(); - decoder.interner().tcx.intern_canonical_var_infos(interned.as_slice()) + decoder.interner().intern_canonical_var_infos(interned.as_slice()) } } -impl<'tcx, D: TyDecoder>> Decodable for AllocId { +impl<'tcx, D: TyDecoder>> Decodable for AllocId { fn decode(decoder: &mut D) -> Self { decoder.decode_alloc_id() } } -impl<'tcx, D: TyDecoder>> Decodable for ty::SymbolName<'tcx> { +impl<'tcx, D: TyDecoder>> Decodable for ty::SymbolName<'tcx> { fn decode(decoder: &mut D) -> Self { - ty::SymbolName::new(decoder.interner().tcx, &decoder.read_str()) + ty::SymbolName::new(decoder.interner(), &decoder.read_str()) } } macro_rules! impl_decodable_via_ref { ($($t:ty),+) => { - $(impl<'tcx, D: TyDecoder>> Decodable for $t { + $(impl<'tcx, D: TyDecoder>> Decodable for $t { fn decode(decoder: &mut D) -> Self { RefDecodable::decode(decoder) } @@ -298,89 +296,86 @@ macro_rules! impl_decodable_via_ref { } } -impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for ty::List> { +impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for ty::List> { fn decode(decoder: &mut D) -> &'tcx Self { let len = decoder.read_usize(); - decoder - .interner() - .tcx - .mk_type_list((0..len).map::, _>(|_| Decodable::decode(decoder))) + decoder.interner().mk_type_list((0..len).map::, _>(|_| Decodable::decode(decoder))) } } -impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> +impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for ty::List>> { fn decode(decoder: &mut D) -> &'tcx Self { let len = decoder.read_usize(); - decoder.interner().tcx.mk_poly_existential_predicates( + decoder.interner().mk_poly_existential_predicates( (0..len).map::, _>(|_| Decodable::decode(decoder)), ) } } -impl<'tcx, D: TyDecoder>> Decodable for ty::Const<'tcx> { +impl<'tcx, D: TyDecoder>> Decodable for ty::Const<'tcx> { fn decode(decoder: &mut D) -> Self { - decoder.interner().tcx.mk_const(Decodable::decode(decoder)) + decoder.interner().mk_const(Decodable::decode(decoder)) } } -impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for [ty::ValTree<'tcx>] { +impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for [ty::ValTree<'tcx>] { fn decode(decoder: &mut D) -> &'tcx Self { - decoder.interner().tcx.arena.alloc_from_iter( + decoder.interner().arena.alloc_from_iter( (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::>(), ) } } -impl<'tcx, D: TyDecoder>> Decodable for ConstAllocation<'tcx> { +impl<'tcx, D: TyDecoder>> Decodable for ConstAllocation<'tcx> { fn decode(decoder: &mut D) -> Self { - decoder.interner().tcx.intern_const_alloc(Decodable::decode(decoder)) + decoder.interner().intern_const_alloc(Decodable::decode(decoder)) } } -impl<'tcx, D: TyDecoder>> Decodable for AdtDef<'tcx> { +impl<'tcx, D: TyDecoder>> Decodable for AdtDef<'tcx> { fn decode(decoder: &mut D) -> Self { - decoder.interner().tcx.intern_adt_def(Decodable::decode(decoder)) + decoder.interner().intern_adt_def(Decodable::decode(decoder)) } } -impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> +impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for [(ty::Predicate<'tcx>, Span)] { fn decode(decoder: &mut D) -> &'tcx Self { - decoder.interner().tcx.arena.alloc_from_iter( + decoder.interner().arena.alloc_from_iter( (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::>(), ) } } -impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> +impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for [thir::abstract_const::Node<'tcx>] { fn decode(decoder: &mut D) -> &'tcx Self { - decoder.interner().tcx.arena.alloc_from_iter( + decoder.interner().arena.alloc_from_iter( (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::>(), ) } } -impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> +impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for [thir::abstract_const::NodeId] { fn decode(decoder: &mut D) -> &'tcx Self { - decoder.interner().tcx.arena.alloc_from_iter( + decoder.interner().arena.alloc_from_iter( (0..decoder.read_usize()).map(|_| Decodable::decode(decoder)).collect::>(), ) } } -impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> +impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for ty::List { fn decode(decoder: &mut D) -> &'tcx Self { let len = decoder.read_usize(); - decoder.interner().tcx.mk_bound_variable_kinds( + decoder.interner().mk_bound_variable_kinds( (0..len).map::(|_| Decodable::decode(decoder)), ) } @@ -414,14 +409,14 @@ macro_rules! impl_arena_allocatable_decoder { ([]$args:tt) => {}; ([decode $(, $attrs:ident)*] [$name:ident: $ty:ty]) => { - impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for $ty { + impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for $ty { #[inline] fn decode(decoder: &mut D) -> &'tcx Self { decode_arena_allocable(decoder) } } - impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for [$ty] { + impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for [$ty] { #[inline] fn decode(decoder: &mut D) -> &'tcx Self { decode_arena_allocable_slice(decoder) @@ -443,17 +438,17 @@ arena_types!(impl_arena_allocatable_decoders); macro_rules! impl_arena_copy_decoder { (<$tcx:tt> $($ty:ty,)*) => { - $(impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for $ty { + $(impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for $ty { #[inline] fn decode(decoder: &mut D) -> &'tcx Self { - decoder.interner().tcx.arena.alloc(Decodable::decode(decoder)) + decoder.interner().arena.alloc(Decodable::decode(decoder)) } } - impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for [$ty] { + impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for [$ty] { #[inline] fn decode(decoder: &mut D) -> &'tcx Self { - decoder.interner().tcx.arena.alloc_from_iter( as Decodable>::decode(decoder)) + decoder.interner().arena.alloc_from_iter( as Decodable>::decode(decoder)) } })* }; @@ -512,13 +507,13 @@ macro_rules! implement_ty_decoder { macro_rules! impl_binder_encode_decode { ($($t:ty),+ $(,)?) => { $( - impl<'tcx, E: TyEncoder>> Encodable for ty::Binder<'tcx, $t> { + impl<'tcx, E: TyEncoder>> Encodable for ty::Binder<'tcx, $t> { fn encode(&self, e: &mut E) -> Result<(), E::Error> { self.bound_vars().encode(e)?; self.as_ref().skip_binder().encode(e) } } - impl<'tcx, D: TyDecoder>> Decodable for ty::Binder<'tcx, $t> { + impl<'tcx, D: TyDecoder>> Decodable for ty::Binder<'tcx, $t> { fn decode(decoder: &mut D) -> Self { let bound_vars = Decodable::decode(decoder); ty::Binder::bind_with_vars(Decodable::decode(decoder), bound_vars) diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index c1c7e1389cb53..a0d92e2a5dd94 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -90,12 +90,8 @@ pub trait OnDiskCache<'tcx>: rustc_data_structures::sync::Sync { fn serialize(&self, tcx: TyCtxt<'tcx>, encoder: &mut FileEncoder) -> FileEncodeResult; } -pub struct TyInterner<'tcx> { - pub tcx: TyCtxt<'tcx>, -} - #[allow(rustc::usage_of_ty_tykind)] -impl<'tcx> Interner for TyInterner<'tcx> { +impl<'tcx> Interner for TyCtxt<'tcx> { type AdtDef = ty::AdtDef<'tcx>; type SubstsRef = ty::SubstsRef<'tcx>; type DefId = DefId; @@ -1103,11 +1099,6 @@ pub struct GlobalCtxt<'tcx> { } impl<'tcx> TyCtxt<'tcx> { - #[inline] - pub fn interner(self) -> TyInterner<'tcx> { - TyInterner { tcx: self } - } - /// Expects a body and returns its codegen attributes. /// /// Unlike `codegen_fn_attrs`, this returns `CodegenFnAttrs::EMPTY` for diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 03e8a9cb96cc6..14e5dc0dd7722 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -68,8 +68,8 @@ pub use self::consts::{ pub use self::context::{ tls, CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, CtxtInterners, DelaySpanBugEmitted, FreeRegionInfo, GeneratorDiagnosticData, - GeneratorInteriorTypeCause, GlobalCtxt, Lift, OnDiskCache, TyCtxt, TyInterner, TypeckResults, - UserType, UserTypeAnnotationIndex, + GeneratorInteriorTypeCause, GlobalCtxt, Lift, OnDiskCache, TyCtxt, TypeckResults, UserType, + UserTypeAnnotationIndex, }; pub use self::instance::{Instance, InstanceDef}; pub use self::list::List; @@ -463,30 +463,17 @@ static_assert_size!(WithStableHash>, 56); #[rustc_pass_by_value] pub struct Ty<'tcx>(Interned<'tcx, WithStableHash>>); -static LEAKED_BOOL_TY_ALREADY: std::sync::atomic::AtomicBool = - std::sync::atomic::AtomicBool::new(false); - -/// "Static" bool only used for internal testing. -/// -/// FIXME(rustc_type_ir): This really should be replaced with something that doesn't leak. -/// however, since it's used for testing, it's not _that_ bad. -pub fn leak_bool_ty_for_unit_testing<'tcx>() -> Ty<'tcx> { - use std::sync::atomic::*; - - if LEAKED_BOOL_TY_ALREADY.load(Ordering::Acquire) { - panic!("Can only leak one bool type, since its equality depends on its address"); - } else { - LEAKED_BOOL_TY_ALREADY.store(true, Ordering::Release); - } - - Ty(Interned::new_unchecked(Box::leak(Box::new(WithStableHash { +impl<'tcx> TyCtxt<'tcx> { + /// A "bool" type used in rustc_mir_transform unit tests when we + /// have not spun up a TyCtxt. + pub const BOOL_TY_FOR_UNIT_TESTING: Ty<'tcx> = Ty(Interned::new_unchecked(&WithStableHash { internee: TyS { kind: ty::Bool, flags: TypeFlags::empty(), outer_exclusive_binder: DebruijnIndex::from_usize(0), }, stable_hash: Fingerprint::ZERO, - })))) + })); } impl<'a, 'tcx> HashStable> for TyS<'tcx> { diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index 9410166ac2013..faeb729c88483 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -32,7 +32,7 @@ use rustc_type_ir::TyKind as IrTyKind; // Re-export the `TyKind` from `rustc_type_ir` here for convenience #[rustc_diagnostic_item = "TyKind"] -pub type TyKind<'tcx> = IrTyKind>; +pub type TyKind<'tcx> = IrTyKind>; #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] #[derive(HashStable, TypeFoldable, Lift)] diff --git a/compiler/rustc_middle/src/ty/subst.rs b/compiler/rustc_middle/src/ty/subst.rs index 8494d5c71fe42..290485ab5fe0f 100644 --- a/compiler/rustc_middle/src/ty/subst.rs +++ b/compiler/rustc_middle/src/ty/subst.rs @@ -4,7 +4,7 @@ use crate::mir; use crate::ty::codec::{TyDecoder, TyEncoder}; use crate::ty::fold::{FallibleTypeFolder, TypeFoldable, TypeFolder, TypeVisitor}; use crate::ty::sty::{ClosureSubsts, GeneratorSubsts, InlineConstSubsts}; -use crate::ty::{self, Lift, List, ParamConst, Ty, TyCtxt, TyInterner}; +use crate::ty::{self, Lift, List, ParamConst, Ty, TyCtxt}; use rustc_data_structures::intern::{Interned, WithStableHash}; use rustc_hir::def_id::DefId; @@ -216,13 +216,13 @@ impl<'tcx> TypeFoldable<'tcx> for GenericArg<'tcx> { } } -impl<'tcx, E: TyEncoder>> Encodable for GenericArg<'tcx> { +impl<'tcx, E: TyEncoder>> Encodable for GenericArg<'tcx> { fn encode(&self, e: &mut E) -> Result<(), E::Error> { self.unpack().encode(e) } } -impl<'tcx, D: TyDecoder>> Decodable for GenericArg<'tcx> { +impl<'tcx, D: TyDecoder>> Decodable for GenericArg<'tcx> { fn decode(d: &mut D) -> GenericArg<'tcx> { GenericArgKind::decode(d).pack() } diff --git a/compiler/rustc_mir_transform/src/coverage/tests.rs b/compiler/rustc_mir_transform/src/coverage/tests.rs index 41f004b0c0043..213bb6608e139 100644 --- a/compiler/rustc_mir_transform/src/coverage/tests.rs +++ b/compiler/rustc_mir_transform/src/coverage/tests.rs @@ -37,7 +37,7 @@ use rustc_data_structures::graph::WithSuccessors; use rustc_index::vec::{Idx, IndexVec}; use rustc_middle::mir::coverage::CoverageKind; use rustc_middle::mir::*; -use rustc_middle::ty::{self, Ty}; +use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_span::{self, BytePos, Pos, Span, DUMMY_SP}; // All `TEMP_BLOCK` targets should be replaced before calling `to_body() -> mir::Body`. @@ -56,7 +56,7 @@ impl<'tcx> MockBlocks<'tcx> { blocks: IndexVec::new(), dummy_place: Place { local: RETURN_PLACE, projection: ty::List::empty() }, next_local: 0, - bool_ty: ty::leak_bool_ty_for_unit_testing(), + bool_ty: TyCtxt::BOOL_TY_FOR_UNIT_TESTING, } } diff --git a/compiler/rustc_query_impl/src/on_disk_cache.rs b/compiler/rustc_query_impl/src/on_disk_cache.rs index 7dc6921a569fd..8e4b3269402e9 100644 --- a/compiler/rustc_query_impl/src/on_disk_cache.rs +++ b/compiler/rustc_query_impl/src/on_disk_cache.rs @@ -11,7 +11,7 @@ use rustc_middle::mir::interpret::{AllocDecodingSession, AllocDecodingState}; use rustc_middle::mir::{self, interpret}; use rustc_middle::thir; use rustc_middle::ty::codec::{RefDecodable, TyDecoder, TyEncoder}; -use rustc_middle::ty::{self, Ty, TyCtxt, TyInterner}; +use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_query_system::dep_graph::DepContext; use rustc_query_system::query::{QueryCache, QueryContext, QuerySideEffects}; use rustc_serialize::{ @@ -548,12 +548,12 @@ where } impl<'a, 'tcx> TyDecoder for CacheDecoder<'a, 'tcx> { - type I = TyInterner<'tcx>; + type I = TyCtxt<'tcx>; const CLEAR_CROSS_CRATE: bool = false; #[inline] - fn interner(&self) -> TyInterner<'tcx> { - TyInterner { tcx: self.tcx } + fn interner(&self) -> TyCtxt<'tcx> { + self.tcx } #[inline] @@ -932,7 +932,7 @@ impl<'a, 'tcx, E> TyEncoder for CacheEncoder<'a, 'tcx, E> where E: 'a + OpaqueEncoder, { - type I = TyInterner<'tcx>; + type I = TyCtxt<'tcx>; const CLEAR_CROSS_CRATE: bool = false; fn position(&self) -> usize { diff --git a/compiler/rustc_query_system/src/ich/mod.rs b/compiler/rustc_query_system/src/ich/mod.rs index ddaac1c78a129..0a1c350b2db13 100644 --- a/compiler/rustc_query_system/src/ich/mod.rs +++ b/compiler/rustc_query_system/src/ich/mod.rs @@ -1,7 +1,6 @@ //! ICH - Incremental Compilation Hash pub use self::hcx::StableHashingContext; -use rustc_data_structures::stable_hasher::HashStable; use rustc_span::symbol::{sym, Symbol}; mod hcx; @@ -18,124 +17,3 @@ pub const IGNORED_ATTRIBUTES: &[Symbol] = &[ sym::rustc_partition_codegened, sym::rustc_expected_cgu_reuse, ]; - -#[allow(rustc::usage_of_ty_tykind)] -impl<'__ctx, I: rustc_type_ir::Interner> HashStable> - for rustc_type_ir::TyKind -where - I::AdtDef: HashStable>, - I::DefId: HashStable>, - I::SubstsRef: HashStable>, - I::Ty: HashStable>, - I::Const: HashStable>, - I::TypeAndMut: HashStable>, - I::PolyFnSig: HashStable>, - I::ListBinderExistentialPredicate: HashStable>, - I::Region: HashStable>, - I::Movability: HashStable>, - I::Mutability: HashStable>, - I::BinderListTy: HashStable>, - I::ListTy: HashStable>, - I::ProjectionTy: HashStable>, - I::BoundTy: HashStable>, - I::ParamTy: HashStable>, - I::PlaceholderType: HashStable>, - I::InferTy: HashStable>, - I::DelaySpanBugEmitted: HashStable>, -{ - #[inline] - fn hash_stable( - &self, - __hcx: &mut crate::ich::StableHashingContext<'__ctx>, - __hasher: &mut rustc_data_structures::stable_hasher::StableHasher, - ) { - std::mem::discriminant(self).hash_stable(__hcx, __hasher); - use rustc_type_ir::TyKind::*; - match self { - Bool => {} - Char => {} - Int(i) => { - i.hash_stable(__hcx, __hasher); - } - Uint(u) => { - u.hash_stable(__hcx, __hasher); - } - Float(f) => { - f.hash_stable(__hcx, __hasher); - } - Adt(adt, substs) => { - adt.hash_stable(__hcx, __hasher); - substs.hash_stable(__hcx, __hasher); - } - Foreign(def_id) => { - def_id.hash_stable(__hcx, __hasher); - } - Str => {} - Array(t, c) => { - t.hash_stable(__hcx, __hasher); - c.hash_stable(__hcx, __hasher); - } - Slice(t) => { - t.hash_stable(__hcx, __hasher); - } - RawPtr(tam) => { - tam.hash_stable(__hcx, __hasher); - } - Ref(r, t, m) => { - r.hash_stable(__hcx, __hasher); - t.hash_stable(__hcx, __hasher); - m.hash_stable(__hcx, __hasher); - } - FnDef(def_id, substs) => { - def_id.hash_stable(__hcx, __hasher); - substs.hash_stable(__hcx, __hasher); - } - FnPtr(polyfnsig) => { - polyfnsig.hash_stable(__hcx, __hasher); - } - Dynamic(l, r) => { - l.hash_stable(__hcx, __hasher); - r.hash_stable(__hcx, __hasher); - } - Closure(def_id, substs) => { - def_id.hash_stable(__hcx, __hasher); - substs.hash_stable(__hcx, __hasher); - } - Generator(def_id, substs, m) => { - def_id.hash_stable(__hcx, __hasher); - substs.hash_stable(__hcx, __hasher); - m.hash_stable(__hcx, __hasher); - } - GeneratorWitness(b) => { - b.hash_stable(__hcx, __hasher); - } - Never => {} - Tuple(substs) => { - substs.hash_stable(__hcx, __hasher); - } - Projection(p) => { - p.hash_stable(__hcx, __hasher); - } - Opaque(def_id, substs) => { - def_id.hash_stable(__hcx, __hasher); - substs.hash_stable(__hcx, __hasher); - } - Param(p) => { - p.hash_stable(__hcx, __hasher); - } - Bound(d, b) => { - d.hash_stable(__hcx, __hasher); - b.hash_stable(__hcx, __hasher); - } - Placeholder(p) => { - p.hash_stable(__hcx, __hasher); - } - Infer(i) => { - i.hash_stable(__hcx, __hasher); - } - Error(d) => { - d.hash_stable(__hcx, __hasher); - } - } - } -} diff --git a/compiler/rustc_type_ir/src/lib.rs b/compiler/rustc_type_ir/src/lib.rs index 766875dd82bdf..6380001b57c08 100644 --- a/compiler/rustc_type_ir/src/lib.rs +++ b/compiler/rustc_type_ir/src/lib.rs @@ -8,7 +8,6 @@ extern crate rustc_macros; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::unify::{EqUnifyValue, UnifyKey}; -//use rustc_serialize::{Decodable, Encodable}; use smallvec::SmallVec; use std::fmt; use std::fmt::Debug; diff --git a/compiler/rustc_type_ir/src/sty.rs b/compiler/rustc_type_ir/src/sty.rs index 33b3a273f44cc..650c3519b562e 100644 --- a/compiler/rustc_type_ir/src/sty.rs +++ b/compiler/rustc_type_ir/src/sty.rs @@ -13,6 +13,7 @@ use crate::UintTy; use self::TyKind::*; +use rustc_data_structures::stable_hasher::HashStable; use rustc_serialize::{Decodable, Encodable}; /// Defines the kinds of types used by the type system. @@ -198,7 +199,10 @@ impl TyKind { } } -fn discriminant(value: &TyKind) -> usize { +// This is manually implemented for `TyKind` because `std::mem::discriminant` +// returns an opaque value that is `PartialEq` but not `PartialOrd` +#[inline] +const fn discriminant(value: &TyKind) -> usize { match value { Bool => 0, Char => 1, @@ -230,6 +234,7 @@ fn discriminant(value: &TyKind) -> usize { } } +// This is manually implemented because a derive would require `I: Clone` impl Clone for TyKind { fn clone(&self) -> Self { match self { @@ -264,6 +269,7 @@ impl Clone for TyKind { } } +// This is manually implemented because a derive would require `I: PartialEq` impl PartialEq for TyKind { #[inline] fn eq(&self, other: &TyKind) -> bool { @@ -324,8 +330,10 @@ impl PartialEq for TyKind { } } +// This is manually implemented because a derive would require `I: Eq` impl Eq for TyKind {} +// This is manually implemented because a derive would require `I: PartialOrd` impl PartialOrd for TyKind { #[inline] fn partial_cmp(&self, other: &TyKind) -> Option { @@ -333,6 +341,7 @@ impl PartialOrd for TyKind { } } +// This is manually implemented because a derive would require `I: Ord` impl Ord for TyKind { #[inline] fn cmp(&self, other: &TyKind) -> Ordering { @@ -430,6 +439,7 @@ impl Ord for TyKind { } } +// This is manually implemented because a derive would require `I: Hash` impl hash::Hash for TyKind { fn hash<__H: hash::Hasher>(&self, state: &mut __H) -> () { match (&*self,) { @@ -541,6 +551,7 @@ impl hash::Hash for TyKind { } } +// This is manually implemented because a derive would require `I: Debug` impl fmt::Debug for TyKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match (&*self,) { @@ -678,6 +689,7 @@ impl fmt::Debug for TyKind { } } +// This is manually implemented because a derive would require `I: Encodable` impl Encodable for TyKind where I::DelaySpanBugEmitted: Encodable, @@ -819,6 +831,7 @@ where } } +// This is manually implemented because a derive would require `I: Decodable` impl> Decodable for TyKind where I::DelaySpanBugEmitted: Decodable, @@ -905,3 +918,123 @@ where } } } + +// This is not a derived impl because a derive would require `I: HashStable` +#[allow(rustc::usage_of_ty_tykind)] +impl HashStable for TyKind +where + I::AdtDef: HashStable, + I::DefId: HashStable, + I::SubstsRef: HashStable, + I::Ty: HashStable, + I::Const: HashStable, + I::TypeAndMut: HashStable, + I::PolyFnSig: HashStable, + I::ListBinderExistentialPredicate: HashStable, + I::Region: HashStable, + I::Movability: HashStable, + I::Mutability: HashStable, + I::BinderListTy: HashStable, + I::ListTy: HashStable, + I::ProjectionTy: HashStable, + I::BoundTy: HashStable, + I::ParamTy: HashStable, + I::PlaceholderType: HashStable, + I::InferTy: HashStable, + I::DelaySpanBugEmitted: HashStable, +{ + #[inline] + fn hash_stable( + &self, + __hcx: &mut CTX, + __hasher: &mut rustc_data_structures::stable_hasher::StableHasher, + ) { + std::mem::discriminant(self).hash_stable(__hcx, __hasher); + match self { + Bool => {} + Char => {} + Int(i) => { + i.hash_stable(__hcx, __hasher); + } + Uint(u) => { + u.hash_stable(__hcx, __hasher); + } + Float(f) => { + f.hash_stable(__hcx, __hasher); + } + Adt(adt, substs) => { + adt.hash_stable(__hcx, __hasher); + substs.hash_stable(__hcx, __hasher); + } + Foreign(def_id) => { + def_id.hash_stable(__hcx, __hasher); + } + Str => {} + Array(t, c) => { + t.hash_stable(__hcx, __hasher); + c.hash_stable(__hcx, __hasher); + } + Slice(t) => { + t.hash_stable(__hcx, __hasher); + } + RawPtr(tam) => { + tam.hash_stable(__hcx, __hasher); + } + Ref(r, t, m) => { + r.hash_stable(__hcx, __hasher); + t.hash_stable(__hcx, __hasher); + m.hash_stable(__hcx, __hasher); + } + FnDef(def_id, substs) => { + def_id.hash_stable(__hcx, __hasher); + substs.hash_stable(__hcx, __hasher); + } + FnPtr(polyfnsig) => { + polyfnsig.hash_stable(__hcx, __hasher); + } + Dynamic(l, r) => { + l.hash_stable(__hcx, __hasher); + r.hash_stable(__hcx, __hasher); + } + Closure(def_id, substs) => { + def_id.hash_stable(__hcx, __hasher); + substs.hash_stable(__hcx, __hasher); + } + Generator(def_id, substs, m) => { + def_id.hash_stable(__hcx, __hasher); + substs.hash_stable(__hcx, __hasher); + m.hash_stable(__hcx, __hasher); + } + GeneratorWitness(b) => { + b.hash_stable(__hcx, __hasher); + } + Never => {} + Tuple(substs) => { + substs.hash_stable(__hcx, __hasher); + } + Projection(p) => { + p.hash_stable(__hcx, __hasher); + } + Opaque(def_id, substs) => { + def_id.hash_stable(__hcx, __hasher); + substs.hash_stable(__hcx, __hasher); + } + Param(p) => { + p.hash_stable(__hcx, __hasher); + } + Bound(d, b) => { + d.hash_stable(__hcx, __hasher); + b.hash_stable(__hcx, __hasher); + } + Placeholder(p) => { + p.hash_stable(__hcx, __hasher); + } + Infer(i) => { + i.hash_stable(__hcx, __hasher); + } + Error(d) => { + d.hash_stable(__hcx, __hasher); + } + } + } +} diff --git a/compiler/rustc_typeck/src/check/op.rs b/compiler/rustc_typeck/src/check/op.rs index 6df9ac5f0a430..3ae04706e4bc3 100644 --- a/compiler/rustc_typeck/src/check/op.rs +++ b/compiler/rustc_typeck/src/check/op.rs @@ -677,8 +677,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { operand_ty: Ty<'tcx>, op: hir::UnOp, ) -> Ty<'tcx> { - use rustc_type_ir::sty::TyKind::*; - assert!(op.is_by_value()); match self.lookup_op_method(operand_ty, None, None, Op::Unary(op, ex.span)) { Ok(method) => {