diff --git a/Cargo.lock b/Cargo.lock index ff755e5bec660..2d3bc59dddb21 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -228,12 +228,6 @@ dependencies = [ "backtrace", ] -[[package]] -name = "ar" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d67af77d68a931ecd5cbd8a3b5987d63a1d1d1278f7f6a60ae33db485cdebb69" - [[package]] name = "ar_archive_writer" version = "0.3.0" @@ -3451,7 +3445,6 @@ dependencies = [ name = "run_make_support" version = "0.2.0" dependencies = [ - "ar", "bstr", "build_helper", "gimli 0.31.0", diff --git a/compiler/rustc_borrowck/src/type_check/relate_tys.rs b/compiler/rustc_borrowck/src/type_check/relate_tys.rs index 02b9c2d48b11b..ea4a94e57b3b8 100644 --- a/compiler/rustc_borrowck/src/type_check/relate_tys.rs +++ b/compiler/rustc_borrowck/src/type_check/relate_tys.rs @@ -309,7 +309,7 @@ impl<'me, 'bccx, 'tcx> NllTypeRelating<'me, 'bccx, 'tcx> { } impl<'bccx, 'tcx> TypeRelation> for NllTypeRelating<'_, 'bccx, 'tcx> { - fn tcx(&self) -> TyCtxt<'tcx> { + fn cx(&self) -> TyCtxt<'tcx> { self.type_checker.infcx.tcx } @@ -370,7 +370,7 @@ impl<'bccx, 'tcx> TypeRelation> for NllTypeRelating<'_, 'bccx, 'tcx // shouldn't ever fail. Instead, it unconditionally emits an // alias-relate goal. assert!(!self.type_checker.infcx.next_trait_solver()); - self.tcx().dcx().span_delayed_bug( + self.cx().dcx().span_delayed_bug( self.span(), "failure to relate an opaque to itself should result in an error later on", ); @@ -540,7 +540,7 @@ impl<'bccx, 'tcx> PredicateEmittingRelation> for NllTypeRelating &mut self, obligations: impl IntoIterator, ty::Predicate<'tcx>>>, ) { - let tcx = self.tcx(); + let tcx = self.cx(); let param_env = self.param_env(); self.register_goals( obligations.into_iter().map(|to_pred| Goal::new(tcx, param_env, to_pred)), @@ -559,7 +559,7 @@ impl<'bccx, 'tcx> PredicateEmittingRelation> for NllTypeRelating .into_iter() .map(|goal| { Obligation::new( - self.tcx(), + self.cx(), ObligationCause::dummy_with_span(self.span()), goal.param_env, goal.predicate, diff --git a/compiler/rustc_const_eval/src/interpret/validity.rs b/compiler/rustc_const_eval/src/interpret/validity.rs index 7fea061766666..4da7e233889f0 100644 --- a/compiler/rustc_const_eval/src/interpret/validity.rs +++ b/compiler/rustc_const_eval/src/interpret/validity.rs @@ -34,7 +34,6 @@ use super::{ Pointer, Projectable, Scalar, ValueVisitor, }; -// for the validation errors use super::InterpError::UndefinedBehavior as Ub; use super::InterpError::Unsupported as Unsup; use super::UndefinedBehaviorInfo::*; diff --git a/compiler/rustc_infer/src/error_reporting/infer/mod.rs b/compiler/rustc_infer/src/error_reporting/infer/mod.rs index ddd5818203cfd..a4af721cf7547 100644 --- a/compiler/rustc_infer/src/error_reporting/infer/mod.rs +++ b/compiler/rustc_infer/src/error_reporting/infer/mod.rs @@ -1930,7 +1930,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { struct SameTypeModuloInfer<'a, 'tcx>(&'a InferCtxt<'tcx>); impl<'tcx> TypeRelation> for SameTypeModuloInfer<'_, 'tcx> { - fn tcx(&self) -> TyCtxt<'tcx> { + fn cx(&self) -> TyCtxt<'tcx> { self.0.tcx } 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 978b92fd8980d..d60d9113d91bf 100644 --- a/compiler/rustc_infer/src/infer/outlives/test_type_match.rs +++ b/compiler/rustc_infer/src/infer/outlives/test_type_match.rs @@ -137,7 +137,7 @@ impl<'tcx> TypeRelation> for MatchAgainstHigherRankedOutlives<'tcx> "MatchAgainstHigherRankedOutlives" } - fn tcx(&self) -> TyCtxt<'tcx> { + fn cx(&self) -> TyCtxt<'tcx> { self.tcx } diff --git a/compiler/rustc_infer/src/infer/relate/generalize.rs b/compiler/rustc_infer/src/infer/relate/generalize.rs index fe3b8d60fb91b..ace439545b84b 100644 --- a/compiler/rustc_infer/src/infer/relate/generalize.rs +++ b/compiler/rustc_infer/src/infer/relate/generalize.rs @@ -372,7 +372,7 @@ impl<'tcx> Generalizer<'_, 'tcx> { let is_nested_alias = mem::replace(&mut self.in_alias, true); let result = match self.relate(alias, alias) { - Ok(alias) => Ok(alias.to_ty(self.tcx())), + Ok(alias) => Ok(alias.to_ty(self.cx())), Err(e) => { if is_nested_alias { return Err(e); @@ -397,7 +397,7 @@ impl<'tcx> Generalizer<'_, 'tcx> { } impl<'tcx> TypeRelation> for Generalizer<'_, 'tcx> { - fn tcx(&self) -> TyCtxt<'tcx> { + fn cx(&self) -> TyCtxt<'tcx> { self.infcx.tcx } @@ -417,7 +417,7 @@ impl<'tcx> TypeRelation> for Generalizer<'_, 'tcx> { // (e.g., #41849). relate::relate_args_invariantly(self, a_arg, b_arg) } else { - let tcx = self.tcx(); + let tcx = self.cx(); let opt_variances = tcx.variances_of(item_def_id); relate::relate_args_with_variances( self, @@ -525,7 +525,7 @@ impl<'tcx> TypeRelation> for Generalizer<'_, 'tcx> { } debug!("replacing original vid={:?} with new={:?}", vid, new_var_id); - Ok(Ty::new_var(self.tcx(), new_var_id)) + Ok(Ty::new_var(self.cx(), new_var_id)) } } } @@ -654,7 +654,7 @@ impl<'tcx> TypeRelation> for Generalizer<'_, 'tcx> { { variable_table.union(vid, new_var_id); } - Ok(ty::Const::new_var(self.tcx(), new_var_id)) + Ok(ty::Const::new_var(self.cx(), new_var_id)) } } } @@ -672,7 +672,7 @@ impl<'tcx> TypeRelation> for Generalizer<'_, 'tcx> { args, args, )?; - Ok(ty::Const::new_unevaluated(self.tcx(), ty::UnevaluatedConst { def, args })) + Ok(ty::Const::new_unevaluated(self.cx(), ty::UnevaluatedConst { def, args })) } ty::ConstKind::Placeholder(placeholder) => { if self.for_universe.can_name(placeholder.universe) { diff --git a/compiler/rustc_infer/src/infer/relate/glb.rs b/compiler/rustc_infer/src/infer/relate/glb.rs index 5bb8a113e173e..819a47fcf93fb 100644 --- a/compiler/rustc_infer/src/infer/relate/glb.rs +++ b/compiler/rustc_infer/src/infer/relate/glb.rs @@ -27,7 +27,7 @@ impl<'tcx> TypeRelation> for Glb<'_, '_, 'tcx> { "Glb" } - fn tcx(&self) -> TyCtxt<'tcx> { + fn cx(&self) -> TyCtxt<'tcx> { self.fields.tcx() } @@ -61,7 +61,7 @@ impl<'tcx> TypeRelation> for Glb<'_, '_, 'tcx> { let origin = SubregionOrigin::Subtype(Box::new(self.fields.trace.clone())); // GLB(&'static u8, &'a u8) == &RegionLUB('static, 'a) u8 == &'static u8 Ok(self.fields.infcx.inner.borrow_mut().unwrap_region_constraints().lub_regions( - self.tcx(), + self.cx(), origin, a, b, diff --git a/compiler/rustc_infer/src/infer/relate/lub.rs b/compiler/rustc_infer/src/infer/relate/lub.rs index 94c1464817f73..56d325c5dc1fd 100644 --- a/compiler/rustc_infer/src/infer/relate/lub.rs +++ b/compiler/rustc_infer/src/infer/relate/lub.rs @@ -27,7 +27,7 @@ impl<'tcx> TypeRelation> for Lub<'_, '_, 'tcx> { "Lub" } - fn tcx(&self) -> TyCtxt<'tcx> { + fn cx(&self) -> TyCtxt<'tcx> { self.fields.tcx() } @@ -61,7 +61,7 @@ impl<'tcx> TypeRelation> for Lub<'_, '_, 'tcx> { let origin = SubregionOrigin::Subtype(Box::new(self.fields.trace.clone())); // LUB(&'static u8, &'a u8) == &RegionGLB('static, 'a) u8 == &'a u8 Ok(self.fields.infcx.inner.borrow_mut().unwrap_region_constraints().glb_regions( - self.tcx(), + self.cx(), origin, a, b, diff --git a/compiler/rustc_infer/src/infer/relate/type_relating.rs b/compiler/rustc_infer/src/infer/relate/type_relating.rs index e206f530519b5..97bd858defbca 100644 --- a/compiler/rustc_infer/src/infer/relate/type_relating.rs +++ b/compiler/rustc_infer/src/infer/relate/type_relating.rs @@ -32,7 +32,7 @@ impl<'tcx> TypeRelation> for TypeRelating<'_, '_, 'tcx> { "TypeRelating" } - fn tcx(&self) -> TyCtxt<'tcx> { + fn cx(&self) -> TyCtxt<'tcx> { self.fields.infcx.tcx } @@ -48,7 +48,7 @@ impl<'tcx> TypeRelation> for TypeRelating<'_, '_, 'tcx> { // (e.g., #41849). relate_args_invariantly(self, a_arg, b_arg) } else { - let tcx = self.tcx(); + let tcx = self.cx(); let opt_variances = tcx.variances_of(item_def_id); relate_args_with_variances(self, item_def_id, opt_variances, a_arg, b_arg, false) } @@ -88,7 +88,7 @@ impl<'tcx> TypeRelation> for TypeRelating<'_, '_, 'tcx> { // can't make progress on `A <: B` if both A and B are // type variables, so record an obligation. self.fields.goals.push(Goal::new( - self.tcx(), + self.cx(), self.fields.param_env, ty::Binder::dummy(ty::PredicateKind::Subtype(ty::SubtypePredicate { a_is_expected: true, @@ -101,7 +101,7 @@ impl<'tcx> TypeRelation> for TypeRelating<'_, '_, 'tcx> { // can't make progress on `B <: A` if both A and B are // type variables, so record an obligation. self.fields.goals.push(Goal::new( - self.tcx(), + self.cx(), self.fields.param_env, ty::Binder::dummy(ty::PredicateKind::Subtype(ty::SubtypePredicate { a_is_expected: false, @@ -134,7 +134,7 @@ impl<'tcx> TypeRelation> for TypeRelating<'_, '_, 'tcx> { (&ty::Error(e), _) | (_, &ty::Error(e)) => { infcx.set_tainted_by_errors(e); - return Ok(Ty::new_error(self.tcx(), e)); + return Ok(Ty::new_error(self.cx(), e)); } ( diff --git a/compiler/rustc_lint/src/lib.rs b/compiler/rustc_lint/src/lib.rs index 8be8996e4c8f0..4e83ef0c6291b 100644 --- a/compiler/rustc_lint/src/lib.rs +++ b/compiler/rustc_lint/src/lib.rs @@ -120,7 +120,6 @@ use types::*; use unit_bindings::*; use unused::*; -/// Useful for other parts of the compiler / Clippy. pub use builtin::{MissingDoc, SoftLints}; pub use context::{CheckLintNameResult, FindLintError, LintStore}; pub use context::{EarlyContext, LateContext, LintContext}; diff --git a/compiler/rustc_macros/src/lift.rs b/compiler/rustc_macros/src/lift.rs index d41ceb29816cc..627f4088d5f5c 100644 --- a/compiler/rustc_macros/src/lift.rs +++ b/compiler/rustc_macros/src/lift.rs @@ -45,7 +45,7 @@ pub fn lift_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::TokenStre quote! { type Lifted = #lifted; - fn lift_to_tcx(self, __tcx: ::rustc_middle::ty::TyCtxt<'__lifted>) -> Option<#lifted> { + fn lift_to_interner(self, __tcx: ::rustc_middle::ty::TyCtxt<'__lifted>) -> Option<#lifted> { Some(match self { #body }) } }, diff --git a/compiler/rustc_middle/src/macros.rs b/compiler/rustc_middle/src/macros.rs index fcea1ea81a7c4..d385be007d33f 100644 --- a/compiler/rustc_middle/src/macros.rs +++ b/compiler/rustc_middle/src/macros.rs @@ -59,7 +59,7 @@ macro_rules! TrivialLiftImpls { $( impl<'tcx> $crate::ty::Lift<$crate::ty::TyCtxt<'tcx>> for $ty { type Lifted = Self; - fn lift_to_tcx(self, _: $crate::ty::TyCtxt<'tcx>) -> Option { + fn lift_to_interner(self, _: $crate::ty::TyCtxt<'tcx>) -> Option { Some(self) } } diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 25070e6b042c9..fd41668ae44c8 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -1484,7 +1484,7 @@ impl<'tcx> TyCtxt<'tcx> { } pub fn lift>>(self, value: T) -> Option { - value.lift_to_tcx(self) + value.lift_to_interner(self) } /// Creates a type context. To use the context call `fn enter` which @@ -2087,7 +2087,7 @@ macro_rules! nop_lift { ($set:ident; $ty:ty => $lifted:ty) => { impl<'a, 'tcx> Lift> for $ty { type Lifted = $lifted; - fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option { + fn lift_to_interner(self, tcx: TyCtxt<'tcx>) -> Option { // Assert that the set has the right type. // Given an argument that has an interned type, the return type has the type of // the corresponding interner set. This won't actually return anything, we're @@ -2122,7 +2122,7 @@ macro_rules! nop_list_lift { ($set:ident; $ty:ty => $lifted:ty) => { impl<'a, 'tcx> Lift> for &'a List<$ty> { type Lifted = &'tcx List<$lifted>; - fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option { + fn lift_to_interner(self, tcx: TyCtxt<'tcx>) -> Option { // Assert that the set has the right type. if false { let _x: &InternedSet<'tcx, List<$lifted>> = &tcx.interners.$set; @@ -2160,7 +2160,7 @@ macro_rules! nop_slice_lift { ($ty:ty => $lifted:ty) => { impl<'a, 'tcx> Lift> for &'a [$ty] { type Lifted = &'tcx [$lifted]; - fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option { + fn lift_to_interner(self, tcx: TyCtxt<'tcx>) -> Option { if self.is_empty() { return Some(&[]); } diff --git a/compiler/rustc_middle/src/ty/generic_args.rs b/compiler/rustc_middle/src/ty/generic_args.rs index 5ac3168196ad7..10919623de728 100644 --- a/compiler/rustc_middle/src/ty/generic_args.rs +++ b/compiler/rustc_middle/src/ty/generic_args.rs @@ -308,7 +308,7 @@ impl<'tcx> GenericArg<'tcx> { impl<'a, 'tcx> Lift> for GenericArg<'a> { type Lifted = GenericArg<'tcx>; - fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option { + fn lift_to_interner(self, tcx: TyCtxt<'tcx>) -> Option { match self.unpack() { GenericArgKind::Lifetime(lt) => tcx.lift(lt).map(|lt| lt.into()), GenericArgKind::Type(ty) => tcx.lift(ty).map(|ty| ty.into()), diff --git a/compiler/rustc_middle/src/ty/relate.rs b/compiler/rustc_middle/src/ty/relate.rs index ebf0d7ed737fa..61c03922ac05f 100644 --- a/compiler/rustc_middle/src/ty/relate.rs +++ b/compiler/rustc_middle/src/ty/relate.rs @@ -69,7 +69,7 @@ impl<'tcx> Relate> for ty::Pattern<'tcx> { if inc_a != inc_b { todo!() } - Ok(relation.tcx().mk_pat(ty::PatternKind::Range { start, end, include_end: inc_a })) + Ok(relation.cx().mk_pat(ty::PatternKind::Range { start, end, include_end: inc_a })) } } } @@ -81,7 +81,7 @@ impl<'tcx> Relate> for &'tcx ty::List RelateResult<'tcx, Self> { - let tcx = relation.tcx(); + let tcx = relation.cx(); // FIXME: this is wasteful, but want to do a perf run to see how slow it is. // We need to perform this deduplication as we sometimes generate duplicate projections diff --git a/compiler/rustc_middle/src/ty/structural_impls.rs b/compiler/rustc_middle/src/ty/structural_impls.rs index 00ea87690c1ab..7cdc0e32953de 100644 --- a/compiler/rustc_middle/src/ty/structural_impls.rs +++ b/compiler/rustc_middle/src/ty/structural_impls.rs @@ -283,7 +283,7 @@ TrivialTypeTraversalAndLiftImpls! { impl<'tcx, T: Lift>> Lift> for Option { type Lifted = Option; - fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option { + fn lift_to_interner(self, tcx: TyCtxt<'tcx>) -> Option { Some(match self { Some(x) => Some(tcx.lift(x)?), None => None, @@ -293,7 +293,7 @@ impl<'tcx, T: Lift>> Lift> for Option { impl<'a, 'tcx> Lift> for Term<'a> { type Lifted = ty::Term<'tcx>; - fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option { + fn lift_to_interner(self, tcx: TyCtxt<'tcx>) -> Option { match self.unpack() { TermKind::Ty(ty) => tcx.lift(ty).map(Into::into), TermKind::Const(c) => tcx.lift(c).map(Into::into), diff --git a/compiler/rustc_pattern_analysis/src/lib.rs b/compiler/rustc_pattern_analysis/src/lib.rs index c9590ad06b05d..1b4bcb789d2da 100644 --- a/compiler/rustc_pattern_analysis/src/lib.rs +++ b/compiler/rustc_pattern_analysis/src/lib.rs @@ -21,9 +21,7 @@ rustc_fluent_macro::fluent_messages! { "../messages.ftl" } use std::fmt; -// Re-exports to avoid rustc_index version issues. -pub use rustc_index::Idx; -pub use rustc_index::IndexVec; +pub use rustc_index::{Idx, IndexVec}; // re-exported to avoid rustc_index version issues #[cfg(feature = "rustc")] use rustc_middle::ty::Ty; diff --git a/compiler/rustc_smir/src/rustc_internal/internal.rs b/compiler/rustc_smir/src/rustc_internal/internal.rs index 7c3553b60fddb..854295dc04818 100644 --- a/compiler/rustc_smir/src/rustc_internal/internal.rs +++ b/compiler/rustc_smir/src/rustc_internal/internal.rs @@ -4,6 +4,7 @@ //! due to incomplete stable coverage. // Prefer importing stable_mir over internal rustc constructs to make this file more readable. + use crate::rustc_smir::Tables; use rustc_middle::ty::{self as rustc_ty, Const as InternalConst, Ty as InternalTy, TyCtxt}; use rustc_span::Symbol; diff --git a/compiler/rustc_trait_selection/src/traits/select/_match.rs b/compiler/rustc_trait_selection/src/traits/select/_match.rs index 50d8e96aaf91f..8676f30a53b6e 100644 --- a/compiler/rustc_trait_selection/src/traits/select/_match.rs +++ b/compiler/rustc_trait_selection/src/traits/select/_match.rs @@ -36,7 +36,7 @@ impl<'tcx> TypeRelation> for MatchAgainstFreshVars<'tcx> { "MatchAgainstFreshVars" } - fn tcx(&self) -> TyCtxt<'tcx> { + fn cx(&self) -> TyCtxt<'tcx> { self.tcx } @@ -77,7 +77,7 @@ impl<'tcx> TypeRelation> for MatchAgainstFreshVars<'tcx> { Err(TypeError::Sorts(ExpectedFound::new(true, a, b))) } - (&ty::Error(guar), _) | (_, &ty::Error(guar)) => Ok(Ty::new_error(self.tcx(), guar)), + (&ty::Error(guar), _) | (_, &ty::Error(guar)) => Ok(Ty::new_error(self.cx(), guar)), _ => structurally_relate_tys(self, a, b), } diff --git a/compiler/rustc_type_ir/src/binder.rs b/compiler/rustc_type_ir/src/binder.rs index 2531219baecc8..17b35a2807a2d 100644 --- a/compiler/rustc_type_ir/src/binder.rs +++ b/compiler/rustc_type_ir/src/binder.rs @@ -49,10 +49,10 @@ where { type Lifted = Binder; - fn lift_to_tcx(self, tcx: U) -> Option { + fn lift_to_interner(self, cx: U) -> Option { Some(Binder { - value: self.value.lift_to_tcx(tcx)?, - bound_vars: self.bound_vars.lift_to_tcx(tcx)?, + value: self.value.lift_to_interner(cx)?, + bound_vars: self.bound_vars.lift_to_interner(cx)?, }) } } @@ -439,11 +439,11 @@ impl EarlyBinder where Iter::Item: TypeFoldable, { - pub fn iter_instantiated(self, tcx: I, args: A) -> IterInstantiated + pub fn iter_instantiated(self, cx: I, args: A) -> IterInstantiated where A: SliceLike, { - IterInstantiated { it: self.value.into_iter(), tcx, args } + IterInstantiated { it: self.value.into_iter(), cx, args } } /// Similar to [`instantiate_identity`](EarlyBinder::instantiate_identity), @@ -455,7 +455,7 @@ where pub struct IterInstantiated { it: Iter::IntoIter, - tcx: I, + cx: I, args: A, } @@ -469,7 +469,7 @@ where fn next(&mut self) -> Option { Some( EarlyBinder { value: self.it.next()?, _tcx: PhantomData } - .instantiate(self.tcx, self.args), + .instantiate(self.cx, self.args), ) } @@ -487,7 +487,7 @@ where fn next_back(&mut self) -> Option { Some( EarlyBinder { value: self.it.next_back()?, _tcx: PhantomData } - .instantiate(self.tcx, self.args), + .instantiate(self.cx, self.args), ) } } @@ -507,10 +507,10 @@ where { pub fn iter_instantiated_copied( self, - tcx: I, + cx: I, args: &'s [I::GenericArg], ) -> IterInstantiatedCopied<'s, I, Iter> { - IterInstantiatedCopied { it: self.value.into_iter(), tcx, args } + IterInstantiatedCopied { it: self.value.into_iter(), cx, args } } /// Similar to [`instantiate_identity`](EarlyBinder::instantiate_identity), @@ -522,7 +522,7 @@ where pub struct IterInstantiatedCopied<'a, I: Interner, Iter: IntoIterator> { it: Iter::IntoIter, - tcx: I, + cx: I, args: &'a [I::GenericArg], } @@ -535,7 +535,7 @@ where fn next(&mut self) -> Option { self.it.next().map(|value| { - EarlyBinder { value: *value, _tcx: PhantomData }.instantiate(self.tcx, self.args) + EarlyBinder { value: *value, _tcx: PhantomData }.instantiate(self.cx, self.args) }) } @@ -552,7 +552,7 @@ where { fn next_back(&mut self) -> Option { self.it.next_back().map(|value| { - EarlyBinder { value: *value, _tcx: PhantomData }.instantiate(self.tcx, self.args) + EarlyBinder { value: *value, _tcx: PhantomData }.instantiate(self.cx, self.args) }) } } @@ -589,11 +589,11 @@ impl Iterator for EarlyBinderIter { } impl> ty::EarlyBinder { - pub fn instantiate(self, tcx: I, args: A) -> T + pub fn instantiate(self, cx: I, args: A) -> T where A: SliceLike, { - let mut folder = ArgFolder { tcx, args: args.as_slice(), binders_passed: 0 }; + let mut folder = ArgFolder { cx, args: args.as_slice(), binders_passed: 0 }; self.value.fold_with(&mut folder) } @@ -619,7 +619,7 @@ impl> ty::EarlyBinder { // The actual instantiation engine itself is a type folder. struct ArgFolder<'a, I: Interner> { - tcx: I, + cx: I, args: &'a [I::GenericArg], /// Number of region binders we have passed through while doing the instantiation @@ -629,7 +629,7 @@ struct ArgFolder<'a, I: Interner> { impl<'a, I: Interner> TypeFolder for ArgFolder<'a, I> { #[inline] fn cx(&self) -> I { - self.tcx + self.cx } fn fold_binder>(&mut self, t: ty::Binder) -> ty::Binder { @@ -858,6 +858,6 @@ impl<'a, I: Interner> ArgFolder<'a, I> { if self.binders_passed == 0 || !region.has_escaping_bound_vars() { return region; } - ty::fold::shift_region(self.tcx, region, self.binders_passed) + ty::fold::shift_region(self.cx, region, self.binders_passed) } } diff --git a/compiler/rustc_type_ir/src/canonical.rs b/compiler/rustc_type_ir/src/canonical.rs index 7b114f565f29e..a9252711b2b66 100644 --- a/compiler/rustc_type_ir/src/canonical.rs +++ b/compiler/rustc_type_ir/src/canonical.rs @@ -330,25 +330,25 @@ impl CanonicalVarValues { // Given a list of canonical variables, construct a set of values which are // the identity response. - pub fn make_identity(tcx: I, infos: I::CanonicalVars) -> CanonicalVarValues { + pub fn make_identity(cx: I, infos: I::CanonicalVars) -> CanonicalVarValues { CanonicalVarValues { - var_values: tcx.mk_args_from_iter(infos.iter().enumerate().map( + var_values: cx.mk_args_from_iter(infos.iter().enumerate().map( |(i, info)| -> I::GenericArg { match info.kind { CanonicalVarKind::Ty(_) | CanonicalVarKind::PlaceholderTy(_) => { - Ty::new_anon_bound(tcx, ty::INNERMOST, ty::BoundVar::from_usize(i)) + Ty::new_anon_bound(cx, ty::INNERMOST, ty::BoundVar::from_usize(i)) .into() } CanonicalVarKind::Region(_) | CanonicalVarKind::PlaceholderRegion(_) => { - Region::new_anon_bound(tcx, ty::INNERMOST, ty::BoundVar::from_usize(i)) + Region::new_anon_bound(cx, ty::INNERMOST, ty::BoundVar::from_usize(i)) .into() } CanonicalVarKind::Effect => { - Const::new_anon_bound(tcx, ty::INNERMOST, ty::BoundVar::from_usize(i)) + Const::new_anon_bound(cx, ty::INNERMOST, ty::BoundVar::from_usize(i)) .into() } CanonicalVarKind::Const(_) | CanonicalVarKind::PlaceholderConst(_) => { - Const::new_anon_bound(tcx, ty::INNERMOST, ty::BoundVar::from_usize(i)) + Const::new_anon_bound(cx, ty::INNERMOST, ty::BoundVar::from_usize(i)) .into() } } diff --git a/compiler/rustc_type_ir/src/effects.rs b/compiler/rustc_type_ir/src/effects.rs index f7942f2f982f5..d1c3c8e52235c 100644 --- a/compiler/rustc_type_ir/src/effects.rs +++ b/compiler/rustc_type_ir/src/effects.rs @@ -10,38 +10,38 @@ pub enum EffectKind { } impl EffectKind { - pub fn try_from_def_id(tcx: I, def_id: I::DefId) -> Option { - if tcx.is_lang_item(def_id, EffectsMaybe) { + pub fn try_from_def_id(cx: I, def_id: I::DefId) -> Option { + if cx.is_lang_item(def_id, EffectsMaybe) { Some(EffectKind::Maybe) - } else if tcx.is_lang_item(def_id, EffectsRuntime) { + } else if cx.is_lang_item(def_id, EffectsRuntime) { Some(EffectKind::Runtime) - } else if tcx.is_lang_item(def_id, EffectsNoRuntime) { + } else if cx.is_lang_item(def_id, EffectsNoRuntime) { Some(EffectKind::NoRuntime) } else { None } } - pub fn to_def_id(self, tcx: I) -> I::DefId { + pub fn to_def_id(self, cx: I) -> I::DefId { let lang_item = match self { EffectKind::Maybe => EffectsMaybe, EffectKind::NoRuntime => EffectsNoRuntime, EffectKind::Runtime => EffectsRuntime, }; - tcx.require_lang_item(lang_item) + cx.require_lang_item(lang_item) } - pub fn try_from_ty(tcx: I, ty: I::Ty) -> Option { + pub fn try_from_ty(cx: I, ty: I::Ty) -> Option { if let crate::Adt(def, _) = ty.kind() { - Self::try_from_def_id(tcx, def.def_id()) + Self::try_from_def_id(cx, def.def_id()) } else { None } } - pub fn to_ty(self, tcx: I) -> I::Ty { - I::Ty::new_adt(tcx, tcx.adt_def(self.to_def_id(tcx)), Default::default()) + pub fn to_ty(self, cx: I) -> I::Ty { + I::Ty::new_adt(cx, cx.adt_def(self.to_def_id(cx)), Default::default()) } /// Returns an intersection between two effect kinds. If one effect kind diff --git a/compiler/rustc_type_ir/src/elaborate.rs b/compiler/rustc_type_ir/src/elaborate.rs index 0def7d12f742a..7dd2f3de3f824 100644 --- a/compiler/rustc_type_ir/src/elaborate.rs +++ b/compiler/rustc_type_ir/src/elaborate.rs @@ -258,17 +258,17 @@ pub fn supertrait_def_ids( } pub fn supertraits( - tcx: I, + cx: I, trait_ref: ty::Binder>, ) -> FilterToTraits> { - elaborate(tcx, [trait_ref.upcast(tcx)]).filter_only_self().filter_to_traits() + elaborate(cx, [trait_ref.upcast(cx)]).filter_only_self().filter_to_traits() } pub fn transitive_bounds( - tcx: I, + cx: I, trait_refs: impl Iterator>>, ) -> FilterToTraits> { - elaborate(tcx, trait_refs.map(|trait_ref| trait_ref.upcast(tcx))) + elaborate(cx, trait_refs.map(|trait_ref| trait_ref.upcast(cx))) .filter_only_self() .filter_to_traits() } diff --git a/compiler/rustc_type_ir/src/fast_reject.rs b/compiler/rustc_type_ir/src/fast_reject.rs index 0810fa5c55832..456accd1a1b78 100644 --- a/compiler/rustc_type_ir/src/fast_reject.rs +++ b/compiler/rustc_type_ir/src/fast_reject.rs @@ -105,7 +105,7 @@ pub enum TreatParams { /// /// ยน meaning that if the outermost layers are different, then the whole types are also different. pub fn simplify_type( - tcx: I, + cx: I, ty: I::Ty, treat_params: TreatParams, ) -> Option> { @@ -119,10 +119,10 @@ pub fn simplify_type( ty::Str => Some(SimplifiedType::Str), ty::Array(..) => Some(SimplifiedType::Array), ty::Slice(..) => Some(SimplifiedType::Slice), - ty::Pat(ty, ..) => simplify_type(tcx, ty, treat_params), + ty::Pat(ty, ..) => simplify_type(cx, ty, treat_params), ty::RawPtr(_, mutbl) => Some(SimplifiedType::Ptr(mutbl)), ty::Dynamic(trait_info, ..) => match trait_info.principal_def_id() { - Some(principal_def_id) if !tcx.trait_is_auto(principal_def_id) => { + Some(principal_def_id) if !cx.trait_is_auto(principal_def_id) => { Some(SimplifiedType::Trait(principal_def_id)) } _ => Some(SimplifiedType::MarkerTraitObject), diff --git a/compiler/rustc_type_ir/src/fold.rs b/compiler/rustc_type_ir/src/fold.rs index 09ee12d1cc391..a4d8dafb246e5 100644 --- a/compiler/rustc_type_ir/src/fold.rs +++ b/compiler/rustc_type_ir/src/fold.rs @@ -345,20 +345,20 @@ impl, Ix: Idx> TypeFoldable for IndexVec { - tcx: I, + cx: I, current_index: ty::DebruijnIndex, amount: u32, } impl Shifter { - pub fn new(tcx: I, amount: u32) -> Self { - Shifter { tcx, current_index: ty::INNERMOST, amount } + pub fn new(cx: I, amount: u32) -> Self { + Shifter { cx, current_index: ty::INNERMOST, amount } } } impl TypeFolder for Shifter { fn cx(&self) -> I { - self.tcx + self.cx } fn fold_binder>(&mut self, t: ty::Binder) -> ty::Binder { @@ -372,7 +372,7 @@ impl TypeFolder for Shifter { match r.kind() { ty::ReBound(debruijn, br) if debruijn >= self.current_index => { let debruijn = debruijn.shifted_in(self.amount); - Region::new_bound(self.tcx, debruijn, br) + Region::new_bound(self.cx, debruijn, br) } _ => r, } @@ -382,7 +382,7 @@ impl TypeFolder for Shifter { match ty.kind() { ty::Bound(debruijn, bound_ty) if debruijn >= self.current_index => { let debruijn = debruijn.shifted_in(self.amount); - Ty::new_bound(self.tcx, debruijn, bound_ty) + Ty::new_bound(self.cx, debruijn, bound_ty) } _ if ty.has_vars_bound_at_or_above(self.current_index) => ty.super_fold_with(self), @@ -394,7 +394,7 @@ impl TypeFolder for Shifter { match ct.kind() { ty::ConstKind::Bound(debruijn, bound_ct) if debruijn >= self.current_index => { let debruijn = debruijn.shifted_in(self.amount); - Const::new_bound(self.tcx, debruijn, bound_ct) + Const::new_bound(self.cx, debruijn, bound_ct) } _ => ct.super_fold_with(self), } @@ -405,16 +405,16 @@ impl TypeFolder for Shifter { } } -pub fn shift_region(tcx: I, region: I::Region, amount: u32) -> I::Region { +pub fn shift_region(cx: I, region: I::Region, amount: u32) -> I::Region { match region.kind() { ty::ReBound(debruijn, br) if amount > 0 => { - Region::new_bound(tcx, debruijn.shifted_in(amount), br) + Region::new_bound(cx, debruijn.shifted_in(amount), br) } _ => region, } } -pub fn shift_vars(tcx: I, value: T, amount: u32) -> T +pub fn shift_vars(cx: I, value: T, amount: u32) -> T where T: TypeFoldable, { @@ -424,5 +424,5 @@ where return value; } - value.fold_with(&mut Shifter::new(tcx, amount)) + value.fold_with(&mut Shifter::new(cx, amount)) } diff --git a/compiler/rustc_type_ir/src/inherent.rs b/compiler/rustc_type_ir/src/inherent.rs index f05d626b47032..63ad36efc8529 100644 --- a/compiler/rustc_type_ir/src/inherent.rs +++ b/compiler/rustc_type_ir/src/inherent.rs @@ -475,7 +475,7 @@ pub trait Clause>: /// poly-trait-ref to supertraits that must hold if that /// poly-trait-ref holds. This is slightly different from a normal /// instantiation in terms of what happens with bound regions. - fn instantiate_supertrait(self, tcx: I, trait_ref: ty::Binder>) -> Self; + fn instantiate_supertrait(self, cx: I, trait_ref: ty::Binder>) -> Self; } /// Common capabilities of placeholder kinds diff --git a/compiler/rustc_type_ir/src/lift.rs b/compiler/rustc_type_ir/src/lift.rs index 839da10db5e56..e5a099d1f5042 100644 --- a/compiler/rustc_type_ir/src/lift.rs +++ b/compiler/rustc_type_ir/src/lift.rs @@ -17,5 +17,5 @@ /// e.g., `()` or `u8`, was interned in a different context. pub trait Lift: std::fmt::Debug { type Lifted: std::fmt::Debug; - fn lift_to_tcx(self, tcx: I) -> Option; + fn lift_to_interner(self, cx: I) -> Option; } diff --git a/compiler/rustc_type_ir/src/opaque_ty.rs b/compiler/rustc_type_ir/src/opaque_ty.rs index d8ed4770e2dc1..e5d18fcb3d1e1 100644 --- a/compiler/rustc_type_ir/src/opaque_ty.rs +++ b/compiler/rustc_type_ir/src/opaque_ty.rs @@ -22,8 +22,8 @@ pub struct OpaqueTypeKey { } impl OpaqueTypeKey { - pub fn iter_captured_args(self, tcx: I) -> impl Iterator { - let variances = tcx.variances_of(self.def_id.into()); + pub fn iter_captured_args(self, cx: I) -> impl Iterator { + let variances = cx.variances_of(self.def_id.into()); std::iter::zip(self.args.iter(), variances.iter()).enumerate().filter_map( |(i, (arg, v))| match (arg.kind(), v) { (_, ty::Invariant) => Some((i, arg)), @@ -35,18 +35,18 @@ impl OpaqueTypeKey { pub fn fold_captured_lifetime_args( self, - tcx: I, + cx: I, mut f: impl FnMut(I::Region) -> I::Region, ) -> Self { let Self { def_id, args } = self; - let variances = tcx.variances_of(def_id.into()); + let variances = cx.variances_of(def_id.into()); let args = std::iter::zip(args.iter(), variances.iter()).map(|(arg, v)| match (arg.kind(), v) { (ty::GenericArgKind::Lifetime(_), ty::Bivariant) => arg, (ty::GenericArgKind::Lifetime(lt), _) => f(lt).into(), _ => arg, }); - let args = tcx.mk_args_from_iter(args); + let args = cx.mk_args_from_iter(args); Self { def_id, args } } } diff --git a/compiler/rustc_type_ir/src/outlives.rs b/compiler/rustc_type_ir/src/outlives.rs index 10b6f3355d92a..eb84f3dd58731 100644 --- a/compiler/rustc_type_ir/src/outlives.rs +++ b/compiler/rustc_type_ir/src/outlives.rs @@ -54,15 +54,15 @@ pub enum Component { /// Push onto `out` all the things that must outlive `'a` for the condition /// `ty0: 'a` to hold. Note that `ty0` must be a **fully resolved type**. pub fn push_outlives_components( - tcx: I, + cx: I, ty: I::Ty, out: &mut SmallVec<[Component; 4]>, ) { - ty.visit_with(&mut OutlivesCollector { tcx, out, visited: Default::default() }); + ty.visit_with(&mut OutlivesCollector { cx, out, visited: Default::default() }); } struct OutlivesCollector<'a, I: Interner> { - tcx: I, + cx: I, out: &'a mut SmallVec<[Component; 4]>, visited: SsoHashSet, } @@ -147,7 +147,7 @@ impl TypeVisitor for OutlivesCollector<'_, I> { // OutlivesProjectionComponents. Continue walking // through and constrain Pi. let mut subcomponents = smallvec![]; - compute_alias_components_recursive(self.tcx, ty, &mut subcomponents); + compute_alias_components_recursive(self.cx, ty, &mut subcomponents); self.out.push(Component::EscapingAlias(subcomponents.into_iter().collect())); } } @@ -206,7 +206,7 @@ impl TypeVisitor for OutlivesCollector<'_, I> { /// This should not be used to get the components of `parent` itself. /// Use [push_outlives_components] instead. pub fn compute_alias_components_recursive( - tcx: I, + cx: I, alias_ty: I::Ty, out: &mut SmallVec<[Component; 4]>, ) { @@ -215,9 +215,9 @@ pub fn compute_alias_components_recursive( }; let opt_variances = - if kind == ty::Opaque { Some(tcx.variances_of(alias_ty.def_id)) } else { None }; + if kind == ty::Opaque { Some(cx.variances_of(alias_ty.def_id)) } else { None }; - let mut visitor = OutlivesCollector { tcx, out, visited: Default::default() }; + let mut visitor = OutlivesCollector { cx, out, visited: Default::default() }; for (index, child) in alias_ty.args.iter().enumerate() { if opt_variances.and_then(|variances| variances.get(index)) == Some(ty::Bivariant) { diff --git a/compiler/rustc_type_ir/src/predicate.rs b/compiler/rustc_type_ir/src/predicate.rs index e5bcbc67f946c..e03f521c5b105 100644 --- a/compiler/rustc_type_ir/src/predicate.rs +++ b/compiler/rustc_type_ir/src/predicate.rs @@ -34,8 +34,8 @@ where { type Lifted = OutlivesPredicate; - fn lift_to_tcx(self, tcx: U) -> Option { - Some(OutlivesPredicate(self.0.lift_to_tcx(tcx)?, self.1.lift_to_tcx(tcx)?)) + fn lift_to_interner(self, cx: U) -> Option { + Some(OutlivesPredicate(self.0.lift_to_interner(cx)?, self.1.lift_to_interner(cx)?)) } } @@ -267,25 +267,23 @@ impl ty::Binder> { /// Given an existential predicate like `?Self: PartialEq` (e.g., derived from `dyn PartialEq`), /// and a concrete type `self_ty`, returns a full predicate where the existentially quantified variable `?Self` /// has been replaced with `self_ty` (e.g., `self_ty: PartialEq`, in our example). - pub fn with_self_ty(&self, tcx: I, self_ty: I::Ty) -> I::Clause { + pub fn with_self_ty(&self, cx: I, self_ty: I::Ty) -> I::Clause { match self.skip_binder() { - ExistentialPredicate::Trait(tr) => { - self.rebind(tr).with_self_ty(tcx, self_ty).upcast(tcx) - } + ExistentialPredicate::Trait(tr) => self.rebind(tr).with_self_ty(cx, self_ty).upcast(cx), ExistentialPredicate::Projection(p) => { - self.rebind(p.with_self_ty(tcx, self_ty)).upcast(tcx) + self.rebind(p.with_self_ty(cx, self_ty)).upcast(cx) } ExistentialPredicate::AutoTrait(did) => { - let generics = tcx.generics_of(did); + let generics = cx.generics_of(did); let trait_ref = if generics.count() == 1 { - ty::TraitRef::new(tcx, did, [self_ty]) + ty::TraitRef::new(cx, did, [self_ty]) } else { // If this is an ill-formed auto trait, then synthesize // new error args for the missing generics. - let err_args = GenericArgs::extend_with_error(tcx, did, &[self_ty.into()]); - ty::TraitRef::new_from_args(tcx, did, err_args) + let err_args = GenericArgs::extend_with_error(cx, did, &[self_ty.into()]); + ty::TraitRef::new_from_args(cx, did, err_args) }; - self.rebind(trait_ref).upcast(tcx) + self.rebind(trait_ref).upcast(cx) } } } @@ -345,8 +343,8 @@ impl ty::Binder> { /// we convert the principal trait-ref into a normal trait-ref, /// you must give *some* self type. A common choice is `mk_err()` /// or some placeholder type. - pub fn with_self_ty(&self, tcx: I, self_ty: I::Ty) -> ty::Binder> { - self.map_bound(|trait_ref| trait_ref.with_self_ty(tcx, self_ty)) + pub fn with_self_ty(&self, cx: I, self_ty: I::Ty) -> ty::Binder> { + self.map_bound(|trait_ref| trait_ref.with_self_ty(cx, self_ty)) } } @@ -406,8 +404,8 @@ impl ExistentialProjection { } impl ty::Binder> { - pub fn with_self_ty(&self, tcx: I, self_ty: I::Ty) -> ty::Binder> { - self.map_bound(|p| p.with_self_ty(tcx, self_ty)) + pub fn with_self_ty(&self, cx: I, self_ty: I::Ty) -> ty::Binder> { + self.map_bound(|p| p.with_self_ty(cx, self_ty)) } pub fn item_def_id(&self) -> I::DefId { @@ -669,21 +667,21 @@ impl ProjectionPredicate { impl ty::Binder> { /// Returns the `DefId` of the trait of the associated item being projected. #[inline] - pub fn trait_def_id(&self, tcx: I) -> I::DefId { - self.skip_binder().projection_term.trait_def_id(tcx) + pub fn trait_def_id(&self, cx: I) -> I::DefId { + self.skip_binder().projection_term.trait_def_id(cx) } /// Get the trait ref required for this projection to be well formed. /// Note that for generic associated types the predicates of the associated /// type also need to be checked. #[inline] - pub fn required_poly_trait_ref(&self, tcx: I) -> ty::Binder> { + pub fn required_poly_trait_ref(&self, cx: I) -> ty::Binder> { // Note: unlike with `TraitRef::to_poly_trait_ref()`, // `self.0.trait_ref` is permitted to have escaping regions. // This is because here `self` has a `Binder` and so does our // return value, so we are preserving the number of binding // levels. - self.map_bound(|predicate| predicate.projection_term.trait_ref(tcx)) + self.map_bound(|predicate| predicate.projection_term.trait_ref(cx)) } pub fn term(&self) -> ty::Binder { diff --git a/compiler/rustc_type_ir/src/relate.rs b/compiler/rustc_type_ir/src/relate.rs index 0439e7f857fe7..a8f48d14af5ce 100644 --- a/compiler/rustc_type_ir/src/relate.rs +++ b/compiler/rustc_type_ir/src/relate.rs @@ -56,7 +56,7 @@ impl VarianceDiagInfo { } pub trait TypeRelation: Sized { - fn tcx(&self) -> I; + fn cx(&self) -> I; /// Returns a static string we can use for printouts. fn tag(&self) -> &'static str; @@ -80,8 +80,8 @@ pub trait TypeRelation: Sized { item_def_id, a_arg, b_arg ); - let tcx = self.tcx(); - let opt_variances = tcx.variances_of(item_def_id); + let cx = self.cx(); + let opt_variances = cx.variances_of(item_def_id); relate_args_with_variances(self, item_def_id, opt_variances, a_arg, b_arg, true) } @@ -128,7 +128,7 @@ pub fn relate_args_invariantly>( a_arg: I::GenericArgs, b_arg: I::GenericArgs, ) -> RelateResult { - relation.tcx().mk_args_from_iter(iter::zip(a_arg.iter(), b_arg.iter()).map(|(a, b)| { + relation.cx().mk_args_from_iter(iter::zip(a_arg.iter(), b_arg.iter()).map(|(a, b)| { relation.relate_with_variance(ty::Invariant, VarianceDiagInfo::default(), a, b) })) } @@ -141,14 +141,13 @@ pub fn relate_args_with_variances>( b_arg: I::GenericArgs, fetch_ty_for_diag: bool, ) -> RelateResult { - let tcx = relation.tcx(); + let cx = relation.cx(); let mut cached_ty = None; let params = iter::zip(a_arg.iter(), b_arg.iter()).enumerate().map(|(i, (a, b))| { let variance = variances.get(i).unwrap(); let variance_info = if variance == ty::Invariant && fetch_ty_for_diag { - let ty = - *cached_ty.get_or_insert_with(|| tcx.type_of(ty_def_id).instantiate(tcx, a_arg)); + let ty = *cached_ty.get_or_insert_with(|| cx.type_of(ty_def_id).instantiate(cx, a_arg)); VarianceDiagInfo::Invariant { ty, param_index: i.try_into().unwrap() } } else { VarianceDiagInfo::default() @@ -156,7 +155,7 @@ pub fn relate_args_with_variances>( relation.relate_with_variance(variance, variance_info, a, b) }); - tcx.mk_args_from_iter(params) + cx.mk_args_from_iter(params) } impl Relate for ty::FnSig { @@ -165,7 +164,7 @@ impl Relate for ty::FnSig { a: ty::FnSig, b: ty::FnSig, ) -> RelateResult> { - let tcx = relation.tcx(); + let cx = relation.cx(); if a.c_variadic != b.c_variadic { return Err(TypeError::VariadicMismatch({ @@ -210,7 +209,7 @@ impl Relate for ty::FnSig { r => r, }); Ok(ty::FnSig { - inputs_and_output: tcx.mk_type_list_from_iter(inputs_and_output)?, + inputs_and_output: cx.mk_type_list_from_iter(inputs_and_output)?, c_variadic: a.c_variadic, safety, abi, @@ -245,11 +244,11 @@ impl Relate for ty::AliasTy { ExpectedFound::new(true, a, b) })) } else { - let args = match a.kind(relation.tcx()) { + let args = match a.kind(relation.cx()) { ty::Opaque => relate_args_with_variances( relation, a.def_id, - relation.tcx().variances_of(a.def_id), + relation.cx().variances_of(a.def_id), a.args, b.args, false, // do not fetch `type_of(a_def_id)`, as it will cause a cycle @@ -258,7 +257,7 @@ impl Relate for ty::AliasTy { relate_args_invariantly(relation, a.args, b.args)? } }; - Ok(ty::AliasTy::new_from_args(relation.tcx(), a.def_id, args)) + Ok(ty::AliasTy::new_from_args(relation.cx(), a.def_id, args)) } } } @@ -276,11 +275,11 @@ impl Relate for ty::AliasTerm { ExpectedFound::new(true, a, b) })) } else { - let args = match a.kind(relation.tcx()) { + let args = match a.kind(relation.cx()) { ty::AliasTermKind::OpaqueTy => relate_args_with_variances( relation, a.def_id, - relation.tcx().variances_of(a.def_id), + relation.cx().variances_of(a.def_id), a.args, b.args, false, // do not fetch `type_of(a_def_id)`, as it will cause a cycle @@ -293,7 +292,7 @@ impl Relate for ty::AliasTerm { relate_args_invariantly(relation, a.args, b.args)? } }; - Ok(ty::AliasTerm::new_from_args(relation.tcx(), a.def_id, args)) + Ok(ty::AliasTerm::new_from_args(relation.cx(), a.def_id, args)) } } } @@ -343,7 +342,7 @@ impl Relate for ty::TraitRef { })) } else { let args = relate_args_invariantly(relation, a.args, b.args)?; - Ok(ty::TraitRef::new_from_args(relation.tcx(), a.def_id, args)) + Ok(ty::TraitRef::new_from_args(relation.cx(), a.def_id, args)) } } } @@ -377,7 +376,7 @@ pub fn structurally_relate_tys>( a: I::Ty, b: I::Ty, ) -> RelateResult { - let tcx = relation.tcx(); + let cx = relation.cx(); match (a.kind(), b.kind()) { (ty::Infer(_), _) | (_, ty::Infer(_)) => { // The caller should handle these cases! @@ -388,7 +387,7 @@ pub fn structurally_relate_tys>( panic!("bound types encountered in structurally_relate_tys") } - (ty::Error(guar), _) | (_, ty::Error(guar)) => Ok(Ty::new_error(tcx, guar)), + (ty::Error(guar), _) | (_, ty::Error(guar)) => Ok(Ty::new_error(cx, guar)), (ty::Never, _) | (ty::Char, _) @@ -412,16 +411,16 @@ pub fn structurally_relate_tys>( (ty::Adt(a_def, a_args), ty::Adt(b_def, b_args)) if a_def == b_def => { let args = relation.relate_item_args(a_def.def_id(), a_args, b_args)?; - Ok(Ty::new_adt(tcx, a_def, args)) + Ok(Ty::new_adt(cx, a_def, args)) } - (ty::Foreign(a_id), ty::Foreign(b_id)) if a_id == b_id => Ok(Ty::new_foreign(tcx, a_id)), + (ty::Foreign(a_id), ty::Foreign(b_id)) if a_id == b_id => Ok(Ty::new_foreign(cx, a_id)), (ty::Dynamic(a_obj, a_region, a_repr), ty::Dynamic(b_obj, b_region, b_repr)) if a_repr == b_repr => { Ok(Ty::new_dynamic( - tcx, + cx, relation.relate(a_obj, b_obj)?, relation.relate(a_region, b_region)?, a_repr, @@ -433,7 +432,7 @@ pub fn structurally_relate_tys>( // the (anonymous) type of the same coroutine expression. So // all of their regions should be equated. let args = relate_args_invariantly(relation, a_args, b_args)?; - Ok(Ty::new_coroutine(tcx, a_id, args)) + Ok(Ty::new_coroutine(cx, a_id, args)) } (ty::CoroutineWitness(a_id, a_args), ty::CoroutineWitness(b_id, b_args)) @@ -443,7 +442,7 @@ pub fn structurally_relate_tys>( // the (anonymous) type of the same coroutine expression. So // all of their regions should be equated. let args = relate_args_invariantly(relation, a_args, b_args)?; - Ok(Ty::new_coroutine_witness(tcx, a_id, args)) + Ok(Ty::new_coroutine_witness(cx, a_id, args)) } (ty::Closure(a_id, a_args), ty::Closure(b_id, b_args)) if a_id == b_id => { @@ -451,14 +450,14 @@ pub fn structurally_relate_tys>( // the (anonymous) type of the same closure expression. So // all of their regions should be equated. let args = relate_args_invariantly(relation, a_args, b_args)?; - Ok(Ty::new_closure(tcx, a_id, args)) + Ok(Ty::new_closure(cx, a_id, args)) } (ty::CoroutineClosure(a_id, a_args), ty::CoroutineClosure(b_id, b_args)) if a_id == b_id => { let args = relate_args_invariantly(relation, a_args, b_args)?; - Ok(Ty::new_coroutine_closure(tcx, a_id, args)) + Ok(Ty::new_coroutine_closure(cx, a_id, args)) } (ty::RawPtr(a_ty, a_mutbl), ty::RawPtr(b_ty, b_mutbl)) => { @@ -475,7 +474,7 @@ pub fn structurally_relate_tys>( let ty = relation.relate_with_variance(variance, info, a_ty, b_ty)?; - Ok(Ty::new_ptr(tcx, ty, a_mutbl)) + Ok(Ty::new_ptr(cx, ty, a_mutbl)) } (ty::Ref(a_r, a_ty, a_mutbl), ty::Ref(b_r, b_ty, b_mutbl)) => { @@ -493,18 +492,18 @@ pub fn structurally_relate_tys>( let r = relation.relate(a_r, b_r)?; let ty = relation.relate_with_variance(variance, info, a_ty, b_ty)?; - Ok(Ty::new_ref(tcx, r, ty, a_mutbl)) + Ok(Ty::new_ref(cx, r, ty, a_mutbl)) } (ty::Array(a_t, sz_a), ty::Array(b_t, sz_b)) => { let t = relation.relate(a_t, b_t)?; match relation.relate(sz_a, sz_b) { - Ok(sz) => Ok(Ty::new_array_with_const_len(tcx, t, sz)), + Ok(sz) => Ok(Ty::new_array_with_const_len(cx, t, sz)), Err(err) => { // Check whether the lengths are both concrete/known values, // but are unequal, for better diagnostics. - let sz_a = sz_a.try_to_target_usize(tcx); - let sz_b = sz_b.try_to_target_usize(tcx); + let sz_a = sz_a.try_to_target_usize(cx); + let sz_b = sz_b.try_to_target_usize(cx); match (sz_a, sz_b) { (Some(sz_a_val), Some(sz_b_val)) if sz_a_val != sz_b_val => Err( @@ -518,13 +517,13 @@ pub fn structurally_relate_tys>( (ty::Slice(a_t), ty::Slice(b_t)) => { let t = relation.relate(a_t, b_t)?; - Ok(Ty::new_slice(tcx, t)) + Ok(Ty::new_slice(cx, t)) } (ty::Tuple(as_), ty::Tuple(bs)) => { if as_.len() == bs.len() { Ok(Ty::new_tup_from_iter( - tcx, + cx, iter::zip(as_.iter(), bs.iter()).map(|(a, b)| relation.relate(a, b)), )?) } else if !(as_.is_empty() || bs.is_empty()) { @@ -536,25 +535,25 @@ pub fn structurally_relate_tys>( (ty::FnDef(a_def_id, a_args), ty::FnDef(b_def_id, b_args)) if a_def_id == b_def_id => { let args = relation.relate_item_args(a_def_id, a_args, b_args)?; - Ok(Ty::new_fn_def(tcx, a_def_id, args)) + Ok(Ty::new_fn_def(cx, a_def_id, args)) } (ty::FnPtr(a_fty), ty::FnPtr(b_fty)) => { let fty = relation.relate(a_fty, b_fty)?; - Ok(Ty::new_fn_ptr(tcx, fty)) + Ok(Ty::new_fn_ptr(cx, fty)) } // Alias tend to mostly already be handled downstream due to normalization. (ty::Alias(a_kind, a_data), ty::Alias(b_kind, b_data)) => { let alias_ty = relation.relate(a_data, b_data)?; assert_eq!(a_kind, b_kind); - Ok(Ty::new_alias(tcx, a_kind, alias_ty)) + Ok(Ty::new_alias(cx, a_kind, alias_ty)) } (ty::Pat(a_ty, a_pat), ty::Pat(b_ty, b_pat)) => { let ty = relation.relate(a_ty, b_ty)?; let pat = relation.relate(a_pat, b_pat)?; - Ok(Ty::new_pat(tcx, ty, pat)) + Ok(Ty::new_pat(cx, ty, pat)) } _ => Err(TypeError::Sorts(ExpectedFound::new(true, a, b))), @@ -573,11 +572,11 @@ pub fn structurally_relate_consts>( mut b: I::Const, ) -> RelateResult { debug!("{}.structurally_relate_consts(a = {:?}, b = {:?})", relation.tag(), a, b); - let tcx = relation.tcx(); + let cx = relation.cx(); - if tcx.features().generic_const_exprs() { - a = tcx.expand_abstract_consts(a); - b = tcx.expand_abstract_consts(b); + if cx.features().generic_const_exprs() { + a = cx.expand_abstract_consts(a); + b = cx.expand_abstract_consts(b); } debug!("{}.structurally_relate_consts(normed_a = {:?}, normed_b = {:?})", relation.tag(), a, b); @@ -607,8 +606,8 @@ pub fn structurally_relate_consts>( // be stabilized. (ty::ConstKind::Unevaluated(au), ty::ConstKind::Unevaluated(bu)) if au.def == bu.def => { if cfg!(debug_assertions) { - let a_ty = tcx.type_of(au.def).instantiate(tcx, au.args); - let b_ty = tcx.type_of(bu.def).instantiate(tcx, bu.args); + let a_ty = cx.type_of(au.def).instantiate(cx, au.args); + let b_ty = cx.type_of(bu.def).instantiate(cx, bu.args); assert_eq!(a_ty, b_ty); } @@ -618,11 +617,11 @@ pub fn structurally_relate_consts>( au.args, bu.args, )?; - return Ok(Const::new_unevaluated(tcx, ty::UnevaluatedConst { def: au.def, args })); + return Ok(Const::new_unevaluated(cx, ty::UnevaluatedConst { def: au.def, args })); } (ty::ConstKind::Expr(ae), ty::ConstKind::Expr(be)) => { let expr = relation.relate(ae, be)?; - return Ok(Const::new_expr(tcx, expr)); + return Ok(Const::new_expr(cx, expr)); } _ => false, }; diff --git a/compiler/rustc_type_ir/src/solve/mod.rs b/compiler/rustc_type_ir/src/solve/mod.rs index 7934f996f0bd2..2449ac47db6fa 100644 --- a/compiler/rustc_type_ir/src/solve/mod.rs +++ b/compiler/rustc_type_ir/src/solve/mod.rs @@ -106,13 +106,13 @@ pub struct Goal { } impl Goal { - pub fn new(tcx: I, param_env: I::ParamEnv, predicate: impl Upcast) -> Goal { - Goal { param_env, predicate: predicate.upcast(tcx) } + pub fn new(cx: I, param_env: I::ParamEnv, predicate: impl Upcast) -> Goal { + Goal { param_env, predicate: predicate.upcast(cx) } } /// Updates the goal to one with a different `predicate` but the same `param_env`. - pub fn with(self, tcx: I, predicate: impl Upcast) -> Goal { - Goal { param_env: self.param_env, predicate: predicate.upcast(tcx) } + pub fn with(self, cx: I, predicate: impl Upcast) -> Goal { + Goal { param_env: self.param_env, predicate: predicate.upcast(cx) } } } diff --git a/compiler/rustc_type_ir/src/ty_kind/closure.rs b/compiler/rustc_type_ir/src/ty_kind/closure.rs index 24a7c0c67e90f..6c5bbbfd59ba9 100644 --- a/compiler/rustc_type_ir/src/ty_kind/closure.rs +++ b/compiler/rustc_type_ir/src/ty_kind/closure.rs @@ -136,9 +136,9 @@ pub struct ClosureArgsParts { impl ClosureArgs { /// Construct `ClosureArgs` from `ClosureArgsParts`, containing `Args` /// for the closure parent, alongside additional closure-specific components. - pub fn new(tcx: I, parts: ClosureArgsParts) -> ClosureArgs { + pub fn new(cx: I, parts: ClosureArgsParts) -> ClosureArgs { ClosureArgs { - args: tcx.mk_args_from_iter(parts.parent_args.iter().chain([ + args: cx.mk_args_from_iter(parts.parent_args.iter().chain([ parts.closure_kind_ty.into(), parts.closure_sig_as_fn_ptr_ty.into(), parts.tupled_upvars_ty.into(), @@ -258,9 +258,9 @@ pub struct CoroutineClosureArgsParts { } impl CoroutineClosureArgs { - pub fn new(tcx: I, parts: CoroutineClosureArgsParts) -> CoroutineClosureArgs { + pub fn new(cx: I, parts: CoroutineClosureArgsParts) -> CoroutineClosureArgs { CoroutineClosureArgs { - args: tcx.mk_args_from_iter(parts.parent_args.iter().chain([ + args: cx.mk_args_from_iter(parts.parent_args.iter().chain([ parts.closure_kind_ty.into(), parts.signature_parts_ty.into(), parts.tupled_upvars_ty.into(), @@ -409,14 +409,14 @@ impl CoroutineClosureSignature { /// When the kind and upvars are known, use the other helper functions. pub fn to_coroutine( self, - tcx: I, + cx: I, parent_args: I::GenericArgsSlice, coroutine_kind_ty: I::Ty, coroutine_def_id: I::DefId, tupled_upvars_ty: I::Ty, ) -> I::Ty { let coroutine_args = ty::CoroutineArgs::new( - tcx, + cx, ty::CoroutineArgsParts { parent_args, kind_ty: coroutine_kind_ty, @@ -428,7 +428,7 @@ impl CoroutineClosureSignature { }, ); - Ty::new_coroutine(tcx, coroutine_def_id, coroutine_args.args) + Ty::new_coroutine(cx, coroutine_def_id, coroutine_args.args) } /// Given known upvars and a [`ClosureKind`](ty::ClosureKind), compute the coroutine @@ -438,7 +438,7 @@ impl CoroutineClosureSignature { /// that the `ClosureKind` is actually supported by the coroutine-closure. pub fn to_coroutine_given_kind_and_upvars( self, - tcx: I, + cx: I, parent_args: I::GenericArgsSlice, coroutine_def_id: I::DefId, goal_kind: ty::ClosureKind, @@ -447,7 +447,7 @@ impl CoroutineClosureSignature { coroutine_captures_by_ref_ty: I::Ty, ) -> I::Ty { let tupled_upvars_ty = Self::tupled_upvars_by_closure_kind( - tcx, + cx, goal_kind, self.tupled_inputs_ty, closure_tupled_upvars_ty, @@ -456,9 +456,9 @@ impl CoroutineClosureSignature { ); self.to_coroutine( - tcx, + cx, parent_args, - Ty::from_coroutine_closure_kind(tcx, goal_kind), + Ty::from_coroutine_closure_kind(cx, goal_kind), coroutine_def_id, tupled_upvars_ty, ) @@ -474,7 +474,7 @@ impl CoroutineClosureSignature { /// lifetimes are related to the lifetime of the borrow on the closure made for /// the call. This allows borrowck to enforce the self-borrows correctly. pub fn tupled_upvars_by_closure_kind( - tcx: I, + cx: I, kind: ty::ClosureKind, tupled_inputs_ty: I::Ty, closure_tupled_upvars_ty: I::Ty, @@ -488,12 +488,12 @@ impl CoroutineClosureSignature { }; let coroutine_captures_by_ref_ty = sig.output().skip_binder().fold_with(&mut FoldEscapingRegions { - interner: tcx, + interner: cx, region: env_region, debruijn: ty::INNERMOST, }); Ty::new_tup_from_iter( - tcx, + cx, tupled_inputs_ty .tuple_fields() .iter() @@ -501,7 +501,7 @@ impl CoroutineClosureSignature { ) } ty::ClosureKind::FnOnce => Ty::new_tup_from_iter( - tcx, + cx, tupled_inputs_ty .tuple_fields() .iter() @@ -615,9 +615,9 @@ pub struct CoroutineArgsParts { impl CoroutineArgs { /// Construct `CoroutineArgs` from `CoroutineArgsParts`, containing `Args` /// for the coroutine parent, alongside additional coroutine-specific components. - pub fn new(tcx: I, parts: CoroutineArgsParts) -> CoroutineArgs { + pub fn new(cx: I, parts: CoroutineArgsParts) -> CoroutineArgs { CoroutineArgs { - args: tcx.mk_args_from_iter(parts.parent_args.iter().chain([ + args: cx.mk_args_from_iter(parts.parent_args.iter().chain([ parts.kind_ty.into(), parts.resume_ty.into(), parts.yield_ty.into(), diff --git a/compiler/rustc_type_ir_macros/src/lib.rs b/compiler/rustc_type_ir_macros/src/lib.rs index 000bcf2d3b27d..f5b90424afbc6 100644 --- a/compiler/rustc_type_ir_macros/src/lib.rs +++ b/compiler/rustc_type_ir_macros/src/lib.rs @@ -71,7 +71,7 @@ fn lift_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::TokenStream { wc.push(parse_quote! { #ty: ::rustc_type_ir::lift::Lift }); let bind = &bindings[index]; quote! { - #bind.lift_to_tcx(interner)? + #bind.lift_to_interner(interner)? } }) }); @@ -89,7 +89,7 @@ fn lift_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::TokenStream { quote! { type Lifted = #lifted_ty; - fn lift_to_tcx( + fn lift_to_interner( self, interner: J, ) -> Option { diff --git a/library/alloc/src/testing/crash_test.rs b/library/alloc/src/testing/crash_test.rs index bcf5f5f72510e..ff72f99b2cbed 100644 --- a/library/alloc/src/testing/crash_test.rs +++ b/library/alloc/src/testing/crash_test.rs @@ -1,5 +1,4 @@ -// We avoid relying on anything else in the crate, apart from the `Debug` trait. -use crate::fmt::Debug; +use crate::fmt::Debug; // the `Debug` trait is the only thing we use from `crate::fmt` use std::cmp::Ordering; use std::sync::atomic::{AtomicUsize, Ordering::SeqCst}; diff --git a/library/core/src/char/mod.rs b/library/core/src/char/mod.rs index 26b463e25ea62..3c641a2e01c93 100644 --- a/library/core/src/char/mod.rs +++ b/library/core/src/char/mod.rs @@ -24,7 +24,6 @@ mod convert; mod decode; mod methods; -// stable re-exports #[stable(feature = "try_from", since = "1.34.0")] pub use self::convert::CharTryFromError; #[stable(feature = "char_from_str", since = "1.20.0")] @@ -32,11 +31,10 @@ pub use self::convert::ParseCharError; #[stable(feature = "decode_utf16", since = "1.9.0")] pub use self::decode::{DecodeUtf16, DecodeUtf16Error}; -// perma-unstable re-exports #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")] -pub use self::methods::encode_utf16_raw; +pub use self::methods::encode_utf16_raw; // perma-unstable #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")] -pub use self::methods::encode_utf8_raw; +pub use self::methods::encode_utf8_raw; // perma-unstable use crate::ascii; use crate::error::Error; diff --git a/library/core/src/ffi/c_str.rs b/library/core/src/ffi/c_str.rs index 76752f22ed89a..563f0a324e3f1 100644 --- a/library/core/src/ffi/c_str.rs +++ b/library/core/src/ffi/c_str.rs @@ -781,8 +781,15 @@ const unsafe fn strlen(ptr: *const c_char) -> usize { pub struct Bytes<'a> { // since we know the string is nul-terminated, we only need one pointer ptr: NonNull, - phantom: PhantomData<&'a u8>, + phantom: PhantomData<&'a [c_char]>, } + +#[unstable(feature = "cstr_bytes", issue = "112115")] +unsafe impl Send for Bytes<'_> {} + +#[unstable(feature = "cstr_bytes", issue = "112115")] +unsafe impl Sync for Bytes<'_> {} + impl<'a> Bytes<'a> { #[inline] fn new(s: &'a CStr) -> Self { @@ -815,7 +822,7 @@ impl Iterator for Bytes<'_> { if ret == 0 { None } else { - self.ptr = self.ptr.offset(1); + self.ptr = self.ptr.add(1); Some(ret) } } @@ -825,6 +832,12 @@ impl Iterator for Bytes<'_> { fn size_hint(&self) -> (usize, Option) { if self.is_empty() { (0, Some(0)) } else { (1, None) } } + + #[inline] + fn count(self) -> usize { + // SAFETY: We always hold a valid pointer to a C string + unsafe { strlen(self.ptr.as_ptr().cast()) } + } } #[unstable(feature = "cstr_bytes", issue = "112115")] diff --git a/library/core/src/num/dec2flt/mod.rs b/library/core/src/num/dec2flt/mod.rs index a4bc8b1c9b0c3..9aac2332dce0d 100644 --- a/library/core/src/num/dec2flt/mod.rs +++ b/library/core/src/num/dec2flt/mod.rs @@ -250,8 +250,10 @@ pub fn dec2flt(s: &str) -> Result { None => return Err(pfe_invalid()), }; num.negative = negative; - if let Some(value) = num.try_fast_path::() { - return Ok(value); + if !cfg!(feature = "optimize_for_size") { + if let Some(value) = num.try_fast_path::() { + return Ok(value); + } } // If significant digits were truncated, then we can have rounding error diff --git a/library/core/src/prelude/common.rs b/library/core/src/prelude/common.rs index a6a1a055e2983..e38ef1e147c76 100644 --- a/library/core/src/prelude/common.rs +++ b/library/core/src/prelude/common.rs @@ -2,6 +2,9 @@ //! //! See the [module-level documentation](super) for more. +// No formatting: this file is nothing but re-exports, and their order is worth preserving. +#![cfg_attr(rustfmt, rustfmt::skip)] + // Re-exported core operators #[stable(feature = "core_prelude", since = "1.4.0")] #[doc(no_inline)] @@ -33,10 +36,7 @@ pub use crate::convert::{AsMut, AsRef, From, Into}; pub use crate::default::Default; #[stable(feature = "core_prelude", since = "1.4.0")] #[doc(no_inline)] -pub use crate::iter::{DoubleEndedIterator, ExactSizeIterator}; -#[stable(feature = "core_prelude", since = "1.4.0")] -#[doc(no_inline)] -pub use crate::iter::{Extend, IntoIterator, Iterator}; +pub use crate::iter::{DoubleEndedIterator, ExactSizeIterator, Extend, IntoIterator, Iterator}; #[stable(feature = "core_prelude", since = "1.4.0")] #[doc(no_inline)] pub use crate::option::Option::{self, None, Some}; diff --git a/library/core/src/prelude/mod.rs b/library/core/src/prelude/mod.rs index ca33ef160e88b..496b78439ea6c 100644 --- a/library/core/src/prelude/mod.rs +++ b/library/core/src/prelude/mod.rs @@ -4,6 +4,9 @@ //! This module is imported by default when `#![no_std]` is used in the same //! manner as the standard library's prelude. +// No formatting: this file is nothing but re-exports, and their order is worth preserving. +#![cfg_attr(rustfmt, rustfmt::skip)] + #![stable(feature = "core_prelude", since = "1.4.0")] mod common; diff --git a/library/core/src/ptr/mod.rs b/library/core/src/ptr/mod.rs index a8a47b69632f7..f2247e83ec5c5 100644 --- a/library/core/src/ptr/mod.rs +++ b/library/core/src/ptr/mod.rs @@ -1809,10 +1809,9 @@ pub(crate) const unsafe fn align_offset(p: *const T, a: usize) -> usiz // FIXME(#75598): Direct use of these intrinsics improves codegen significantly at opt-level <= // 1, where the method versions of these operations are not inlined. use intrinsics::{ - assume, cttz_nonzero, exact_div, mul_with_overflow, unchecked_rem, unchecked_sub, - wrapping_add, wrapping_mul, wrapping_sub, + assume, cttz_nonzero, exact_div, mul_with_overflow, unchecked_rem, unchecked_shl, + unchecked_shr, unchecked_sub, wrapping_add, wrapping_mul, wrapping_sub, }; - use intrinsics::{unchecked_shl, unchecked_shr}; /// Calculate multiplicative modular inverse of `x` modulo `m`. /// diff --git a/library/core/src/unicode/mod.rs b/library/core/src/unicode/mod.rs index e1faa407d54c5..5ddd9f7476dd8 100644 --- a/library/core/src/unicode/mod.rs +++ b/library/core/src/unicode/mod.rs @@ -1,6 +1,19 @@ #![unstable(feature = "unicode_internals", issue = "none")] #![allow(missing_docs)] +// The `pub use` ones are for use in alloc, and are not re-exported in std. + +pub(crate) use unicode_data::alphabetic::lookup as Alphabetic; +pub use unicode_data::case_ignorable::lookup as Case_Ignorable; +pub use unicode_data::cased::lookup as Cased; +pub(crate) use unicode_data::cc::lookup as Cc; +pub use unicode_data::conversions; +pub(crate) use unicode_data::grapheme_extend::lookup as Grapheme_Extend; +pub(crate) use unicode_data::lowercase::lookup as Lowercase; +pub(crate) use unicode_data::n::lookup as N; +pub(crate) use unicode_data::uppercase::lookup as Uppercase; +pub(crate) use unicode_data::white_space::lookup as White_Space; + pub(crate) mod printable; mod unicode_data; @@ -16,16 +29,3 @@ mod unicode_data; /// [Unicode 11.0 or later, Section 3.1 Versions of the Unicode Standard](https://www.unicode.org/versions/Unicode11.0.0/ch03.pdf#page=4). #[stable(feature = "unicode_version", since = "1.45.0")] pub const UNICODE_VERSION: (u8, u8, u8) = unicode_data::UNICODE_VERSION; - -// For use in alloc, not re-exported in std. -pub use unicode_data::{ - case_ignorable::lookup as Case_Ignorable, cased::lookup as Cased, conversions, -}; - -pub(crate) use unicode_data::alphabetic::lookup as Alphabetic; -pub(crate) use unicode_data::cc::lookup as Cc; -pub(crate) use unicode_data::grapheme_extend::lookup as Grapheme_Extend; -pub(crate) use unicode_data::lowercase::lookup as Lowercase; -pub(crate) use unicode_data::n::lookup as N; -pub(crate) use unicode_data::uppercase::lookup as Uppercase; -pub(crate) use unicode_data::white_space::lookup as White_Space; diff --git a/library/std/src/env.rs b/library/std/src/env.rs index 36add02d68c5c..fc9b8cfd46d65 100644 --- a/library/std/src/env.rs +++ b/library/std/src/env.rs @@ -120,11 +120,8 @@ pub struct VarsOs { /// # Examples /// /// ``` -/// use std::env; -/// -/// // We will iterate through the references to the element returned by -/// // env::vars(); -/// for (key, value) in env::vars() { +/// // Print all environment variables. +/// for (key, value) in std::env::vars() { /// println!("{key}: {value}"); /// } /// ``` @@ -150,11 +147,8 @@ pub fn vars() -> Vars { /// # Examples /// /// ``` -/// use std::env; -/// -/// // We will iterate through the references to the element returned by -/// // env::vars_os(); -/// for (key, value) in env::vars_os() { +/// // Print all environment variables. +/// for (key, value) in std::env::vars_os() { /// println!("{key:?}: {value:?}"); /// } /// ``` diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index d4d68c2068d8a..f0a73a308a4a4 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -470,7 +470,6 @@ pub mod rt; // The Rust prelude pub mod prelude; -// Public module declarations and re-exports #[stable(feature = "rust1", since = "1.0.0")] pub use alloc_crate::borrow; #[stable(feature = "rust1", since = "1.0.0")] diff --git a/library/std/src/os/fortanix_sgx/mod.rs b/library/std/src/os/fortanix_sgx/mod.rs index 39a42f4e17fec..b31dc06f8dfbd 100644 --- a/library/std/src/os/fortanix_sgx/mod.rs +++ b/library/std/src/os/fortanix_sgx/mod.rs @@ -28,7 +28,6 @@ pub mod usercalls { pub use crate::sys::abi::usercalls::raw::{do_usercall, Usercalls as UsercallNrs}; pub use crate::sys::abi::usercalls::raw::{Register, RegisterArgument, ReturnValue}; - // fortanix-sgx-abi re-exports pub use crate::sys::abi::usercalls::raw::Error; pub use crate::sys::abi::usercalls::raw::{ ByteBuffer, Cancel, FifoDescriptor, Return, Usercall, diff --git a/library/std/src/os/uefi/mod.rs b/library/std/src/os/uefi/mod.rs index 8ef05eee1f4e7..b42d796b28f69 100644 --- a/library/std/src/os/uefi/mod.rs +++ b/library/std/src/os/uefi/mod.rs @@ -2,6 +2,7 @@ #![unstable(feature = "uefi_std", issue = "100499")] #![doc(cfg(target_os = "uefi"))] +#![forbid(unsafe_op_in_unsafe_fn)] pub mod env; #[path = "../windows/ffi.rs"] diff --git a/library/std/src/os/xous/mod.rs b/library/std/src/os/xous/mod.rs index 153694a89a78d..4b21695c4ac7e 100644 --- a/library/std/src/os/xous/mod.rs +++ b/library/std/src/os/xous/mod.rs @@ -1,5 +1,6 @@ #![stable(feature = "rust1", since = "1.0.0")] #![doc(cfg(target_os = "xous"))] +#![forbid(unsafe_op_in_unsafe_fn)] pub mod ffi; diff --git a/library/std/src/prelude/common.rs b/library/std/src/prelude/common.rs index 055ab7eb6d987..b231bd871b3b4 100644 --- a/library/std/src/prelude/common.rs +++ b/library/std/src/prelude/common.rs @@ -2,6 +2,9 @@ //! //! See the [module-level documentation](super) for more. +// No formatting: this file is nothing but re-exports, and their order is worth preserving. +#![cfg_attr(rustfmt, rustfmt::skip)] + // Re-exported core operators #[stable(feature = "rust1", since = "1.0.0")] #[doc(no_inline)] diff --git a/library/std/src/prelude/mod.rs b/library/std/src/prelude/mod.rs index 2d4639342bf85..0c610ba67e65c 100644 --- a/library/std/src/prelude/mod.rs +++ b/library/std/src/prelude/mod.rs @@ -95,6 +95,9 @@ //! [book-enums]: ../../book/ch06-01-defining-an-enum.html //! [book-iter]: ../../book/ch13-02-iterators.html +// No formatting: this file is nothing but re-exports, and their order is worth preserving. +#![cfg_attr(rustfmt, rustfmt::skip)] + #![stable(feature = "rust1", since = "1.0.0")] mod common; diff --git a/library/std/src/rt.rs b/library/std/src/rt.rs index d030017cfb4ec..deb4a8fa7eed0 100644 --- a/library/std/src/rt.rs +++ b/library/std/src/rt.rs @@ -16,7 +16,6 @@ #![deny(unsafe_op_in_unsafe_fn)] #![allow(unused_macros)] -// Re-export some of our utilities which are expected by other crates. pub use crate::panicking::{begin_panic, panic_count}; pub use core::panicking::{panic_display, panic_fmt}; diff --git a/library/std/src/sys/pal/hermit/futex.rs b/library/std/src/sys/pal/hermit/futex.rs index b2d74d1311bcb..21c5facd52fbd 100644 --- a/library/std/src/sys/pal/hermit/futex.rs +++ b/library/std/src/sys/pal/hermit/futex.rs @@ -3,6 +3,11 @@ use crate::ptr::null; use crate::sync::atomic::AtomicU32; use crate::time::Duration; +/// An atomic for use as a futex that is at least 8-bits but may be larger. +pub type SmallAtomic = AtomicU32; +/// Must be the underlying type of SmallAtomic +pub type SmallPrimitive = u32; + pub fn futex_wait(futex: &AtomicU32, expected: u32, timeout: Option) -> bool { // Calculate the timeout as a relative timespec. // diff --git a/library/std/src/sys/pal/uefi/mod.rs b/library/std/src/sys/pal/uefi/mod.rs index 408031a461665..4d50d9e8c3d9c 100644 --- a/library/std/src/sys/pal/uefi/mod.rs +++ b/library/std/src/sys/pal/uefi/mod.rs @@ -11,6 +11,7 @@ //! //! [`OsStr`]: crate::ffi::OsStr //! [`OsString`]: crate::ffi::OsString +#![forbid(unsafe_op_in_unsafe_fn)] pub mod alloc; pub mod args; diff --git a/library/std/src/sys/pal/unix/futex.rs b/library/std/src/sys/pal/unix/futex.rs index 26161a9af79d8..b8900da4cddb5 100644 --- a/library/std/src/sys/pal/unix/futex.rs +++ b/library/std/src/sys/pal/unix/futex.rs @@ -11,6 +11,11 @@ use crate::sync::atomic::AtomicU32; use crate::time::Duration; +/// An atomic for use as a futex that is at least 8-bits but may be larger. +pub type SmallAtomic = AtomicU32; +/// Must be the underlying type of SmallAtomic +pub type SmallPrimitive = u32; + /// Wait for a futex_wake operation to wake us. /// /// Returns directly if the futex doesn't hold the expected value. diff --git a/library/std/src/sys/pal/wasi/mod.rs b/library/std/src/sys/pal/wasi/mod.rs index 8dfb733043e77..d8fe06d1973c9 100644 --- a/library/std/src/sys/pal/wasi/mod.rs +++ b/library/std/src/sys/pal/wasi/mod.rs @@ -39,12 +39,15 @@ pub mod time; #[deny(unsafe_op_in_unsafe_fn)] #[allow(unused)] mod common; + pub use common::*; mod helpers; -// These exports are listed individually to work around Rust's glob import -// conflict rules. If we glob export `helpers` and `common` together, then -// the compiler complains about conflicts. + +// The following exports are listed individually to work around Rust's glob +// import conflict rules. If we glob export `helpers` and `common` together, +// then the compiler complains about conflicts. + pub use helpers::abort_internal; pub use helpers::decode_error_kind; use helpers::err2io; diff --git a/library/std/src/sys/pal/wasip2/mod.rs b/library/std/src/sys/pal/wasip2/mod.rs index 7af0917b8ed42..0930d2e22fa8d 100644 --- a/library/std/src/sys/pal/wasip2/mod.rs +++ b/library/std/src/sys/pal/wasip2/mod.rs @@ -41,13 +41,16 @@ pub mod time; #[deny(unsafe_op_in_unsafe_fn)] #[allow(unused)] mod common; + pub use common::*; #[path = "../wasi/helpers.rs"] mod helpers; -// These exports are listed individually to work around Rust's glob import -// conflict rules. If we glob export `helpers` and `common` together, then -// the compiler complains about conflicts. + +// The following exports are listed individually to work around Rust's glob +// import conflict rules. If we glob export `helpers` and `common` together, +// then the compiler complains about conflicts. + pub use helpers::abort_internal; pub use helpers::decode_error_kind; use helpers::err2io; diff --git a/library/std/src/sys/pal/wasm/atomics/futex.rs b/library/std/src/sys/pal/wasm/atomics/futex.rs index a21b71efbbc69..3584138ca0447 100644 --- a/library/std/src/sys/pal/wasm/atomics/futex.rs +++ b/library/std/src/sys/pal/wasm/atomics/futex.rs @@ -6,6 +6,11 @@ use core::arch::wasm64 as wasm; use crate::sync::atomic::AtomicU32; use crate::time::Duration; +/// An atomic for use as a futex that is at least 8-bits but may be larger. +pub type SmallAtomic = AtomicU32; +/// Must be the underlying type of SmallAtomic +pub type SmallPrimitive = u32; + /// Wait for a futex_wake operation to wake us. /// /// Returns directly if the futex doesn't hold the expected value. diff --git a/library/std/src/sys/pal/windows/futex.rs b/library/std/src/sys/pal/windows/futex.rs index 08b7fe300dc3c..cb802fdd9c96d 100644 --- a/library/std/src/sys/pal/windows/futex.rs +++ b/library/std/src/sys/pal/windows/futex.rs @@ -10,6 +10,11 @@ use core::sync::atomic::{ }; use core::time::Duration; +/// An atomic for use as a futex that is at least 8-bits but may be larger. +pub type SmallAtomic = AtomicU8; +/// Must be the underlying type of SmallAtomic +pub type SmallPrimitive = u8; + pub unsafe trait Waitable { type Atomic; } diff --git a/library/std/src/sys/pal/xous/mod.rs b/library/std/src/sys/pal/xous/mod.rs index a28a52e305e22..961d45c5e834f 100644 --- a/library/std/src/sys/pal/xous/mod.rs +++ b/library/std/src/sys/pal/xous/mod.rs @@ -1,4 +1,4 @@ -#![deny(unsafe_op_in_unsafe_fn)] +#![forbid(unsafe_op_in_unsafe_fn)] pub mod alloc; #[path = "../unsupported/args.rs"] diff --git a/library/std/src/sys/pal/zkvm/alloc.rs b/library/std/src/sys/pal/zkvm/alloc.rs index fd333f1215150..2fdca22352470 100644 --- a/library/std/src/sys/pal/zkvm/alloc.rs +++ b/library/std/src/sys/pal/zkvm/alloc.rs @@ -5,7 +5,7 @@ use crate::alloc::{GlobalAlloc, Layout, System}; unsafe impl GlobalAlloc for System { #[inline] unsafe fn alloc(&self, layout: Layout) -> *mut u8 { - abi::sys_alloc_aligned(layout.size(), layout.align()) + unsafe { abi::sys_alloc_aligned(layout.size(), layout.align()) } } #[inline] diff --git a/library/std/src/sys/pal/zkvm/mod.rs b/library/std/src/sys/pal/zkvm/mod.rs index bacde9d880c2c..651f25d66236b 100644 --- a/library/std/src/sys/pal/zkvm/mod.rs +++ b/library/std/src/sys/pal/zkvm/mod.rs @@ -6,6 +6,7 @@ //! This is all super highly experimental and not actually intended for //! wide/production use yet, it's still all in the experimental category. This //! will likely change over time. +#![forbid(unsafe_op_in_unsafe_fn)] const WORD_SIZE: usize = core::mem::size_of::(); diff --git a/library/std/src/sys/personality/dwarf/mod.rs b/library/std/src/sys/personality/dwarf/mod.rs index 652fbe95a14d1..89f7f133e21b4 100644 --- a/library/std/src/sys/personality/dwarf/mod.rs +++ b/library/std/src/sys/personality/dwarf/mod.rs @@ -17,32 +17,30 @@ pub struct DwarfReader { pub ptr: *const u8, } -#[repr(C, packed)] -struct Unaligned(T); - +#[forbid(unsafe_op_in_unsafe_fn)] impl DwarfReader { pub fn new(ptr: *const u8) -> DwarfReader { DwarfReader { ptr } } - // DWARF streams are packed, so e.g., a u32 would not necessarily be aligned - // on a 4-byte boundary. This may cause problems on platforms with strict - // alignment requirements. By wrapping data in a "packed" struct, we are - // telling the backend to generate "misalignment-safe" code. + /// Read a type T and then bump the pointer by that amount. + /// + /// DWARF streams are "packed", so all types must be read at align 1. pub unsafe fn read(&mut self) -> T { - let Unaligned(result) = *(self.ptr as *const Unaligned); - self.ptr = self.ptr.add(mem::size_of::()); - result + unsafe { + let result = self.ptr.cast::().read_unaligned(); + self.ptr = self.ptr.byte_add(mem::size_of::()); + result + } } - // ULEB128 and SLEB128 encodings are defined in Section 7.6 - "Variable - // Length Data". + /// ULEB128 and SLEB128 encodings are defined in Section 7.6 - "Variable Length Data". pub unsafe fn read_uleb128(&mut self) -> u64 { let mut shift: usize = 0; let mut result: u64 = 0; let mut byte: u8; loop { - byte = self.read::(); + byte = unsafe { self.read::() }; result |= ((byte & 0x7F) as u64) << shift; shift += 7; if byte & 0x80 == 0 { @@ -57,7 +55,7 @@ impl DwarfReader { let mut result: u64 = 0; let mut byte: u8; loop { - byte = self.read::(); + byte = unsafe { self.read::() }; result |= ((byte & 0x7F) as u64) << shift; shift += 7; if byte & 0x80 == 0 { diff --git a/library/std/src/sys/sync/mutex/futex.rs b/library/std/src/sys/sync/mutex/futex.rs index 7427cae94d68a..81afa94b14787 100644 --- a/library/std/src/sys/sync/mutex/futex.rs +++ b/library/std/src/sys/sync/mutex/futex.rs @@ -1,19 +1,8 @@ -use crate::sync::atomic::{ - self, - Ordering::{Acquire, Relaxed, Release}, -}; -use crate::sys::futex::{futex_wait, futex_wake}; - -cfg_if::cfg_if! { -if #[cfg(windows)] { - // On Windows we can have a smol futex - type Atomic = atomic::AtomicU8; - type State = u8; -} else { - type Atomic = atomic::AtomicU32; - type State = u32; -} -} +use crate::sync::atomic::Ordering::{Acquire, Relaxed, Release}; +use crate::sys::futex::{self, futex_wait, futex_wake}; + +type Atomic = futex::SmallAtomic; +type State = futex::SmallPrimitive; pub struct Mutex { futex: Atomic, diff --git a/library/std/src/sys/sync/thread_parking/futex.rs b/library/std/src/sys/sync/thread_parking/futex.rs index 588e7b27826f6..034eececb2a28 100644 --- a/library/std/src/sys/sync/thread_parking/futex.rs +++ b/library/std/src/sys/sync/thread_parking/futex.rs @@ -1,15 +1,18 @@ +#![forbid(unsafe_op_in_unsafe_fn)] use crate::pin::Pin; -use crate::sync::atomic::AtomicU32; use crate::sync::atomic::Ordering::{Acquire, Release}; -use crate::sys::futex::{futex_wait, futex_wake}; +use crate::sys::futex::{self, futex_wait, futex_wake}; use crate::time::Duration; -const PARKED: u32 = u32::MAX; -const EMPTY: u32 = 0; -const NOTIFIED: u32 = 1; +type Atomic = futex::SmallAtomic; +type State = futex::SmallPrimitive; + +const PARKED: State = State::MAX; +const EMPTY: State = 0; +const NOTIFIED: State = 1; pub struct Parker { - state: AtomicU32, + state: Atomic, } // Notes about memory ordering: @@ -36,7 +39,7 @@ impl Parker { /// Construct the futex parker. The UNIX parker implementation /// requires this to happen in-place. pub unsafe fn new_in_place(parker: *mut Parker) { - parker.write(Self { state: AtomicU32::new(EMPTY) }); + unsafe { parker.write(Self { state: Atomic::new(EMPTY) }) }; } // Assumes this is only called by the thread that owns the Parker, diff --git a/library/std/src/sys/sync/thread_parking/mod.rs b/library/std/src/sys/sync/thread_parking/mod.rs index ed1a6437faaaf..0ebc5e093ee2a 100644 --- a/library/std/src/sys/sync/thread_parking/mod.rs +++ b/library/std/src/sys/sync/thread_parking/mod.rs @@ -1,5 +1,6 @@ cfg_if::cfg_if! { if #[cfg(any( + all(target_os = "windows", not(target_vendor = "win7")), target_os = "linux", target_os = "android", all(target_arch = "wasm32", target_feature = "atomics"), @@ -18,9 +19,9 @@ cfg_if::cfg_if! { ))] { mod id; pub use id::Parker; - } else if #[cfg(target_os = "windows")] { - mod windows; - pub use windows::Parker; + } else if #[cfg(target_vendor = "win7")] { + mod windows7; + pub use windows7::Parker; } else if #[cfg(all(target_vendor = "apple", not(miri)))] { mod darwin; pub use darwin::Parker; diff --git a/library/std/src/sys/sync/thread_parking/windows.rs b/library/std/src/sys/sync/thread_parking/windows7.rs similarity index 100% rename from library/std/src/sys/sync/thread_parking/windows.rs rename to library/std/src/sys/sync/thread_parking/windows7.rs diff --git a/library/test/src/lib.rs b/library/test/src/lib.rs index 7aff7fe1fdd68..71cb796b93705 100644 --- a/library/test/src/lib.rs +++ b/library/test/src/lib.rs @@ -25,7 +25,6 @@ #![feature(test)] #![allow(internal_features)] -// Public reexports pub use self::bench::{black_box, Bencher}; pub use self::console::run_tests_console; pub use self::options::{ColorConfig, Options, OutputFormat, RunIgnored, ShouldPanic}; diff --git a/src/tools/run-make-support/Cargo.toml b/src/tools/run-make-support/Cargo.toml index 681284b1a489c..b391373283921 100644 --- a/src/tools/run-make-support/Cargo.toml +++ b/src/tools/run-make-support/Cargo.toml @@ -10,6 +10,4 @@ similar = "2.5.0" wasmparser = "0.118.2" regex = "1.8" # 1.8 to avoid memchr 2.6.0, as 2.5.0 is pinned in the workspace gimli = "0.31.0" -ar = "0.9.0" - build_helper = { path = "../build_helper" } diff --git a/src/tools/run-make-support/src/cc.rs b/src/tools/run-make-support/src/cc.rs index 31b9e8a23b88b..75a20a21a3107 100644 --- a/src/tools/run-make-support/src/cc.rs +++ b/src/tools/run-make-support/src/cc.rs @@ -1,7 +1,7 @@ use std::path::Path; use crate::command::Command; -use crate::{bin_name, cygpath_windows, env_var, is_msvc, is_windows, uname}; +use crate::{cygpath_windows, env_var, is_msvc, is_windows, uname}; /// Construct a new platform-specific C compiler invocation. /// @@ -68,9 +68,14 @@ impl Cc { // endif // ``` + let mut path = std::path::PathBuf::from(name); + if is_msvc() { - let fe_path = cygpath_windows(bin_name(name)); - let fo_path = cygpath_windows(format!("{name}.obj")); + path.set_extension("exe"); + let fe_path = cygpath_windows(&path); + path.set_extension(""); + path.set_extension("obj"); + let fo_path = cygpath_windows(path); self.cmd.arg(format!("-Fe:{fe_path}")); self.cmd.arg(format!("-Fo:{fo_path}")); } else { diff --git a/src/tools/run-make-support/src/lib.rs b/src/tools/run-make-support/src/lib.rs index e5f1ce1bf345e..cec2cedd15c9f 100644 --- a/src/tools/run-make-support/src/lib.rs +++ b/src/tools/run-make-support/src/lib.rs @@ -30,8 +30,8 @@ pub use cc::{cc, extra_c_flags, extra_cxx_flags, Cc}; pub use clang::{clang, Clang}; pub use diff::{diff, Diff}; pub use llvm::{ - llvm_filecheck, llvm_objdump, llvm_profdata, llvm_readobj, LlvmFilecheck, LlvmObjdump, - LlvmProfdata, LlvmReadobj, + llvm_ar, llvm_filecheck, llvm_objdump, llvm_profdata, llvm_readobj, LlvmAr, LlvmFilecheck, + LlvmObjdump, LlvmProfdata, LlvmReadobj, }; pub use run::{cmd, run, run_fail, run_with_args}; pub use rustc::{aux_build, bare_rustc, rustc, Rustc}; @@ -61,19 +61,6 @@ pub fn target() -> String { env_var("TARGET") } -/// `AR` -#[track_caller] -pub fn ar(inputs: &[impl AsRef], output_path: impl AsRef) { - let output = fs::File::create(&output_path).expect(&format!( - "the file in path \"{}\" could not be created", - output_path.as_ref().display() - )); - let mut builder = ar::Builder::new(output); - for input in inputs { - builder.append_path(input).unwrap(); - } -} - /// Check if target is windows-like. #[must_use] pub fn is_windows() -> bool { @@ -294,6 +281,26 @@ pub fn not_contains>(path: P, expected: &str) -> bool { !path.as_ref().file_name().is_some_and(|name| name.to_str().unwrap().contains(expected)) } +/// Builds a static lib (`.lib` on Windows MSVC and `.a` for the rest) with the given name. +#[track_caller] +pub fn build_native_static_lib(lib_name: &str) -> PathBuf { + let obj_file = if is_msvc() { format!("{lib_name}") } else { format!("{lib_name}.o") }; + let src = format!("{lib_name}.c"); + let lib_path = static_lib_name(lib_name); + if is_msvc() { + cc().arg("-c").out_exe(&obj_file).input(src).run(); + } else { + cc().arg("-v").arg("-c").out_exe(&obj_file).input(src).run(); + }; + let obj_file = if is_msvc() { + PathBuf::from(format!("{lib_name}.obj")) + } else { + PathBuf::from(format!("{lib_name}.o")) + }; + llvm_ar().obj_to_ar().output_input(&lib_path, &obj_file).run(); + path(lib_path) +} + /// Returns true if the filename at `path` is not in `expected`. pub fn filename_not_in_denylist, V: AsRef<[String]>>(path: P, expected: V) -> bool { let expected = expected.as_ref(); diff --git a/src/tools/run-make-support/src/llvm.rs b/src/tools/run-make-support/src/llvm.rs index 4c9e9a5323025..064dc62a4afa2 100644 --- a/src/tools/run-make-support/src/llvm.rs +++ b/src/tools/run-make-support/src/llvm.rs @@ -29,6 +29,12 @@ pub fn llvm_objdump() -> LlvmObjdump { LlvmObjdump::new() } +/// Construct a new `llvm-ar` invocation. This assumes that `llvm-ar` is available +/// at `$LLVM_BIN_DIR/llvm-ar`. +pub fn llvm_ar() -> LlvmAr { + LlvmAr::new() +} + /// A `llvm-readobj` invocation builder. #[derive(Debug)] #[must_use] @@ -57,10 +63,18 @@ pub struct LlvmObjdump { cmd: Command, } +/// A `llvm-ar` invocation builder. +#[derive(Debug)] +#[must_use] +pub struct LlvmAr { + cmd: Command, +} + crate::impl_common_helpers!(LlvmReadobj); crate::impl_common_helpers!(LlvmProfdata); crate::impl_common_helpers!(LlvmFilecheck); crate::impl_common_helpers!(LlvmObjdump); +crate::impl_common_helpers!(LlvmAr); /// Generate the path to the bin directory of LLVM. #[must_use] @@ -204,3 +218,26 @@ impl LlvmObjdump { self } } + +impl LlvmAr { + /// Construct a new `llvm-ar` invocation. This assumes that `llvm-ar` is available + /// at `$LLVM_BIN_DIR/llvm-ar`. + pub fn new() -> Self { + let llvm_ar = llvm_bin_dir().join("llvm-ar"); + let cmd = Command::new(llvm_ar); + Self { cmd } + } + + pub fn obj_to_ar(&mut self) -> &mut Self { + self.cmd.arg("rcus"); + self + } + + /// Provide an output, then an input file. Bundled in one function, as llvm-ar has + /// no "--output"-style flag. + pub fn output_input(&mut self, out: impl AsRef, input: impl AsRef) -> &mut Self { + self.cmd.arg(out.as_ref()); + self.cmd.arg(input.as_ref()); + self + } +} diff --git a/src/tools/run-make-support/src/rustc.rs b/src/tools/run-make-support/src/rustc.rs index ae200d5143107..6b08608cc62f5 100644 --- a/src/tools/run-make-support/src/rustc.rs +++ b/src/tools/run-make-support/src/rustc.rs @@ -242,6 +242,19 @@ impl Rustc { self } + /// Add a directory to the library search path with a restriction, where `kind` is a dependency + /// type. Equivalent to `-L KIND=PATH` in rustc. + pub fn specific_library_search_path>( + &mut self, + kind: &str, + path: P, + ) -> &mut Self { + assert!(["dependency", "native", "all", "framework", "crate"].contains(&kind)); + let path = path.as_ref().to_string_lossy(); + self.cmd.arg(format!("-L{kind}={path}")); + self + } + /// Override the system root. Equivalent to `--sysroot` in rustc. pub fn sysroot>(&mut self, path: P) -> &mut Self { self.cmd.arg("--sysroot"); diff --git a/src/tools/tidy/src/allowed_run_make_makefiles.txt b/src/tools/tidy/src/allowed_run_make_makefiles.txt index e6376a8df0feb..2e26f9344b899 100644 --- a/src/tools/tidy/src/allowed_run_make_makefiles.txt +++ b/src/tools/tidy/src/allowed_run_make_makefiles.txt @@ -10,7 +10,6 @@ run-make/c-unwind-abi-catch-panic/Makefile run-make/cat-and-grep-sanity-check/Makefile run-make/cdylib-dylib-linkage/Makefile run-make/compiler-lookup-paths-2/Makefile -run-make/compiler-lookup-paths/Makefile run-make/compiler-rt-works-on-mingw/Makefile run-make/crate-hash-rustc-version/Makefile run-make/cross-lang-lto-clang/Makefile @@ -21,7 +20,6 @@ run-make/dep-info-doesnt-run-much/Makefile run-make/dep-info-spaces/Makefile run-make/dep-info/Makefile run-make/dump-ice-to-disk/Makefile -run-make/dump-mono-stats/Makefile run-make/emit-to-stdout/Makefile run-make/export-executable-symbols/Makefile run-make/extern-diff-internal-name/Makefile @@ -93,7 +91,6 @@ run-make/pgo-indirect-call-promotion/Makefile run-make/pointer-auth-link-with-c/Makefile run-make/print-calling-conventions/Makefile run-make/print-target-list/Makefile -run-make/prune-link-args/Makefile run-make/raw-dylib-alt-calling-convention/Makefile run-make/raw-dylib-c/Makefile run-make/raw-dylib-import-name-type/Makefile diff --git a/tests/run-make/compiler-lookup-paths/Makefile b/tests/run-make/compiler-lookup-paths/Makefile deleted file mode 100644 index fc0cbde4c3524..0000000000000 --- a/tests/run-make/compiler-lookup-paths/Makefile +++ /dev/null @@ -1,44 +0,0 @@ -# rustc supports different types of lookup paths, such as dependency, native or crate. This test checks that these lookup paths are functional and result in functional compilation. -# See https://github.com/rust-lang/rust/pull/19941 - -include ../tools.mk - -# ignore-wasm32 (need a C compiler) -# ignore-wasm64 (need a C compiler) - -all: $(TMPDIR)/libnative.a - mkdir -p $(TMPDIR)/crate - mkdir -p $(TMPDIR)/native - mv $(TMPDIR)/libnative.a $(TMPDIR)/native - $(RUSTC) a.rs - mv $(TMPDIR)/liba.rlib $(TMPDIR)/crate - $(RUSTC) b.rs -L native=$(TMPDIR)/crate && exit 1 || exit 0 - $(RUSTC) b.rs -L dependency=$(TMPDIR)/crate && exit 1 || exit 0 - $(RUSTC) b.rs -L crate=$(TMPDIR)/crate - $(RUSTC) b.rs -L all=$(TMPDIR)/crate - $(RUSTC) c.rs -L native=$(TMPDIR)/crate && exit 1 || exit 0 - $(RUSTC) c.rs -L crate=$(TMPDIR)/crate && exit 1 || exit 0 - $(RUSTC) c.rs -L dependency=$(TMPDIR)/crate - $(RUSTC) c.rs -L all=$(TMPDIR)/crate - $(RUSTC) d.rs -L dependency=$(TMPDIR)/native && exit 1 || exit 0 - $(RUSTC) d.rs -L crate=$(TMPDIR)/native && exit 1 || exit 0 - $(RUSTC) d.rs -L native=$(TMPDIR)/native - $(RUSTC) d.rs -L all=$(TMPDIR)/native - # Deduplication tests: - # Same hash, no errors. - mkdir -p $(TMPDIR)/e1 - mkdir -p $(TMPDIR)/e2 - $(RUSTC) e.rs -o $(TMPDIR)/e1/libe.rlib - $(RUSTC) e.rs -o $(TMPDIR)/e2/libe.rlib - $(RUSTC) f.rs -L $(TMPDIR)/e1 -L $(TMPDIR)/e2 - $(RUSTC) f.rs -L crate=$(TMPDIR)/e1 -L $(TMPDIR)/e2 - $(RUSTC) f.rs -L crate=$(TMPDIR)/e1 -L crate=$(TMPDIR)/e2 - # Different hash, errors. - $(RUSTC) e2.rs -o $(TMPDIR)/e2/libe.rlib - $(RUSTC) f.rs -L $(TMPDIR)/e1 -L $(TMPDIR)/e2 && exit 1 || exit 0 - $(RUSTC) f.rs -L crate=$(TMPDIR)/e1 -L $(TMPDIR)/e2 && exit 1 || exit 0 - $(RUSTC) f.rs -L crate=$(TMPDIR)/e1 -L crate=$(TMPDIR)/e2 && exit 1 || exit 0 - # Native/dependency paths don't cause errors. - $(RUSTC) f.rs -L native=$(TMPDIR)/e1 -L $(TMPDIR)/e2 - $(RUSTC) f.rs -L dependency=$(TMPDIR)/e1 -L $(TMPDIR)/e2 - $(RUSTC) f.rs -L dependency=$(TMPDIR)/e1 -L crate=$(TMPDIR)/e2 diff --git a/tests/run-make/compiler-lookup-paths/rmake.rs b/tests/run-make/compiler-lookup-paths/rmake.rs new file mode 100644 index 0000000000000..0f79185282134 --- /dev/null +++ b/tests/run-make/compiler-lookup-paths/rmake.rs @@ -0,0 +1,84 @@ +// Since #19941, rustc can accept specifications on its library search paths. +// This test runs Rust programs with varied library dependencies, expecting them +// to succeed or fail depending on the situation. +// The second part of the tests also checks that libraries with an incorrect hash +// fail to be used by the compiler. +// See https://github.com/rust-lang/rust/pull/19941 + +//@ ignore-wasm32 +//@ ignore-wasm64 +// Reason: a C compiler is required for build_native_static_lib + +use run_make_support::{build_native_static_lib, fs_wrapper, rustc, static_lib_name}; + +fn main() { + build_native_static_lib("native"); + let lib_native = static_lib_name("native"); + fs_wrapper::create_dir_all("crate"); + fs_wrapper::create_dir_all("native"); + fs_wrapper::rename(&lib_native, format!("native/{}", &lib_native)); + rustc().input("a.rs").run(); + fs_wrapper::rename("liba.rlib", "crate/liba.rlib"); + rustc().input("b.rs").specific_library_search_path("native", "crate").run_fail(); + rustc().input("b.rs").specific_library_search_path("dependency", "crate").run_fail(); + rustc().input("b.rs").specific_library_search_path("crate", "crate").run(); + rustc().input("b.rs").specific_library_search_path("all", "crate").run(); + + rustc().input("c.rs").specific_library_search_path("native", "crate").run_fail(); + rustc().input("c.rs").specific_library_search_path("crate", "crate").run_fail(); + rustc().input("c.rs").specific_library_search_path("dependency", "crate").run(); + rustc().input("c.rs").specific_library_search_path("all", "crate").run(); + + rustc().input("d.rs").specific_library_search_path("dependency", "native").run_fail(); + rustc().input("d.rs").specific_library_search_path("crate", "native").run_fail(); + rustc().input("d.rs").specific_library_search_path("native", "native").run(); + rustc().input("d.rs").specific_library_search_path("all", "native").run(); + + // Deduplication tests. + fs_wrapper::create_dir_all("e1"); + fs_wrapper::create_dir_all("e2"); + + rustc().input("e.rs").output("e1/libe.rlib").run(); + rustc().input("e.rs").output("e2/libe.rlib").run(); + // If the library hash is correct, compilation should succeed. + rustc().input("f.rs").library_search_path("e1").library_search_path("e2").run(); + rustc() + .input("f.rs") + .specific_library_search_path("crate", "e1") + .library_search_path("e2") + .run(); + rustc() + .input("f.rs") + .specific_library_search_path("crate", "e1") + .specific_library_search_path("crate", "e2") + .run(); + // If the library has a different hash, errors should occur. + rustc().input("e2.rs").output("e2/libe.rlib").run(); + rustc().input("f.rs").library_search_path("e1").library_search_path("e2").run_fail(); + rustc() + .input("f.rs") + .specific_library_search_path("crate", "e1") + .library_search_path("e2") + .run_fail(); + rustc() + .input("f.rs") + .specific_library_search_path("crate", "e1") + .specific_library_search_path("crate", "e2") + .run_fail(); + // Native and dependency paths do not cause errors. + rustc() + .input("f.rs") + .specific_library_search_path("native", "e1") + .library_search_path("e2") + .run(); + rustc() + .input("f.rs") + .specific_library_search_path("dependency", "e1") + .library_search_path("e2") + .run(); + rustc() + .input("f.rs") + .specific_library_search_path("dependency", "e1") + .specific_library_search_path("crate", "e2") + .run(); +} diff --git a/tests/run-make/dump-mono-stats/Makefile b/tests/run-make/dump-mono-stats/Makefile deleted file mode 100644 index 196f84be6ecaa..0000000000000 --- a/tests/run-make/dump-mono-stats/Makefile +++ /dev/null @@ -1,5 +0,0 @@ -include ../tools.mk - -all: - $(RUSTC) --crate-type lib foo.rs -Z dump-mono-stats=$(TMPDIR) -Zdump-mono-stats-format=json - cat $(TMPDIR)/foo.mono_items.json | $(CGREP) '"name":"bar"' diff --git a/tests/run-make/dump-mono-stats/rmake.rs b/tests/run-make/dump-mono-stats/rmake.rs new file mode 100644 index 0000000000000..05ba2e6b8ff2b --- /dev/null +++ b/tests/run-make/dump-mono-stats/rmake.rs @@ -0,0 +1,17 @@ +// A flag named dump-mono-stats was added to the compiler in 2022, which +// collects stats on instantiation of items and their associated costs. +// This test checks that the output stat file exists, and that it contains +// a specific expected string. +// See https://github.com/rust-lang/rust/pull/105481 + +use run_make_support::{cwd, fs_wrapper, rustc}; + +fn main() { + rustc() + .crate_type("lib") + .input("foo.rs") + .arg(format!("-Zdump-mono-stats={}", cwd().display())) + .arg("-Zdump-mono-stats-format=json") + .run(); + assert!(fs_wrapper::read_to_string("foo.mono_items.json").contains(r#""name":"bar""#)); +} diff --git a/tests/run-make/invalid-library/rmake.rs b/tests/run-make/invalid-library/rmake.rs index 750fcd05c8ac5..9ebab1c8b0f09 100644 --- a/tests/run-make/invalid-library/rmake.rs +++ b/tests/run-make/invalid-library/rmake.rs @@ -1,8 +1,14 @@ +// When the metadata format changes, old libraries used to cause librustc to abort +// when reading their metadata. The error message for this scenario was unhelpful at best. +// A better error message was implemented in #12645, and this test checks that it is the +// one appearing in stderr in this scenario. +// See https://github.com/rust-lang/rust/pull/12645 + use run_make_support::fs_wrapper::create_file; -use run_make_support::{ar, rustc}; +use run_make_support::{llvm_ar, rustc}; fn main() { create_file("lib.rmeta"); - ar(&["lib.rmeta"], "libfoo-ffffffff-1.0.rlib"); + llvm_ar().obj_to_ar().output_input("libfoo-ffffffff-1.0.rlib", "lib.rmeta").run(); rustc().input("foo.rs").run_fail().assert_stderr_contains("found invalid metadata"); } diff --git a/tests/run-make/prune-link-args/Makefile b/tests/run-make/prune-link-args/Makefile deleted file mode 100644 index c21ba6ace38d6..0000000000000 --- a/tests/run-make/prune-link-args/Makefile +++ /dev/null @@ -1,10 +0,0 @@ -# ignore-cross-compile -include ../tools.mk - -# ignore-windows - -# Notice the space in the end, this emulates the output of pkg-config -RUSTC_FLAGS = -C link-args="-lc " - -all: - $(RUSTC) $(RUSTC_FLAGS) empty.rs diff --git a/tests/run-make/prune-link-args/rmake.rs b/tests/run-make/prune-link-args/rmake.rs new file mode 100644 index 0000000000000..ea4ffa732bf3f --- /dev/null +++ b/tests/run-make/prune-link-args/rmake.rs @@ -0,0 +1,17 @@ +// Passing link-args with an unexpected space +// could result in the flag being parsed and receiving +// an unexpected, empty linker argument. This test +// ensures successful compilation even when a space is +// present. +// See https://github.com/rust-lang/rust/pull/10749 + +//@ ignore-cross-compile +//@ ignore-windows-gnu +// Reason: The space is parsed as an empty linker argument on windows-gnu. + +use run_make_support::rustc; + +fn main() { + // Notice the space at the end of -lc, which emulates the output of pkg-config. + rustc().arg("-Clink-args=-lc ").input("empty.rs").run(); +}