From 25c13655072475476f6ff3f26dc5cfda39db44d8 Mon Sep 17 00:00:00 2001 From: James Barford-Evans Date: Mon, 22 Dec 2025 14:45:08 +0000 Subject: [PATCH] Part 2 refactoring of moving placeholder types to `rustc_type_ir` --- .../src/diagnostics/bound_region_errors.rs | 4 +- .../src/region_infer/graphviz.rs | 2 +- .../rustc_borrowck/src/region_infer/values.rs | 10 +- compiler/rustc_borrowck/src/type_check/mod.rs | 2 +- .../src/type_check/relate_tys.rs | 14 +- .../src/check/compare_impl_item.rs | 6 +- .../src/collect/item_bounds.rs | 5 +- .../src/collect/resolve_bound_vars.rs | 48 +-- .../src/hir_ty_lowering/bounds.rs | 6 +- .../src/hir_ty_lowering/mod.rs | 6 +- .../src/infer/canonical/canonicalizer.rs | 6 +- compiler/rustc_infer/src/infer/mod.rs | 8 +- .../src/infer/outlives/test_type_match.rs | 4 +- .../src/infer/relate/higher_ranked.rs | 6 +- .../rustc_lint/src/impl_trait_overcaptures.rs | 2 +- .../src/middle/resolve_bound_vars.rs | 4 +- compiler/rustc_middle/src/query/erase.rs | 2 +- compiler/rustc_middle/src/query/mod.rs | 4 +- compiler/rustc_middle/src/ty/codec.rs | 6 +- compiler/rustc_middle/src/ty/consts.rs | 8 +- compiler/rustc_middle/src/ty/context.rs | 26 +- compiler/rustc_middle/src/ty/fold.rs | 49 ++- compiler/rustc_middle/src/ty/mod.rs | 104 +----- compiler/rustc_middle/src/ty/print/pretty.rs | 14 +- compiler/rustc_middle/src/ty/region.rs | 95 +---- .../rustc_middle/src/ty/structural_impls.rs | 28 +- compiler/rustc_middle/src/ty/sty.rs | 84 ++--- compiler/rustc_middle/src/ty/visit.rs | 14 +- .../src/canonical/canonicalizer.rs | 25 +- .../src/canonical/mod.rs | 4 +- .../src/placeholder.rs | 22 +- .../src/unstable/convert/internal.rs | 2 +- .../src/unstable/convert/stable/ty.rs | 10 +- .../src/unstable/internal_cx/mod.rs | 5 +- compiler/rustc_public/src/unstable/mod.rs | 5 +- .../nice_region_error/placeholder_relation.rs | 8 +- .../src/error_reporting/infer/region.rs | 2 +- .../src/traits/coherence.rs | 8 +- .../rustc_trait_selection/src/traits/mod.rs | 2 +- .../rustc_trait_selection/src/traits/util.rs | 12 +- compiler/rustc_ty_utils/src/ty.rs | 2 +- compiler/rustc_type_ir/src/binder.rs | 352 +++++++++++++++++- compiler/rustc_type_ir/src/canonical.rs | 6 +- compiler/rustc_type_ir/src/const_kind.rs | 4 +- compiler/rustc_type_ir/src/error.rs | 2 +- compiler/rustc_type_ir/src/inherent.rs | 74 +--- compiler/rustc_type_ir/src/interner.rs | 18 +- compiler/rustc_type_ir/src/outlives.rs | 2 +- compiler/rustc_type_ir/src/region_kind.rs | 10 +- compiler/rustc_type_ir/src/ty_kind.rs | 4 +- src/librustdoc/clean/mod.rs | 2 +- src/tools/clippy/clippy_utils/src/ty/mod.rs | 8 +- 52 files changed, 610 insertions(+), 546 deletions(-) diff --git a/compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs b/compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs index 254d28d243ff2..6ed07cf9b1c8c 100644 --- a/compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs @@ -169,7 +169,7 @@ pub(crate) trait TypeOpInfo<'tcx> { let placeholder_region = ty::Region::new_placeholder( tcx, - ty::Placeholder::new(adjusted_universe.into(), placeholder.bound), + ty::PlaceholderRegion::new(adjusted_universe.into(), placeholder.bound), ); let error_region = @@ -179,7 +179,7 @@ pub(crate) trait TypeOpInfo<'tcx> { adjusted_universe.map(|adjusted| { ty::Region::new_placeholder( tcx, - ty::Placeholder::new(adjusted.into(), error_placeholder.bound), + ty::PlaceholderRegion::new(adjusted.into(), error_placeholder.bound), ) }) } else { diff --git a/compiler/rustc_borrowck/src/region_infer/graphviz.rs b/compiler/rustc_borrowck/src/region_infer/graphviz.rs index 526e1850c2ef9..ceb33d82deba8 100644 --- a/compiler/rustc_borrowck/src/region_infer/graphviz.rs +++ b/compiler/rustc_borrowck/src/region_infer/graphviz.rs @@ -52,7 +52,7 @@ fn render_region_vid<'tcx>( format!(" (for<{}>)", tcx.item_name(def_id)) } ty::BoundRegionKind::ClosureEnv | ty::BoundRegionKind::Anon => " (for<'_>)".to_string(), - ty::BoundRegionKind::NamedAnon(_) => { + ty::BoundRegionKind::NamedForPrinting(_) => { bug!("only used for pretty printing") } }, diff --git a/compiler/rustc_borrowck/src/region_infer/values.rs b/compiler/rustc_borrowck/src/region_infer/values.rs index 0063af25d781a..1dd3bc831f45a 100644 --- a/compiler/rustc_borrowck/src/region_infer/values.rs +++ b/compiler/rustc_borrowck/src/region_infer/values.rs @@ -10,8 +10,8 @@ use rustc_middle::ty::{self, RegionVid}; use rustc_mir_dataflow::points::{DenseLocationMap, PointIndex}; use tracing::debug; +use crate::BorrowIndex; use crate::polonius::LiveLoans; -use crate::{BorrowIndex, TyCtxt}; rustc_index::newtype_index! { /// A single integer representing a `ty::Placeholder`. @@ -420,18 +420,18 @@ impl ToElementIndex<'_> for RegionVid { impl<'tcx> ToElementIndex<'tcx> for ty::PlaceholderRegion<'tcx> { fn add_to_row(self, values: &mut RegionValues<'tcx, N>, row: N) -> bool where - Self: Into, ty::BoundRegion>>, + Self: Into>, { - let placeholder: ty::Placeholder, ty::BoundRegion> = self.into(); + let placeholder: ty::PlaceholderRegion<'tcx> = self.into(); let index = values.placeholder_indices.lookup_index(placeholder); values.placeholders.insert(row, index) } fn contained_in_row(self, values: &RegionValues<'tcx, N>, row: N) -> bool where - Self: Into, ty::BoundRegion>>, + Self: Into>, { - let placeholder: ty::Placeholder, ty::BoundRegion> = self.into(); + let placeholder: ty::PlaceholderRegion<'tcx> = self.into(); let index = values.placeholder_indices.lookup_index(placeholder); values.placeholders.contains(row, index) } diff --git a/compiler/rustc_borrowck/src/type_check/mod.rs b/compiler/rustc_borrowck/src/type_check/mod.rs index d2464c7e99ee5..e9dfea6043a39 100644 --- a/compiler/rustc_borrowck/src/type_check/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/mod.rs @@ -772,7 +772,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { ty::BoundRegionKind::Anon => sym::anon, ty::BoundRegionKind::Named(def_id) => tcx.item_name(def_id), ty::BoundRegionKind::ClosureEnv => sym::env, - ty::BoundRegionKind::NamedAnon(_) => { + ty::BoundRegionKind::NamedForPrinting(_) => { bug!("only used for pretty printing") } }; diff --git a/compiler/rustc_borrowck/src/type_check/relate_tys.rs b/compiler/rustc_borrowck/src/type_check/relate_tys.rs index 045507ceb4b43..e2d684e12a816 100644 --- a/compiler/rustc_borrowck/src/type_check/relate_tys.rs +++ b/compiler/rustc_borrowck/src/type_check/relate_tys.rs @@ -174,7 +174,7 @@ impl<'a, 'b, 'tcx> NllTypeRelating<'a, 'b, 'tcx> { let infcx = self.type_checker.infcx; let mut lazy_universe = None; let delegate = FnMutDelegate { - regions: &mut |br: ty::BoundRegion| { + regions: &mut |br: ty::BoundRegion<'tcx>| { // The first time this closure is called, create a // new universe for the placeholders we will make // from here out. @@ -191,10 +191,10 @@ impl<'a, 'b, 'tcx> NllTypeRelating<'a, 'b, 'tcx> { placeholder_reg }, - types: &mut |_bound_ty: ty::BoundTy| { + types: &mut |_bound_ty: ty::BoundTy<'tcx>| { unreachable!("we only replace regions in nll_relate, not types") }, - consts: &mut |_bound_const: ty::BoundConst| { + consts: &mut |_bound_const: ty::BoundConst<'tcx>| { unreachable!("we only replace regions in nll_relate, not consts") }, }; @@ -218,7 +218,7 @@ impl<'a, 'b, 'tcx> NllTypeRelating<'a, 'b, 'tcx> { let infcx = self.type_checker.infcx; let mut reg_map = FxHashMap::default(); let delegate = FnMutDelegate { - regions: &mut |br: ty::BoundRegion| { + regions: &mut |br: ty::BoundRegion<'tcx>| { if let Some(ex_reg_var) = reg_map.get(&br) { *ex_reg_var } else { @@ -230,10 +230,10 @@ impl<'a, 'b, 'tcx> NllTypeRelating<'a, 'b, 'tcx> { ex_reg_var } }, - types: &mut |_bound_ty: ty::BoundTy| { + types: &mut |_bound_ty: ty::BoundTy<'tcx>| { unreachable!("we only replace regions in nll_relate, not types") }, - consts: &mut |_bound_const: ty::BoundConst| { + consts: &mut |_bound_const: ty::BoundConst<'tcx>| { unreachable!("we only replace regions in nll_relate, not consts") }, }; @@ -268,7 +268,7 @@ impl<'a, 'b, 'tcx> NllTypeRelating<'a, 'b, 'tcx> { ty::BoundRegionKind::Anon => sym::anon, ty::BoundRegionKind::Named(def_id) => self.type_checker.tcx().item_name(def_id), ty::BoundRegionKind::ClosureEnv => sym::env, - ty::BoundRegionKind::NamedAnon(_) => bug!("only used for pretty printing"), + ty::BoundRegionKind::NamedForPrinting(_) => bug!("only used for pretty printing"), }; if cfg!(debug_assertions) { diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs index 4534cfcf962e8..dd7b03c9dac3f 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs @@ -592,7 +592,7 @@ pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>( ty, Ty::new_placeholder( tcx, - ty::Placeholder::new( + ty::PlaceholderType::new( universe, ty::BoundTy { var: idx, kind: ty::BoundTyKind::Anon }, ), @@ -2551,7 +2551,7 @@ fn param_env_with_gat_bounds<'tcx>( } }; - let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> = + let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind<'tcx>; 8]> = smallvec::SmallVec::with_capacity(tcx.generics_of(impl_ty.def_id).own_params.len()); // Extend the impl's identity args with late-bound GAT vars let normalize_impl_ty_args = ty::GenericArgs::identity_for_item(tcx, container_id) @@ -2587,7 +2587,7 @@ fn param_env_with_gat_bounds<'tcx>( ty::Const::new_bound( tcx, ty::INNERMOST, - ty::BoundConst { var: ty::BoundVar::from_usize(bound_vars.len() - 1) }, + ty::BoundConst::new(ty::BoundVar::from_usize(bound_vars.len() - 1)), ) .into() } diff --git a/compiler/rustc_hir_analysis/src/collect/item_bounds.rs b/compiler/rustc_hir_analysis/src/collect/item_bounds.rs index 7025f7ac84b02..a01ee2d31a3de 100644 --- a/compiler/rustc_hir_analysis/src/collect/item_bounds.rs +++ b/compiler/rustc_hir_analysis/src/collect/item_bounds.rs @@ -241,7 +241,7 @@ struct MapAndCompressBoundVars<'tcx> { binder: ty::DebruijnIndex, /// List of bound vars that remain unsubstituted because they were not /// mentioned in the GAT's args. - still_bound_vars: Vec, + still_bound_vars: Vec>, /// Subtle invariant: If the `GenericArg` is bound, then it should be /// stored with the debruijn index of `INNERMOST` so it can be shifted /// correctly during substitution. @@ -330,7 +330,8 @@ impl<'tcx> TypeFolder> for MapAndCompressBoundVars<'tcx> { } else { let var = ty::BoundVar::from_usize(self.still_bound_vars.len()); self.still_bound_vars.push(ty::BoundVariableKind::Const); - let mapped = ty::Const::new_bound(self.tcx, ty::INNERMOST, ty::BoundConst { var }); + let mapped = + ty::Const::new_bound(self.tcx, ty::INNERMOST, ty::BoundConst::new(var)); self.mapping.insert(old_bound.var, mapped.into()); mapped }; diff --git a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs index 02443b577d385..26f79d374075b 100644 --- a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs +++ b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs @@ -63,9 +63,9 @@ impl ResolvedArg { struct BoundVarContext<'a, 'tcx> { tcx: TyCtxt<'tcx>, - rbv: &'a mut ResolveBoundVars, + rbv: &'a mut ResolveBoundVars<'tcx>, disambiguator: &'a mut DisambiguatorState, - scope: ScopeRef<'a>, + scope: ScopeRef<'a, 'tcx>, opaque_capture_errors: RefCell>, } @@ -76,7 +76,7 @@ struct OpaqueHigherRankedLifetimeCaptureErrors { } #[derive(Debug)] -enum Scope<'a> { +enum Scope<'a, 'tcx> { /// Declares lifetimes, and each can be early-bound or late-bound. /// The `DebruijnIndex` of late-bound lifetimes starts at `1` and /// it should be shifted by the number of `Binder`s in between the @@ -94,7 +94,7 @@ enum Scope<'a> { /// to append to. hir_id: HirId, - s: ScopeRef<'a>, + s: ScopeRef<'a, 'tcx>, /// If this binder comes from a where clause, specify how it was created. /// This is used to diagnose inaccessible lifetimes in APIT: @@ -110,7 +110,7 @@ enum Scope<'a> { /// e.g., `(&T, fn(&T) -> &T);` becomes `(&'_ T, for<'a> fn(&'a T) -> &'a T)`. Body { id: hir::BodyId, - s: ScopeRef<'a>, + s: ScopeRef<'a, 'tcx>, }, /// Use a specific lifetime (if `Some`) or leave it unset (to be @@ -118,7 +118,7 @@ enum Scope<'a> { /// for the default choice of lifetime in a trait object type. ObjectLifetimeDefault { lifetime: Option, - s: ScopeRef<'a>, + s: ScopeRef<'a, 'tcx>, }, /// When we have nested trait refs, we concatenate late bound vars for inner @@ -126,12 +126,12 @@ enum Scope<'a> { /// lifetimes encountered when identifying the trait that an associated type /// is declared on. Supertrait { - bound_vars: Vec, - s: ScopeRef<'a>, + bound_vars: Vec>, + s: ScopeRef<'a, 'tcx>, }, TraitRefBoundary { - s: ScopeRef<'a>, + s: ScopeRef<'a, 'tcx>, }, /// Remap lifetimes that appear in opaque types to fresh lifetime parameters. Given: @@ -148,7 +148,7 @@ enum Scope<'a> { /// Mapping from each captured lifetime `'a` to the duplicate generic parameter `'b`. captures: &'a RefCell>, - s: ScopeRef<'a>, + s: ScopeRef<'a, 'tcx>, }, /// Disallows capturing late-bound vars from parent scopes. @@ -157,7 +157,7 @@ enum Scope<'a> { /// since we don't do something more correct like replacing any captured /// late-bound vars with early-bound params in the const's own generics. LateBoundary { - s: ScopeRef<'a>, + s: ScopeRef<'a, 'tcx>, what: &'static str, deny_late_regions: bool, }, @@ -167,7 +167,7 @@ enum Scope<'a> { }, } -impl<'a> Scope<'a> { +impl<'a, 'tcx> Scope<'a, 'tcx> { // A helper for debugging scopes without printing parent scopes fn debug_truncated(&self) -> impl fmt::Debug { fmt::from_fn(move |f| match self { @@ -227,7 +227,7 @@ enum BinderScopeType { Concatenating, } -type ScopeRef<'a> = &'a Scope<'a>; +type ScopeRef<'a, 'tcx> = &'a Scope<'a, 'tcx>; /// Adds query implementations to the [Providers] vtable, see [`rustc_middle::query`] pub(crate) fn provide(providers: &mut Providers) { @@ -253,7 +253,7 @@ pub(crate) fn provide(providers: &mut Providers) { /// You should not read the result of this query directly, but rather use /// `named_variable_map`, `late_bound_vars_map`, etc. #[instrument(level = "debug", skip(tcx))] -fn resolve_bound_vars(tcx: TyCtxt<'_>, local_def_id: hir::OwnerId) -> ResolveBoundVars { +fn resolve_bound_vars(tcx: TyCtxt<'_>, local_def_id: hir::OwnerId) -> ResolveBoundVars<'_> { let mut rbv = ResolveBoundVars::default(); let mut visitor = BoundVarContext { tcx, @@ -287,7 +287,7 @@ fn resolve_bound_vars(tcx: TyCtxt<'_>, local_def_id: hir::OwnerId) -> ResolveBou rbv } -fn late_arg_as_bound_arg<'tcx>(param: &GenericParam<'tcx>) -> ty::BoundVariableKind { +fn late_arg_as_bound_arg<'tcx>(param: &GenericParam<'tcx>) -> ty::BoundVariableKind<'tcx> { let def_id = param.def_id.to_def_id(); match param.kind { GenericParamKind::Lifetime { .. } => { @@ -301,7 +301,9 @@ fn late_arg_as_bound_arg<'tcx>(param: &GenericParam<'tcx>) -> ty::BoundVariableK /// Turn a [`ty::GenericParamDef`] into a bound arg. Generally, this should only /// be used when turning early-bound vars into late-bound vars when lowering /// return type notation. -fn generic_param_def_as_bound_arg(param: &ty::GenericParamDef) -> ty::BoundVariableKind { +fn generic_param_def_as_bound_arg<'tcx>( + param: &ty::GenericParamDef, +) -> ty::BoundVariableKind<'tcx> { match param.kind { ty::GenericParamDefKind::Lifetime => { ty::BoundVariableKind::Region(ty::BoundRegionKind::Named(param.def_id)) @@ -329,7 +331,9 @@ fn opaque_captures_all_in_scope_lifetimes<'tcx>(opaque: &'tcx hir::OpaqueTy<'tcx impl<'a, 'tcx> BoundVarContext<'a, 'tcx> { /// Returns the binders in scope and the type of `Binder` that should be created for a poly trait ref. - fn poly_trait_ref_binder_info(&mut self) -> (Vec, BinderScopeType) { + fn poly_trait_ref_binder_info( + &mut self, + ) -> (Vec>, BinderScopeType) { let mut scope = self.scope; let mut supertrait_bound_vars = vec![]; loop { @@ -364,7 +368,7 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> { Scope::Binder { hir_id, .. } => { // Nested poly trait refs have the binders concatenated - let mut full_binders = + let mut full_binders: Vec> = self.rbv.late_bound_vars.get_mut_or_insert_default(hir_id.local_id).clone(); full_binders.extend(supertrait_bound_vars); break (full_binders, BinderScopeType::Concatenating); @@ -1094,7 +1098,7 @@ fn object_lifetime_default(tcx: TyCtxt<'_>, param_def_id: LocalDefId) -> ObjectL } impl<'a, 'tcx> BoundVarContext<'a, 'tcx> { - fn with(&mut self, wrap_scope: Scope<'_>, f: F) + fn with(&mut self, wrap_scope: Scope<'_, 'tcx>, f: F) where F: for<'b> FnOnce(&mut BoundVarContext<'b, 'tcx>), { @@ -1115,7 +1119,7 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> { *self.opaque_capture_errors.borrow_mut() = this.opaque_capture_errors.into_inner(); } - fn record_late_bound_vars(&mut self, hir_id: HirId, binder: Vec) { + fn record_late_bound_vars(&mut self, hir_id: HirId, binder: Vec>) { if let Some(old) = self.rbv.late_bound_vars.insert(hir_id.local_id, binder) { bug!( "overwrote bound vars for {hir_id:?}:\nold={old:?}\nnew={:?}", @@ -1931,7 +1935,7 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> { def_id: DefId, assoc_ident: Ident, assoc_tag: ty::AssocTag, - ) -> Option<(Vec, &'tcx ty::AssocItem)> { + ) -> Option<(Vec>, &'tcx ty::AssocItem)> { let trait_defines_associated_item_named = |trait_def_id: DefId| { tcx.associated_items(trait_def_id).find_by_ident_and_kind( tcx, @@ -1942,7 +1946,7 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> { }; use smallvec::{SmallVec, smallvec}; - let mut stack: SmallVec<[(DefId, SmallVec<[ty::BoundVariableKind; 8]>); 8]> = + let mut stack: SmallVec<[(DefId, SmallVec<[ty::BoundVariableKind<'tcx>; 8]>); 8]> = smallvec![(def_id, smallvec![])]; let mut visited: FxHashSet = FxHashSet::default(); loop { diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs index d6441702b268c..3515ce4ea9399 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs @@ -362,7 +362,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { param_ty: Ty<'tcx>, hir_bounds: I, bounds: &mut Vec<(ty::Clause<'tcx>, Span)>, - bound_vars: &'tcx ty::List, + bound_vars: &'tcx ty::List>, predicate_filter: PredicateFilter, overlapping_assoc_constraints: OverlappingAsssocItemConstraints, ) where @@ -1000,7 +1000,9 @@ impl<'tcx> TypeVisitor> for GenericParamAndBoundVarCollector<'_, 't .delayed_bug(format!("unexpected bound region kind: {:?}", br.kind)); return ControlFlow::Break(guar); } - ty::BoundRegionKind::NamedAnon(_) => bug!("only used for pretty printing"), + ty::BoundRegionKind::NamedForPrinting(_) => { + bug!("only used for pretty printing") + } }); } _ => {} diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs index 867c588e302d3..9f84f652698b4 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs @@ -2310,7 +2310,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { Some(rbv::ResolvedArg::LateBound(debruijn, index, _)) => ty::Const::new_bound( tcx, debruijn, - ty::BoundConst { var: ty::BoundVar::from_u32(index) }, + ty::BoundConst::new(ty::BoundVar::from_u32(index)), ), Some(rbv::ResolvedArg::Error(guar)) => ty::Const::new_error(tcx, guar), arg => bug!("unexpected bound var resolution for {:?}: {arg:?}", path_hir_id), @@ -3196,8 +3196,8 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { #[instrument(level = "trace", skip(self, generate_err))] fn validate_late_bound_regions<'cx>( &'cx self, - constrained_regions: FxIndexSet, - referenced_regions: FxIndexSet, + constrained_regions: FxIndexSet>, + referenced_regions: FxIndexSet>, generate_err: impl Fn(&str) -> Diag<'cx>, ) { for br in referenced_regions.difference(&constrained_regions) { diff --git a/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs b/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs index 23f6fee406a55..89ea6324d8543 100644 --- a/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs +++ b/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs @@ -684,19 +684,19 @@ impl<'cx, 'tcx> Canonicalizer<'cx, 'tcx> { CanonicalVarKind::Region(u) => CanonicalVarKind::Region(reverse_universe_map[&u]), CanonicalVarKind::Const(u) => CanonicalVarKind::Const(reverse_universe_map[&u]), CanonicalVarKind::PlaceholderTy(placeholder) => { - CanonicalVarKind::PlaceholderTy(ty::Placeholder::new( + CanonicalVarKind::PlaceholderTy(ty::PlaceholderType::new( reverse_universe_map[&placeholder.universe], placeholder.bound, )) } CanonicalVarKind::PlaceholderRegion(placeholder) => { - CanonicalVarKind::PlaceholderRegion(ty::Placeholder::new( + CanonicalVarKind::PlaceholderRegion(ty::PlaceholderRegion::new( reverse_universe_map[&placeholder.universe], placeholder.bound, )) } CanonicalVarKind::PlaceholderConst(placeholder) => { - CanonicalVarKind::PlaceholderConst(ty::Placeholder::new( + CanonicalVarKind::PlaceholderConst(ty::PlaceholderConst::new( reverse_universe_map[&placeholder.universe], placeholder.bound, )) diff --git a/compiler/rustc_infer/src/infer/mod.rs b/compiler/rustc_infer/src/infer/mod.rs index c9ea420944e23..e15b25500bb57 100644 --- a/compiler/rustc_infer/src/infer/mod.rs +++ b/compiler/rustc_infer/src/infer/mod.rs @@ -447,7 +447,7 @@ pub enum RegionVariableOrigin<'tcx> { /// Region variables created when instantiating a binder with /// existential variables, e.g. when calling a function or method. - BoundRegion(Span, ty::BoundRegionKind, BoundRegionConversionTime), + BoundRegion(Span, ty::BoundRegionKind<'tcx>, BoundRegionConversionTime), UpvarRegion(ty::UpvarId, Span), @@ -1300,13 +1300,13 @@ impl<'tcx> InferCtxt<'tcx> { } impl<'tcx> BoundVarReplacerDelegate<'tcx> for ToFreshVars<'tcx> { - fn replace_region(&mut self, br: ty::BoundRegion) -> ty::Region<'tcx> { + fn replace_region(&mut self, br: ty::BoundRegion<'tcx>) -> ty::Region<'tcx> { self.args[br.var.index()].expect_region() } - fn replace_ty(&mut self, bt: ty::BoundTy) -> Ty<'tcx> { + fn replace_ty(&mut self, bt: ty::BoundTy<'tcx>) -> Ty<'tcx> { self.args[bt.var.index()].expect_ty() } - fn replace_const(&mut self, bc: ty::BoundConst) -> ty::Const<'tcx> { + fn replace_const(&mut self, bc: ty::BoundConst<'tcx>) -> ty::Const<'tcx> { self.args[bc.var.index()].expect_const() } } diff --git a/compiler/rustc_infer/src/infer/outlives/test_type_match.rs b/compiler/rustc_infer/src/infer/outlives/test_type_match.rs index 7be5daf610565..479daf67a8ba3 100644 --- a/compiler/rustc_infer/src/infer/outlives/test_type_match.rs +++ b/compiler/rustc_infer/src/infer/outlives/test_type_match.rs @@ -91,7 +91,7 @@ pub(super) fn can_match_erased_ty<'tcx>( struct MatchAgainstHigherRankedOutlives<'tcx> { tcx: TyCtxt<'tcx>, pattern_depth: ty::DebruijnIndex, - map: FxHashMap>, + map: FxHashMap, ty::Region<'tcx>>, } impl<'tcx> MatchAgainstHigherRankedOutlives<'tcx> { @@ -115,7 +115,7 @@ impl<'tcx> MatchAgainstHigherRankedOutlives<'tcx> { #[instrument(level = "trace", skip(self))] fn bind( &mut self, - br: ty::BoundRegion, + br: ty::BoundRegion<'tcx>, value: ty::Region<'tcx>, ) -> RelateResult<'tcx, ty::Region<'tcx>> { match self.map.entry(br) { diff --git a/compiler/rustc_infer/src/infer/relate/higher_ranked.rs b/compiler/rustc_infer/src/infer/relate/higher_ranked.rs index 7a0f70e979b83..324725a079bbe 100644 --- a/compiler/rustc_infer/src/infer/relate/higher_ranked.rs +++ b/compiler/rustc_infer/src/infer/relate/higher_ranked.rs @@ -33,13 +33,13 @@ impl<'tcx> InferCtxt<'tcx> { let next_universe = self.create_next_universe(); let delegate = FnMutDelegate { - regions: &mut |br: ty::BoundRegion| { + regions: &mut |br: ty::BoundRegion<'tcx>| { ty::Region::new_placeholder(self.tcx, ty::PlaceholderRegion::new(next_universe, br)) }, - types: &mut |bound_ty: ty::BoundTy| { + types: &mut |bound_ty: ty::BoundTy<'tcx>| { Ty::new_placeholder(self.tcx, ty::PlaceholderType::new(next_universe, bound_ty)) }, - consts: &mut |bound_const: ty::BoundConst| { + consts: &mut |bound_const: ty::BoundConst<'tcx>| { ty::Const::new_placeholder( self.tcx, ty::PlaceholderConst::new(next_universe, bound_const), diff --git a/compiler/rustc_lint/src/impl_trait_overcaptures.rs b/compiler/rustc_lint/src/impl_trait_overcaptures.rs index f6c2e5946079b..1cdc5e4a1b36b 100644 --- a/compiler/rustc_lint/src/impl_trait_overcaptures.rs +++ b/compiler/rustc_lint/src/impl_trait_overcaptures.rs @@ -211,7 +211,7 @@ where // When we get into a binder, we need to add its own bound vars to the scope. let mut added = vec![]; for arg in t.bound_vars() { - let arg: ty::BoundVariableKind = arg; + let arg: ty::BoundVariableKind<'tcx> = arg; match arg { ty::BoundVariableKind::Region(ty::BoundRegionKind::Named(def_id)) | ty::BoundVariableKind::Ty(ty::BoundTyKind::Param(def_id)) => { diff --git a/compiler/rustc_middle/src/middle/resolve_bound_vars.rs b/compiler/rustc_middle/src/middle/resolve_bound_vars.rs index 51a079e8bc122..d625e9ea08cc5 100644 --- a/compiler/rustc_middle/src/middle/resolve_bound_vars.rs +++ b/compiler/rustc_middle/src/middle/resolve_bound_vars.rs @@ -48,7 +48,7 @@ pub enum ObjectLifetimeDefault { /// Maps the id of each bound variable reference to the variable decl /// that it corresponds to. #[derive(Debug, Default, HashStable)] -pub struct ResolveBoundVars { +pub struct ResolveBoundVars<'tcx> { // Maps from every use of a named (not anonymous) bound var to a // `ResolvedArg` describing how that variable is bound. pub defs: SortedMap, @@ -59,7 +59,7 @@ pub struct ResolveBoundVars { // - closures // - trait refs // - bound types (like `T` in `for<'a> T<'a>: Foo`) - pub late_bound_vars: SortedMap>, + pub late_bound_vars: SortedMap>>, // List captured variables for each opaque type. pub opaque_captured_lifetimes: LocalDefIdMap>, diff --git a/compiler/rustc_middle/src/query/erase.rs b/compiler/rustc_middle/src/query/erase.rs index 940cc30c17e6e..afda0da48611e 100644 --- a/compiler/rustc_middle/src/query/erase.rs +++ b/compiler/rustc_middle/src/query/erase.rs @@ -346,7 +346,6 @@ trivial! { rustc_middle::ty::AssocContainer, rustc_middle::ty::Asyncness, rustc_middle::ty::AsyncDestructor, - rustc_middle::ty::BoundVariableKind, rustc_middle::ty::AnonConstKind, rustc_middle::ty::Destructor, rustc_middle::ty::fast_reject::SimplifiedType, @@ -415,6 +414,7 @@ tcx_lifetime! { rustc_middle::ty::ConstConditions, rustc_middle::ty::inhabitedness::InhabitedPredicate, rustc_middle::ty::Instance, + rustc_middle::ty::BoundVariableKind, rustc_middle::ty::InstanceKind, rustc_middle::ty::layout::FnAbiError, rustc_middle::ty::layout::LayoutError, diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index 2f83f3078e89f..1a60cc2530d88 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -2116,7 +2116,7 @@ rustc_queries! { /// Does lifetime resolution on items. Importantly, we can't resolve /// lifetimes directly on things like trait methods, because of trait params. /// See `rustc_resolve::late::lifetimes` for details. - query resolve_bound_vars(owner_id: hir::OwnerId) -> &'tcx ResolveBoundVars { + query resolve_bound_vars(owner_id: hir::OwnerId) -> &'tcx ResolveBoundVars<'tcx> { arena_cache desc { |tcx| "resolving lifetimes for `{}`", tcx.def_path_str(owner_id) } } @@ -2145,7 +2145,7 @@ rustc_queries! { separate_provide_extern } query late_bound_vars_map(owner_id: hir::OwnerId) - -> &'tcx SortedMap> { + -> &'tcx SortedMap>> { desc { |tcx| "looking up late bound vars inside `{}`", tcx.def_path_str(owner_id) } } /// For an opaque type, return the list of (captured lifetime, inner generic param). diff --git a/compiler/rustc_middle/src/ty/codec.rs b/compiler/rustc_middle/src/ty/codec.rs index 75b1317e022bd..4856df3a6222a 100644 --- a/compiler/rustc_middle/src/ty/codec.rs +++ b/compiler/rustc_middle/src/ty/codec.rs @@ -427,11 +427,11 @@ impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [Spanned } } -impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::List { +impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::List> { fn decode(decoder: &mut D) -> &'tcx Self { let len = decoder.read_usize(); decoder.interner().mk_bound_variable_kinds_from_iter( - (0..len).map::(|_| Decodable::decode(decoder)), + (0..len).map::, _>(|_| Decodable::decode(decoder)), ) } } @@ -495,7 +495,7 @@ impl_decodable_via_ref! { &'tcx ty::List>, &'tcx traits::ImplSource<'tcx, ()>, &'tcx mir::Body<'tcx>, - &'tcx ty::List, + &'tcx ty::List>, &'tcx ty::List>, &'tcx ty::ListWithCachedTypeInfo>, } diff --git a/compiler/rustc_middle/src/ty/consts.rs b/compiler/rustc_middle/src/ty/consts.rs index da3caf0bb2103..5581ad5669aa9 100644 --- a/compiler/rustc_middle/src/ty/consts.rs +++ b/compiler/rustc_middle/src/ty/consts.rs @@ -94,7 +94,7 @@ impl<'tcx> Const<'tcx> { pub fn new_bound( tcx: TyCtxt<'tcx>, debruijn: ty::DebruijnIndex, - bound_const: ty::BoundConst, + bound_const: ty::BoundConst<'tcx>, ) -> Const<'tcx> { Const::new(tcx, ty::ConstKind::Bound(ty::BoundVarIndexKind::Bound(debruijn), bound_const)) } @@ -103,7 +103,7 @@ impl<'tcx> Const<'tcx> { pub fn new_canonical_bound(tcx: TyCtxt<'tcx>, var: ty::BoundVar) -> Const<'tcx> { Const::new( tcx, - ty::ConstKind::Bound(ty::BoundVarIndexKind::Canonical, ty::BoundConst { var }), + ty::ConstKind::Bound(ty::BoundVarIndexKind::Canonical, ty::BoundConst::new(var)), ) } @@ -183,13 +183,13 @@ impl<'tcx> rustc_type_ir::inherent::Const> for Const<'tcx> { fn new_bound( interner: TyCtxt<'tcx>, debruijn: ty::DebruijnIndex, - bound_const: ty::BoundConst, + bound_const: ty::BoundConst<'tcx>, ) -> Self { Const::new_bound(interner, debruijn, bound_const) } fn new_anon_bound(tcx: TyCtxt<'tcx>, debruijn: ty::DebruijnIndex, var: ty::BoundVar) -> Self { - Const::new_bound(tcx, debruijn, ty::BoundConst { var }) + Const::new_bound(tcx, debruijn, ty::BoundConst::new(var)) } fn new_canonical_bound(tcx: TyCtxt<'tcx>, var: rustc_type_ir::BoundVar) -> Self { diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index f015d0edc56c8..a6960523f6cf8 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -108,9 +108,8 @@ impl<'tcx> Interner for TyCtxt<'tcx> { type GenericArgsSlice = &'tcx [ty::GenericArg<'tcx>]; type GenericArg = ty::GenericArg<'tcx>; type Term = ty::Term<'tcx>; - type BoundVarKinds = &'tcx List; + type BoundVarKinds = &'tcx List>; - type BoundVarKind = ty::BoundVariableKind; type PredefinedOpaques = solve::PredefinedOpaques<'tcx>; fn mk_predefined_opaques_in_body( @@ -144,10 +143,8 @@ impl<'tcx> Interner for TyCtxt<'tcx> { type FnInputTys = &'tcx [Ty<'tcx>]; type ParamTy = ParamTy; - type BoundTy = ty::BoundTy; type Symbol = Symbol; - type PlaceholderTy = ty::PlaceholderType<'tcx>; type ErrorGuaranteed = ErrorGuaranteed; type BoundExistentialPredicates = &'tcx List>; @@ -157,10 +154,8 @@ impl<'tcx> Interner for TyCtxt<'tcx> { type Safety = hir::Safety; type Abi = ExternAbi; type Const = ty::Const<'tcx>; - type PlaceholderConst = ty::PlaceholderConst<'tcx>; type ParamConst = ty::ParamConst; - type BoundConst = ty::BoundConst; type ValueConst = ty::Value<'tcx>; type ExprConst = ty::Expr<'tcx>; type ValTree = ty::ValTree<'tcx>; @@ -169,8 +164,6 @@ impl<'tcx> Interner for TyCtxt<'tcx> { type Region = Region<'tcx>; type EarlyParamRegion = ty::EarlyParamRegion; type LateParamRegion = ty::LateParamRegion; - type BoundRegion = ty::BoundRegion; - type PlaceholderRegion = ty::PlaceholderRegion<'tcx>; type RegionAssumptions = &'tcx ty::List>; @@ -776,6 +769,13 @@ impl<'tcx> Interner for TyCtxt<'tcx> { ) -> (QueryResult<'tcx>, &'tcx inspect::Probe>) { self.evaluate_root_goal_for_proof_tree_raw(canonical_goal) } + + fn item_name(self, id: DefId) -> Symbol { + let id = id.into_query_param(); + self.opt_item_name(id).unwrap_or_else(|| { + bug!("item_name: no name for {:?}", self.def_path(id)); + }) + } } macro_rules! bidirectional_lang_item_map { @@ -938,7 +938,7 @@ pub struct CtxtInterners<'tcx> { const_: InternedSet<'tcx, WithCachedTypeInfo>>, pat: InternedSet<'tcx, PatternKind<'tcx>>, const_allocation: InternedSet<'tcx, Allocation>, - bound_variable_kinds: InternedSet<'tcx, List>, + bound_variable_kinds: InternedSet<'tcx, List>>, layout: InternedSet<'tcx, LayoutData>, adt_def: InternedSet<'tcx, AdtDefData>, external_constraints: InternedSet<'tcx, ExternalConstraintsData>>, @@ -2530,7 +2530,7 @@ nop_list_lift! { type_lists; Ty<'a> => Ty<'tcx> } nop_list_lift! { poly_existential_predicates; PolyExistentialPredicate<'a> => PolyExistentialPredicate<'tcx> } -nop_list_lift! { bound_variable_kinds; ty::BoundVariableKind => ty::BoundVariableKind } +nop_list_lift! { bound_variable_kinds; ty::BoundVariableKind<'a> => ty::BoundVariableKind<'tcx> } // This is the impl for `&'a GenericArgs<'a>`. nop_list_lift! { args; GenericArg<'a> => GenericArg<'tcx> } @@ -2817,7 +2817,7 @@ slice_interners!( poly_existential_predicates: intern_poly_existential_predicates(PolyExistentialPredicate<'tcx>), projs: pub mk_projs(ProjectionKind), place_elems: pub mk_place_elems(PlaceElem<'tcx>), - bound_variable_kinds: pub mk_bound_variable_kinds(ty::BoundVariableKind), + bound_variable_kinds: pub mk_bound_variable_kinds(ty::BoundVariableKind<'tcx>), fields: pub mk_fields(FieldIdx), local_def_ids: intern_local_def_ids(LocalDefId), captures: intern_captures(&'tcx ty::CapturedPlace<'tcx>), @@ -3242,7 +3242,7 @@ impl<'tcx> TyCtxt<'tcx> { pub fn mk_bound_variable_kinds_from_iter(self, iter: I) -> T::Output where I: Iterator, - T: CollectAndApply>, + T: CollectAndApply, &'tcx List>>, { T::collect_and_apply(iter, |xs| self.mk_bound_variable_kinds(xs)) } @@ -3362,7 +3362,7 @@ impl<'tcx> TyCtxt<'tcx> { self.is_late_bound_map(id.owner).is_some_and(|set| set.contains(&id.local_id)) } - pub fn late_bound_vars(self, id: HirId) -> &'tcx List { + pub fn late_bound_vars(self, id: HirId) -> &'tcx List> { self.mk_bound_variable_kinds( &self .late_bound_vars_map(id.owner) diff --git a/compiler/rustc_middle/src/ty/fold.rs b/compiler/rustc_middle/src/ty/fold.rs index ee29afcff638d..3d9148d6ed7ba 100644 --- a/compiler/rustc_middle/src/ty/fold.rs +++ b/compiler/rustc_middle/src/ty/fold.rs @@ -3,7 +3,7 @@ use rustc_hir::def_id::DefId; use rustc_type_ir::data_structures::DelayedMap; use crate::ty::{ - self, Binder, BoundConst, BoundTy, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, + self, Binder, BoundTy, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt, }; @@ -58,28 +58,28 @@ where /// gets mapped to the same result. `BoundVarReplacer` caches by using /// a `DelayedMap` which does not cache the first few types it encounters. pub trait BoundVarReplacerDelegate<'tcx> { - fn replace_region(&mut self, br: ty::BoundRegion) -> ty::Region<'tcx>; - fn replace_ty(&mut self, bt: ty::BoundTy) -> Ty<'tcx>; - fn replace_const(&mut self, bc: ty::BoundConst) -> ty::Const<'tcx>; + fn replace_region(&mut self, br: ty::BoundRegion<'tcx>) -> ty::Region<'tcx>; + fn replace_ty(&mut self, bt: ty::BoundTy<'tcx>) -> Ty<'tcx>; + fn replace_const(&mut self, bc: ty::BoundConst<'tcx>) -> ty::Const<'tcx>; } /// A simple delegate taking 3 mutable functions. The used functions must /// always return the same result for each bound variable, no matter how /// frequently they are called. pub struct FnMutDelegate<'a, 'tcx> { - pub regions: &'a mut (dyn FnMut(ty::BoundRegion) -> ty::Region<'tcx> + 'a), - pub types: &'a mut (dyn FnMut(ty::BoundTy) -> Ty<'tcx> + 'a), - pub consts: &'a mut (dyn FnMut(ty::BoundConst) -> ty::Const<'tcx> + 'a), + pub regions: &'a mut (dyn FnMut(ty::BoundRegion<'tcx>) -> ty::Region<'tcx> + 'a), + pub types: &'a mut (dyn FnMut(ty::BoundTy<'tcx>) -> Ty<'tcx> + 'a), + pub consts: &'a mut (dyn FnMut(ty::BoundConst<'tcx>) -> ty::Const<'tcx> + 'a), } impl<'a, 'tcx> BoundVarReplacerDelegate<'tcx> for FnMutDelegate<'a, 'tcx> { - fn replace_region(&mut self, br: ty::BoundRegion) -> ty::Region<'tcx> { + fn replace_region(&mut self, br: ty::BoundRegion<'tcx>) -> ty::Region<'tcx> { (self.regions)(br) } - fn replace_ty(&mut self, bt: ty::BoundTy) -> Ty<'tcx> { + fn replace_ty(&mut self, bt: ty::BoundTy<'tcx>) -> Ty<'tcx> { (self.types)(bt) } - fn replace_const(&mut self, bc: ty::BoundConst) -> ty::Const<'tcx> { + fn replace_const(&mut self, bc: ty::BoundConst<'tcx>) -> ty::Const<'tcx> { (self.consts)(bc) } } @@ -207,13 +207,14 @@ impl<'tcx> TyCtxt<'tcx> { self, value: Binder<'tcx, T>, mut fld_r: F, - ) -> (T, FxIndexMap>) + ) -> (T, FxIndexMap, ty::Region<'tcx>>) where - F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>, + F: FnMut(ty::BoundRegion<'tcx>) -> ty::Region<'tcx>, T: TypeFoldable>, { let mut region_map = FxIndexMap::default(); - let real_fld_r = |br: ty::BoundRegion| *region_map.entry(br).or_insert_with(|| fld_r(br)); + let real_fld_r = + |br: ty::BoundRegion<'tcx>| *region_map.entry(br).or_insert_with(|| fld_r(br)); let value = self.instantiate_bound_regions_uncached(value, real_fld_r); (value, region_map) } @@ -224,7 +225,7 @@ impl<'tcx> TyCtxt<'tcx> { mut replace_regions: F, ) -> T where - F: FnMut(ty::BoundRegion) -> ty::Region<'tcx>, + F: FnMut(ty::BoundRegion<'tcx>) -> ty::Region<'tcx>, T: TypeFoldable>, { let value = value.skip_binder(); @@ -292,14 +293,14 @@ impl<'tcx> TyCtxt<'tcx> { self.replace_escaping_bound_vars_uncached( value, FnMutDelegate { - regions: &mut |r: ty::BoundRegion| { + regions: &mut |r: ty::BoundRegion<'tcx>| { ty::Region::new_bound( self, ty::INNERMOST, ty::BoundRegion { var: shift_bv(r.var), kind: r.kind }, ) }, - types: &mut |t: ty::BoundTy| { + types: &mut |t: ty::BoundTy<'tcx>| { Ty::new_bound( self, ty::INNERMOST, @@ -307,11 +308,7 @@ impl<'tcx> TyCtxt<'tcx> { ) }, consts: &mut |c| { - ty::Const::new_bound( - self, - ty::INNERMOST, - ty::BoundConst { var: shift_bv(c.var) }, - ) + ty::Const::new_bound(self, ty::INNERMOST, ty::BoundConst::new(shift_bv(c.var))) }, }, ) @@ -333,10 +330,10 @@ impl<'tcx> TyCtxt<'tcx> { { struct Anonymize<'a, 'tcx> { tcx: TyCtxt<'tcx>, - map: &'a mut FxIndexMap, + map: &'a mut FxIndexMap>, } impl<'tcx> BoundVarReplacerDelegate<'tcx> for Anonymize<'_, 'tcx> { - fn replace_region(&mut self, br: ty::BoundRegion) -> ty::Region<'tcx> { + fn replace_region(&mut self, br: ty::BoundRegion<'tcx>) -> ty::Region<'tcx> { let entry = self.map.entry(br.var); let index = entry.index(); let var = ty::BoundVar::from_usize(index); @@ -346,7 +343,7 @@ impl<'tcx> TyCtxt<'tcx> { let br = ty::BoundRegion { var, kind }; ty::Region::new_bound(self.tcx, ty::INNERMOST, br) } - fn replace_ty(&mut self, bt: ty::BoundTy) -> Ty<'tcx> { + fn replace_ty(&mut self, bt: ty::BoundTy<'tcx>) -> Ty<'tcx> { let entry = self.map.entry(bt.var); let index = entry.index(); let var = ty::BoundVar::from_usize(index); @@ -355,12 +352,12 @@ impl<'tcx> TyCtxt<'tcx> { .expect_ty(); Ty::new_bound(self.tcx, ty::INNERMOST, BoundTy { var, kind }) } - fn replace_const(&mut self, bc: ty::BoundConst) -> ty::Const<'tcx> { + fn replace_const(&mut self, bc: ty::BoundConst<'tcx>) -> ty::Const<'tcx> { let entry = self.map.entry(bc.var); let index = entry.index(); let var = ty::BoundVar::from_usize(index); let () = entry.or_insert_with(|| ty::BoundVariableKind::Const).expect_const(); - ty::Const::new_bound(self.tcx, ty::INNERMOST, BoundConst { var }) + ty::Const::new_bound(self.tcx, ty::INNERMOST, ty::BoundConst::new(var)) } } diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index ce713dcf42f54..3e3c9e27186ac 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -97,13 +97,13 @@ pub use self::predicate::{ RegionOutlivesPredicate, SubtypePredicate, TraitPredicate, TraitRef, TypeOutlivesPredicate, }; pub use self::region::{ - BoundRegion, BoundRegionKind, EarlyParamRegion, LateParamRegion, LateParamRegionKind, Region, - RegionKind, RegionVid, + EarlyParamRegion, LateParamRegion, LateParamRegionKind, Region, RegionKind, RegionVid, }; pub use self::sty::{ - AliasTy, Article, Binder, BoundTy, BoundTyKind, BoundVariableKind, CanonicalPolyFnSig, - CoroutineArgsExt, EarlyBinder, FnSig, InlineConstArgs, InlineConstArgsParts, ParamConst, - ParamTy, PolyFnSig, TyKind, TypeAndMut, TypingMode, UpvarArgs, + AliasTy, Article, Binder, BoundConst, BoundRegion, BoundRegionKind, BoundTy, BoundTyKind, + BoundVariableKind, CanonicalPolyFnSig, CoroutineArgsExt, EarlyBinder, FnSig, InlineConstArgs, + InlineConstArgsParts, ParamConst, ParamTy, PlaceholderConst, PlaceholderRegion, + PlaceholderType, PolyFnSig, TyKind, TypeAndMut, TypingMode, UpvarArgs, }; pub use self::trait_def::TraitDef; pub use self::typeck_results::{ @@ -914,100 +914,6 @@ impl<'tcx> DefinitionSiteHiddenType<'tcx> { } } -pub type PlaceholderRegion<'tcx> = ty::Placeholder, BoundRegion>; - -impl<'tcx> rustc_type_ir::inherent::PlaceholderLike> for PlaceholderRegion<'tcx> { - type Bound = BoundRegion; - - fn universe(self) -> UniverseIndex { - self.universe - } - - fn var(self) -> BoundVar { - self.bound.var - } - - fn with_updated_universe(self, ui: UniverseIndex) -> Self { - ty::Placeholder::new(ui, self.bound) - } - - fn new(ui: UniverseIndex, bound: BoundRegion) -> Self { - ty::Placeholder::new(ui, bound) - } - - fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self { - ty::Placeholder::new(ui, BoundRegion { var, kind: BoundRegionKind::Anon }) - } -} - -pub type PlaceholderType<'tcx> = ty::Placeholder, BoundTy>; - -impl<'tcx> rustc_type_ir::inherent::PlaceholderLike> for PlaceholderType<'tcx> { - type Bound = BoundTy; - - fn universe(self) -> UniverseIndex { - self.universe - } - - fn var(self) -> BoundVar { - self.bound.var - } - - fn with_updated_universe(self, ui: UniverseIndex) -> Self { - ty::Placeholder::new(ui, self.bound) - } - - fn new(ui: UniverseIndex, bound: BoundTy) -> Self { - ty::Placeholder::new(ui, bound) - } - - fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self { - ty::Placeholder::new(ui, BoundTy { var, kind: BoundTyKind::Anon }) - } -} - -#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)] -#[derive(TyEncodable, TyDecodable)] -pub struct BoundConst { - pub var: BoundVar, -} - -impl<'tcx> rustc_type_ir::inherent::BoundVarLike> for BoundConst { - fn var(self) -> BoundVar { - self.var - } - - fn assert_eq(self, var: ty::BoundVariableKind) { - var.expect_const() - } -} - -pub type PlaceholderConst<'tcx> = ty::Placeholder, BoundConst>; - -impl<'tcx> rustc_type_ir::inherent::PlaceholderLike> for PlaceholderConst<'tcx> { - type Bound = BoundConst; - - fn universe(self) -> UniverseIndex { - self.universe - } - - fn var(self) -> BoundVar { - self.bound.var - } - - fn with_updated_universe(self, ui: UniverseIndex) -> Self { - ty::Placeholder::new(ui, self.bound) - } - - fn new(ui: UniverseIndex, bound: BoundConst) -> Self { - ty::Placeholder::new(ui, bound) - } - - fn new_anon(ui: UniverseIndex, var: BoundVar) -> Self { - ty::Placeholder::new(ui, BoundConst { var }) - } -} - pub type Clauses<'tcx> = &'tcx ListWithCachedTypeInfo>; impl<'tcx> rustc_type_ir::Flags for Clauses<'tcx> { diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index de13c4f836a5f..724be7b15ff2a 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -199,7 +199,7 @@ pub struct RegionHighlightMode<'tcx> { /// This is used when you have a signature like `fn foo(x: &u32, /// y: &'a u32)` and we want to give a name to the region of the /// reference `x`. - highlight_bound_region: Option<(ty::BoundRegionKind, usize)>, + highlight_bound_region: Option<(ty::BoundRegionKind<'tcx>, usize)>, } impl<'tcx> RegionHighlightMode<'tcx> { @@ -248,7 +248,7 @@ impl<'tcx> RegionHighlightMode<'tcx> { /// Highlight the given bound region. /// We can only highlight one bound region at a time. See /// the field `highlight_bound_region` for more detailed notes. - pub fn highlighting_bound_region(&mut self, br: ty::BoundRegionKind, number: usize) { + pub fn highlighting_bound_region(&mut self, br: ty::BoundRegionKind<'tcx>, number: usize) { assert!(self.highlight_bound_region.is_none()); self.highlight_bound_region = Some((br, number)); } @@ -2641,12 +2641,12 @@ impl<'tcx> FmtPrinter<'_, 'tcx> { struct RegionFolder<'a, 'tcx> { tcx: TyCtxt<'tcx>, current_index: ty::DebruijnIndex, - region_map: UnordMap>, + region_map: UnordMap, ty::Region<'tcx>>, name: &'a mut ( dyn FnMut( Option, // Debruijn index of the folded late-bound region ty::DebruijnIndex, // Index corresponding to binder level - ty::BoundRegion, + ty::BoundRegion<'tcx>, ) -> ty::Region<'tcx> + 'a ), @@ -2719,7 +2719,7 @@ impl<'tcx> FmtPrinter<'_, 'tcx> { &mut self, value: &ty::Binder<'tcx, T>, mode: WrapBinderMode, - ) -> Result<(T, UnordMap>), fmt::Error> + ) -> Result<(T, UnordMap, ty::Region<'tcx>>), fmt::Error> where T: TypeFoldable>, { @@ -2812,12 +2812,12 @@ impl<'tcx> FmtPrinter<'_, 'tcx> { // see issue #102392. let mut name = |lifetime_idx: Option, binder_level_idx: ty::DebruijnIndex, - br: ty::BoundRegion| { + br: ty::BoundRegion<'tcx>| { let (name, kind) = if let Some(name) = br.kind.get_name(tcx) { (name, br.kind) } else { let name = next_name(self); - (name, ty::BoundRegionKind::NamedAnon(name)) + (name, ty::BoundRegionKind::NamedForPrinting(name)) }; if let Some(lt_idx) = lifetime_idx { diff --git a/compiler/rustc_middle/src/ty/region.rs b/compiler/rustc_middle/src/ty/region.rs index 61994d928decd..a497501ef19d5 100644 --- a/compiler/rustc_middle/src/ty/region.rs +++ b/compiler/rustc_middle/src/ty/region.rs @@ -50,7 +50,7 @@ impl<'tcx> Region<'tcx> { pub fn new_bound( tcx: TyCtxt<'tcx>, debruijn: ty::DebruijnIndex, - bound_region: ty::BoundRegion, + bound_region: ty::BoundRegion<'tcx>, ) -> Region<'tcx> { // Use a pre-interned one when possible. if let ty::BoundRegion { var, kind: ty::BoundRegionKind::Anon } = bound_region @@ -160,7 +160,7 @@ impl<'tcx> rustc_type_ir::inherent::Region> for Region<'tcx> { fn new_bound( interner: TyCtxt<'tcx>, debruijn: ty::DebruijnIndex, - var: ty::BoundRegion, + var: ty::BoundRegion<'tcx>, ) -> Self { Region::new_bound(interner, debruijn, var) } @@ -388,7 +388,7 @@ pub struct LateParamRegion { pub kind: LateParamRegionKind, } -/// When liberating bound regions, we map their [`BoundRegionKind`] +/// When liberating bound regions, we map their [`ty::BoundRegionKind`] /// to this as we need to track the index of anonymous regions. We /// otherwise end up liberating multiple bound regions to the same /// late-bound region. @@ -397,7 +397,7 @@ pub struct LateParamRegion { pub enum LateParamRegionKind { /// An anonymous region parameter for a given fn (&T) /// - /// Unlike [`BoundRegionKind::Anon`], this tracks the index of the + /// Unlike [`ty::BoundRegionKind::Anon`], this tracks the index of the /// liberated bound region. /// /// We should ideally never liberate anonymous regions, but do so for the @@ -418,12 +418,14 @@ pub enum LateParamRegionKind { } impl LateParamRegionKind { - pub fn from_bound(var: BoundVar, br: BoundRegionKind) -> LateParamRegionKind { + pub fn from_bound(var: BoundVar, br: ty::BoundRegionKind<'_>) -> LateParamRegionKind { match br { - BoundRegionKind::Anon => LateParamRegionKind::Anon(var.as_u32()), - BoundRegionKind::Named(def_id) => LateParamRegionKind::Named(def_id), - BoundRegionKind::ClosureEnv => LateParamRegionKind::ClosureEnv, - BoundRegionKind::NamedAnon(name) => LateParamRegionKind::NamedAnon(var.as_u32(), name), + ty::BoundRegionKind::Anon => LateParamRegionKind::Anon(var.as_u32()), + ty::BoundRegionKind::Named(def_id) => LateParamRegionKind::Named(def_id), + ty::BoundRegionKind::ClosureEnv => LateParamRegionKind::ClosureEnv, + ty::BoundRegionKind::NamedForPrinting(name) => { + LateParamRegionKind::NamedAnon(var.as_u32(), name) + } } } @@ -450,81 +452,6 @@ impl LateParamRegionKind { } } -#[derive(Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, Copy)] -#[derive(HashStable)] -pub enum BoundRegionKind { - /// An anonymous region parameter for a given fn (&T) - Anon, - - /// An anonymous region parameter with a `Symbol` name. - /// - /// Used to give late-bound regions names for things like pretty printing. - NamedAnon(Symbol), - - /// Late-bound regions that appear in the AST. - Named(DefId), - - /// Anonymous region for the implicit env pointer parameter - /// to a closure - ClosureEnv, -} - -#[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable)] -#[derive(HashStable)] -pub struct BoundRegion { - pub var: BoundVar, - pub kind: BoundRegionKind, -} - -impl<'tcx> rustc_type_ir::inherent::BoundVarLike> for BoundRegion { - fn var(self) -> BoundVar { - self.var - } - - fn assert_eq(self, var: ty::BoundVariableKind) { - assert_eq!(self.kind, var.expect_region()) - } -} - -impl core::fmt::Debug for BoundRegion { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self.kind { - BoundRegionKind::Anon => write!(f, "{:?}", self.var), - BoundRegionKind::ClosureEnv => write!(f, "{:?}.Env", self.var), - BoundRegionKind::Named(def) => { - write!(f, "{:?}.Named({:?})", self.var, def) - } - BoundRegionKind::NamedAnon(symbol) => { - write!(f, "{:?}.NamedAnon({:?})", self.var, symbol) - } - } - } -} - -impl BoundRegionKind { - pub fn is_named(&self, tcx: TyCtxt<'_>) -> bool { - self.get_name(tcx).is_some() - } - - pub fn get_name(&self, tcx: TyCtxt<'_>) -> Option { - match *self { - BoundRegionKind::Named(def_id) => { - let name = tcx.item_name(def_id); - if name != kw::UnderscoreLifetime { Some(name) } else { None } - } - BoundRegionKind::NamedAnon(name) => Some(name), - _ => None, - } - } - - pub fn get_id(&self) -> Option { - match *self { - BoundRegionKind::Named(id) => Some(id), - _ => None, - } - } -} - // Some types are used a lot. Make sure they don't unintentionally get bigger. #[cfg(target_pointer_width = "64")] mod size_asserts { diff --git a/compiler/rustc_middle/src/ty/structural_impls.rs b/compiler/rustc_middle/src/ty/structural_impls.rs index 314d2ba396327..8707b03e4b8f2 100644 --- a/compiler/rustc_middle/src/ty/structural_impls.rs +++ b/compiler/rustc_middle/src/ty/structural_impls.rs @@ -65,21 +65,6 @@ impl<'tcx> fmt::Debug for ty::adjustment::PatAdjustment<'tcx> { } } -impl fmt::Debug for ty::BoundRegionKind { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match *self { - ty::BoundRegionKind::Anon => write!(f, "BrAnon"), - ty::BoundRegionKind::NamedAnon(name) => { - write!(f, "BrNamedAnon({name})") - } - ty::BoundRegionKind::Named(did) => { - write!(f, "BrNamed({did:?})") - } - ty::BoundRegionKind::ClosureEnv => write!(f, "BrEnv"), - } - } -} - impl fmt::Debug for ty::LateParamRegion { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "ReLateParam({:?}, {:?})", self.scope, self.kind) @@ -175,15 +160,6 @@ impl<'tcx> fmt::Debug for ty::Const<'tcx> { } } -impl fmt::Debug for ty::BoundTy { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self.kind { - ty::BoundTyKind::Anon => write!(f, "{:?}", self.var), - ty::BoundTyKind::Param(def_id) => write!(f, "{def_id:?}"), - } - } -} - impl<'tcx> fmt::Debug for GenericArg<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.kind() { @@ -255,7 +231,8 @@ TrivialTypeTraversalImpls! { crate::ty::AdtKind, crate::ty::AssocItem, crate::ty::AssocKind, - crate::ty::BoundRegion, + crate::ty::BoundRegion<'tcx>, + crate::ty::BoundTy<'tcx>, crate::ty::ScalarInt, crate::ty::UserTypeAnnotationIndex, crate::ty::abstract_const::NotConstEvaluatable, @@ -284,7 +261,6 @@ TrivialTypeTraversalImpls! { TrivialTypeTraversalAndLiftImpls! { // tidy-alphabetical-start crate::mir::RuntimeChecks, - crate::ty::BoundTy, crate::ty::ParamTy, crate::ty::instance::ReifyReason, rustc_hir::def_id::DefId, diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index b0b5a783b00e6..4c5bd85e6b726 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -13,7 +13,7 @@ use rustc_hir as hir; use rustc_hir::LangItem; use rustc_hir::def_id::DefId; use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, extension}; -use rustc_span::{DUMMY_SP, Span, Symbol, sym}; +use rustc_span::{DUMMY_SP, Span, Symbol, kw, sym}; use rustc_type_ir::TyKind::*; use rustc_type_ir::solve::SizedTraitKind; use rustc_type_ir::walk::TypeWalker; @@ -26,8 +26,8 @@ use crate::infer::canonical::Canonical; use crate::traits::ObligationCause; use crate::ty::InferTy::*; use crate::ty::{ - self, AdtDef, BoundRegionKind, Discr, GenericArg, GenericArgs, GenericArgsRef, List, ParamEnv, - Region, Ty, TyCtxt, TypeFlags, TypeSuperVisitable, TypeVisitable, TypeVisitor, UintTy, + self, AdtDef, Discr, GenericArg, GenericArgs, GenericArgsRef, List, ParamEnv, Region, Ty, + TyCtxt, TypeFlags, TypeSuperVisitable, TypeVisitable, TypeVisitor, UintTy, }; // Re-export and re-parameterize some `I = TyCtxt<'tcx>` types here @@ -40,6 +40,15 @@ pub type Binder<'tcx, T> = ir::Binder, T>; pub type EarlyBinder<'tcx, T> = ir::EarlyBinder, T>; pub type TypingMode<'tcx> = ir::TypingMode>; pub type Placeholder<'tcx, T> = ir::Placeholder, T>; +pub type PlaceholderRegion<'tcx> = ir::PlaceholderRegion>; +pub type PlaceholderType<'tcx> = ir::PlaceholderType>; +pub type PlaceholderConst<'tcx> = ir::PlaceholderConst>; +pub type BoundTy<'tcx> = ir::BoundTy>; +pub type BoundConst<'tcx> = ir::BoundConst>; +pub type BoundRegion<'tcx> = ir::BoundRegion>; +pub type BoundVariableKind<'tcx> = ir::BoundVariableKind>; +pub type BoundRegionKind<'tcx> = ir::BoundRegionKind>; +pub type BoundTyKind<'tcx> = ir::BoundTyKind>; pub trait Article { fn article(&self) -> &'static str; @@ -257,37 +266,6 @@ impl<'tcx> InlineConstArgs<'tcx> { } } -#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)] -#[derive(HashStable)] -pub enum BoundVariableKind { - Ty(BoundTyKind), - Region(BoundRegionKind), - Const, -} - -impl BoundVariableKind { - pub fn expect_region(self) -> BoundRegionKind { - match self { - BoundVariableKind::Region(lt) => lt, - _ => bug!("expected a region, but found another kind"), - } - } - - pub fn expect_ty(self) -> BoundTyKind { - match self { - BoundVariableKind::Ty(ty) => ty, - _ => bug!("expected a type, but found another kind"), - } - } - - pub fn expect_const(self) { - match self { - BoundVariableKind::Const => (), - _ => bug!("expected a const, but found another kind"), - } - } -} - pub type PolyFnSig<'tcx> = Binder<'tcx, FnSig<'tcx>>; pub type CanonicalPolyFnSig<'tcx> = Canonical<'tcx, Binder<'tcx, FnSig<'tcx>>>; @@ -381,30 +359,6 @@ impl ParamConst { } } -#[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable)] -#[derive(HashStable)] -pub struct BoundTy { - pub var: BoundVar, - pub kind: BoundTyKind, -} - -impl<'tcx> rustc_type_ir::inherent::BoundVarLike> for BoundTy { - fn var(self) -> BoundVar { - self.var - } - - fn assert_eq(self, var: ty::BoundVariableKind) { - assert_eq!(self.kind, var.expect_ty()) - } -} - -#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, TyEncodable, TyDecodable)] -#[derive(HashStable)] -pub enum BoundTyKind { - Anon, - Param(DefId), -} - /// Constructors for `Ty` impl<'tcx> Ty<'tcx> { /// Avoid using this in favour of more specific `new_*` methods, where possible. @@ -479,7 +433,7 @@ impl<'tcx> Ty<'tcx> { pub fn new_bound( tcx: TyCtxt<'tcx>, index: ty::DebruijnIndex, - bound_ty: ty::BoundTy, + bound_ty: ty::BoundTy<'tcx>, ) -> Ty<'tcx> { // Use a pre-interned one when possible. if let ty::BoundTy { var, kind: ty::BoundTyKind::Anon } = bound_ty @@ -961,7 +915,11 @@ impl<'tcx> rustc_type_ir::inherent::Ty> for Ty<'tcx> { Ty::new_placeholder(tcx, placeholder) } - fn new_bound(interner: TyCtxt<'tcx>, debruijn: ty::DebruijnIndex, var: ty::BoundTy) -> Self { + fn new_bound( + interner: TyCtxt<'tcx>, + debruijn: ty::DebruijnIndex, + var: ty::BoundTy<'tcx>, + ) -> Self { Ty::new_bound(interner, debruijn, var) } @@ -2135,6 +2093,12 @@ impl<'tcx> rustc_type_ir::inherent::Tys> for &'tcx ty::List rustc_type_ir::inherent::Symbol> for Symbol { + fn is_kw_underscore_lifetime(self) -> bool { + self == kw::UnderscoreLifetime + } +} + // Some types are used a lot. Make sure they don't unintentionally get bigger. #[cfg(target_pointer_width = "64")] mod size_asserts { diff --git a/compiler/rustc_middle/src/ty/visit.rs b/compiler/rustc_middle/src/ty/visit.rs index e84ac56b31dfd..8f79f8e3564e7 100644 --- a/compiler/rustc_middle/src/ty/visit.rs +++ b/compiler/rustc_middle/src/ty/visit.rs @@ -113,7 +113,7 @@ impl<'tcx> TyCtxt<'tcx> { pub fn collect_constrained_late_bound_regions( self, value: Binder<'tcx, T>, - ) -> FxIndexSet + ) -> FxIndexSet> where T: TypeFoldable>, { @@ -124,7 +124,7 @@ impl<'tcx> TyCtxt<'tcx> { pub fn collect_referenced_late_bound_regions( self, value: Binder<'tcx, T>, - ) -> FxIndexSet + ) -> FxIndexSet> where T: TypeFoldable>, { @@ -135,7 +135,7 @@ impl<'tcx> TyCtxt<'tcx> { self, value: Binder<'tcx, T>, just_constrained: bool, - ) -> FxIndexSet + ) -> FxIndexSet> where T: TypeFoldable>, { @@ -149,9 +149,9 @@ impl<'tcx> TyCtxt<'tcx> { /// Collects all the late-bound regions at the innermost binding level /// into a hash set. -struct LateBoundRegionsCollector { +struct LateBoundRegionsCollector<'tcx> { current_index: ty::DebruijnIndex, - regions: FxIndexSet, + regions: FxIndexSet>, /// `true` if we only want regions that are known to be /// "constrained" when you equate this type with another type. In @@ -163,13 +163,13 @@ struct LateBoundRegionsCollector { just_constrained: bool, } -impl LateBoundRegionsCollector { +impl LateBoundRegionsCollector<'_> { fn new(just_constrained: bool) -> Self { Self { current_index: ty::INNERMOST, regions: Default::default(), just_constrained } } } -impl<'tcx> TypeVisitor> for LateBoundRegionsCollector { +impl<'tcx> TypeVisitor> for LateBoundRegionsCollector<'tcx> { fn visit_binder>>(&mut self, t: &Binder<'tcx, T>) { self.current_index.shift_in(1); t.super_visit_with(self); diff --git a/compiler/rustc_next_trait_solver/src/canonical/canonicalizer.rs b/compiler/rustc_next_trait_solver/src/canonical/canonicalizer.rs index 61a2dcd226b7b..ce2be24adc586 100644 --- a/compiler/rustc_next_trait_solver/src/canonical/canonicalizer.rs +++ b/compiler/rustc_next_trait_solver/src/canonical/canonicalizer.rs @@ -3,7 +3,8 @@ use rustc_type_ir::inherent::*; use rustc_type_ir::solve::{Goal, QueryInput}; use rustc_type_ir::{ self as ty, Canonical, CanonicalParamEnvCacheEntry, CanonicalVarKind, Flags, InferCtxtLike, - Interner, TypeFlags, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt, + Interner, PlaceholderConst, PlaceholderType, TypeFlags, TypeFoldable, TypeFolder, + TypeSuperFoldable, TypeVisitableExt, }; use crate::delegate::SolverDelegate; @@ -357,13 +358,13 @@ impl<'a, D: SolverDelegate, I: Interner> Canonicalizer<'a, D, I> { }, ty::Placeholder(placeholder) => match self.canonicalize_mode { CanonicalizeMode::Input { .. } => CanonicalVarKind::PlaceholderTy( - PlaceholderLike::new_anon(ty::UniverseIndex::ROOT, self.variables.len().into()), + PlaceholderType::new_anon(ty::UniverseIndex::ROOT, self.variables.len().into()), ), CanonicalizeMode::Response { .. } => CanonicalVarKind::PlaceholderTy(placeholder), }, ty::Param(_) => match self.canonicalize_mode { CanonicalizeMode::Input { .. } => CanonicalVarKind::PlaceholderTy( - PlaceholderLike::new_anon(ty::UniverseIndex::ROOT, self.variables.len().into()), + PlaceholderType::new_anon(ty::UniverseIndex::ROOT, self.variables.len().into()), ), CanonicalizeMode::Response { .. } => panic!("param ty in response: {t:?}"), }, @@ -513,17 +514,23 @@ impl, I: Interner> TypeFolder for Canonicaliz ty::InferConst::Fresh(_) => todo!(), }, ty::ConstKind::Placeholder(placeholder) => match self.canonicalize_mode { - CanonicalizeMode::Input { .. } => CanonicalVarKind::PlaceholderConst( - PlaceholderLike::new_anon(ty::UniverseIndex::ROOT, self.variables.len().into()), - ), + CanonicalizeMode::Input { .. } => { + CanonicalVarKind::PlaceholderConst(PlaceholderConst::new_anon( + ty::UniverseIndex::ROOT, + self.variables.len().into(), + )) + } CanonicalizeMode::Response { .. } => { CanonicalVarKind::PlaceholderConst(placeholder) } }, ty::ConstKind::Param(_) => match self.canonicalize_mode { - CanonicalizeMode::Input { .. } => CanonicalVarKind::PlaceholderConst( - PlaceholderLike::new_anon(ty::UniverseIndex::ROOT, self.variables.len().into()), - ), + CanonicalizeMode::Input { .. } => { + CanonicalVarKind::PlaceholderConst(PlaceholderConst::new_anon( + ty::UniverseIndex::ROOT, + self.variables.len().into(), + )) + } CanonicalizeMode::Response { .. } => panic!("param ty in response: {c:?}"), }, // FIXME: See comment above -- we could fold the region separately or something. diff --git a/compiler/rustc_next_trait_solver/src/canonical/mod.rs b/compiler/rustc_next_trait_solver/src/canonical/mod.rs index 96fea09013a1e..1f64f09fe787f 100644 --- a/compiler/rustc_next_trait_solver/src/canonical/mod.rs +++ b/compiler/rustc_next_trait_solver/src/canonical/mod.rs @@ -177,9 +177,9 @@ where } } ty::GenericArgKind::Const(c) => { - if let ty::ConstKind::Bound(index_kind, bv) = c.kind() { + if let ty::ConstKind::Bound(index_kind, bc) = c.kind() { assert!(matches!(index_kind, ty::BoundVarIndexKind::Canonical)); - opt_values[bv.var()] = Some(*original_value); + opt_values[bc.var()] = Some(*original_value); } } } diff --git a/compiler/rustc_next_trait_solver/src/placeholder.rs b/compiler/rustc_next_trait_solver/src/placeholder.rs index c8016759f239a..31fce0601697b 100644 --- a/compiler/rustc_next_trait_solver/src/placeholder.rs +++ b/compiler/rustc_next_trait_solver/src/placeholder.rs @@ -3,8 +3,8 @@ use core::panic; use rustc_type_ir::data_structures::IndexMap; use rustc_type_ir::inherent::*; use rustc_type_ir::{ - self as ty, InferCtxtLike, Interner, TypeFoldable, TypeFolder, TypeSuperFoldable, - TypeVisitableExt, + self as ty, InferCtxtLike, Interner, PlaceholderConst, PlaceholderRegion, PlaceholderType, + TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt, }; pub struct BoundVarReplacer<'a, Infcx, I = ::Interner> @@ -16,9 +16,9 @@ where // These three maps track the bound variable that were replaced by placeholders. It might be // nice to remove these since we already have the `kind` in the placeholder; we really just need // the `var` (but we *could* bring that into scope if we were to track them as we pass them). - mapped_regions: IndexMap, - mapped_types: IndexMap, - mapped_consts: IndexMap, + mapped_regions: IndexMap, ty::BoundRegion>, + mapped_types: IndexMap, ty::BoundTy>, + mapped_consts: IndexMap, ty::BoundConst>, // The current depth relative to *this* folding, *not* the entire normalization. In other words, // the depth of binders we've passed here. current_index: ty::DebruijnIndex, @@ -40,9 +40,9 @@ where value: T, ) -> ( T, - IndexMap, - IndexMap, - IndexMap, + IndexMap, ty::BoundRegion>, + IndexMap, ty::BoundTy>, + IndexMap, ty::BoundConst>, ) { let mut replacer = BoundVarReplacer { infcx, @@ -103,7 +103,7 @@ where if debruijn >= self.current_index => { let universe = self.universe_for(debruijn); - let p = PlaceholderLike::new(universe, br); + let p = PlaceholderRegion::new(universe, br); self.mapped_regions.insert(p, br); Region::new_placeholder(self.cx(), p) } @@ -126,7 +126,7 @@ where if debruijn >= self.current_index => { let universe = self.universe_for(debruijn); - let p = PlaceholderLike::new(universe, bound_ty); + let p = PlaceholderType::new(universe, bound_ty); self.mapped_types.insert(p, bound_ty); Ty::new_placeholder(self.cx(), p) } @@ -150,7 +150,7 @@ where if debruijn >= self.current_index => { let universe = self.universe_for(debruijn); - let p = PlaceholderLike::new(universe, bound_const); + let p = PlaceholderConst::new(universe, bound_const); self.mapped_consts.insert(p, bound_const); Const::new_placeholder(self.cx(), p) } diff --git a/compiler/rustc_public/src/unstable/convert/internal.rs b/compiler/rustc_public/src/unstable/convert/internal.rs index 73a3fed111b36..8594f65100415 100644 --- a/compiler/rustc_public/src/unstable/convert/internal.rs +++ b/compiler/rustc_public/src/unstable/convert/internal.rs @@ -433,7 +433,7 @@ where } impl RustcInternal for BoundVariableKind { - type T<'tcx> = rustc_ty::BoundVariableKind; + type T<'tcx> = rustc_ty::BoundVariableKind<'tcx>; fn internal<'tcx>( &self, diff --git a/compiler/rustc_public/src/unstable/convert/stable/ty.rs b/compiler/rustc_public/src/unstable/convert/stable/ty.rs index cee144122c0ed..70cdae43126c4 100644 --- a/compiler/rustc_public/src/unstable/convert/stable/ty.rs +++ b/compiler/rustc_public/src/unstable/convert/stable/ty.rs @@ -271,7 +271,7 @@ impl<'tcx> Stable<'tcx> for ty::FnSig<'tcx> { } } -impl<'tcx> Stable<'tcx> for ty::BoundTyKind { +impl<'tcx> Stable<'tcx> for ty::BoundTyKind<'tcx> { type T = crate::ty::BoundTyKind; fn stable<'cx>( @@ -290,7 +290,7 @@ impl<'tcx> Stable<'tcx> for ty::BoundTyKind { } } -impl<'tcx> Stable<'tcx> for ty::BoundRegionKind { +impl<'tcx> Stable<'tcx> for ty::BoundRegionKind<'tcx> { type T = crate::ty::BoundRegionKind; fn stable<'cx>( @@ -307,12 +307,12 @@ impl<'tcx> Stable<'tcx> for ty::BoundRegionKind { cx.tcx.item_name(*def_id).to_string(), ), ty::BoundRegionKind::ClosureEnv => BoundRegionKind::BrEnv, - ty::BoundRegionKind::NamedAnon(_) => bug!("only used for pretty printing"), + ty::BoundRegionKind::NamedForPrinting(_) => bug!("only used for pretty printing"), } } } -impl<'tcx> Stable<'tcx> for ty::BoundVariableKind { +impl<'tcx> Stable<'tcx> for ty::BoundVariableKind<'tcx> { type T = crate::ty::BoundVariableKind; fn stable<'cx>( @@ -546,7 +546,7 @@ impl<'tcx> Stable<'tcx> for ty::ParamTy { } } -impl<'tcx> Stable<'tcx> for ty::BoundTy { +impl<'tcx> Stable<'tcx> for ty::BoundTy<'tcx> { type T = crate::ty::BoundTy; fn stable<'cx>( &self, diff --git a/compiler/rustc_public/src/unstable/internal_cx/mod.rs b/compiler/rustc_public/src/unstable/internal_cx/mod.rs index 601ca4fb5cfdb..4da86b9442f1d 100644 --- a/compiler/rustc_public/src/unstable/internal_cx/mod.rs +++ b/compiler/rustc_public/src/unstable/internal_cx/mod.rs @@ -78,7 +78,10 @@ impl<'tcx> InternalCx<'tcx> for TyCtxt<'tcx> { fn mk_bound_variable_kinds_from_iter(self, iter: I) -> T::Output where I: Iterator, - T: ty::CollectAndApply>, + T: ty::CollectAndApply< + ty::BoundVariableKind<'tcx>, + &'tcx List>, + >, { TyCtxt::mk_bound_variable_kinds_from_iter(self, iter) } diff --git a/compiler/rustc_public/src/unstable/mod.rs b/compiler/rustc_public/src/unstable/mod.rs index 2b69fb5408cf9..583493c23d66f 100644 --- a/compiler/rustc_public/src/unstable/mod.rs +++ b/compiler/rustc_public/src/unstable/mod.rs @@ -47,7 +47,10 @@ pub trait InternalCx<'tcx>: Copy + Clone { fn mk_bound_variable_kinds_from_iter(self, iter: I) -> T::Output where I: Iterator, - T: ty::CollectAndApply>; + T: ty::CollectAndApply< + ty::BoundVariableKind<'tcx>, + &'tcx List>, + >; fn mk_place_elems(self, v: &[mir::PlaceElem<'tcx>]) -> &'tcx List>; diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_relation.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_relation.rs index 3bab09bc587f0..05a1e3fe95dd9 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_relation.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_relation.rs @@ -34,14 +34,18 @@ impl<'tcx> NiceRegionError<'_, 'tcx> { (Some(self.tcx().def_span(def_id)), Some(self.tcx().item_name(def_id))) } ty::BoundRegionKind::Anon | ty::BoundRegionKind::ClosureEnv => (None, None), - ty::BoundRegionKind::NamedAnon(_) => bug!("only used for pretty printing"), + ty::BoundRegionKind::NamedForPrinting(_) => { + bug!("only used for pretty printing") + } }; let (sup_span, sup_symbol) = match *sup_name { ty::BoundRegionKind::Named(def_id) => { (Some(self.tcx().def_span(def_id)), Some(self.tcx().item_name(def_id))) } ty::BoundRegionKind::Anon | ty::BoundRegionKind::ClosureEnv => (None, None), - ty::BoundRegionKind::NamedAnon(_) => bug!("only used for pretty printing"), + ty::BoundRegionKind::NamedForPrinting(_) => { + bug!("only used for pretty printing") + } }; let diag = match (sub_span, sup_span, sub_symbol, sup_symbol) { (Some(sub_span), Some(sup_span), Some(sub_symbol), Some(sup_symbol)) => { diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs index fdaf2d619dd56..b11461cd0e32d 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs @@ -1052,7 +1052,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } fn report_inference_failure(&self, var_origin: RegionVariableOrigin<'tcx>) -> Diag<'_> { - let br_string = |br: ty::BoundRegionKind| { + let br_string = |br: ty::BoundRegionKind<'tcx>| { let mut s = match br { ty::BoundRegionKind::Named(def_id) => self.tcx.item_name(def_id).to_string(), _ => String::new(), diff --git a/compiler/rustc_trait_selection/src/traits/coherence.rs b/compiler/rustc_trait_selection/src/traits/coherence.rs index 2aae5f2cde1e8..9f59f6c592509 100644 --- a/compiler/rustc_trait_selection/src/traits/coherence.rs +++ b/compiler/rustc_trait_selection/src/traits/coherence.rs @@ -566,7 +566,7 @@ fn plug_infer_with_placeholders<'tcx>( ty, Ty::new_placeholder( self.infcx.tcx, - ty::Placeholder::new( + ty::PlaceholderType::new( self.universe, ty::BoundTy { var: self.next_var(), kind: ty::BoundTyKind::Anon }, ), @@ -592,9 +592,9 @@ fn plug_infer_with_placeholders<'tcx>( ct, ty::Const::new_placeholder( self.infcx.tcx, - ty::Placeholder::new( + ty::PlaceholderConst::new( self.universe, - ty::BoundConst { var: self.next_var() }, + ty::BoundConst::new(self.next_var()), ), ), ) @@ -623,7 +623,7 @@ fn plug_infer_with_placeholders<'tcx>( r, ty::Region::new_placeholder( self.infcx.tcx, - ty::Placeholder::new( + ty::PlaceholderRegion::new( self.universe, ty::BoundRegion { var: self.next_var(), diff --git a/compiler/rustc_trait_selection/src/traits/mod.rs b/compiler/rustc_trait_selection/src/traits/mod.rs index 5839a8c2e2951..4e027a301cc8b 100644 --- a/compiler/rustc_trait_selection/src/traits/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/mod.rs @@ -772,7 +772,7 @@ fn replace_param_and_infer_args_with_placeholder<'tcx>( self.idx += 1; ty::Const::new_placeholder( self.tcx, - ty::PlaceholderConst::new(ty::UniverseIndex::ROOT, ty::BoundConst { var: idx }), + ty::PlaceholderConst::new(ty::UniverseIndex::ROOT, ty::BoundConst::new(idx)), ) } else { c.super_fold_with(self) diff --git a/compiler/rustc_trait_selection/src/traits/util.rs b/compiler/rustc_trait_selection/src/traits/util.rs index 19ccf6a55bf1a..c3f46aa51c737 100644 --- a/compiler/rustc_trait_selection/src/traits/util.rs +++ b/compiler/rustc_trait_selection/src/traits/util.rs @@ -220,9 +220,9 @@ pub fn with_replaced_escaping_bound_vars< /// The inverse of [`BoundVarReplacer`]: replaces placeholders with the bound vars from which they came. pub struct PlaceholderReplacer<'a, 'tcx> { infcx: &'a InferCtxt<'tcx>, - mapped_regions: FxIndexMap, ty::BoundRegion>, - mapped_types: FxIndexMap, ty::BoundTy>, - mapped_consts: FxIndexMap, ty::BoundConst>, + mapped_regions: FxIndexMap, ty::BoundRegion<'tcx>>, + mapped_types: FxIndexMap, ty::BoundTy<'tcx>>, + mapped_consts: FxIndexMap, ty::BoundConst<'tcx>>, universe_indices: &'a [Option], current_index: ty::DebruijnIndex, } @@ -230,9 +230,9 @@ pub struct PlaceholderReplacer<'a, 'tcx> { impl<'a, 'tcx> PlaceholderReplacer<'a, 'tcx> { pub fn replace_placeholders>>( infcx: &'a InferCtxt<'tcx>, - mapped_regions: FxIndexMap, ty::BoundRegion>, - mapped_types: FxIndexMap, ty::BoundTy>, - mapped_consts: FxIndexMap, ty::BoundConst>, + mapped_regions: FxIndexMap, ty::BoundRegion<'tcx>>, + mapped_types: FxIndexMap, ty::BoundTy<'tcx>>, + mapped_consts: FxIndexMap, ty::BoundConst<'tcx>>, universe_indices: &'a [Option], value: T, ) -> T { diff --git a/compiler/rustc_ty_utils/src/ty.rs b/compiler/rustc_ty_utils/src/ty.rs index bb25a14ef7443..d6a29aba22b90 100644 --- a/compiler/rustc_ty_utils/src/ty.rs +++ b/compiler/rustc_ty_utils/src/ty.rs @@ -210,7 +210,7 @@ struct ImplTraitInTraitFinder<'a, 'tcx> { tcx: TyCtxt<'tcx>, predicates: &'a mut Vec>, fn_def_id: DefId, - bound_vars: &'tcx ty::List, + bound_vars: &'tcx ty::List>, seen: FxHashSet, depth: ty::DebruijnIndex, } diff --git a/compiler/rustc_type_ir/src/binder.rs b/compiler/rustc_type_ir/src/binder.rs index b5c9080154cea..fc8b39f7c01f0 100644 --- a/compiler/rustc_type_ir/src/binder.rs +++ b/compiler/rustc_type_ir/src/binder.rs @@ -1,11 +1,14 @@ use std::fmt; +use std::hash::Hash; use std::marker::PhantomData; use std::ops::{ControlFlow, Deref}; use derive_where::derive_where; #[cfg(feature = "nightly")] use rustc_macros::{Decodable_NoContext, Encodable_NoContext, HashStable_NoContext}; -use rustc_type_ir_macros::{GenericTypeVisitable, TypeFoldable_Generic, TypeVisitable_Generic}; +use rustc_type_ir_macros::{ + GenericTypeVisitable, Lift_Generic, TypeFoldable_Generic, TypeVisitable_Generic, +}; use tracing::instrument; use crate::data_structures::SsoHashSet; @@ -23,8 +26,11 @@ use crate::{self as ty, DebruijnIndex, Interner, UniverseIndex}; /// for more details. /// /// `Decodable` and `Encodable` are implemented for `Binder` using the `impl_binder_encode_decode!` macro. -#[derive_where(Clone, Hash, PartialEq, Debug; I: Interner, T)] +// FIXME(derive-where#136): Need to use separate `derive_where` for +// `Copy` and `Ord` to prevent the emitted `Clone` and `PartialOrd` +// impls from incorrectly relying on `T: Copy` and `T: Ord`. #[derive_where(Copy; I: Interner, T: Copy)] +#[derive_where(Clone, Hash, PartialEq, Debug; I: Interner, T)] #[derive(GenericTypeVisitable)] #[cfg_attr(feature = "nightly", derive(HashStable_NoContext))] pub struct Binder { @@ -359,9 +365,12 @@ impl TypeVisitor for ValidateBoundVars { /// `instantiate`. /// /// See for more details. -#[derive_where(Clone, PartialEq, Ord, Hash, Debug; I: Interner, T)] -#[derive_where(PartialOrd; I: Interner, T: Ord)] +// FIXME(derive-where#136): Need to use separate `derive_where` for +// `Copy` and `Ord` to prevent the emitted `Clone` and `PartialOrd` +// impls from incorrectly relying on `T: Copy` and `T: Ord`. +#[derive_where(Ord; I: Interner, T: Ord)] #[derive_where(Copy; I: Interner, T: Copy)] +#[derive_where(Clone, PartialOrd, PartialEq, Hash, Debug; I: Interner, T)] #[derive(GenericTypeVisitable)] #[cfg_attr( feature = "nightly", @@ -955,11 +964,12 @@ pub enum BoundVarIndexKind { /// The "placeholder index" fully defines a placeholder region, type, or const. Placeholders are /// identified by both a universe, as well as a name residing within that universe. Distinct bound /// regions/types/consts within the same universe simply have an unknown relationship to one -/// another. -#[derive_where(Clone, PartialEq, Ord, Hash; I: Interner, T)] -#[derive_where(PartialOrd; I: Interner, T: Ord)] -#[derive_where(Copy; I: Interner, T: Copy, T)] -#[derive_where(Eq; T)] +// FIXME(derive-where#136): Need to use separate `derive_where` for +// `Copy` and `Ord` to prevent the emitted `Clone` and `PartialOrd` +// impls from incorrectly relying on `T: Copy` and `T: Ord`. +#[derive_where(Ord; I: Interner, T: Ord)] +#[derive_where(Copy; I: Interner, T: Copy)] +#[derive_where(Clone, PartialOrd, PartialEq, Eq, Hash; I: Interner, T)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic)] #[cfg_attr( feature = "nightly", @@ -973,12 +983,6 @@ pub struct Placeholder { _tcx: PhantomData I>, } -impl Placeholder { - pub fn new(universe: UniverseIndex, bound: T) -> Self { - Placeholder { universe, bound, _tcx: PhantomData } - } -} - impl fmt::Debug for ty::Placeholder { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.universe == ty::UniverseIndex::ROOT { @@ -1003,3 +1007,321 @@ where }) } } + +#[derive_where(Clone, Copy, PartialEq, Eq, Hash; I: Interner)] +#[derive(Lift_Generic)] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) +)] + +pub enum BoundRegionKind { + /// An anonymous region parameter for a given fn (&T) + Anon, + + /// An anonymous region parameter with a `Symbol` name. + /// + /// Used to give late-bound regions names for things like pretty printing. + NamedForPrinting(I::Symbol), + + /// Late-bound regions that appear in the AST. + Named(I::DefId), + + /// Anonymous region for the implicit env pointer parameter + /// to a closure + ClosureEnv, +} + +impl fmt::Debug for ty::BoundRegionKind { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + ty::BoundRegionKind::Anon => write!(f, "BrAnon"), + ty::BoundRegionKind::NamedForPrinting(name) => { + write!(f, "BrNamedForPrinting({:?})", name) + } + ty::BoundRegionKind::Named(did) => { + write!(f, "BrNamed({did:?})") + } + ty::BoundRegionKind::ClosureEnv => write!(f, "BrEnv"), + } + } +} + +impl BoundRegionKind { + pub fn is_named(&self, tcx: I) -> bool { + self.get_name(tcx).is_some() + } + + pub fn get_name(&self, tcx: I) -> Option { + match *self { + ty::BoundRegionKind::Named(def_id) => { + let name = tcx.item_name(def_id); + if name.is_kw_underscore_lifetime() { None } else { Some(name) } + } + ty::BoundRegionKind::NamedForPrinting(name) => Some(name), + _ => None, + } + } + + pub fn get_id(&self) -> Option { + match *self { + ty::BoundRegionKind::Named(id) => Some(id), + _ => None, + } + } +} + +#[derive_where(Clone, Copy, PartialEq, Eq, Debug, Hash; I: Interner)] +#[derive(Lift_Generic)] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) +)] +pub enum BoundTyKind { + Anon, + Param(I::DefId), +} + +#[derive_where(Clone, Copy, PartialEq, Eq, Debug, Hash; I: Interner)] +#[derive(Lift_Generic)] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) +)] +pub enum BoundVariableKind { + Ty(BoundTyKind), + Region(BoundRegionKind), + Const, +} + +impl BoundVariableKind { + pub fn expect_region(self) -> BoundRegionKind { + match self { + BoundVariableKind::Region(lt) => lt, + _ => panic!("expected a region, but found another kind"), + } + } + + pub fn expect_ty(self) -> BoundTyKind { + match self { + BoundVariableKind::Ty(ty) => ty, + _ => panic!("expected a type, but found another kind"), + } + } + + pub fn expect_const(self) { + match self { + BoundVariableKind::Const => (), + _ => panic!("expected a const, but found another kind"), + } + } +} + +#[derive_where(Clone, Copy, PartialEq, Eq, Hash; I: Interner)] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, HashStable_NoContext, Decodable_NoContext) +)] +pub struct BoundRegion { + pub var: ty::BoundVar, + pub kind: BoundRegionKind, +} + +impl core::fmt::Debug for BoundRegion { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self.kind { + BoundRegionKind::Anon => write!(f, "{:?}", self.var), + BoundRegionKind::ClosureEnv => write!(f, "{:?}.Env", self.var), + BoundRegionKind::Named(def) => { + write!(f, "{:?}.Named({:?})", self.var, def) + } + BoundRegionKind::NamedForPrinting(symbol) => { + write!(f, "{:?}.NamedAnon({:?})", self.var, symbol) + } + } + } +} + +impl BoundRegion { + pub fn var(self) -> ty::BoundVar { + self.var + } + + pub fn assert_eq(self, var: BoundVariableKind) { + assert_eq!(self.kind, var.expect_region()) + } +} + +pub type PlaceholderRegion = ty::Placeholder>; + +impl PlaceholderRegion { + pub fn universe(self) -> UniverseIndex { + self.universe + } + + pub fn var(self) -> ty::BoundVar { + self.bound.var() + } + + pub fn with_updated_universe(self, ui: UniverseIndex) -> Self { + Self { universe: ui, bound: self.bound, _tcx: PhantomData } + } + + pub fn new(ui: UniverseIndex, bound: BoundRegion) -> Self { + Self { universe: ui, bound, _tcx: PhantomData } + } + + pub fn new_anon(ui: UniverseIndex, var: ty::BoundVar) -> Self { + let bound = BoundRegion { var, kind: BoundRegionKind::Anon }; + Self { universe: ui, bound, _tcx: PhantomData } + } +} + +#[derive_where(Clone, Copy, PartialEq, Eq, Hash; I: Interner)] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) +)] +pub struct BoundTy { + pub var: ty::BoundVar, + pub kind: BoundTyKind, +} + +impl Lift for BoundTy +where + BoundTyKind: Lift>, +{ + type Lifted = BoundTy; + + fn lift_to_interner(self, cx: U) -> Option { + Some(BoundTy { var: self.var, kind: self.kind.lift_to_interner(cx)? }) + } +} + +impl fmt::Debug for ty::BoundTy { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.kind { + ty::BoundTyKind::Anon => write!(f, "{:?}", self.var), + ty::BoundTyKind::Param(def_id) => write!(f, "{def_id:?}"), + } + } +} + +impl BoundTy { + pub fn var(self) -> ty::BoundVar { + self.var + } + + pub fn assert_eq(self, var: BoundVariableKind) { + assert_eq!(self.kind, var.expect_ty()) + } +} + +pub type PlaceholderType = ty::Placeholder>; + +impl PlaceholderType { + pub fn universe(self) -> UniverseIndex { + self.universe + } + + pub fn var(self) -> ty::BoundVar { + self.bound.var + } + + pub fn with_updated_universe(self, ui: UniverseIndex) -> Self { + Self { universe: ui, bound: self.bound, _tcx: PhantomData } + } + + pub fn new(ui: UniverseIndex, bound: BoundTy) -> Self { + Self { universe: ui, bound, _tcx: PhantomData } + } + + pub fn new_anon(ui: UniverseIndex, var: ty::BoundVar) -> Self { + let bound = BoundTy { var, kind: BoundTyKind::Anon }; + Self { universe: ui, bound, _tcx: PhantomData } + } +} + +#[derive_where(Clone, Copy, PartialEq, Debug, Eq, Hash; I: Interner)] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) +)] +pub struct BoundConst { + pub var: ty::BoundVar, + #[derive_where(skip(Debug))] + pub _tcx: PhantomData I>, +} + +impl BoundConst { + pub fn var(self) -> ty::BoundVar { + self.var + } + + pub fn assert_eq(self, var: BoundVariableKind) { + var.expect_const() + } + + pub fn new(var: ty::BoundVar) -> Self { + Self { var, _tcx: PhantomData } + } +} + +pub type PlaceholderConst = ty::Placeholder>; + +impl PlaceholderConst { + pub fn universe(self) -> UniverseIndex { + self.universe + } + + pub fn var(self) -> ty::BoundVar { + self.bound.var + } + + pub fn with_updated_universe(self, ui: UniverseIndex) -> Self { + Self { universe: ui, bound: self.bound, _tcx: PhantomData } + } + + pub fn new(ui: UniverseIndex, bound: BoundConst) -> Self { + Self { universe: ui, bound, _tcx: PhantomData } + } + + pub fn new_anon(ui: UniverseIndex, var: ty::BoundVar) -> Self { + let bound = BoundConst::new(var); + Self { universe: ui, bound, _tcx: PhantomData } + } + + pub fn find_const_ty_from_env(self, env: I::ParamEnv) -> I::Ty { + let mut candidates = env.caller_bounds().iter().filter_map(|clause| { + // `ConstArgHasType` are never desugared to be higher ranked. + match clause.kind().skip_binder() { + ty::ClauseKind::ConstArgHasType(placeholder_ct, ty) => { + assert!(!(placeholder_ct, ty).has_escaping_bound_vars()); + + match placeholder_ct.kind() { + ty::ConstKind::Placeholder(placeholder_ct) if placeholder_ct == self => { + Some(ty) + } + _ => None, + } + } + _ => None, + } + }); + + // N.B. it may be tempting to fix ICEs by making this function return + // `Option>` instead of `Ty<'tcx>`; however, this is generally + // considered to be a bandaid solution, since it hides more important + // underlying issues with how we construct generics and predicates of + // items. It's advised to fix the underlying issue rather than trying + // to modify this function. + let ty = candidates.next().unwrap_or_else(|| { + panic!("cannot find `{self:?}` in param-env: {env:#?}"); + }); + assert!( + candidates.next().is_none(), + "did not expect duplicate `ConstParamHasTy` for `{self:?}` in param-env: {env:#?}" + ); + ty + } +} diff --git a/compiler/rustc_type_ir/src/canonical.rs b/compiler/rustc_type_ir/src/canonical.rs index 12d222258b0c6..8e7414674c6e7 100644 --- a/compiler/rustc_type_ir/src/canonical.rs +++ b/compiler/rustc_type_ir/src/canonical.rs @@ -108,7 +108,7 @@ pub enum CanonicalVarKind { Float, /// A "placeholder" that represents "any type". - PlaceholderTy(I::PlaceholderTy), + PlaceholderTy(ty::PlaceholderType), /// Region variable `'?R`. Region(UniverseIndex), @@ -116,13 +116,13 @@ pub enum CanonicalVarKind { /// A "placeholder" that represents "any region". Created when you /// are solving a goal like `for<'a> T: Foo<'a>` to represent the /// bound region `'a`. - PlaceholderRegion(I::PlaceholderRegion), + PlaceholderRegion(ty::PlaceholderRegion), /// Some kind of const inference variable. Const(UniverseIndex), /// A "placeholder" that represents "any const". - PlaceholderConst(I::PlaceholderConst), + PlaceholderConst(ty::PlaceholderConst), } impl Eq for CanonicalVarKind {} diff --git a/compiler/rustc_type_ir/src/const_kind.rs b/compiler/rustc_type_ir/src/const_kind.rs index 5b136ae03121e..b215230ea443c 100644 --- a/compiler/rustc_type_ir/src/const_kind.rs +++ b/compiler/rustc_type_ir/src/const_kind.rs @@ -26,10 +26,10 @@ pub enum ConstKind { Infer(InferConst), /// Bound const variable, used only when preparing a trait query. - Bound(BoundVarIndexKind, I::BoundConst), + Bound(BoundVarIndexKind, ty::BoundConst), /// A placeholder const - universally quantified higher-ranked const. - Placeholder(I::PlaceholderConst), + Placeholder(ty::PlaceholderConst), /// An unnormalized const item such as an anon const or assoc const or free const item. /// Right now anything other than anon consts does not actually work properly but this diff --git a/compiler/rustc_type_ir/src/error.rs b/compiler/rustc_type_ir/src/error.rs index 502622aa50ca8..eba4c7c6644ac 100644 --- a/compiler/rustc_type_ir/src/error.rs +++ b/compiler/rustc_type_ir/src/error.rs @@ -33,7 +33,7 @@ pub enum TypeError { ArgCount, RegionsDoesNotOutlive(I::Region, I::Region), - RegionsInsufficientlyPolymorphic(I::BoundRegion, I::Region), + RegionsInsufficientlyPolymorphic(ty::BoundRegion, I::Region), RegionsPlaceholderMismatch, Sorts(ExpectedFound), diff --git a/compiler/rustc_type_ir/src/inherent.rs b/compiler/rustc_type_ir/src/inherent.rs index 4323b1ca64690..89cb236d38c6d 100644 --- a/compiler/rustc_type_ir/src/inherent.rs +++ b/compiler/rustc_type_ir/src/inherent.rs @@ -12,7 +12,7 @@ use crate::elaborate::Elaboratable; use crate::fold::{TypeFoldable, TypeSuperFoldable}; use crate::relate::Relate; use crate::solve::{AdtDestructorKind, SizedTraitKind}; -use crate::visit::{Flags, TypeSuperVisitable, TypeVisitable, TypeVisitableExt}; +use crate::visit::{Flags, TypeSuperVisitable, TypeVisitable}; use crate::{self as ty, CollectAndApply, Interner, UpcastFrom}; pub trait Ty>: @@ -42,9 +42,9 @@ pub trait Ty>: fn new_param(interner: I, param: I::ParamTy) -> Self; - fn new_placeholder(interner: I, param: I::PlaceholderTy) -> Self; + fn new_placeholder(interner: I, param: ty::PlaceholderType) -> Self; - fn new_bound(interner: I, debruijn: ty::DebruijnIndex, var: I::BoundTy) -> Self; + fn new_bound(interner: I, debruijn: ty::DebruijnIndex, var: ty::BoundTy) -> Self; fn new_anon_bound(interner: I, debruijn: ty::DebruijnIndex, var: ty::BoundVar) -> Self; @@ -228,7 +228,7 @@ pub trait Region>: + Flags + Relate { - fn new_bound(interner: I, debruijn: ty::DebruijnIndex, var: I::BoundRegion) -> Self; + fn new_bound(interner: I, debruijn: ty::DebruijnIndex, var: ty::BoundRegion) -> Self; fn new_anon_bound(interner: I, debruijn: ty::DebruijnIndex, var: ty::BoundVar) -> Self; @@ -236,7 +236,7 @@ pub trait Region>: fn new_static(interner: I) -> Self; - fn new_placeholder(interner: I, var: I::PlaceholderRegion) -> Self; + fn new_placeholder(interner: I, var: ty::PlaceholderRegion) -> Self; fn is_bound(self) -> bool { matches!(self.kind(), ty::ReBound(..)) @@ -260,13 +260,13 @@ pub trait Const>: fn new_var(interner: I, var: ty::ConstVid) -> Self; - fn new_bound(interner: I, debruijn: ty::DebruijnIndex, bound_const: I::BoundConst) -> Self; + fn new_bound(interner: I, debruijn: ty::DebruijnIndex, bound_const: ty::BoundConst) -> Self; fn new_anon_bound(interner: I, debruijn: ty::DebruijnIndex, var: ty::BoundVar) -> Self; fn new_canonical_bound(interner: I, var: ty::BoundVar) -> Self; - fn new_placeholder(interner: I, param: I::PlaceholderConst) -> Self; + fn new_placeholder(interner: I, param: ty::PlaceholderConst) -> Self; fn new_unevaluated(interner: I, uv: ty::UnevaluatedConst) -> Self; @@ -543,68 +543,12 @@ pub trait Clauses>: { } -/// Common capabilities of placeholder kinds -pub trait PlaceholderLike: Copy + Debug + Hash + Eq { - fn universe(self) -> ty::UniverseIndex; - fn var(self) -> ty::BoundVar; - - type Bound: BoundVarLike; - fn new(ui: ty::UniverseIndex, bound: Self::Bound) -> Self; - fn new_anon(ui: ty::UniverseIndex, var: ty::BoundVar) -> Self; - fn with_updated_universe(self, ui: ty::UniverseIndex) -> Self; -} - -pub trait PlaceholderConst: PlaceholderLike { - fn find_const_ty_from_env(self, env: I::ParamEnv) -> I::Ty; -} -impl PlaceholderConst for I::PlaceholderConst { - fn find_const_ty_from_env(self, env: I::ParamEnv) -> I::Ty { - let mut candidates = env.caller_bounds().iter().filter_map(|clause| { - // `ConstArgHasType` are never desugared to be higher ranked. - match clause.kind().skip_binder() { - ty::ClauseKind::ConstArgHasType(placeholder_ct, ty) => { - assert!(!(placeholder_ct, ty).has_escaping_bound_vars()); - - match placeholder_ct.kind() { - ty::ConstKind::Placeholder(placeholder_ct) if placeholder_ct == self => { - Some(ty) - } - _ => None, - } - } - _ => None, - } - }); - - // N.B. it may be tempting to fix ICEs by making this function return - // `Option>` instead of `Ty<'tcx>`; however, this is generally - // considered to be a bandaid solution, since it hides more important - // underlying issues with how we construct generics and predicates of - // items. It's advised to fix the underlying issue rather than trying - // to modify this function. - let ty = candidates.next().unwrap_or_else(|| { - panic!("cannot find `{self:?}` in param-env: {env:#?}"); - }); - assert!( - candidates.next().is_none(), - "did not expect duplicate `ConstParamHasTy` for `{self:?}` in param-env: {env:#?}" - ); - ty - } -} - pub trait IntoKind { type Kind; fn kind(self) -> Self::Kind; } -pub trait BoundVarLike: Copy + Debug + Hash + Eq { - fn var(self) -> ty::BoundVar; - - fn assert_eq(self, var: I::BoundVarKind); -} - pub trait ParamLike: Copy + Debug + Hash + Eq { fn index(self) -> u32; } @@ -768,3 +712,7 @@ impl<'a, S: SliceLike> SliceLike for &'a S { (*self).as_slice() } } + +pub trait Symbol: Copy + Hash + PartialEq + Eq + Debug { + fn is_kw_underscore_lifetime(self) -> bool; +} diff --git a/compiler/rustc_type_ir/src/interner.rs b/compiler/rustc_type_ir/src/interner.rs index 0ab27a65c6879..59ae6733fb847 100644 --- a/compiler/rustc_type_ir/src/interner.rs +++ b/compiler/rustc_type_ir/src/interner.rs @@ -61,8 +61,12 @@ pub trait Interner: type GenericArg: GenericArg; type Term: Term; - type BoundVarKinds: Copy + Debug + Hash + Eq + SliceLike + Default; - type BoundVarKind: Copy + Debug + Hash + Eq; + type BoundVarKinds: Copy + + Debug + + Hash + + Eq + + SliceLike> + + Default; type PredefinedOpaques: Copy + Debug @@ -120,9 +124,7 @@ pub trait Interner: type Tys: Tys; type FnInputTys: Copy + Debug + Hash + Eq + SliceLike + TypeVisitable; type ParamTy: ParamLike; - type BoundTy: BoundVarLike; - type PlaceholderTy: PlaceholderLike; - type Symbol: Copy + Hash + PartialEq + Eq + Debug; + type Symbol: Symbol; // Things stored inside of tys type ErrorGuaranteed: Copy + Debug + Hash + Eq; @@ -149,8 +151,6 @@ pub trait Interner: // Kinds of consts type Const: Const; type ParamConst: Copy + Debug + Hash + Eq + ParamLike; - type BoundConst: BoundVarLike; - type PlaceholderConst: PlaceholderConst; type ValueConst: ValueConst; type ExprConst: ExprConst; type ValTree: ValTree; @@ -160,8 +160,6 @@ pub trait Interner: type Region: Region; type EarlyParamRegion: ParamLike; type LateParamRegion: Copy + Debug + Hash + Eq; - type BoundRegion: BoundVarLike; - type PlaceholderRegion: PlaceholderLike; type RegionAssumptions: Copy + Debug @@ -411,6 +409,8 @@ pub trait Interner: self, canonical_goal: CanonicalInput, ) -> (QueryResult, Self::Probe); + + fn item_name(self, item_index: Self::DefId) -> Self::Symbol; } /// Imagine you have a function `F: FnOnce(&[T]) -> R`, plus an iterator `iter` diff --git a/compiler/rustc_type_ir/src/outlives.rs b/compiler/rustc_type_ir/src/outlives.rs index c7dccea6adc12..300e5c0b46956 100644 --- a/compiler/rustc_type_ir/src/outlives.rs +++ b/compiler/rustc_type_ir/src/outlives.rs @@ -14,7 +14,7 @@ use crate::{self as ty, Interner}; pub enum Component { Region(I::Region), Param(I::ParamTy), - Placeholder(I::PlaceholderTy), + Placeholder(ty::PlaceholderType), UnresolvedInferenceVariable(ty::InferTy), // Projections like `T::Foo` are tricky because a constraint like diff --git a/compiler/rustc_type_ir/src/region_kind.rs b/compiler/rustc_type_ir/src/region_kind.rs index 9acf9ff8557e7..e08c274f9f147 100644 --- a/compiler/rustc_type_ir/src/region_kind.rs +++ b/compiler/rustc_type_ir/src/region_kind.rs @@ -8,7 +8,7 @@ use rustc_macros::{Decodable_NoContext, Encodable_NoContext, HashStable_NoContex use rustc_type_ir_macros::GenericTypeVisitable; use self::RegionKind::*; -use crate::{BoundVarIndexKind, Interner}; +use crate::{BoundRegion, BoundVarIndexKind, Interner, PlaceholderRegion}; rustc_index::newtype_index! { /// A **region** **v**ariable **ID**. @@ -149,7 +149,7 @@ pub enum RegionKind { /// Bound regions inside of types **must not** be erased, as they impact trait /// selection and the `TypeId` of that type. `for<'a> fn(&'a ())` and /// `fn(&'static ())` are different types and have to be treated as such. - ReBound(BoundVarIndexKind, I::BoundRegion), + ReBound(BoundVarIndexKind, BoundRegion), /// Late-bound function parameters are represented using a `ReBound`. When /// inside of a function, we convert these bound variables to placeholder @@ -170,7 +170,7 @@ pub enum RegionKind { /// Should not exist outside of type inference. /// /// Used when instantiating a `forall` binder via `infcx.enter_forall`. - RePlaceholder(I::PlaceholderRegion), + RePlaceholder(PlaceholderRegion), /// Erased region, used by trait selection, in MIR and during codegen. ReErased, @@ -214,9 +214,9 @@ impl fmt::Debug for RegionKind { impl HashStable for RegionKind where I::EarlyParamRegion: HashStable, - I::BoundRegion: HashStable, I::LateParamRegion: HashStable, - I::PlaceholderRegion: HashStable, + I::DefId: HashStable, + I::Symbol: HashStable, { #[inline] fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { diff --git a/compiler/rustc_type_ir/src/ty_kind.rs b/compiler/rustc_type_ir/src/ty_kind.rs index 498797bef653a..7cb71387e8680 100644 --- a/compiler/rustc_type_ir/src/ty_kind.rs +++ b/compiler/rustc_type_ir/src/ty_kind.rs @@ -233,7 +233,7 @@ pub enum TyKind { /// /// [1]: https://rustc-dev-guide.rust-lang.org/traits/hrtb.html /// [2]: https://rustc-dev-guide.rust-lang.org/traits/canonical-queries.html - Bound(BoundVarIndexKind, I::BoundTy), + Bound(BoundVarIndexKind, ty::BoundTy), /// A placeholder type, used during higher ranked subtyping to instantiate /// bound variables. @@ -243,7 +243,7 @@ pub enum TyKind { /// to the bound variable's index from the binder from which it was instantiated), /// and `U` is the universe index in which it is instantiated, or totally omitted /// if the universe index is zero. - Placeholder(I::PlaceholderTy), + Placeholder(ty::PlaceholderType), /// A type variable used during type checking. /// diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 9d6038367419d..1c9154238657d 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -3178,7 +3178,7 @@ fn clean_assoc_item_constraint<'tcx>( } fn clean_bound_vars<'tcx>( - bound_vars: &ty::List, + bound_vars: &ty::List>, cx: &mut DocContext<'tcx>, ) -> Vec { bound_vars diff --git a/src/tools/clippy/clippy_utils/src/ty/mod.rs b/src/tools/clippy/clippy_utils/src/ty/mod.rs index 2926a329ce16c..0f11df98fc17b 100644 --- a/src/tools/clippy/clippy_utils/src/ty/mod.rs +++ b/src/tools/clippy/clippy_utils/src/ty/mod.rs @@ -782,15 +782,15 @@ pub fn is_c_void(cx: &LateContext<'_>, ty: Ty<'_>) -> bool { } } -pub fn for_each_top_level_late_bound_region( - ty: Ty<'_>, - f: impl FnMut(BoundRegion) -> ControlFlow, +pub fn for_each_top_level_late_bound_region<'cx, B>( + ty: Ty<'cx>, + f: impl FnMut(BoundRegion<'cx>) -> ControlFlow, ) -> ControlFlow { struct V { index: u32, f: F, } - impl<'tcx, B, F: FnMut(BoundRegion) -> ControlFlow> TypeVisitor> for V { + impl<'tcx, B, F: FnMut(BoundRegion<'tcx>) -> ControlFlow> TypeVisitor> for V { type Result = ControlFlow; fn visit_region(&mut self, r: Region<'tcx>) -> Self::Result { if let RegionKind::ReBound(BoundVarIndexKind::Bound(idx), bound) = r.kind()