diff options
448 files changed, 4416 insertions, 2625 deletions
diff --git a/Cargo.lock b/Cargo.lock index 77653530925..18d5b66eb73 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -186,6 +186,9 @@ name = "anyhow" version = "1.0.95" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34ac096ce696dc2fcabef30516bb13c0a68a11d30131d3df6f04711467681b04" +dependencies = [ + "backtrace", +] [[package]] name = "ar_archive_writer" @@ -1196,6 +1199,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" [[package]] +name = "features-status-dump" +version = "0.1.0" +dependencies = [ + "anyhow", + "clap", + "serde", + "serde_json", + "tidy", +] + +[[package]] name = "field-offset" version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -5418,6 +5432,7 @@ dependencies = [ "regex", "rustc-hash 2.1.0", "semver", + "serde", "similar", "termcolor", "walkdir", diff --git a/Cargo.toml b/Cargo.toml index b773030b4ca..68d142ebe92 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -47,6 +47,7 @@ members = [ "src/tools/coverage-dump", "src/tools/rustc-perf-wrapper", "src/tools/wasm-component-ld", + "src/tools/features-status-dump", ] exclude = [ diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index 1267281f73e..98d6372ca89 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -284,9 +284,6 @@ impl<'hir> LoweringContext<'_, 'hir> { ExprKind::Index(el, er, brackets_span) => { hir::ExprKind::Index(self.lower_expr(el), self.lower_expr(er), *brackets_span) } - ExprKind::Range(Some(e1), Some(e2), RangeLimits::Closed) => { - self.lower_expr_range_closed(e.span, e1, e2) - } ExprKind::Range(e1, e2, lims) => { self.lower_expr_range(e.span, e1.as_deref(), e2.as_deref(), *lims) } @@ -1512,15 +1509,39 @@ impl<'hir> LoweringContext<'_, 'hir> { let lang_item = match (e1, e2, lims) { (None, None, HalfOpen) => hir::LangItem::RangeFull, - (Some(..), None, HalfOpen) => hir::LangItem::RangeFrom, + (Some(..), None, HalfOpen) => { + if self.tcx.features().new_range() { + hir::LangItem::RangeFromCopy + } else { + hir::LangItem::RangeFrom + } + } (None, Some(..), HalfOpen) => hir::LangItem::RangeTo, - (Some(..), Some(..), HalfOpen) => hir::LangItem::Range, + (Some(..), Some(..), HalfOpen) => { + if self.tcx.features().new_range() { + hir::LangItem::RangeCopy + } else { + hir::LangItem::Range + } + } (None, Some(..), Closed) => hir::LangItem::RangeToInclusive, - (Some(..), Some(..), Closed) => unreachable!(), + (Some(e1), Some(e2), Closed) => { + if self.tcx.features().new_range() { + hir::LangItem::RangeInclusiveCopy + } else { + return self.lower_expr_range_closed(span, e1, e2); + } + } (start, None, Closed) => { self.dcx().emit_err(InclusiveRangeWithNoEnd { span }); match start { - Some(..) => hir::LangItem::RangeFrom, + Some(..) => { + if self.tcx.features().new_range() { + hir::LangItem::RangeFromCopy + } else { + hir::LangItem::RangeFrom + } + } None => hir::LangItem::RangeFull, } } diff --git a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs index 841cb782bc3..3e474225afd 100644 --- a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs +++ b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs @@ -622,8 +622,25 @@ impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> { } } + // NLL doesn't consider boring locals for liveness, and wouldn't encounter a + // `Cause::LiveVar` for such a local. Polonius can't avoid computing liveness for boring + // locals yet, and will encounter them when trying to explain why a borrow contains a given + // point. + // + // We want to focus on relevant live locals in diagnostics, so when polonius is enabled, we + // ensure that we don't emit live boring locals as explanations. + let is_local_boring = |local| { + if let Some(polonius_diagnostics) = self.polonius_diagnostics { + polonius_diagnostics.boring_nll_locals.contains(&local) + } else { + assert!(!tcx.sess.opts.unstable_opts.polonius.is_next_enabled()); + + // Boring locals are never the cause of a borrow explanation in NLLs. + false + } + }; match find_use::find(body, regioncx, tcx, region_sub, use_location) { - Some(Cause::LiveVar(local, location)) => { + Some(Cause::LiveVar(local, location)) if !is_local_boring(local) => { let span = body.source_info(location).span; let spans = self .move_spans(Place::from(local).as_ref(), location) @@ -666,7 +683,9 @@ impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> { } } - None => { + Some(Cause::LiveVar(..)) | None => { + // Here, under NLL: no cause was found. Under polonius: no cause was found, or a + // boring local was found, which we ignore like NLLs do to match its diagnostics. if let Some(region) = self.to_error_region_vid(borrow_region_vid) { let (category, from_closure, span, region_name, path) = self.free_region_constraint_info(borrow_region_vid, region); diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs index 077d8f49df8..8ddc8add675 100644 --- a/compiler/rustc_borrowck/src/lib.rs +++ b/compiler/rustc_borrowck/src/lib.rs @@ -60,6 +60,7 @@ use crate::diagnostics::{ use crate::path_utils::*; use crate::place_ext::PlaceExt; use crate::places_conflict::{PlaceConflictBias, places_conflict}; +use crate::polonius::PoloniusDiagnosticsContext; use crate::polonius::legacy::{PoloniusLocationTable, PoloniusOutput}; use crate::prefixes::PrefixSet; use crate::region_infer::RegionInferenceContext; @@ -198,7 +199,7 @@ fn do_mir_borrowck<'tcx>( polonius_output, opt_closure_req, nll_errors, - localized_outlives_constraints, + polonius_diagnostics, } = nll::compute_regions( &infcx, free_regions, @@ -270,6 +271,7 @@ fn do_mir_borrowck<'tcx>( polonius_output: None, move_errors: Vec::new(), diags_buffer, + polonius_diagnostics: polonius_diagnostics.as_ref(), }; struct MoveVisitor<'a, 'b, 'infcx, 'tcx> { ctxt: &'a mut MirBorrowckCtxt<'b, 'infcx, 'tcx>, @@ -308,6 +310,7 @@ fn do_mir_borrowck<'tcx>( polonius_output, move_errors: Vec::new(), diags_buffer, + polonius_diagnostics: polonius_diagnostics.as_ref(), }; // Compute and report region errors, if any. @@ -329,7 +332,7 @@ fn do_mir_borrowck<'tcx>( body, ®ioncx, &borrow_set, - localized_outlives_constraints, + polonius_diagnostics.as_ref(), &opt_closure_req, ); @@ -579,6 +582,9 @@ struct MirBorrowckCtxt<'a, 'infcx, 'tcx> { diags_buffer: &'a mut BorrowckDiagnosticsBuffer<'infcx, 'tcx>, move_errors: Vec<MoveError<'tcx>>, + + /// When using `-Zpolonius=next`: the data used to compute errors and diagnostics. + polonius_diagnostics: Option<&'a PoloniusDiagnosticsContext>, } // Check that: diff --git a/compiler/rustc_borrowck/src/nll.rs b/compiler/rustc_borrowck/src/nll.rs index 35264bd1a70..2031579dfd5 100644 --- a/compiler/rustc_borrowck/src/nll.rs +++ b/compiler/rustc_borrowck/src/nll.rs @@ -27,7 +27,7 @@ use tracing::{debug, instrument}; use crate::borrow_set::BorrowSet; use crate::consumers::ConsumerOptions; use crate::diagnostics::{BorrowckDiagnosticsBuffer, RegionErrors}; -use crate::polonius::LocalizedOutlivesConstraintSet; +use crate::polonius::PoloniusDiagnosticsContext; use crate::polonius::legacy::{ PoloniusFacts, PoloniusFactsExt, PoloniusLocationTable, PoloniusOutput, }; @@ -46,8 +46,9 @@ pub(crate) struct NllOutput<'tcx> { pub opt_closure_req: Option<ClosureRegionRequirements<'tcx>>, pub nll_errors: RegionErrors<'tcx>, - /// When using `-Zpolonius=next`: the localized typeck and liveness constraints. - pub localized_outlives_constraints: Option<LocalizedOutlivesConstraintSet>, + /// When using `-Zpolonius=next`: the data used to compute errors and diagnostics, e.g. + /// localized typeck and liveness constraints. + pub polonius_diagnostics: Option<PoloniusDiagnosticsContext>, } /// Rewrites the regions in the MIR to use NLL variables, also scraping out the set of universal @@ -144,7 +145,7 @@ pub(crate) fn compute_regions<'a, 'tcx>( // If requested for `-Zpolonius=next`, convert NLL constraints to localized outlives constraints // and use them to compute loan liveness. - let localized_outlives_constraints = polonius_context.as_ref().map(|polonius_context| { + let polonius_diagnostics = polonius_context.map(|polonius_context| { polonius_context.compute_loan_liveness(infcx.tcx, &mut regioncx, body, borrow_set) }); @@ -188,7 +189,7 @@ pub(crate) fn compute_regions<'a, 'tcx>( polonius_output, opt_closure_req: closure_region_requirements, nll_errors, - localized_outlives_constraints, + polonius_diagnostics, } } diff --git a/compiler/rustc_borrowck/src/polonius/dump.rs b/compiler/rustc_borrowck/src/polonius/dump.rs index 6d32ee17f4c..5f9fa3612b8 100644 --- a/compiler/rustc_borrowck/src/polonius/dump.rs +++ b/compiler/rustc_borrowck/src/polonius/dump.rs @@ -12,7 +12,9 @@ use rustc_session::config::MirIncludeSpans; use crate::borrow_set::BorrowSet; use crate::constraints::OutlivesConstraint; -use crate::polonius::{LocalizedOutlivesConstraint, LocalizedOutlivesConstraintSet}; +use crate::polonius::{ + LocalizedOutlivesConstraint, LocalizedOutlivesConstraintSet, PoloniusDiagnosticsContext, +}; use crate::region_infer::values::LivenessValues; use crate::type_check::Locations; use crate::{BorrowckInferCtxt, RegionInferenceContext}; @@ -23,7 +25,7 @@ pub(crate) fn dump_polonius_mir<'tcx>( body: &Body<'tcx>, regioncx: &RegionInferenceContext<'tcx>, borrow_set: &BorrowSet<'tcx>, - localized_outlives_constraints: Option<LocalizedOutlivesConstraintSet>, + polonius_diagnostics: Option<&PoloniusDiagnosticsContext>, closure_region_requirements: &Option<ClosureRegionRequirements<'tcx>>, ) { let tcx = infcx.tcx; @@ -35,8 +37,8 @@ pub(crate) fn dump_polonius_mir<'tcx>( return; } - let localized_outlives_constraints = localized_outlives_constraints - .expect("missing localized constraints with `-Zpolonius=next`"); + let polonius_diagnostics = + polonius_diagnostics.expect("missing diagnostics context with `-Zpolonius=next`"); let _: io::Result<()> = try { let mut file = create_dump_file(tcx, "html", false, "polonius", &0, body)?; @@ -45,7 +47,7 @@ pub(crate) fn dump_polonius_mir<'tcx>( body, regioncx, borrow_set, - localized_outlives_constraints, + &polonius_diagnostics.localized_outlives_constraints, closure_region_requirements, &mut file, )?; @@ -63,7 +65,7 @@ fn emit_polonius_dump<'tcx>( body: &Body<'tcx>, regioncx: &RegionInferenceContext<'tcx>, borrow_set: &BorrowSet<'tcx>, - localized_outlives_constraints: LocalizedOutlivesConstraintSet, + localized_outlives_constraints: &LocalizedOutlivesConstraintSet, closure_region_requirements: &Option<ClosureRegionRequirements<'tcx>>, out: &mut dyn io::Write, ) -> io::Result<()> { diff --git a/compiler/rustc_borrowck/src/polonius/liveness_constraints.rs b/compiler/rustc_borrowck/src/polonius/liveness_constraints.rs index 75ee29c9d0d..6ab09f731c0 100644 --- a/compiler/rustc_borrowck/src/polonius/liveness_constraints.rs +++ b/compiler/rustc_borrowck/src/polonius/liveness_constraints.rs @@ -1,7 +1,6 @@ use std::collections::BTreeMap; use rustc_index::bit_set::SparseBitMatrix; -use rustc_index::interval::SparseIntervalMatrix; use rustc_middle::mir::{Body, Location}; use rustc_middle::ty::relate::{self, Relate, RelateResult, TypeRelation}; use rustc_middle::ty::{self, RegionVid, Ty, TyCtxt, TypeVisitable}; @@ -9,12 +8,12 @@ use rustc_mir_dataflow::points::PointIndex; use super::{ ConstraintDirection, LocalizedOutlivesConstraint, LocalizedOutlivesConstraintSet, - PoloniusContext, + PoloniusLivenessContext, }; use crate::region_infer::values::LivenessValues; use crate::universal_regions::UniversalRegions; -impl PoloniusContext { +impl PoloniusLivenessContext { /// Record the variance of each region contained within the given value. pub(crate) fn record_live_region_variance<'tcx>( &mut self, @@ -30,25 +29,6 @@ impl PoloniusContext { }; extractor.relate(value, value).expect("Can't have a type error relating to itself"); } - - /// Unlike NLLs, in polonius we traverse the cfg to look for regions live across an edge, so we - /// need to transpose the "points where each region is live" matrix to a "live regions per point" - /// matrix. - // FIXME: avoid this conversion by always storing liveness data in this shape in the rest of - // borrowck. - pub(crate) fn record_live_regions_per_point( - &mut self, - num_regions: usize, - points_per_live_region: &SparseIntervalMatrix<RegionVid, PointIndex>, - ) { - let mut live_regions_per_point = SparseBitMatrix::new(num_regions); - for region in points_per_live_region.rows() { - for point in points_per_live_region.row(region).unwrap().iter() { - live_regions_per_point.insert(point, region); - } - } - self.live_regions = Some(live_regions_per_point); - } } /// Propagate loans throughout the CFG: for each statement in the MIR, create localized outlives diff --git a/compiler/rustc_borrowck/src/polonius/mod.rs b/compiler/rustc_borrowck/src/polonius/mod.rs index 502c868194a..142ef8ba28e 100644 --- a/compiler/rustc_borrowck/src/polonius/mod.rs +++ b/compiler/rustc_borrowck/src/polonius/mod.rs @@ -32,6 +32,16 @@ //! - <https://smallcultfollowing.com/babysteps/blog/2023/09/22/polonius-part-1/> //! - <https://smallcultfollowing.com/babysteps/blog/2023/09/29/polonius-part-2/> //! +//! +//! Data flows like this: +//! 1) during MIR typeck, record liveness data needed later: live region variances, as well as the +//! usual NLL liveness data (just computed on more locals). That's the [PoloniusLivenessContext]. +//! 2) once that is done, variance data is transferred, and the NLL region liveness is converted to +//! the polonius shape. That's the main [PoloniusContext]. +//! 3) during region inference, that data and the NLL outlives constraints are used to create the +//! localized outlives constraints, as described above. That's the [PoloniusDiagnosticsContext]. +//! 4) transfer this back to the main borrowck procedure: it handles computing errors and +//! diagnostics, debugging and MIR dumping concerns. mod constraints; mod dump; @@ -42,8 +52,10 @@ mod typeck_constraints; use std::collections::BTreeMap; +use rustc_data_structures::fx::FxHashSet; use rustc_index::bit_set::SparseBitMatrix; -use rustc_middle::mir::Body; +use rustc_index::interval::SparseIntervalMatrix; +use rustc_middle::mir::{Body, Local}; use rustc_middle::ty::{RegionVid, TyCtxt}; use rustc_mir_dataflow::points::PointIndex; @@ -57,15 +69,40 @@ use crate::{BorrowSet, RegionInferenceContext}; pub(crate) type LiveLoans = SparseBitMatrix<PointIndex, BorrowIndex>; -/// This struct holds the data needed to create the Polonius localized constraints. +/// This struct holds the liveness data created during MIR typeck, and which will be used later in +/// the process, to compute the polonius localized constraints. +#[derive(Default)] +pub(crate) struct PoloniusLivenessContext { + /// The expected edge direction per live region: the kind of directed edge we'll create as + /// liveness constraints depends on the variance of types with respect to each contained region. + live_region_variances: BTreeMap<RegionVid, ConstraintDirection>, + + /// The regions that outlive free regions are used to distinguish relevant live locals from + /// boring locals. A boring local is one whose type contains only such regions. Polonius + /// currently has more boring locals than NLLs so we record the latter to use in errors and + /// diagnostics, to focus on the locals we consider relevant and match NLL diagnostics. + pub(crate) boring_nll_locals: FxHashSet<Local>, +} + +/// This struct holds the data needed to create the Polonius localized constraints. Its data is +/// transferred and converted from the [PoloniusLivenessContext] at the end of MIR typeck. pub(crate) struct PoloniusContext { + /// The liveness data we recorded during MIR typeck. + liveness_context: PoloniusLivenessContext, + /// The set of regions that are live at a given point in the CFG, used to create localized /// outlives constraints between regions that are live at connected points in the CFG. - live_regions: Option<SparseBitMatrix<PointIndex, RegionVid>>, + live_regions: SparseBitMatrix<PointIndex, RegionVid>, +} - /// The expected edge direction per live region: the kind of directed edge we'll create as - /// liveness constraints depends on the variance of types with respect to each contained region. - live_region_variances: BTreeMap<RegionVid, ConstraintDirection>, +/// This struct holds the data needed by the borrowck error computation and diagnostics. Its data is +/// computed from the [PoloniusContext] when computing NLL regions. +pub(crate) struct PoloniusDiagnosticsContext { + /// The localized outlives constraints that were computed in the main analysis. + localized_outlives_constraints: LocalizedOutlivesConstraintSet, + + /// The liveness data computed during MIR typeck: [PoloniusLivenessContext::boring_nll_locals]. + pub(crate) boring_nll_locals: FxHashSet<Local>, } /// The direction a constraint can flow into. Used to create liveness constraints according to @@ -83,8 +120,24 @@ enum ConstraintDirection { } impl PoloniusContext { - pub(crate) fn new() -> PoloniusContext { - Self { live_region_variances: BTreeMap::new(), live_regions: None } + /// Unlike NLLs, in polonius we traverse the cfg to look for regions live across an edge, so we + /// need to transpose the "points where each region is live" matrix to a "live regions per point" + /// matrix. + // FIXME: avoid this conversion by always storing liveness data in this shape in the rest of + // borrowck. + pub(crate) fn create_from_liveness( + liveness_context: PoloniusLivenessContext, + num_regions: usize, + points_per_live_region: &SparseIntervalMatrix<RegionVid, PointIndex>, + ) -> PoloniusContext { + let mut live_regions_per_point = SparseBitMatrix::new(num_regions); + for region in points_per_live_region.rows() { + for point in points_per_live_region.row(region).unwrap().iter() { + live_regions_per_point.insert(point, region); + } + } + + PoloniusContext { live_regions: live_regions_per_point, liveness_context } } /// Computes live loans using the set of loans model for `-Zpolonius=next`. @@ -95,13 +148,18 @@ impl PoloniusContext { /// /// Then, this graph is traversed, and combined with kills, reachability is recorded as loan /// liveness, to be used by the loan scope and active loans computations. + /// + /// The constraint data will be used to compute errors and diagnostics. pub(crate) fn compute_loan_liveness<'tcx>( - &self, + self, tcx: TyCtxt<'tcx>, regioncx: &mut RegionInferenceContext<'tcx>, body: &Body<'tcx>, borrow_set: &BorrowSet<'tcx>, - ) -> LocalizedOutlivesConstraintSet { + ) -> PoloniusDiagnosticsContext { + let PoloniusLivenessContext { live_region_variances, boring_nll_locals } = + self.liveness_context; + let mut localized_outlives_constraints = LocalizedOutlivesConstraintSet::default(); convert_typeck_constraints( tcx, @@ -112,14 +170,11 @@ impl PoloniusContext { &mut localized_outlives_constraints, ); - let live_regions = self.live_regions.as_ref().expect( - "live regions per-point data should have been created at the end of MIR typeck", - ); create_liveness_constraints( body, regioncx.liveness_constraints(), - live_regions, - &self.live_region_variances, + &self.live_regions, + &live_region_variances, regioncx.universal_regions(), &mut localized_outlives_constraints, ); @@ -136,6 +191,6 @@ impl PoloniusContext { ); regioncx.record_live_loans(live_loans); - localized_outlives_constraints + PoloniusDiagnosticsContext { localized_outlives_constraints, boring_nll_locals } } } diff --git a/compiler/rustc_borrowck/src/type_check/liveness/mod.rs b/compiler/rustc_borrowck/src/type_check/liveness/mod.rs index 4e0b2a4e296..dcc17903002 100644 --- a/compiler/rustc_borrowck/src/type_check/liveness/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/liveness/mod.rs @@ -14,7 +14,7 @@ use tracing::debug; use super::TypeChecker; use crate::constraints::OutlivesConstraintSet; -use crate::polonius::PoloniusContext; +use crate::polonius::PoloniusLivenessContext; use crate::region_infer::values::LivenessValues; use crate::universal_regions::UniversalRegions; @@ -38,19 +38,24 @@ pub(super) fn generate<'a, 'tcx>( ) { debug!("liveness::generate"); + let mut free_regions = regions_that_outlive_free_regions( + typeck.infcx.num_region_vars(), + &typeck.universal_regions, + &typeck.constraints.outlives_constraints, + ); + // NLLs can avoid computing some liveness data here because its constraints are // location-insensitive, but that doesn't work in polonius: locals whose type contains a region // that outlives a free region are not necessarily live everywhere in a flow-sensitive setting, // unlike NLLs. - let free_regions = if !typeck.tcx().sess.opts.unstable_opts.polonius.is_next_enabled() { - regions_that_outlive_free_regions( - typeck.infcx.num_region_vars(), - &typeck.universal_regions, - &typeck.constraints.outlives_constraints, - ) - } else { - typeck.universal_regions.universal_regions_iter().collect() - }; + // We do record these regions in the polonius context, since they're used to differentiate + // relevant and boring locals, which is a key distinction used later in diagnostics. + if typeck.tcx().sess.opts.unstable_opts.polonius.is_next_enabled() { + let (_, boring_locals) = compute_relevant_live_locals(typeck.tcx(), &free_regions, body); + typeck.polonius_liveness.as_mut().unwrap().boring_nll_locals = + boring_locals.into_iter().collect(); + free_regions = typeck.universal_regions.universal_regions_iter().collect(); + } let (relevant_live_locals, boring_locals) = compute_relevant_live_locals(typeck.tcx(), &free_regions, body); @@ -70,7 +75,7 @@ pub(super) fn generate<'a, 'tcx>( typeck.tcx(), &mut typeck.constraints.liveness_constraints, &typeck.universal_regions, - &mut typeck.polonius_context, + &mut typeck.polonius_liveness, body, ); } @@ -147,11 +152,11 @@ fn record_regular_live_regions<'tcx>( tcx: TyCtxt<'tcx>, liveness_constraints: &mut LivenessValues, universal_regions: &UniversalRegions<'tcx>, - polonius_context: &mut Option<PoloniusContext>, + polonius_liveness: &mut Option<PoloniusLivenessContext>, body: &Body<'tcx>, ) { let mut visitor = - LiveVariablesVisitor { tcx, liveness_constraints, universal_regions, polonius_context }; + LiveVariablesVisitor { tcx, liveness_constraints, universal_regions, polonius_liveness }; for (bb, data) in body.basic_blocks.iter_enumerated() { visitor.visit_basic_block_data(bb, data); } @@ -162,7 +167,7 @@ struct LiveVariablesVisitor<'a, 'tcx> { tcx: TyCtxt<'tcx>, liveness_constraints: &'a mut LivenessValues, universal_regions: &'a UniversalRegions<'tcx>, - polonius_context: &'a mut Option<PoloniusContext>, + polonius_liveness: &'a mut Option<PoloniusLivenessContext>, } impl<'a, 'tcx> Visitor<'tcx> for LiveVariablesVisitor<'a, 'tcx> { @@ -214,8 +219,8 @@ impl<'a, 'tcx> LiveVariablesVisitor<'a, 'tcx> { }); // When using `-Zpolonius=next`, we record the variance of each live region. - if let Some(polonius_context) = self.polonius_context { - polonius_context.record_live_region_variance(self.tcx, self.universal_regions, value); + if let Some(polonius_liveness) = self.polonius_liveness { + polonius_liveness.record_live_region_variance(self.tcx, self.universal_regions, value); } } } diff --git a/compiler/rustc_borrowck/src/type_check/liveness/trace.rs b/compiler/rustc_borrowck/src/type_check/liveness/trace.rs index c564d85616e..62d49a62744 100644 --- a/compiler/rustc_borrowck/src/type_check/liveness/trace.rs +++ b/compiler/rustc_borrowck/src/type_check/liveness/trace.rs @@ -580,8 +580,8 @@ impl<'tcx> LivenessContext<'_, '_, '_, 'tcx> { }); // When using `-Zpolonius=next`, we record the variance of each live region. - if let Some(polonius_context) = typeck.polonius_context { - polonius_context.record_live_region_variance( + if let Some(polonius_liveness) = typeck.polonius_liveness.as_mut() { + polonius_liveness.record_live_region_variance( typeck.infcx.tcx, typeck.universal_regions, value, diff --git a/compiler/rustc_borrowck/src/type_check/mod.rs b/compiler/rustc_borrowck/src/type_check/mod.rs index 92492bfdb8d..78aa38e9e48 100644 --- a/compiler/rustc_borrowck/src/type_check/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/mod.rs @@ -48,8 +48,8 @@ use crate::borrow_set::BorrowSet; use crate::constraints::{OutlivesConstraint, OutlivesConstraintSet}; use crate::diagnostics::UniverseInfo; use crate::member_constraints::MemberConstraintSet; -use crate::polonius::PoloniusContext; use crate::polonius::legacy::{PoloniusFacts, PoloniusLocationTable}; +use crate::polonius::{PoloniusContext, PoloniusLivenessContext}; use crate::region_infer::TypeTest; use crate::region_infer::values::{LivenessValues, PlaceholderIndex, PlaceholderIndices}; use crate::renumber::RegionCtxt; @@ -148,8 +148,8 @@ pub(crate) fn type_check<'a, 'tcx>( debug!(?normalized_inputs_and_output); - let mut polonius_context = if infcx.tcx.sess.opts.unstable_opts.polonius.is_next_enabled() { - Some(PoloniusContext::new()) + let polonius_liveness = if infcx.tcx.sess.opts.unstable_opts.polonius.is_next_enabled() { + Some(PoloniusLivenessContext::default()) } else { None }; @@ -168,7 +168,7 @@ pub(crate) fn type_check<'a, 'tcx>( polonius_facts, borrow_set, constraints: &mut constraints, - polonius_context: &mut polonius_context, + polonius_liveness, }; typeck.check_user_type_annotations(); @@ -185,11 +185,14 @@ pub(crate) fn type_check<'a, 'tcx>( let opaque_type_values = opaque_types::take_opaques_and_register_member_constraints(&mut typeck); - if let Some(polonius_context) = typeck.polonius_context.as_mut() { - let num_regions = infcx.num_region_vars(); - let points_per_live_region = typeck.constraints.liveness_constraints.points(); - polonius_context.record_live_regions_per_point(num_regions, points_per_live_region); - } + // We're done with typeck, we can finalize the polonius liveness context for region inference. + let polonius_context = typeck.polonius_liveness.take().map(|liveness_context| { + PoloniusContext::create_from_liveness( + liveness_context, + infcx.num_region_vars(), + typeck.constraints.liveness_constraints.points(), + ) + }); MirTypeckResults { constraints, @@ -583,8 +586,8 @@ struct TypeChecker<'a, 'tcx> { polonius_facts: &'a mut Option<PoloniusFacts>, borrow_set: &'a BorrowSet<'tcx>, constraints: &'a mut MirTypeckRegionConstraints<'tcx>, - /// When using `-Zpolonius=next`, the helper data used to create polonius constraints. - polonius_context: &'a mut Option<PoloniusContext>, + /// When using `-Zpolonius=next`, the liveness helper data used to create polonius constraints. + polonius_liveness: Option<PoloniusLivenessContext>, } /// Holder struct for passing results from MIR typeck to the rest of the non-lexical regions diff --git a/compiler/rustc_codegen_ssa/src/back/write.rs b/compiler/rustc_codegen_ssa/src/back/write.rs index 914f2c21fa7..ce2161a07eb 100644 --- a/compiler/rustc_codegen_ssa/src/back/write.rs +++ b/compiler/rustc_codegen_ssa/src/back/write.rs @@ -403,7 +403,7 @@ fn generate_lto_work<B: ExtraBackendMethods>( assert!(needs_thin_lto.is_empty()); let mut module = B::run_fat_lto(cgcx, needs_fat_lto, import_only_modules).unwrap_or_else(|e| e.raise()); - if cgcx.lto == Lto::Fat { + if cgcx.lto == Lto::Fat && !autodiff.is_empty() { let config = cgcx.config(ModuleKind::Regular); module = unsafe { module.autodiff(cgcx, autodiff, config).unwrap() }; } diff --git a/compiler/rustc_const_eval/messages.ftl b/compiler/rustc_const_eval/messages.ftl index d600d223bff..eecc6690f51 100644 --- a/compiler/rustc_const_eval/messages.ftl +++ b/compiler/rustc_const_eval/messages.ftl @@ -280,7 +280,9 @@ const_eval_nullary_intrinsic_fail = could not evaluate nullary intrinsic const_eval_offset_from_different_allocations = - `{$name}` called on pointers into different allocations + `{$name}` called on two different pointers that are not both derived from the same allocation +const_eval_offset_from_out_of_bounds = + `{$name}` called on two different pointers where the memory range between them is not in-bounds of an allocation const_eval_offset_from_overflow = `{$name}` called when first pointer is too far ahead of second const_eval_offset_from_test = diff --git a/compiler/rustc_const_eval/src/const_eval/mod.rs b/compiler/rustc_const_eval/src/const_eval/mod.rs index 34f795bda75..c0438fb3ff8 100644 --- a/compiler/rustc_const_eval/src/const_eval/mod.rs +++ b/compiler/rustc_const_eval/src/const_eval/mod.rs @@ -1,7 +1,7 @@ // Not in interpret to make sure we do not use private implementation details use rustc_abi::VariantIdx; -use rustc_middle::query::{Key, TyCtxtAt}; +use rustc_middle::query::Key; use rustc_middle::ty::layout::LayoutOf; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_middle::{bug, mir}; @@ -35,16 +35,17 @@ pub(crate) type ValTreeCreationResult<'tcx> = Result<ty::ValTree<'tcx>, ValTreeC #[instrument(skip(tcx), level = "debug")] pub(crate) fn try_destructure_mir_constant_for_user_output<'tcx>( - tcx: TyCtxtAt<'tcx>, + tcx: TyCtxt<'tcx>, val: mir::ConstValue<'tcx>, ty: Ty<'tcx>, ) -> Option<mir::DestructuredConstant<'tcx>> { let typing_env = ty::TypingEnv::fully_monomorphized(); - let (ecx, op) = mk_eval_cx_for_const_val(tcx, typing_env, val, ty)?; + // FIXME: use a proper span here? + let (ecx, op) = mk_eval_cx_for_const_val(tcx.at(rustc_span::DUMMY_SP), typing_env, val, ty)?; // We go to `usize` as we cannot allocate anything bigger anyway. let (field_count, variant, down) = match ty.kind() { - ty::Array(_, len) => (len.try_to_target_usize(tcx.tcx)? as usize, None, op), + ty::Array(_, len) => (len.try_to_target_usize(tcx)? as usize, None, op), ty::Adt(def, _) if def.variants().is_empty() => { return None; } diff --git a/compiler/rustc_const_eval/src/const_eval/valtrees.rs b/compiler/rustc_const_eval/src/const_eval/valtrees.rs index 4d625f76aba..c35910a706b 100644 --- a/compiler/rustc_const_eval/src/const_eval/valtrees.rs +++ b/compiler/rustc_const_eval/src/const_eval/valtrees.rs @@ -273,59 +273,63 @@ pub(crate) fn eval_to_valtree<'tcx>( /// Converts a `ValTree` to a `ConstValue`, which is needed after mir /// construction has finished. // FIXME(valtrees): Merge `valtree_to_const_value` and `valtree_into_mplace` into one function -// FIXME(valtrees): Accept `ty::Value` instead of `Ty` and `ty::ValTree` separately. #[instrument(skip(tcx), level = "debug", ret)] pub fn valtree_to_const_value<'tcx>( tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>, - ty: Ty<'tcx>, - valtree: ty::ValTree<'tcx>, + cv: ty::Value<'tcx>, ) -> mir::ConstValue<'tcx> { // Basic idea: We directly construct `Scalar` values from trivial `ValTree`s // (those for constants with type bool, int, uint, float or char). // For all other types we create an `MPlace` and fill that by walking // the `ValTree` and using `place_projection` and `place_field` to // create inner `MPlace`s which are filled recursively. - // FIXME Does this need an example? - match *ty.kind() { + // FIXME: Does this need an example? + match *cv.ty.kind() { ty::FnDef(..) => { - assert!(valtree.unwrap_branch().is_empty()); + assert!(cv.valtree.unwrap_branch().is_empty()); mir::ConstValue::ZeroSized } ty::Bool | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Char | ty::RawPtr(_, _) => { - match valtree { + match cv.valtree { ty::ValTree::Leaf(scalar_int) => mir::ConstValue::Scalar(Scalar::Int(scalar_int)), ty::ValTree::Branch(_) => bug!( "ValTrees for Bool, Int, Uint, Float, Char or RawPtr should have the form ValTree::Leaf" ), } } - ty::Pat(ty, _) => valtree_to_const_value(tcx, typing_env, ty, valtree), + ty::Pat(ty, _) => { + let cv = ty::Value { valtree: cv.valtree, ty }; + valtree_to_const_value(tcx, typing_env, cv) + } ty::Ref(_, inner_ty, _) => { let mut ecx = mk_eval_cx_to_read_const_val(tcx, DUMMY_SP, typing_env, CanAccessMutGlobal::No); - let imm = valtree_to_ref(&mut ecx, valtree, inner_ty); - let imm = - ImmTy::from_immediate(imm, tcx.layout_of(typing_env.as_query_input(ty)).unwrap()); + let imm = valtree_to_ref(&mut ecx, cv.valtree, inner_ty); + let imm = ImmTy::from_immediate( + imm, + tcx.layout_of(typing_env.as_query_input(cv.ty)).unwrap(), + ); op_to_const(&ecx, &imm.into(), /* for diagnostics */ false) } ty::Tuple(_) | ty::Array(_, _) | ty::Adt(..) => { - let layout = tcx.layout_of(typing_env.as_query_input(ty)).unwrap(); + let layout = tcx.layout_of(typing_env.as_query_input(cv.ty)).unwrap(); if layout.is_zst() { // Fast path to avoid some allocations. return mir::ConstValue::ZeroSized; } if layout.backend_repr.is_scalar() - && (matches!(ty.kind(), ty::Tuple(_)) - || matches!(ty.kind(), ty::Adt(def, _) if def.is_struct())) + && (matches!(cv.ty.kind(), ty::Tuple(_)) + || matches!(cv.ty.kind(), ty::Adt(def, _) if def.is_struct())) { // A Scalar tuple/struct; we can avoid creating an allocation. - let branches = valtree.unwrap_branch(); + let branches = cv.valtree.unwrap_branch(); // Find the non-ZST field. (There can be aligned ZST!) for (i, &inner_valtree) in branches.iter().enumerate() { let field = layout.field(&LayoutCx::new(tcx, typing_env), i); if !field.is_zst() { - return valtree_to_const_value(tcx, typing_env, field.ty, inner_valtree); + let cv = ty::Value { valtree: inner_valtree, ty: field.ty }; + return valtree_to_const_value(tcx, typing_env, cv); } } bug!("could not find non-ZST field during in {layout:#?}"); @@ -335,9 +339,9 @@ pub fn valtree_to_const_value<'tcx>( mk_eval_cx_to_read_const_val(tcx, DUMMY_SP, typing_env, CanAccessMutGlobal::No); // Need to create a place for this valtree. - let place = create_valtree_place(&mut ecx, layout, valtree); + let place = create_valtree_place(&mut ecx, layout, cv.valtree); - valtree_into_mplace(&mut ecx, &place, valtree); + valtree_into_mplace(&mut ecx, &place, cv.valtree); dump_place(&ecx, &place); intern_const_alloc_recursive(&mut ecx, InternKind::Constant, &place).unwrap(); @@ -362,7 +366,7 @@ pub fn valtree_to_const_value<'tcx>( | ty::Slice(_) | ty::Dynamic(..) | ty::UnsafeBinder(_) => { - bug!("no ValTree should have been created for type {:?}", ty.kind()) + bug!("no ValTree should have been created for type {:?}", cv.ty.kind()) } } } diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics.rs b/compiler/rustc_const_eval/src/interpret/intrinsics.rs index 9f5f2533e08..4ca317e3a1e 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics.rs @@ -319,7 +319,25 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { // Check that the memory between them is dereferenceable at all, starting from the // origin pointer: `dist` is `a - b`, so it is based on `b`. - self.check_ptr_access_signed(b, dist, CheckInAllocMsg::OffsetFromTest)?; + self.check_ptr_access_signed(b, dist, CheckInAllocMsg::OffsetFromTest) + .map_err_kind(|_| { + // This could mean they point to different allocations, or they point to the same allocation + // but not the entire range between the pointers is in-bounds. + if let Ok((a_alloc_id, ..)) = self.ptr_try_get_alloc_id(a, 0) + && let Ok((b_alloc_id, ..)) = self.ptr_try_get_alloc_id(b, 0) + && a_alloc_id == b_alloc_id + { + err_ub_custom!( + fluent::const_eval_offset_from_out_of_bounds, + name = intrinsic_name, + ) + } else { + err_ub_custom!( + fluent::const_eval_offset_from_different_allocations, + name = intrinsic_name, + ) + } + })?; // Then check that this is also dereferenceable from `a`. This ensures that they are // derived from the same allocation. self.check_ptr_access_signed( diff --git a/compiler/rustc_const_eval/src/lib.rs b/compiler/rustc_const_eval/src/lib.rs index ecf9745b779..b44d2a01d57 100644 --- a/compiler/rustc_const_eval/src/lib.rs +++ b/compiler/rustc_const_eval/src/lib.rs @@ -46,14 +46,8 @@ pub fn provide(providers: &mut Providers) { }; providers.hooks.try_destructure_mir_constant_for_user_output = const_eval::try_destructure_mir_constant_for_user_output; - providers.valtree_to_const_val = |tcx, cv| { - const_eval::valtree_to_const_value( - tcx, - ty::TypingEnv::fully_monomorphized(), - cv.ty, - cv.valtree, - ) - }; + providers.valtree_to_const_val = + |tcx, cv| const_eval::valtree_to_const_value(tcx, ty::TypingEnv::fully_monomorphized(), cv); providers.check_validity_requirement = |tcx, (init_kind, param_env_and_ty)| { util::check_validity_requirement(tcx, init_kind, param_env_and_ty) }; diff --git a/compiler/rustc_const_eval/src/util/caller_location.rs b/compiler/rustc_const_eval/src/util/caller_location.rs index 6dd9447cf5a..e926040e9ba 100644 --- a/compiler/rustc_const_eval/src/util/caller_location.rs +++ b/compiler/rustc_const_eval/src/util/caller_location.rs @@ -1,7 +1,6 @@ use rustc_hir::LangItem; -use rustc_middle::query::TyCtxtAt; use rustc_middle::ty::layout::LayoutOf; -use rustc_middle::ty::{self}; +use rustc_middle::ty::{self, TyCtxt}; use rustc_middle::{bug, mir}; use rustc_span::Symbol; use tracing::trace; @@ -48,15 +47,15 @@ fn alloc_caller_location<'tcx>( } pub(crate) fn const_caller_location_provider( - tcx: TyCtxtAt<'_>, + tcx: TyCtxt<'_>, file: Symbol, line: u32, col: u32, ) -> mir::ConstValue<'_> { trace!("const_caller_location: {}:{}:{}", file, line, col); let mut ecx = mk_eval_cx_to_read_const_val( - tcx.tcx, - tcx.span, + tcx, + rustc_span::DUMMY_SP, // FIXME: use a proper span here? ty::TypingEnv::fully_monomorphized(), CanAccessMutGlobal::No, ); diff --git a/compiler/rustc_data_structures/src/vec_cache.rs b/compiler/rustc_data_structures/src/vec_cache.rs index eb251b587c8..2ff60ab7f36 100644 --- a/compiler/rustc_data_structures/src/vec_cache.rs +++ b/compiler/rustc_data_structures/src/vec_cache.rs @@ -206,6 +206,19 @@ impl SlotIndex { } } +/// In-memory cache for queries whose keys are densely-numbered IDs +/// (e.g `CrateNum`, `LocalDefId`), and can therefore be used as indices +/// into a dense vector of cached values. +/// +/// (As of [#124780] the underlying storage is not an actual `Vec`, but rather +/// a series of increasingly-large buckets, for improved performance when the +/// parallel frontend is using multiple threads.) +/// +/// Each entry in the cache stores the query's return value (`V`), and also +/// an associated index (`I`), which in practice is a `DepNodeIndex` used for +/// query dependency tracking. +/// +/// [#124780]: https://github.com/rust-lang/rust/pull/124780 pub struct VecCache<K: Idx, V, I> { // Entries per bucket: // Bucket 0: 4096 2^12 diff --git a/compiler/rustc_feature/src/unstable.rs b/compiler/rustc_feature/src/unstable.rs index 1a216ebf117..784063b0e31 100644 --- a/compiler/rustc_feature/src/unstable.rs +++ b/compiler/rustc_feature/src/unstable.rs @@ -529,6 +529,8 @@ declare_features! ( (unstable, inline_const_pat, "1.58.0", Some(76001)), /// Allows using `pointer` and `reference` in intra-doc links (unstable, intra_doc_pointers, "1.51.0", Some(80896)), + // Allows using the `kl` and `widekl` target features and the associated intrinsics + (unstable, keylocker_x86, "CURRENT_RUSTC_VERSION", Some(134813)), // Allows setting the threshold for the `large_assignments` lint. (unstable, large_assignments, "1.52.0", Some(83518)), /// Allow to have type alias types for inter-crate use. @@ -568,6 +570,8 @@ declare_features! ( (unstable, never_type, "1.13.0", Some(35121)), /// Allows diverging expressions to fall back to `!` rather than `()`. (unstable, never_type_fallback, "1.41.0", Some(65992)), + /// Switch `..` syntax to use the new (`Copy + IntoIterator`) range types. + (unstable, new_range, "CURRENT_RUSTC_VERSION", Some(123741)), /// Allows `#![no_core]`. (unstable, no_core, "1.3.0", Some(29639)), /// Allows the use of `no_sanitize` attribute. diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 4113c7ed4bb..4631432038b 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -2330,6 +2330,18 @@ impl Expr<'_> { [val2], StructTailExpr::None, ), + ) + | ( + ExprKind::Struct( + QPath::LangItem(LangItem::RangeFromCopy, _), + [val1], + StructTailExpr::None, + ), + ExprKind::Struct( + QPath::LangItem(LangItem::RangeFromCopy, _), + [val2], + StructTailExpr::None, + ), ) => val1.expr.equivalent_for_indexing(val2.expr), ( ExprKind::Struct( @@ -2342,6 +2354,30 @@ impl Expr<'_> { [val2, val4], StructTailExpr::None, ), + ) + | ( + ExprKind::Struct( + QPath::LangItem(LangItem::RangeCopy, _), + [val1, val3], + StructTailExpr::None, + ), + ExprKind::Struct( + QPath::LangItem(LangItem::RangeCopy, _), + [val2, val4], + StructTailExpr::None, + ), + ) + | ( + ExprKind::Struct( + QPath::LangItem(LangItem::RangeInclusiveCopy, _), + [val1, val3], + StructTailExpr::None, + ), + ExprKind::Struct( + QPath::LangItem(LangItem::RangeInclusiveCopy, _), + [val2, val4], + StructTailExpr::None, + ), ) => { val1.expr.equivalent_for_indexing(val2.expr) && val3.expr.equivalent_for_indexing(val4.expr) @@ -2371,7 +2407,10 @@ pub fn is_range_literal(expr: &Expr<'_>) -> bool { | LangItem::RangeTo | LangItem::RangeFrom | LangItem::RangeFull - | LangItem::RangeToInclusive, + | LangItem::RangeToInclusive + | LangItem::RangeCopy + | LangItem::RangeFromCopy + | LangItem::RangeInclusiveCopy, .. ) ), diff --git a/compiler/rustc_hir/src/lang_items.rs b/compiler/rustc_hir/src/lang_items.rs index d9759580e8f..0f988568341 100644 --- a/compiler/rustc_hir/src/lang_items.rs +++ b/compiler/rustc_hir/src/lang_items.rs @@ -416,6 +416,11 @@ language_item_table! { RangeToInclusive, sym::RangeToInclusive, range_to_inclusive_struct, Target::Struct, GenericRequirement::None; RangeTo, sym::RangeTo, range_to_struct, Target::Struct, GenericRequirement::None; + // `new_range` types that are `Copy + IntoIterator` + RangeFromCopy, sym::RangeFromCopy, range_from_copy_struct, Target::Struct, GenericRequirement::None; + RangeCopy, sym::RangeCopy, range_copy_struct, Target::Struct, GenericRequirement::None; + RangeInclusiveCopy, sym::RangeInclusiveCopy, range_inclusive_copy_struct, Target::Struct, GenericRequirement::None; + String, sym::String, string, Target::Struct, GenericRequirement::None; CStr, sym::CStr, c_str, Target::Struct, GenericRequirement::None; } diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index 79e2d764ac5..20eb96f3ab1 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -328,16 +328,20 @@ fn check_item<'tcx>(tcx: TyCtxt<'tcx>, item: &'tcx hir::Item<'tcx>) -> Result<() hir::ItemKind::TraitAlias(..) => check_trait(tcx, item), // `ForeignItem`s are handled separately. hir::ItemKind::ForeignMod { .. } => Ok(()), - hir::ItemKind::TyAlias(hir_ty, hir_generics) => { - if tcx.type_alias_is_lazy(item.owner_id) { - // Bounds of lazy type aliases and of eager ones that contain opaque types are respected. - // E.g: `type X = impl Trait;`, `type X = (impl Trait, Y);`. - let res = check_item_type(tcx, def_id, hir_ty.span, UnsizedHandling::Allow); - check_variances_for_type_defn(tcx, item, hir_generics); - res - } else { + hir::ItemKind::TyAlias(hir_ty, hir_generics) if tcx.type_alias_is_lazy(item.owner_id) => { + let res = enter_wf_checking_ctxt(tcx, item.span, def_id, |wfcx| { + let ty = tcx.type_of(def_id).instantiate_identity(); + let item_ty = wfcx.normalize(hir_ty.span, Some(WellFormedLoc::Ty(def_id)), ty); + wfcx.register_wf_obligation( + hir_ty.span, + Some(WellFormedLoc::Ty(def_id)), + item_ty.into(), + ); + check_where_clauses(wfcx, item.span, def_id); Ok(()) - } + }); + check_variances_for_type_defn(tcx, item, hir_generics); + res } _ => Ok(()), }; @@ -1061,6 +1065,7 @@ fn check_associated_item( let ty = tcx.type_of(item.def_id).instantiate_identity(); let ty = wfcx.normalize(span, Some(WellFormedLoc::Ty(item_id)), ty); wfcx.register_wf_obligation(span, loc, ty.into()); + check_sized_if_body(wfcx, item.def_id.expect_local(), ty, Some(span)); Ok(()) } ty::AssocKind::Fn => { @@ -1185,7 +1190,7 @@ fn check_type_defn<'tcx>( ), wfcx.param_env, ty, - tcx.require_lang_item(LangItem::Sized, None), + tcx.require_lang_item(LangItem::Sized, Some(hir_ty.span)), ); } @@ -1276,7 +1281,6 @@ fn check_item_fn( enum UnsizedHandling { Forbid, - Allow, AllowIfForeignTail, } @@ -1294,7 +1298,6 @@ fn check_item_type( let forbid_unsized = match unsized_handling { UnsizedHandling::Forbid => true, - UnsizedHandling::Allow => false, UnsizedHandling::AllowIfForeignTail => { let tail = tcx.struct_tail_for_codegen(item_ty, wfcx.infcx.typing_env(wfcx.param_env)); @@ -1312,7 +1315,7 @@ fn check_item_type( ), wfcx.param_env, item_ty, - tcx.require_lang_item(LangItem::Sized, None), + tcx.require_lang_item(LangItem::Sized, Some(ty_span)), ); } @@ -1642,6 +1645,31 @@ fn check_fn_or_method<'tcx>( ); } } + + // If the function has a body, additionally require that the return type is sized. + check_sized_if_body(wfcx, def_id, sig.output(), match hir_decl.output { + hir::FnRetTy::Return(ty) => Some(ty.span), + hir::FnRetTy::DefaultReturn(_) => None, + }); +} + +fn check_sized_if_body<'tcx>( + wfcx: &WfCheckingCtxt<'_, 'tcx>, + def_id: LocalDefId, + ty: Ty<'tcx>, + maybe_span: Option<Span>, +) { + let tcx = wfcx.tcx(); + if let Some(body) = tcx.hir().maybe_body_owned_by(def_id) { + let span = maybe_span.unwrap_or(body.value.span); + + wfcx.register_bound( + ObligationCause::new(span, def_id, traits::ObligationCauseCode::SizedReturnType), + wfcx.param_env, + ty, + tcx.require_lang_item(LangItem::Sized, Some(span)), + ); + } } /// The `arbitrary_self_types_pointers` feature implies `arbitrary_self_types`. diff --git a/compiler/rustc_hir_typeck/src/check.rs b/compiler/rustc_hir_typeck/src/check.rs index b0698183b57..9fdc5a0ae4e 100644 --- a/compiler/rustc_hir_typeck/src/check.rs +++ b/compiler/rustc_hir_typeck/src/check.rs @@ -117,22 +117,17 @@ pub(super) fn check_fn<'a, 'tcx>( fcx.typeck_results.borrow_mut().liberated_fn_sigs_mut().insert(fn_id, fn_sig); - let return_or_body_span = match decl.output { - hir::FnRetTy::DefaultReturn(_) => body.value.span, - hir::FnRetTy::Return(ty) => ty.span, - }; - - fcx.require_type_is_sized( - declared_ret_ty, - return_or_body_span, - ObligationCauseCode::SizedReturnType, - ); - // We checked the root's signature during wfcheck, but not the child. + // We checked the root's ret ty during wfcheck, but not the child. if fcx.tcx.is_typeck_child(fn_def_id.to_def_id()) { + let return_or_body_span = match decl.output { + hir::FnRetTy::DefaultReturn(_) => body.value.span, + hir::FnRetTy::Return(ty) => ty.span, + }; + fcx.require_type_is_sized( declared_ret_ty, return_or_body_span, - ObligationCauseCode::WellFormed(None), + ObligationCauseCode::SizedReturnType, ); } diff --git a/compiler/rustc_hir_typeck/src/lib.rs b/compiler/rustc_hir_typeck/src/lib.rs index 07e013e4afa..02fbd46173c 100644 --- a/compiler/rustc_hir_typeck/src/lib.rs +++ b/compiler/rustc_hir_typeck/src/lib.rs @@ -186,8 +186,6 @@ fn typeck_with_inspect<'tcx>( let wf_code = ObligationCauseCode::WellFormed(Some(WellFormedLoc::Ty(def_id))); fcx.register_wf_obligation(expected_type.into(), body.value.span, wf_code); - fcx.require_type_is_sized(expected_type, body.value.span, ObligationCauseCode::ConstSized); - // Gather locals in statics (because of block expressions). GatherLocalsVisitor::new(&fcx).visit_body(body); diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index 920418407c0..cbbda0b6cbc 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -2395,6 +2395,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let lang_item = match parent_expr.kind { ExprKind::Struct(qpath, _, _) => match *qpath { QPath::LangItem(LangItem::Range, ..) => Some(LangItem::Range), + QPath::LangItem(LangItem::RangeCopy, ..) => Some(LangItem::RangeCopy), + QPath::LangItem(LangItem::RangeInclusiveCopy, ..) => { + Some(LangItem::RangeInclusiveCopy) + } QPath::LangItem(LangItem::RangeTo, ..) => Some(LangItem::RangeTo), QPath::LangItem(LangItem::RangeToInclusive, ..) => { Some(LangItem::RangeToInclusive) diff --git a/compiler/rustc_incremental/src/lib.rs b/compiler/rustc_incremental/src/lib.rs index 6dab6468870..563ed7614c6 100644 --- a/compiler/rustc_incremental/src/lib.rs +++ b/compiler/rustc_incremental/src/lib.rs @@ -24,7 +24,7 @@ use rustc_middle::util::Providers; #[allow(missing_docs)] pub fn provide(providers: &mut Providers) { providers.hooks.save_dep_graph = - |tcx| tcx.sess.time("serialize_dep_graph", || persist::save_dep_graph(tcx.tcx)); + |tcx| tcx.sess.time("serialize_dep_graph", || persist::save_dep_graph(tcx)); } rustc_fluent_macro::fluent_messages! { "../messages.ftl" } diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index 0324ebf9fd2..8a121c5a865 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -268,6 +268,7 @@ fn configure_and_expand( resolver.resolve_crate(&krate); + CStore::from_tcx(tcx).report_incompatible_target_modifiers(tcx, &krate); krate } diff --git a/compiler/rustc_lint/src/context.rs b/compiler/rustc_lint/src/context.rs index 50bb1fb942e..e0863aa035c 100644 --- a/compiler/rustc_lint/src/context.rs +++ b/compiler/rustc_lint/src/context.rs @@ -4,7 +4,7 @@ //! overview of how lints are implemented. use std::cell::Cell; -use std::{iter, slice}; +use std::slice; use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::sync; @@ -718,30 +718,6 @@ impl<'tcx> LateContext<'tcx> { } } - /// Check if a `DefId`'s path matches the given absolute type path usage. - /// - /// Anonymous scopes such as `extern` imports are matched with `kw::Empty`; - /// inherent `impl` blocks are matched with the name of the type. - /// - /// Instead of using this method, it is often preferable to instead use - /// `rustc_diagnostic_item` or a `lang_item`. This is less prone to errors - /// as paths get invalidated if the target definition moves. - /// - /// # Examples - /// - /// ```rust,ignore (no context or def id available) - /// if cx.match_def_path(def_id, &[sym::core, sym::option, sym::Option]) { - /// // The given `def_id` is that of an `Option` type - /// } - /// ``` - /// - /// Used by clippy, but should be replaced by diagnostic items eventually. - pub fn match_def_path(&self, def_id: DefId, path: &[Symbol]) -> bool { - let names = self.get_def_path(def_id); - - names.len() == path.len() && iter::zip(names, path).all(|(a, &b)| a == b) - } - /// Gets the absolute path of `def_id` as a vector of `Symbol`. /// /// # Examples diff --git a/compiler/rustc_metadata/messages.ftl b/compiler/rustc_metadata/messages.ftl index d2b5ae53185..6fc84b06647 100644 --- a/compiler/rustc_metadata/messages.ftl +++ b/compiler/rustc_metadata/messages.ftl @@ -113,6 +113,14 @@ metadata_incompatible_rustc = found crate `{$crate_name}` compiled by an incompatible version of rustc{$add_info} .help = please recompile that crate using this compiler ({$rustc_version}) (consider running `cargo clean` first) +metadata_incompatible_target_modifiers = + mixing `{$flag_name_prefixed}` will cause an ABI mismatch in crate `{$local_crate}` + .note = `{$flag_name_prefixed}={$flag_local_value}` in this crate is incompatible with `{$flag_name_prefixed}={$flag_extern_value}` in dependency `{$extern_crate}` + .help = the `{$flag_name_prefixed}` flag modifies the ABI so Rust crates compiled with different values of this flag cannot be used together safely + +metadata_incompatible_target_modifiers_help_allow = if you are sure this will not cause problems, you may use `-Cunsafe-allow-abi-mismatch={$flag_name}` to silence this error +metadata_incompatible_target_modifiers_help_fix = set `{$flag_name_prefixed}={$flag_extern_value}` in this crate or `{$flag_name_prefixed}={$flag_local_value}` in `{$extern_crate}` + metadata_incompatible_wasm_link = `wasm_import_module` is incompatible with other arguments in `#[link]` attributes @@ -284,6 +292,8 @@ metadata_unknown_link_kind = metadata_unknown_link_modifier = unknown linking modifier `{$modifier}`, expected one of: bundle, verbatim, whole-archive, as-needed +metadata_unknown_target_modifier_unsafe_allowed = unknown target modifier `{$flag_name}`, requested by `-Cunsafe-allow-abi-mismatch={$flag_name}` + metadata_unsupported_abi = ABI not supported by `#[link(kind = "raw-dylib")]` on this architecture diff --git a/compiler/rustc_metadata/src/creader.rs b/compiler/rustc_metadata/src/creader.rs index a6cd0ecafd0..6bad8312790 100644 --- a/compiler/rustc_metadata/src/creader.rs +++ b/compiler/rustc_metadata/src/creader.rs @@ -23,7 +23,10 @@ use rustc_hir::definitions::Definitions; use rustc_index::IndexVec; use rustc_middle::bug; use rustc_middle::ty::{TyCtxt, TyCtxtFeed}; -use rustc_session::config::{self, CrateType, ExternLocation}; +use rustc_session::config::{ + self, CrateType, ExtendedTargetModifierInfo, ExternLocation, OptionsTargetModifiers, + TargetModifier, +}; use rustc_session::cstore::{CrateDepKind, CrateSource, ExternCrate, ExternCrateSource}; use rustc_session::lint::{self, BuiltinLintDiag}; use rustc_session::output::validate_crate_name; @@ -35,7 +38,9 @@ use tracing::{debug, info, trace}; use crate::errors; use crate::locator::{CrateError, CrateLocator, CratePaths}; -use crate::rmeta::{CrateDep, CrateMetadata, CrateNumMap, CrateRoot, MetadataBlob}; +use crate::rmeta::{ + CrateDep, CrateMetadata, CrateNumMap, CrateRoot, MetadataBlob, TargetModifiers, +}; /// The backend's way to give the crate store access to the metadata in a library. /// Note that it returns the raw metadata bytes stored in the library file, whether @@ -296,6 +301,94 @@ impl CStore { } } + fn report_target_modifiers_extended( + tcx: TyCtxt<'_>, + krate: &Crate, + mods: &TargetModifiers, + dep_mods: &TargetModifiers, + data: &CrateMetadata, + ) { + let span = krate.spans.inner_span.shrink_to_lo(); + let allowed_flag_mismatches = &tcx.sess.opts.cg.unsafe_allow_abi_mismatch; + let name = tcx.crate_name(LOCAL_CRATE); + let tmod_extender = |tmod: &TargetModifier| (tmod.extend(), tmod.clone()); + let report_diff = |prefix: &String, + opt_name: &String, + flag_local_value: &String, + flag_extern_value: &String| { + if allowed_flag_mismatches.contains(&opt_name) { + return; + } + tcx.dcx().emit_err(errors::IncompatibleTargetModifiers { + span, + extern_crate: data.name(), + local_crate: name, + flag_name: opt_name.clone(), + flag_name_prefixed: format!("-{}{}", prefix, opt_name), + flag_local_value: flag_local_value.to_string(), + flag_extern_value: flag_extern_value.to_string(), + }); + }; + let mut it1 = mods.iter().map(tmod_extender); + let mut it2 = dep_mods.iter().map(tmod_extender); + let mut left_name_val: Option<(ExtendedTargetModifierInfo, TargetModifier)> = None; + let mut right_name_val: Option<(ExtendedTargetModifierInfo, TargetModifier)> = None; + let no_val = "*".to_string(); + loop { + left_name_val = left_name_val.or_else(|| it1.next()); + right_name_val = right_name_val.or_else(|| it2.next()); + match (&left_name_val, &right_name_val) { + (Some(l), Some(r)) => match l.1.opt.cmp(&r.1.opt) { + cmp::Ordering::Equal => { + if l.0.tech_value != r.0.tech_value { + report_diff(&l.0.prefix, &l.0.name, &l.1.value_name, &r.1.value_name); + } + left_name_val = None; + right_name_val = None; + } + cmp::Ordering::Greater => { + report_diff(&r.0.prefix, &r.0.name, &no_val, &r.1.value_name); + right_name_val = None; + } + cmp::Ordering::Less => { + report_diff(&l.0.prefix, &l.0.name, &l.1.value_name, &no_val); + left_name_val = None; + } + }, + (Some(l), None) => { + report_diff(&l.0.prefix, &l.0.name, &l.1.value_name, &no_val); + left_name_val = None; + } + (None, Some(r)) => { + report_diff(&r.0.prefix, &r.0.name, &no_val, &r.1.value_name); + right_name_val = None; + } + (None, None) => break, + } + } + } + + pub fn report_incompatible_target_modifiers(&self, tcx: TyCtxt<'_>, krate: &Crate) { + for flag_name in &tcx.sess.opts.cg.unsafe_allow_abi_mismatch { + if !OptionsTargetModifiers::is_target_modifier(flag_name) { + tcx.dcx().emit_err(errors::UnknownTargetModifierUnsafeAllowed { + span: krate.spans.inner_span.shrink_to_lo(), + flag_name: flag_name.clone(), + }); + } + } + let mods = tcx.sess.opts.gather_target_modifiers(); + for (_cnum, data) in self.iter_crate_data() { + if data.is_proc_macro_crate() { + continue; + } + let dep_mods = data.target_modifiers(); + if mods != dep_mods { + Self::report_target_modifiers_extended(tcx, krate, &mods, &dep_mods, data); + } + } + } + pub fn new(metadata_loader: Box<MetadataLoaderDyn>) -> CStore { CStore { metadata_loader, diff --git a/compiler/rustc_metadata/src/errors.rs b/compiler/rustc_metadata/src/errors.rs index cefc6498f68..a77f9bc623b 100644 --- a/compiler/rustc_metadata/src/errors.rs +++ b/compiler/rustc_metadata/src/errors.rs @@ -739,3 +739,28 @@ pub(crate) struct WasmCAbi { #[primary_span] pub span: Span, } + +#[derive(Diagnostic)] +#[diag(metadata_incompatible_target_modifiers)] +#[help] +#[note] +#[help(metadata_incompatible_target_modifiers_help_fix)] +#[help(metadata_incompatible_target_modifiers_help_allow)] +pub struct IncompatibleTargetModifiers { + #[primary_span] + pub span: Span, + pub extern_crate: Symbol, + pub local_crate: Symbol, + pub flag_name: String, + pub flag_name_prefixed: String, + pub flag_local_value: String, + pub flag_extern_value: String, +} + +#[derive(Diagnostic)] +#[diag(metadata_unknown_target_modifier_unsafe_allowed)] +pub struct UnknownTargetModifierUnsafeAllowed { + #[primary_span] + pub span: Span, + pub flag_name: String, +} diff --git a/compiler/rustc_metadata/src/rmeta/decoder.rs b/compiler/rustc_metadata/src/rmeta/decoder.rs index e02c4871f35..2ae4a6a6066 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder.rs @@ -29,6 +29,7 @@ use rustc_middle::{bug, implement_ty_decoder}; use rustc_serialize::opaque::MemDecoder; use rustc_serialize::{Decodable, Decoder}; use rustc_session::Session; +use rustc_session::config::TargetModifier; use rustc_session::cstore::{CrateSource, ExternCrate}; use rustc_span::hygiene::HygieneDecodeContext; use rustc_span::{BytePos, DUMMY_SP, Pos, SpanData, SpanDecoder, SyntaxContext, kw}; @@ -73,6 +74,9 @@ impl MetadataBlob { /// own crate numbers. pub(crate) type CrateNumMap = IndexVec<CrateNum, CrateNum>; +/// Target modifiers - abi or exploit mitigations flags +pub(crate) type TargetModifiers = Vec<TargetModifier>; + pub(crate) struct CrateMetadata { /// The primary crate data - binary metadata blob. blob: MetadataBlob, @@ -961,6 +965,13 @@ impl CrateRoot { ) -> impl ExactSizeIterator<Item = CrateDep> + Captures<'a> { self.crate_deps.decode(metadata) } + + pub(crate) fn decode_target_modifiers<'a>( + &self, + metadata: &'a MetadataBlob, + ) -> impl ExactSizeIterator<Item = TargetModifier> + Captures<'a> { + self.target_modifiers.decode(metadata) + } } impl<'a> CrateMetadataRef<'a> { @@ -1883,6 +1894,10 @@ impl CrateMetadata { self.dependencies.push(cnum); } + pub(crate) fn target_modifiers(&self) -> TargetModifiers { + self.root.decode_target_modifiers(&self.blob).collect() + } + pub(crate) fn update_extern_crate(&mut self, new_extern_crate: ExternCrate) -> bool { let update = Some(new_extern_crate.rank()) > self.extern_crate.as_ref().map(ExternCrate::rank); diff --git a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs index 5fcb9c85035..028ff56155f 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs @@ -689,7 +689,7 @@ fn provide_cstore_hooks(providers: &mut Providers) { providers.hooks.def_path_hash_to_def_id_extern = |tcx, hash, stable_crate_id| { // If this is a DefPathHash from an upstream crate, let the CrateStore map // it to a DefId. - let cstore = CStore::from_tcx(tcx.tcx); + let cstore = CStore::from_tcx(tcx); let cnum = *tcx .untracked() .stable_crate_ids @@ -702,11 +702,11 @@ fn provide_cstore_hooks(providers: &mut Providers) { }; providers.hooks.expn_hash_to_expn_id = |tcx, cnum, index_guess, hash| { - let cstore = CStore::from_tcx(tcx.tcx); + let cstore = CStore::from_tcx(tcx); cstore.get_crate_data(cnum).expn_hash_to_expn_id(tcx.sess, index_guess, hash) }; providers.hooks.import_source_files = |tcx, cnum| { - let cstore = CStore::from_tcx(tcx.tcx); + let cstore = CStore::from_tcx(tcx); let cdata = cstore.get_crate_data(cnum); for file_index in 0..cdata.root.source_map.size() { cdata.imported_source_file(file_index as u32, tcx.sess); diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 6e562e457d2..db41a33dcc5 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -25,7 +25,7 @@ use rustc_middle::ty::fast_reject::{self, TreatParams}; use rustc_middle::ty::{AssocItemContainer, SymbolName}; use rustc_middle::{bug, span_bug}; use rustc_serialize::{Decodable, Decoder, Encodable, Encoder, opaque}; -use rustc_session::config::{CrateType, OptLevel}; +use rustc_session::config::{CrateType, OptLevel, TargetModifier}; use rustc_span::hygiene::HygieneEncodeContext; use rustc_span::{ ExternalSource, FileName, SourceFile, SpanData, SpanEncoder, StableSourceFileId, SyntaxContext, @@ -692,6 +692,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { // Encode source_map. This needs to be done last, because encoding `Span`s tells us which // `SourceFiles` we actually need to encode. let source_map = stat!("source-map", || self.encode_source_map()); + let target_modifiers = stat!("target-modifiers", || self.encode_target_modifiers()); let root = stat!("final", || { let attrs = tcx.hir().krate_attrs(); @@ -735,6 +736,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { native_libraries, foreign_modules, source_map, + target_modifiers, traits, impls, incoherent_impls, @@ -2009,6 +2011,12 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { self.lazy_array(deps.iter().map(|(_, dep)| dep)) } + fn encode_target_modifiers(&mut self) -> LazyArray<TargetModifier> { + empty_proc_macro!(self); + let tcx = self.tcx; + self.lazy_array(tcx.sess.opts.gather_target_modifiers()) + } + fn encode_lib_features(&mut self) -> LazyArray<(Symbol, FeatureStability)> { empty_proc_macro!(self); let tcx = self.tcx; diff --git a/compiler/rustc_metadata/src/rmeta/mod.rs b/compiler/rustc_metadata/src/rmeta/mod.rs index d1d356c5220..7b34e605c53 100644 --- a/compiler/rustc_metadata/src/rmeta/mod.rs +++ b/compiler/rustc_metadata/src/rmeta/mod.rs @@ -1,7 +1,7 @@ use std::marker::PhantomData; use std::num::NonZero; -pub(crate) use decoder::{CrateMetadata, CrateNumMap, MetadataBlob}; +pub(crate) use decoder::{CrateMetadata, CrateNumMap, MetadataBlob, TargetModifiers}; use decoder::{DecodeContext, Metadata}; use def_path_hash_map::DefPathHashMapRef; use encoder::EncodeContext; @@ -32,7 +32,7 @@ use rustc_middle::ty::{ use rustc_middle::util::Providers; use rustc_middle::{mir, trivially_parameterized_over_tcx}; use rustc_serialize::opaque::FileEncoder; -use rustc_session::config::SymbolManglingVersion; +use rustc_session::config::{SymbolManglingVersion, TargetModifier}; use rustc_session::cstore::{CrateDepKind, ForeignModule, LinkagePreference, NativeLib}; use rustc_span::edition::Edition; use rustc_span::hygiene::{ExpnIndex, MacroKind, SyntaxContextData}; @@ -282,6 +282,7 @@ pub(crate) struct CrateRoot { def_path_hash_map: LazyValue<DefPathHashMapRef<'static>>, source_map: LazyTable<u32, Option<LazyValue<rustc_span::SourceFile>>>, + target_modifiers: LazyArray<TargetModifier>, compiler_builtins: bool, needs_allocator: bool, diff --git a/compiler/rustc_middle/src/dep_graph/dep_node.rs b/compiler/rustc_middle/src/dep_graph/dep_node.rs index fcfc31575f8..7525aeb9227 100644 --- a/compiler/rustc_middle/src/dep_graph/dep_node.rs +++ b/compiler/rustc_middle/src/dep_graph/dep_node.rs @@ -1,61 +1,3 @@ -//! Nodes in the dependency graph. -//! -//! A node in the [dependency graph] is represented by a [`DepNode`]. -//! A `DepNode` consists of a [`DepKind`] (which -//! specifies the kind of thing it represents, like a piece of HIR, MIR, etc.) -//! and a [`Fingerprint`], a 128-bit hash value, the exact meaning of which -//! depends on the node's `DepKind`. Together, the kind and the fingerprint -//! fully identify a dependency node, even across multiple compilation sessions. -//! In other words, the value of the fingerprint does not depend on anything -//! that is specific to a given compilation session, like an unpredictable -//! interning key (e.g., `NodeId`, `DefId`, `Symbol`) or the numeric value of a -//! pointer. The concept behind this could be compared to how git commit hashes -//! uniquely identify a given commit. The fingerprinting approach has -//! a few advantages: -//! -//! * A `DepNode` can simply be serialized to disk and loaded in another session -//! without the need to do any "rebasing" (like we have to do for Spans and -//! NodeIds) or "retracing" (like we had to do for `DefId` in earlier -//! implementations of the dependency graph). -//! * A `Fingerprint` is just a bunch of bits, which allows `DepNode` to -//! implement `Copy`, `Sync`, `Send`, `Freeze`, etc. -//! * Since we just have a bit pattern, `DepNode` can be mapped from disk into -//! memory without any post-processing (e.g., "abomination-style" pointer -//! reconstruction). -//! * Because a `DepNode` is self-contained, we can instantiate `DepNodes` that -//! refer to things that do not exist anymore. In previous implementations -//! `DepNode` contained a `DefId`. A `DepNode` referring to something that -//! had been removed between the previous and the current compilation session -//! could not be instantiated because the current compilation session -//! contained no `DefId` for thing that had been removed. -//! -//! `DepNode` definition happens in the `define_dep_nodes!()` macro. This macro -//! defines the `DepKind` enum. Each `DepKind` has its own parameters that are -//! needed at runtime in order to construct a valid `DepNode` fingerprint. -//! However, only `CompileCodegenUnit` and `CompileMonoItem` are constructed -//! explicitly (with `make_compile_codegen_unit` cq `make_compile_mono_item`). -//! -//! Because the macro sees what parameters a given `DepKind` requires, it can -//! "infer" some properties for each kind of `DepNode`: -//! -//! * Whether a `DepNode` of a given kind has any parameters at all. Some -//! `DepNode`s could represent global concepts with only one value. -//! * Whether it is possible, in principle, to reconstruct a query key from a -//! given `DepNode`. Many `DepKind`s only require a single `DefId` parameter, -//! in which case it is possible to map the node's fingerprint back to the -//! `DefId` it was computed from. In other cases, too much information gets -//! lost during fingerprint computation. -//! -//! `make_compile_codegen_unit` and `make_compile_mono_items`, together with -//! `DepNode::new()`, ensures that only valid `DepNode` instances can be -//! constructed. For example, the API does not allow for constructing -//! parameterless `DepNode`s with anything other than a zeroed out fingerprint. -//! More generally speaking, it relieves the user of the `DepNode` API of -//! having to know how to compute the expected fingerprint for a given set of -//! node parameters. -//! -//! [dependency graph]: https://rustc-dev-guide.rust-lang.org/query.html - use rustc_data_structures::fingerprint::Fingerprint; use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE, LocalDefId, LocalModDefId, ModDefId}; use rustc_hir::definitions::DefPathHash; @@ -158,26 +100,14 @@ pub(crate) fn make_compile_mono_item<'tcx>( } pub trait DepNodeExt: Sized { - /// Extracts the DefId corresponding to this DepNode. This will work - /// if two conditions are met: - /// - /// 1. The Fingerprint of the DepNode actually is a DefPathHash, and - /// 2. the item that the DefPath refers to exists in the current tcx. - /// - /// Condition (1) is determined by the DepKind variant of the - /// DepNode. Condition (2) might not be fulfilled if a DepNode - /// refers to something from the previous compilation session that - /// has been removed. fn extract_def_id(&self, tcx: TyCtxt<'_>) -> Option<DefId>; - /// Used in testing fn from_label_string( tcx: TyCtxt<'_>, label: &str, def_path_hash: DefPathHash, ) -> Result<Self, ()>; - /// Used in testing fn has_label_string(label: &str) -> bool; } @@ -399,52 +329,46 @@ impl<'tcx> DepNodeParams<TyCtxt<'tcx>> for HirId { } } -macro_rules! impl_for_typed_def_id { - ($Name:ident, $LocalName:ident) => { - impl<'tcx> DepNodeParams<TyCtxt<'tcx>> for $Name { - #[inline(always)] - fn fingerprint_style() -> FingerprintStyle { - FingerprintStyle::DefPathHash - } +impl<'tcx> DepNodeParams<TyCtxt<'tcx>> for ModDefId { + #[inline(always)] + fn fingerprint_style() -> FingerprintStyle { + FingerprintStyle::DefPathHash + } - #[inline(always)] - fn to_fingerprint(&self, tcx: TyCtxt<'tcx>) -> Fingerprint { - self.to_def_id().to_fingerprint(tcx) - } + #[inline(always)] + fn to_fingerprint(&self, tcx: TyCtxt<'tcx>) -> Fingerprint { + self.to_def_id().to_fingerprint(tcx) + } - #[inline(always)] - fn to_debug_str(&self, tcx: TyCtxt<'tcx>) -> String { - self.to_def_id().to_debug_str(tcx) - } + #[inline(always)] + fn to_debug_str(&self, tcx: TyCtxt<'tcx>) -> String { + self.to_def_id().to_debug_str(tcx) + } - #[inline(always)] - fn recover(tcx: TyCtxt<'tcx>, dep_node: &DepNode) -> Option<Self> { - DefId::recover(tcx, dep_node).map($Name::new_unchecked) - } - } + #[inline(always)] + fn recover(tcx: TyCtxt<'tcx>, dep_node: &DepNode) -> Option<Self> { + DefId::recover(tcx, dep_node).map(ModDefId::new_unchecked) + } +} - impl<'tcx> DepNodeParams<TyCtxt<'tcx>> for $LocalName { - #[inline(always)] - fn fingerprint_style() -> FingerprintStyle { - FingerprintStyle::DefPathHash - } +impl<'tcx> DepNodeParams<TyCtxt<'tcx>> for LocalModDefId { + #[inline(always)] + fn fingerprint_style() -> FingerprintStyle { + FingerprintStyle::DefPathHash + } - #[inline(always)] - fn to_fingerprint(&self, tcx: TyCtxt<'tcx>) -> Fingerprint { - self.to_def_id().to_fingerprint(tcx) - } + #[inline(always)] + fn to_fingerprint(&self, tcx: TyCtxt<'tcx>) -> Fingerprint { + self.to_def_id().to_fingerprint(tcx) + } - #[inline(always)] - fn to_debug_str(&self, tcx: TyCtxt<'tcx>) -> String { - self.to_def_id().to_debug_str(tcx) - } + #[inline(always)] + fn to_debug_str(&self, tcx: TyCtxt<'tcx>) -> String { + self.to_def_id().to_debug_str(tcx) + } - #[inline(always)] - fn recover(tcx: TyCtxt<'tcx>, dep_node: &DepNode) -> Option<Self> { - LocalDefId::recover(tcx, dep_node).map($LocalName::new_unchecked) - } - } - }; + #[inline(always)] + fn recover(tcx: TyCtxt<'tcx>, dep_node: &DepNode) -> Option<Self> { + LocalDefId::recover(tcx, dep_node).map(LocalModDefId::new_unchecked) + } } - -impl_for_typed_def_id! { ModDefId, LocalModDefId } diff --git a/compiler/rustc_middle/src/hooks/mod.rs b/compiler/rustc_middle/src/hooks/mod.rs index 2be242364c1..276a02b4e0f 100644 --- a/compiler/rustc_middle/src/hooks/mod.rs +++ b/compiler/rustc_middle/src/hooks/mod.rs @@ -6,11 +6,9 @@ use rustc_hir::def_id::{DefId, DefPathHash}; use rustc_session::StableCrateId; use rustc_span::def_id::{CrateNum, LocalDefId}; -use rustc_span::{DUMMY_SP, ExpnHash, ExpnId}; -use tracing::instrument; +use rustc_span::{ExpnHash, ExpnId}; use crate::mir; -use crate::query::TyCtxtAt; use crate::ty::{Ty, TyCtxt}; macro_rules! declare_hooks { @@ -22,26 +20,14 @@ macro_rules! declare_hooks { #[inline(always)] pub fn $name(self, $($arg: $K,)*) -> $V { - self.at(DUMMY_SP).$name($($arg,)*) - } - )* - } - - impl<'tcx> TyCtxtAt<'tcx> { - $( - $(#[$attr])* - #[inline(always)] - #[instrument(level = "debug", skip(self), ret)] - pub fn $name(self, $($arg: $K,)*) -> $V - { - (self.tcx.hooks.$name)(self, $($arg,)*) + (self.hooks.$name)(self, $($arg,)*) } )* } pub struct Providers { $(pub $name: for<'tcx> fn( - TyCtxtAt<'tcx>, + TyCtxt<'tcx>, $($arg: $K,)* ) -> $V,)* } diff --git a/compiler/rustc_middle/src/lib.rs b/compiler/rustc_middle/src/lib.rs index bbe23d8abe8..7a6d329fd47 100644 --- a/compiler/rustc_middle/src/lib.rs +++ b/compiler/rustc_middle/src/lib.rs @@ -1,10 +1,11 @@ //! The "main crate" of the Rust compiler. This crate contains common //! type definitions that are used by the other crates in the rustc -//! "family". Some prominent examples (note that each of these modules -//! has their own README with further details). +//! "family". The following are some prominent examples. //! //! - **HIR.** The "high-level (H) intermediate representation (IR)" is //! defined in the [`hir`] module. +//! - **THIR.** The "typed high-level (H) intermediate representation (IR)" +//! is defined in the [`thir`] module. //! - **MIR.** The "mid-level (M) intermediate representation (IR)" is //! defined in the [`mir`] module. This module contains only the //! *definition* of the MIR; the passes that transform and operate @@ -37,7 +38,6 @@ #![feature(box_as_ptr)] #![feature(box_patterns)] #![feature(closure_track_caller)] -#![feature(const_type_name)] #![feature(core_intrinsics)] #![feature(coroutines)] #![feature(debug_closure_helpers)] @@ -50,7 +50,6 @@ #![feature(intra_doc_pointers)] #![feature(iter_from_coroutine)] #![feature(let_chains)] -#![feature(macro_metavar_expr)] #![feature(min_specialization)] #![feature(negative_impls)] #![feature(never_type)] diff --git a/compiler/rustc_middle/src/mir/pretty.rs b/compiler/rustc_middle/src/mir/pretty.rs index 09d7e60e199..aa8ec3aff04 100644 --- a/compiler/rustc_middle/src/mir/pretty.rs +++ b/compiler/rustc_middle/src/mir/pretty.rs @@ -12,6 +12,7 @@ use rustc_middle::mir::interpret::{ use rustc_middle::mir::visit::Visitor; use rustc_middle::mir::*; use tracing::trace; +use ty::print::PrettyPrinter; use super::graphviz::write_mir_fn_graphviz; use crate::mir::interpret::ConstAllocation; @@ -1439,10 +1440,10 @@ impl<'tcx> Visitor<'tcx> for ExtraComments<'tcx> { }) }; - // FIXME: call pretty_print_const_valtree? - let fmt_valtree = |valtree: &ty::ValTree<'tcx>| match valtree { - ty::ValTree::Leaf(leaf) => format!("Leaf({leaf:?})"), - ty::ValTree::Branch(_) => "Branch(..)".to_string(), + let fmt_valtree = |cv: &ty::Value<'tcx>| { + let mut cx = FmtPrinter::new(self.tcx, Namespace::ValueNS); + cx.pretty_print_const_valtree(*cv, /*print_ty*/ true).unwrap(); + cx.into_buffer() }; let val = match const_ { @@ -1452,7 +1453,7 @@ impl<'tcx> Visitor<'tcx> for ExtraComments<'tcx> { format!("ty::Unevaluated({}, {:?})", self.tcx.def_path_str(uv.def), uv.args,) } ty::ConstKind::Value(cv) => { - format!("ty::Valtree({})", fmt_valtree(&cv.valtree)) + format!("ty::Valtree({})", fmt_valtree(&cv)) } // No `ty::` prefix since we also use this to represent errors from `mir::Unevaluated`. ty::ConstKind::Error(_) => "Error".to_string(), diff --git a/compiler/rustc_middle/src/query/keys.rs b/compiler/rustc_middle/src/query/keys.rs index 949d8303385..1489d57aba6 100644 --- a/compiler/rustc_middle/src/query/keys.rs +++ b/compiler/rustc_middle/src/query/keys.rs @@ -20,6 +20,12 @@ pub struct LocalCrate; /// The `Key` trait controls what types can legally be used as the key /// for a query. pub trait Key: Sized { + /// The type of in-memory cache to use for queries with this key type. + /// + /// In practice the cache type must implement [`QueryCache`], though that + /// constraint is not enforced here. + /// + /// [`QueryCache`]: rustc_query_system::query::QueryCache // N.B. Most of the keys down below have `type Cache<V> = DefaultCache<Self, V>;`, // it would be reasonable to use associated type defaults, to remove the duplication... // diff --git a/compiler/rustc_middle/src/thir.rs b/compiler/rustc_middle/src/thir.rs index d56046136c7..e2e2029a362 100644 --- a/compiler/rustc_middle/src/thir.rs +++ b/compiler/rustc_middle/src/thir.rs @@ -18,7 +18,7 @@ use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_hir::{BindingMode, ByRef, HirId, MatchSource, RangeEnd}; use rustc_index::{IndexVec, newtype_index}; -use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeVisitable}; +use rustc_macros::{HashStable, TypeVisitable}; use rustc_middle::middle::region; use rustc_middle::mir::interpret::AllocId; use rustc_middle::mir::{self, BinOp, BorrowKind, FakeReadCause, UnOp}; @@ -37,9 +37,6 @@ pub mod visit; macro_rules! thir_with_elements { ( - $($field_name:ident: $field_ty:ty,)* - - @elements: $($name:ident: $id:ty => $value:ty => $format:literal,)* ) => { $( @@ -53,22 +50,18 @@ macro_rules! thir_with_elements { /// A container for a THIR body. /// /// This can be indexed directly by any THIR index (e.g. [`ExprId`]). - #[derive(Debug, HashStable, Clone)] + #[derive(Debug, HashStable)] pub struct Thir<'tcx> { - $( - pub $field_name: $field_ty, - )* + pub body_type: BodyTy<'tcx>, $( pub $name: IndexVec<$id, $value>, )* } impl<'tcx> Thir<'tcx> { - pub fn new($($field_name: $field_ty,)*) -> Thir<'tcx> { + pub fn new(body_type: BodyTy<'tcx>) -> Thir<'tcx> { Thir { - $( - $field_name, - )* + body_type, $( $name: IndexVec::new(), )* @@ -88,9 +81,6 @@ macro_rules! thir_with_elements { } thir_with_elements! { - body_type: BodyTy<'tcx>, - -@elements: arms: ArmId => Arm<'tcx> => "a{}", blocks: BlockId => Block => "b{}", exprs: ExprId => Expr<'tcx> => "e{}", @@ -98,14 +88,14 @@ thir_with_elements! { params: ParamId => Param<'tcx> => "p{}", } -#[derive(Debug, HashStable, Clone)] +#[derive(Debug, HashStable)] pub enum BodyTy<'tcx> { Const(Ty<'tcx>), Fn(FnSig<'tcx>), } /// Description of a type-checked function parameter. -#[derive(Clone, Debug, HashStable)] +#[derive(Debug, HashStable)] pub struct Param<'tcx> { /// The pattern that appears in the parameter list, or None for implicit parameters. pub pat: Option<Box<Pat<'tcx>>>, @@ -125,7 +115,7 @@ pub enum LintLevel { Explicit(HirId), } -#[derive(Clone, Debug, HashStable)] +#[derive(Debug, HashStable)] pub struct Block { /// Whether the block itself has a label. Used by `label: {}` /// and `try` blocks. @@ -145,7 +135,7 @@ pub struct Block { type UserTy<'tcx> = Option<Box<CanonicalUserType<'tcx>>>; -#[derive(Clone, Debug, HashStable)] +#[derive(Debug, HashStable)] pub struct AdtExpr<'tcx> { /// The ADT we're constructing. pub adt_def: AdtDef<'tcx>, @@ -162,7 +152,7 @@ pub struct AdtExpr<'tcx> { pub base: AdtExprBase<'tcx>, } -#[derive(Clone, Debug, HashStable)] +#[derive(Debug, HashStable)] pub enum AdtExprBase<'tcx> { /// A struct expression where all the fields are explicitly enumerated: `Foo { a, b }`. None, @@ -175,7 +165,7 @@ pub enum AdtExprBase<'tcx> { DefaultFields(Box<[Ty<'tcx>]>), } -#[derive(Clone, Debug, HashStable)] +#[derive(Debug, HashStable)] pub struct ClosureExpr<'tcx> { pub closure_id: LocalDefId, pub args: UpvarArgs<'tcx>, @@ -184,7 +174,7 @@ pub struct ClosureExpr<'tcx> { pub fake_reads: Vec<(ExprId, FakeReadCause, HirId)>, } -#[derive(Clone, Debug, HashStable)] +#[derive(Debug, HashStable)] pub struct InlineAsmExpr<'tcx> { pub asm_macro: AsmMacro, pub template: &'tcx [InlineAsmTemplatePiece], @@ -202,12 +192,12 @@ pub enum BlockSafety { ExplicitUnsafe(HirId), } -#[derive(Clone, Debug, HashStable)] +#[derive(Debug, HashStable)] pub struct Stmt<'tcx> { pub kind: StmtKind<'tcx>, } -#[derive(Clone, Debug, HashStable)] +#[derive(Debug, HashStable)] pub enum StmtKind<'tcx> { /// An expression with a trailing semicolon. Expr { @@ -247,11 +237,11 @@ pub enum StmtKind<'tcx> { }, } -#[derive(Clone, Debug, Copy, PartialEq, Eq, Hash, HashStable, TyEncodable, TyDecodable)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, HashStable)] pub struct LocalVarId(pub HirId); /// A THIR expression. -#[derive(Clone, Debug, HashStable)] +#[derive(Debug, HashStable)] pub struct Expr<'tcx> { /// kind of expression pub kind: ExprKind<'tcx>, @@ -278,7 +268,7 @@ pub struct TempLifetime { pub backwards_incompatible: Option<region::Scope>, } -#[derive(Clone, Debug, HashStable)] +#[derive(Debug, HashStable)] pub enum ExprKind<'tcx> { /// `Scope`s are used to explicitly mark destruction scopes, /// and to track the `HirId` of the expressions within the scope. @@ -556,20 +546,20 @@ pub enum ExprKind<'tcx> { /// Represents the association of a field identifier and an expression. /// /// This is used in struct constructors. -#[derive(Clone, Debug, HashStable)] +#[derive(Debug, HashStable)] pub struct FieldExpr { pub name: FieldIdx, pub expr: ExprId, } -#[derive(Clone, Debug, HashStable)] +#[derive(Debug, HashStable)] pub struct FruInfo<'tcx> { pub base: ExprId, pub field_types: Box<[Ty<'tcx>]>, } /// A `match` arm. -#[derive(Clone, Debug, HashStable)] +#[derive(Debug, HashStable)] pub struct Arm<'tcx> { pub pattern: Box<Pat<'tcx>>, pub guard: Option<ExprId>, @@ -587,7 +577,7 @@ pub enum LogicalOp { Or, } -#[derive(Clone, Debug, HashStable)] +#[derive(Debug, HashStable)] pub enum InlineAsmOperand<'tcx> { In { reg: InlineAsmRegOrRegClass, @@ -625,13 +615,13 @@ pub enum InlineAsmOperand<'tcx> { }, } -#[derive(Clone, Debug, HashStable, TypeVisitable)] +#[derive(Debug, HashStable, TypeVisitable)] pub struct FieldPat<'tcx> { pub field: FieldIdx, pub pattern: Box<Pat<'tcx>>, } -#[derive(Clone, Debug, HashStable, TypeVisitable)] +#[derive(Debug, HashStable, TypeVisitable)] pub struct Pat<'tcx> { pub ty: Ty<'tcx>, pub span: Span, @@ -739,7 +729,7 @@ impl<'tcx> Pat<'tcx> { } } -#[derive(Clone, Debug, HashStable, TypeVisitable)] +#[derive(Debug, HashStable, TypeVisitable)] pub struct Ascription<'tcx> { pub annotation: CanonicalUserTypeAnnotation<'tcx>, /// Variance to use when relating the `user_ty` to the **type of the value being @@ -763,7 +753,7 @@ pub struct Ascription<'tcx> { pub variance: ty::Variance, } -#[derive(Clone, Debug, HashStable, TypeVisitable)] +#[derive(Debug, HashStable, TypeVisitable)] pub enum PatKind<'tcx> { /// A wildcard pattern: `_`. Wild, diff --git a/compiler/rustc_middle/src/thir/visit.rs b/compiler/rustc_middle/src/thir/visit.rs index 2aeb13942a3..13b8af55e51 100644 --- a/compiler/rustc_middle/src/thir/visit.rs +++ b/compiler/rustc_middle/src/thir/visit.rs @@ -1,8 +1,7 @@ use super::{ - AdtExpr, Arm, Block, ClosureExpr, Expr, ExprKind, InlineAsmExpr, InlineAsmOperand, Pat, - PatKind, Stmt, StmtKind, Thir, + AdtExpr, AdtExprBase, Arm, Block, ClosureExpr, Expr, ExprKind, InlineAsmExpr, InlineAsmOperand, + Pat, PatKind, Stmt, StmtKind, Thir, }; -use crate::thir::AdtExprBase; pub trait Visitor<'thir, 'tcx: 'thir>: Sized { fn thir(&self) -> &'thir Thir<'tcx>; diff --git a/compiler/rustc_middle/src/traits/mod.rs b/compiler/rustc_middle/src/traits/mod.rs index 28a6eba75aa..d0ce4e6242e 100644 --- a/compiler/rustc_middle/src/traits/mod.rs +++ b/compiler/rustc_middle/src/traits/mod.rs @@ -21,13 +21,12 @@ use rustc_macros::{ }; use rustc_span::def_id::{CRATE_DEF_ID, LocalDefId}; use rustc_span::{DUMMY_SP, Span, Symbol}; -// FIXME: Remove this import and import via `solve::` -pub use rustc_type_ir::solve::BuiltinImplSource; use smallvec::{SmallVec, smallvec}; use thin_vec::ThinVec; pub use self::select::{EvaluationCache, EvaluationResult, OverflowError, SelectionCache}; use crate::mir::ConstraintCategory; +pub use crate::traits::solve::BuiltinImplSource; use crate::ty::abstract_const::NotConstEvaluatable; use crate::ty::{self, AdtKind, GenericArgsRef, Ty}; diff --git a/compiler/rustc_middle/src/traits/query.rs b/compiler/rustc_middle/src/traits/query.rs index f049da95f29..8cd04a6f5e4 100644 --- a/compiler/rustc_middle/src/traits/query.rs +++ b/compiler/rustc_middle/src/traits/query.rs @@ -7,11 +7,10 @@ use rustc_macros::{HashStable, TypeFoldable, TypeVisitable}; use rustc_span::Span; -// FIXME: Remove this import and import via `traits::solve`. -pub use rustc_type_ir::solve::NoSolution; use crate::error::DropCheckOverflow; use crate::infer::canonical::{Canonical, CanonicalQueryInput, QueryResponse}; +pub use crate::traits::solve::NoSolution; use crate::ty::{self, GenericArg, Ty, TyCtxt}; pub mod type_op { diff --git a/compiler/rustc_middle/src/ty/consts/valtree.rs b/compiler/rustc_middle/src/ty/consts/valtree.rs index d914b7576dc..5905076c4d0 100644 --- a/compiler/rustc_middle/src/ty/consts/valtree.rs +++ b/compiler/rustc_middle/src/ty/consts/valtree.rs @@ -78,30 +78,6 @@ impl<'tcx> ValTree<'tcx> { Self::Branch(_) => None, } } - - /// Get the values inside the ValTree as a slice of bytes. This only works for - /// constants with types &str, &[u8], or [u8; _]. - pub fn try_to_raw_bytes(self, tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Option<&'tcx [u8]> { - match ty.kind() { - ty::Ref(_, inner_ty, _) => match inner_ty.kind() { - // `&str` can be interpreted as raw bytes - ty::Str => {} - // `&[u8]` can be interpreted as raw bytes - ty::Slice(slice_ty) if *slice_ty == tcx.types.u8 => {} - // other `&_` can't be interpreted as raw bytes - _ => return None, - }, - // `[u8; N]` can be interpreted as raw bytes - ty::Array(array_ty, _) if *array_ty == tcx.types.u8 => {} - // Otherwise, type cannot be interpreted as raw bytes - _ => return None, - } - - Some( - tcx.arena - .alloc_from_iter(self.unwrap_branch().into_iter().map(|v| v.unwrap_leaf().to_u8())), - ) - } } /// A type-level constant value. @@ -143,6 +119,29 @@ impl<'tcx> Value<'tcx> { } self.valtree.try_to_scalar_int().map(|s| s.to_target_usize(tcx)) } + + /// Get the values inside the ValTree as a slice of bytes. This only works for + /// constants with types &str, &[u8], or [u8; _]. + pub fn try_to_raw_bytes(self, tcx: TyCtxt<'tcx>) -> Option<&'tcx [u8]> { + match self.ty.kind() { + ty::Ref(_, inner_ty, _) => match inner_ty.kind() { + // `&str` can be interpreted as raw bytes + ty::Str => {} + // `&[u8]` can be interpreted as raw bytes + ty::Slice(slice_ty) if *slice_ty == tcx.types.u8 => {} + // other `&_` can't be interpreted as raw bytes + _ => return None, + }, + // `[u8; N]` can be interpreted as raw bytes + ty::Array(array_ty, _) if *array_ty == tcx.types.u8 => {} + // Otherwise, type cannot be interpreted as raw bytes + _ => return None, + } + + Some(tcx.arena.alloc_from_iter( + self.valtree.unwrap_branch().into_iter().map(|v| v.unwrap_leaf().to_u8()), + )) + } } impl<'tcx> rustc_type_ir::inherent::ValueConst<TyCtxt<'tcx>> for Value<'tcx> { diff --git a/compiler/rustc_middle/src/ty/parameterized.rs b/compiler/rustc_middle/src/ty/parameterized.rs index 6b6c6f3c72f..8eaf0a58f70 100644 --- a/compiler/rustc_middle/src/ty/parameterized.rs +++ b/compiler/rustc_middle/src/ty/parameterized.rs @@ -101,6 +101,7 @@ trivially_parameterized_over_tcx! { rustc_session::cstore::ForeignModule, rustc_session::cstore::LinkagePreference, rustc_session::cstore::NativeLib, + rustc_session::config::TargetModifier, rustc_span::ExpnData, rustc_span::ExpnHash, rustc_span::ExpnId, diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index 6c8591dae89..3431081b189 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -1487,7 +1487,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { }, ty::ConstKind::Param(ParamConst { name, .. }) => p!(write("{}", name)), ty::ConstKind::Value(cv) => { - return self.pretty_print_const_valtree(cv.valtree, cv.ty, print_ty); + return self.pretty_print_const_valtree(cv, print_ty); } ty::ConstKind::Bound(debruijn, bound_var) => { @@ -1787,48 +1787,47 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { Ok(()) } - // FIXME(valtrees): Accept `ty::Value` instead of `Ty` and `ty::ValTree` separately. fn pretty_print_const_valtree( &mut self, - valtree: ty::ValTree<'tcx>, - ty: Ty<'tcx>, + cv: ty::Value<'tcx>, print_ty: bool, ) -> Result<(), PrintError> { define_scoped_cx!(self); if self.should_print_verbose() { - p!(write("ValTree({:?}: ", valtree), print(ty), ")"); + p!(write("ValTree({:?}: ", cv.valtree), print(cv.ty), ")"); return Ok(()); } let u8_type = self.tcx().types.u8; - match (valtree, ty.kind()) { + match (cv.valtree, cv.ty.kind()) { (ty::ValTree::Branch(_), ty::Ref(_, inner_ty, _)) => match inner_ty.kind() { ty::Slice(t) if *t == u8_type => { - let bytes = valtree.try_to_raw_bytes(self.tcx(), ty).unwrap_or_else(|| { + let bytes = cv.try_to_raw_bytes(self.tcx()).unwrap_or_else(|| { bug!( "expected to convert valtree {:?} to raw bytes for type {:?}", - valtree, + cv.valtree, t ) }); return self.pretty_print_byte_str(bytes); } ty::Str => { - let bytes = valtree.try_to_raw_bytes(self.tcx(), ty).unwrap_or_else(|| { - bug!("expected to convert valtree to raw bytes for type {:?}", ty) + let bytes = cv.try_to_raw_bytes(self.tcx()).unwrap_or_else(|| { + bug!("expected to convert valtree to raw bytes for type {:?}", cv.ty) }); p!(write("{:?}", String::from_utf8_lossy(bytes))); return Ok(()); } _ => { + let cv = ty::Value { valtree: cv.valtree, ty: *inner_ty }; p!("&"); - p!(pretty_print_const_valtree(valtree, *inner_ty, print_ty)); + p!(pretty_print_const_valtree(cv, print_ty)); return Ok(()); } }, (ty::ValTree::Branch(_), ty::Array(t, _)) if *t == u8_type => { - let bytes = valtree.try_to_raw_bytes(self.tcx(), ty).unwrap_or_else(|| { + let bytes = cv.try_to_raw_bytes(self.tcx()).unwrap_or_else(|| { bug!("expected to convert valtree to raw bytes for type {:?}", t) }); p!("*"); @@ -1837,10 +1836,13 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } // Aggregates, printed as array/tuple/struct/variant construction syntax. (ty::ValTree::Branch(_), ty::Array(..) | ty::Tuple(..) | ty::Adt(..)) => { - let contents = - self.tcx().destructure_const(ty::Const::new_value(self.tcx(), valtree, ty)); + let contents = self.tcx().destructure_const(ty::Const::new_value( + self.tcx(), + cv.valtree, + cv.ty, + )); let fields = contents.fields.iter().copied(); - match *ty.kind() { + match *cv.ty.kind() { ty::Array(..) => { p!("[", comma_sep(fields), "]"); } @@ -1857,7 +1859,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { write!(this, "unreachable()")?; Ok(()) }, - |this| this.print_type(ty), + |this| this.print_type(cv.ty), ": ", )?; } @@ -1894,7 +1896,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { return self.pretty_print_const_scalar_int(leaf, *inner_ty, print_ty); } (ty::ValTree::Leaf(leaf), _) => { - return self.pretty_print_const_scalar_int(leaf, ty, print_ty); + return self.pretty_print_const_scalar_int(leaf, cv.ty, print_ty); } // FIXME(oli-obk): also pretty print arrays and other aggregate constants by reading // their fields instead of just dumping the memory. @@ -1902,13 +1904,13 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } // fallback - if valtree == ty::ValTree::zst() { + if cv.valtree == ty::ValTree::zst() { p!(write("<ZST>")); } else { - p!(write("{:?}", valtree)); + p!(write("{:?}", cv.valtree)); } if print_ty { - p!(": ", print(ty)); + p!(": ", print(cv.ty)); } Ok(()) } diff --git a/compiler/rustc_middle/src/ty/structural_impls.rs b/compiler/rustc_middle/src/ty/structural_impls.rs index 9e9de4fb064..03b26b44538 100644 --- a/compiler/rustc_middle/src/ty/structural_impls.rs +++ b/compiler/rustc_middle/src/ty/structural_impls.rs @@ -170,7 +170,7 @@ impl<'tcx> fmt::Debug for ty::Const<'tcx> { bug!("we checked that this is a valtree") }; let mut cx = FmtPrinter::new(tcx, Namespace::ValueNS); - cx.pretty_print_const_valtree(cv.valtree, cv.ty, /*print_ty*/ true)?; + cx.pretty_print_const_valtree(cv, /*print_ty*/ true)?; f.write_str(&cx.into_buffer()) }); } diff --git a/compiler/rustc_mir_build/src/check_tail_calls.rs b/compiler/rustc_mir_build/src/check_tail_calls.rs index 0659e3ea314..921205428db 100644 --- a/compiler/rustc_mir_build/src/check_tail_calls.rs +++ b/compiler/rustc_mir_build/src/check_tail_calls.rs @@ -1,4 +1,5 @@ use rustc_abi::ExternAbi; +use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_errors::Applicability; use rustc_hir::LangItem; use rustc_hir::def::DefKind; @@ -344,12 +345,14 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for TailCallCkVisitor<'a, 'tcx> { } fn visit_expr(&mut self, expr: &'a Expr<'tcx>) { - if let ExprKind::Become { value } = expr.kind { - let call = &self.thir[value]; - self.check_tail_call(call, expr); - } + ensure_sufficient_stack(|| { + if let ExprKind::Become { value } = expr.kind { + let call = &self.thir[value]; + self.check_tail_call(call, expr); + } - visit::walk_expr(self, expr); + visit::walk_expr(self, expr); + }); } } diff --git a/compiler/rustc_mir_build/src/check_unsafety.rs b/compiler/rustc_mir_build/src/check_unsafety.rs index e47c14b8bfa..b6494173b0f 100644 --- a/compiler/rustc_mir_build/src/check_unsafety.rs +++ b/compiler/rustc_mir_build/src/check_unsafety.rs @@ -2,6 +2,7 @@ use std::borrow::Cow; use std::mem; use std::ops::Bound; +use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_errors::DiagArgValue; use rustc_hir::def::DefKind; use rustc_hir::{self as hir, BindingMode, ByRef, HirId, Mutability}; @@ -476,7 +477,9 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> { ExprKind::Scope { value, lint_level: LintLevel::Explicit(hir_id), region_scope: _ } => { let prev_id = self.hir_context; self.hir_context = hir_id; - self.visit_expr(&self.thir[value]); + ensure_sufficient_stack(|| { + self.visit_expr(&self.thir[value]); + }); self.hir_context = prev_id; return; // don't visit the whole expression } diff --git a/compiler/rustc_mir_build/src/thir/pattern/mod.rs b/compiler/rustc_mir_build/src/thir/pattern/mod.rs index 20a728d6d5b..0aa61152330 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/mod.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/mod.rs @@ -155,42 +155,41 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { fn lower_pattern_range_endpoint( &mut self, expr: Option<&'tcx hir::PatExpr<'tcx>>, - ) -> Result< - (Option<PatRangeBoundary<'tcx>>, Option<Ascription<'tcx>>, Option<LocalDefId>), - ErrorGuaranteed, - > { - match expr { - None => Ok((None, None, None)), - Some(expr) => { - let (kind, ascr, inline_const) = match self.lower_lit(expr) { - PatKind::ExpandedConstant { subpattern, def_id, is_inline: true } => { - (subpattern.kind, None, def_id.as_local()) - } - PatKind::ExpandedConstant { subpattern, is_inline: false, .. } => { - (subpattern.kind, None, None) - } - PatKind::AscribeUserType { ascription, subpattern: box Pat { kind, .. } } => { - (kind, Some(ascription), None) - } - kind => (kind, None, None), - }; - let value = match kind { - PatKind::Constant { value } => value, - PatKind::ExpandedConstant { subpattern, .. } - if let PatKind::Constant { value } = subpattern.kind => - { - value - } - _ => { - let msg = format!( - "found bad range pattern endpoint `{expr:?}` outside of error recovery" - ); - return Err(self.tcx.dcx().span_delayed_bug(expr.span, msg)); + // Out-parameters collecting extra data to be reapplied by the caller + ascriptions: &mut Vec<Ascription<'tcx>>, + inline_consts: &mut Vec<LocalDefId>, + ) -> Result<Option<PatRangeBoundary<'tcx>>, ErrorGuaranteed> { + let Some(expr) = expr else { return Ok(None) }; + + // Lower the endpoint into a temporary `PatKind` that will then be + // deconstructed to obtain the constant value and other data. + let mut kind: PatKind<'tcx> = self.lower_lit(expr); + + // Unpeel any ascription or inline-const wrapper nodes. + loop { + match kind { + PatKind::AscribeUserType { ascription, subpattern } => { + ascriptions.push(ascription); + kind = subpattern.kind; + } + PatKind::ExpandedConstant { is_inline, def_id, subpattern } => { + if is_inline { + inline_consts.extend(def_id.as_local()); } - }; - Ok((Some(PatRangeBoundary::Finite(value)), ascr, inline_const)) + kind = subpattern.kind; + } + _ => break, } } + + // The unpeeled kind should now be a constant, giving us the endpoint value. + let PatKind::Constant { value } = kind else { + let msg = + format!("found bad range pattern endpoint `{expr:?}` outside of error recovery"); + return Err(self.tcx.dcx().span_delayed_bug(expr.span, msg)); + }; + + Ok(Some(PatRangeBoundary::Finite(value))) } /// Overflowing literals are linted against in a late pass. This is mostly fine, except when we @@ -253,11 +252,15 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { self.tcx.dcx().span_bug(span, msg); } - let (lo, lo_ascr, lo_inline) = self.lower_pattern_range_endpoint(lo_expr)?; - let (hi, hi_ascr, hi_inline) = self.lower_pattern_range_endpoint(hi_expr)?; + // Collect extra data while lowering the endpoints, to be reapplied later. + let mut ascriptions = vec![]; + let mut inline_consts = vec![]; + + let mut lower_endpoint = + |expr| self.lower_pattern_range_endpoint(expr, &mut ascriptions, &mut inline_consts); - let lo = lo.unwrap_or(PatRangeBoundary::NegInfinity); - let hi = hi.unwrap_or(PatRangeBoundary::PosInfinity); + let lo = lower_endpoint(lo_expr)?.unwrap_or(PatRangeBoundary::NegInfinity); + let hi = lower_endpoint(hi_expr)?.unwrap_or(PatRangeBoundary::PosInfinity); let cmp = lo.compare_with(hi, ty, self.tcx, self.typing_env); let mut kind = PatKind::Range(Box::new(PatRange { lo, hi, end, ty })); @@ -298,13 +301,13 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { // If we are handling a range with associated constants (e.g. // `Foo::<'a>::A..=Foo::B`), we need to put the ascriptions for the associated // constants somewhere. Have them on the range pattern. - for ascription in [lo_ascr, hi_ascr].into_iter().flatten() { + for ascription in ascriptions { kind = PatKind::AscribeUserType { ascription, subpattern: Box::new(Pat { span, ty, kind }), }; } - for def in [lo_inline, hi_inline].into_iter().flatten() { + for def in inline_consts { kind = PatKind::ExpandedConstant { def_id: def.to_def_id(), is_inline: true, diff --git a/compiler/rustc_mir_transform/src/coverage/query.rs b/compiler/rustc_mir_transform/src/coverage/query.rs index 5e7b46182dc..a849ed4c3e2 100644 --- a/compiler/rustc_mir_transform/src/coverage/query.rs +++ b/compiler/rustc_mir_transform/src/coverage/query.rs @@ -6,7 +6,6 @@ use rustc_middle::mir::coverage::{ FunctionCoverageInfo, MappingKind, Op, }; use rustc_middle::mir::{Body, Statement, StatementKind}; -use rustc_middle::query::TyCtxtAt; use rustc_middle::ty::{self, TyCtxt}; use rustc_middle::util::Providers; use rustc_span::def_id::LocalDefId; @@ -15,8 +14,7 @@ use tracing::trace; /// Registers query/hook implementations related to coverage. pub(crate) fn provide(providers: &mut Providers) { - providers.hooks.is_eligible_for_coverage = - |TyCtxtAt { tcx, .. }, def_id| is_eligible_for_coverage(tcx, def_id); + providers.hooks.is_eligible_for_coverage = is_eligible_for_coverage; providers.queries.coverage_attr_on = coverage_attr_on; providers.queries.coverage_ids_info = coverage_ids_info; } diff --git a/compiler/rustc_monomorphize/src/collector.rs b/compiler/rustc_monomorphize/src/collector.rs index de8a20c5dee..ae31ed59391 100644 --- a/compiler/rustc_monomorphize/src/collector.rs +++ b/compiler/rustc_monomorphize/src/collector.rs @@ -953,7 +953,7 @@ fn visit_instance_use<'tcx>( /// Returns `true` if we should codegen an instance in the local crate, or returns `false` if we /// can just link to the upstream crate and therefore don't need a mono item. -fn should_codegen_locally<'tcx>(tcx: TyCtxtAt<'tcx>, instance: Instance<'tcx>) -> bool { +fn should_codegen_locally<'tcx>(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) -> bool { let Some(def_id) = instance.def.def_id_if_not_guaranteed_local_codegen() else { return true; }; @@ -976,7 +976,7 @@ fn should_codegen_locally<'tcx>(tcx: TyCtxtAt<'tcx>, instance: Instance<'tcx>) - return true; } - if tcx.is_reachable_non_generic(def_id) || instance.upstream_monomorphization(*tcx).is_some() { + if tcx.is_reachable_non_generic(def_id) || instance.upstream_monomorphization(tcx).is_some() { // We can link to the item in question, no instance needed in this crate. return false; } diff --git a/compiler/rustc_monomorphize/src/partitioning.rs b/compiler/rustc_monomorphize/src/partitioning.rs index c985ea04278..3ef061195da 100644 --- a/compiler/rustc_monomorphize/src/partitioning.rs +++ b/compiler/rustc_monomorphize/src/partitioning.rs @@ -1179,23 +1179,23 @@ fn collect_and_partition_mono_items(tcx: TyCtxt<'_>, (): ()) -> MonoItemPartitio } } + #[cfg(not(llvm_enzyme))] + let autodiff_mono_items: Vec<_> = vec![]; + #[cfg(llvm_enzyme)] + let mut autodiff_mono_items: Vec<_> = vec![]; let mono_items: DefIdSet = items .iter() .filter_map(|mono_item| match *mono_item { - MonoItem::Fn(ref instance) => Some(instance.def_id()), + MonoItem::Fn(ref instance) => { + #[cfg(llvm_enzyme)] + autodiff_mono_items.push((mono_item, instance)); + Some(instance.def_id()) + } MonoItem::Static(def_id) => Some(def_id), _ => None, }) .collect(); - let autodiff_mono_items: Vec<_> = items - .iter() - .filter_map(|item| match *item { - MonoItem::Fn(ref instance) => Some((item, instance)), - _ => None, - }) - .collect(); - let autodiff_items = autodiff::find_autodiff_source_functions(tcx, &usage_map, autodiff_mono_items); let autodiff_items = tcx.arena.alloc_from_iter(autodiff_items); diff --git a/compiler/rustc_query_impl/src/lib.rs b/compiler/rustc_query_impl/src/lib.rs index d2bb0b3f277..bbc83cca99d 100644 --- a/compiler/rustc_query_impl/src/lib.rs +++ b/compiler/rustc_query_impl/src/lib.rs @@ -224,7 +224,6 @@ pub fn query_system<'a>( rustc_middle::rustc_query_append! { define_queries! } pub fn provide(providers: &mut rustc_middle::util::Providers) { - providers.hooks.alloc_self_profile_query_strings = - |tcx| alloc_self_profile_query_strings(tcx.tcx); - providers.hooks.query_key_hash_verify_all = |tcx| query_key_hash_verify_all(tcx.tcx); + providers.hooks.alloc_self_profile_query_strings = alloc_self_profile_query_strings; + providers.hooks.query_key_hash_verify_all = query_key_hash_verify_all; } diff --git a/compiler/rustc_query_system/src/dep_graph/dep_node.rs b/compiler/rustc_query_system/src/dep_graph/dep_node.rs index 2902d17d687..9d3368607a2 100644 --- a/compiler/rustc_query_system/src/dep_graph/dep_node.rs +++ b/compiler/rustc_query_system/src/dep_graph/dep_node.rs @@ -1,19 +1,20 @@ -//! This module defines the `DepNode` type which the compiler uses to represent -//! nodes in the dependency graph. A `DepNode` consists of a `DepKind` (which -//! specifies the kind of thing it represents, like a piece of HIR, MIR, etc) -//! and a `Fingerprint`, a 128 bit hash value the exact meaning of which +//! This module defines the [`DepNode`] type which the compiler uses to represent +//! nodes in the [dependency graph]. A `DepNode` consists of a [`DepKind`] (which +//! specifies the kind of thing it represents, like a piece of HIR, MIR, etc.) +//! and a [`Fingerprint`], a 128-bit hash value, the exact meaning of which //! depends on the node's `DepKind`. Together, the kind and the fingerprint //! fully identify a dependency node, even across multiple compilation sessions. //! In other words, the value of the fingerprint does not depend on anything //! that is specific to a given compilation session, like an unpredictable -//! interning key (e.g., NodeId, DefId, Symbol) or the numeric value of a +//! interning key (e.g., `NodeId`, `DefId`, `Symbol`) or the numeric value of a //! pointer. The concept behind this could be compared to how git commit hashes -//! uniquely identify a given commit and has a few advantages: +//! uniquely identify a given commit. The fingerprinting approach has +//! a few advantages: //! //! * A `DepNode` can simply be serialized to disk and loaded in another session -//! without the need to do any "rebasing (like we have to do for Spans and -//! NodeIds) or "retracing" like we had to do for `DefId` in earlier -//! implementations of the dependency graph. +//! without the need to do any "rebasing" (like we have to do for Spans and +//! NodeIds) or "retracing" (like we had to do for `DefId` in earlier +//! implementations of the dependency graph). //! * A `Fingerprint` is just a bunch of bits, which allows `DepNode` to //! implement `Copy`, `Sync`, `Send`, `Freeze`, etc. //! * Since we just have a bit pattern, `DepNode` can be mapped from disk into @@ -26,10 +27,12 @@ //! could not be instantiated because the current compilation session //! contained no `DefId` for thing that had been removed. //! -//! `DepNode` definition happens in `rustc_middle` with the `define_dep_nodes!()` macro. -//! This macro defines the `DepKind` enum and a corresponding `DepConstructor` enum. The -//! `DepConstructor` enum links a `DepKind` to the parameters that are needed at runtime in order -//! to construct a valid `DepNode` fingerprint. +//! `DepNode` definition happens in `rustc_middle` with the +//! `define_dep_nodes!()` macro. This macro defines the `DepKind` enum. Each +//! `DepKind` has its own parameters that are needed at runtime in order to +//! construct a valid `DepNode` fingerprint. However, only `CompileCodegenUnit` +//! and `CompileMonoItem` are constructed explicitly (with +//! `make_compile_codegen_unit` and `make_compile_mono_item`). //! //! Because the macro sees what parameters a given `DepKind` requires, it can //! "infer" some properties for each kind of `DepNode`: @@ -41,6 +44,16 @@ //! in which case it is possible to map the node's fingerprint back to the //! `DefId` it was computed from. In other cases, too much information gets //! lost during fingerprint computation. +//! +//! `make_compile_codegen_unit` and `make_compile_mono_items`, together with +//! `DepNode::new()`, ensure that only valid `DepNode` instances can be +//! constructed. For example, the API does not allow for constructing +//! parameterless `DepNode`s with anything other than a zeroed out fingerprint. +//! More generally speaking, it relieves the user of the `DepNode` API of +//! having to know how to compute the expected fingerprint for a given set of +//! node parameters. +//! +//! [dependency graph]: https://rustc-dev-guide.rust-lang.org/query.html use std::fmt; use std::hash::Hash; diff --git a/compiler/rustc_query_system/src/query/caches.rs b/compiler/rustc_query_system/src/query/caches.rs index e6f3d97742d..e11123dff26 100644 --- a/compiler/rustc_query_system/src/query/caches.rs +++ b/compiler/rustc_query_system/src/query/caches.rs @@ -11,18 +11,30 @@ use rustc_span::def_id::{DefId, DefIndex}; use crate::dep_graph::DepNodeIndex; +/// Trait for types that serve as an in-memory cache for query results, +/// for a given key (argument) type and value (return) type. +/// +/// Types implementing this trait are associated with actual key/value types +/// by the `Cache` associated type of the `rustc_middle::query::Key` trait. pub trait QueryCache: Sized { type Key: Hash + Eq + Copy + Debug; type Value: Copy; - /// Checks if the query is already computed and in the cache. + /// Returns the cached value (and other information) associated with the + /// given key, if it is present in the cache. fn lookup(&self, key: &Self::Key) -> Option<(Self::Value, DepNodeIndex)>; + /// Adds a key/value entry to this cache. + /// + /// Called by some part of the query system, after having obtained the + /// value by executing the query or loading a cached value from disk. fn complete(&self, key: Self::Key, value: Self::Value, index: DepNodeIndex); fn iter(&self, f: &mut dyn FnMut(&Self::Key, &Self::Value, DepNodeIndex)); } +/// In-memory cache for queries whose keys aren't suitable for any of the +/// more specialized kinds of cache. Backed by a sharded hashmap. pub struct DefaultCache<K, V> { cache: Sharded<FxHashMap<K, (V, DepNodeIndex)>>, } @@ -67,6 +79,8 @@ where } } +/// In-memory cache for queries whose key type only has one value (e.g. `()`). +/// The cache therefore only needs to store one query return value. pub struct SingleCache<V> { cache: OnceLock<(V, DepNodeIndex)>, } @@ -101,6 +115,10 @@ where } } +/// In-memory cache for queries whose key is a [`DefId`]. +/// +/// Selects between one of two internal caches, depending on whether the key +/// is a local ID or foreign-crate ID. pub struct DefIdCache<V> { /// Stores the local DefIds in a dense map. Local queries are much more often dense, so this is /// a win over hashing query keys at marginal memory cost (~5% at most) compared to FxHashMap. diff --git a/compiler/rustc_query_system/src/query/plumbing.rs b/compiler/rustc_query_system/src/query/plumbing.rs index 6fb5e37d2d0..18aae8c00b2 100644 --- a/compiler/rustc_query_system/src/query/plumbing.rs +++ b/compiler/rustc_query_system/src/query/plumbing.rs @@ -222,10 +222,10 @@ pub struct CycleError { pub cycle: Vec<QueryInfo>, } -/// Checks if the query is already computed and in the cache. -/// It returns the shard index and a lock guard to the shard, -/// which will be used if the query is not in the cache and we need -/// to compute it. +/// Checks whether there is already a value for this key in the in-memory +/// query cache, returning that value if present. +/// +/// (Also performs some associated bookkeeping, if a value was found.) #[inline(always)] pub fn try_get_cached<Tcx, C>(tcx: Tcx, cache: &C, key: &C::Key) -> Option<C::Value> where diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index 67e314cc685..2fb4b27b889 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -1224,6 +1224,7 @@ impl Default for Options { color: ColorConfig::Auto, logical_env: FxIndexMap::default(), verbose: false, + target_modifiers: BTreeMap::default(), } } } @@ -2370,14 +2371,16 @@ pub fn build_session_options(early_dcx: &mut EarlyDiagCtxt, matches: &getopts::M let crate_types = parse_crate_types_from_list(unparsed_crate_types) .unwrap_or_else(|e| early_dcx.early_fatal(e)); - let mut unstable_opts = UnstableOptions::build(early_dcx, matches); + let mut target_modifiers = BTreeMap::<OptionsTargetModifiers, String>::new(); + + let mut unstable_opts = UnstableOptions::build(early_dcx, matches, &mut target_modifiers); let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(early_dcx, matches); check_error_format_stability(early_dcx, &unstable_opts, error_format); let output_types = parse_output_types(early_dcx, &unstable_opts, matches); - let mut cg = CodegenOptions::build(early_dcx, matches); + let mut cg = CodegenOptions::build(early_dcx, matches, &mut target_modifiers); let (disable_local_thinlto, codegen_units) = should_override_cgus_and_disable_thinlto( early_dcx, &output_types, @@ -2648,6 +2651,7 @@ pub fn build_session_options(early_dcx: &mut EarlyDiagCtxt, matches: &getopts::M color, logical_env, verbose, + target_modifiers, } } diff --git a/compiler/rustc_session/src/lib.rs b/compiler/rustc_session/src/lib.rs index dcf86d1a408..924350b8cbc 100644 --- a/compiler/rustc_session/src/lib.rs +++ b/compiler/rustc_session/src/lib.rs @@ -4,6 +4,9 @@ #![feature(let_chains)] #![feature(map_many_mut)] #![feature(rustc_attrs)] +// To generate CodegenOptionsTargetModifiers and UnstableOptionsTargetModifiers enums +// with macro_rules, it is necessary to use recursive mechanic ("Incremental TT Munchers"). +#![recursion_limit = "256"] #![warn(unreachable_pub)] // tidy-alphabetical-end diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index cc86c85f3f0..4ed5499d32c 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -10,6 +10,7 @@ use rustc_data_structures::profiling::TimePassesFormat; use rustc_data_structures::stable_hasher::Hash64; use rustc_errors::{ColorConfig, LanguageIdentifier, TerminalUrl}; use rustc_feature::UnstableFeatures; +use rustc_macros::{Decodable, Encodable}; use rustc_span::edition::Edition; use rustc_span::{RealFileName, SourceFileHashAlgorithm}; use rustc_target::spec::{ @@ -59,18 +60,194 @@ macro_rules! hash_substruct { }; } +/// Extended target modifier info. +/// For example, when external target modifier is '-Zregparm=2': +/// Target modifier enum value + user value ('2') from external crate +/// is converted into description: prefix ('Z'), name ('regparm'), tech value ('Some(2)'). +pub struct ExtendedTargetModifierInfo { + /// Flag prefix (usually, 'C' for codegen flags or 'Z' for unstable flags) + pub prefix: String, + /// Flag name + pub name: String, + /// Flag parsed technical value + pub tech_value: String, +} + +/// A recorded -Zopt_name=opt_value (or -Copt_name=opt_value) +/// which alter the ABI or effectiveness of exploit mitigations. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Encodable, Decodable)] +pub struct TargetModifier { + /// Option enum value + pub opt: OptionsTargetModifiers, + /// User-provided option value (before parsing) + pub value_name: String, +} + +impl TargetModifier { + pub fn extend(&self) -> ExtendedTargetModifierInfo { + self.opt.reparse(&self.value_name) + } +} + +fn tmod_push_impl( + opt: OptionsTargetModifiers, + tmod_vals: &BTreeMap<OptionsTargetModifiers, String>, + tmods: &mut Vec<TargetModifier>, +) { + tmods.push(TargetModifier { opt, value_name: tmod_vals.get(&opt).cloned().unwrap_or_default() }) +} + +macro_rules! tmod_push { + ($struct_name:ident, $tmod_enum_name:ident, $opt_name:ident, $mods:expr, $tmod_vals:expr) => { + tmod_push_impl( + OptionsTargetModifiers::$struct_name($tmod_enum_name::$opt_name), + $tmod_vals, + $mods, + ); + }; +} + +macro_rules! gather_tmods { + ($struct_name:ident, $tmod_enum_name:ident, $opt_name:ident, $opt_expr:expr, $mods:expr, $tmod_vals:expr, + [SUBSTRUCT], [TARGET_MODIFIER]) => { + compile_error!("SUBSTRUCT can't be target modifier"); + }; + ($struct_name:ident, $tmod_enum_name:ident, $opt_name:ident, $opt_expr:expr, $mods:expr, $tmod_vals:expr, + [UNTRACKED], [TARGET_MODIFIER]) => { + tmod_push!($struct_name, $tmod_enum_name, $opt_name, $mods, $tmod_vals) + }; + ($struct_name:ident, $tmod_enum_name:ident, $opt_name:ident, $opt_expr:expr, $mods:expr, $tmod_vals:expr, + [TRACKED], [TARGET_MODIFIER]) => { + tmod_push!($struct_name, $tmod_enum_name, $opt_name, $mods, $tmod_vals) + }; + ($struct_name:ident, $tmod_enum_name:ident, $opt_name:ident, $opt_expr:expr, $mods:expr, $tmod_vals:expr, + [TRACKED_NO_CRATE_HASH], [TARGET_MODIFIER]) => { + tmod_push!($struct_name, $tmod_enum_name, $opt_name, $mods, $tmod_vals) + }; + ($struct_name:ident, $tmod_enum_name:ident, $opt_name:ident, $opt_expr:expr, $mods:expr, $tmod_vals:expr, + [SUBSTRUCT], []) => { + $opt_expr.gather_target_modifiers($mods, $tmod_vals); + }; + ($struct_name:ident, $tmod_enum_name:ident, $opt_name:ident, $opt_expr:expr, $mods:expr, $tmod_vals:expr, + [UNTRACKED], []) => {{}}; + ($struct_name:ident, $tmod_enum_name:ident, $opt_name:ident, $opt_expr:expr, $mods:expr, $tmod_vals:expr, + [TRACKED], []) => {{}}; + ($struct_name:ident, $tmod_enum_name:ident, $opt_name:ident, $opt_expr:expr, $mods:expr, $tmod_vals:expr, + [TRACKED_NO_CRATE_HASH], []) => {{}}; +} + +macro_rules! gather_tmods_top_level { + ($_opt_name:ident, $opt_expr:expr, $mods:expr, $tmod_vals:expr, [SUBSTRUCT $substruct_enum:ident]) => { + $opt_expr.gather_target_modifiers($mods, $tmod_vals); + }; + ($opt_name:ident, $opt_expr:expr, $mods:expr, $tmod_vals:expr, [$non_substruct:ident TARGET_MODIFIER]) => { + compile_error!("Top level option can't be target modifier"); + }; + ($opt_name:ident, $opt_expr:expr, $mods:expr, $tmod_vals:expr, [$non_substruct:ident]) => {}; +} + +/// Macro for generating OptionsTargetsModifiers top-level enum with impl. +/// Will generate something like: +/// ```rust,ignore (illustrative) +/// pub enum OptionsTargetModifiers { +/// CodegenOptions(CodegenOptionsTargetModifiers), +/// UnstableOptions(UnstableOptionsTargetModifiers), +/// } +/// impl OptionsTargetModifiers { +/// pub fn reparse(&self, user_value: &str) -> ExtendedTargetModifierInfo { +/// match self { +/// Self::CodegenOptions(v) => v.reparse(user_value), +/// Self::UnstableOptions(v) => v.reparse(user_value), +/// } +/// } +/// pub fn is_target_modifier(flag_name: &str) -> bool { +/// CodegenOptionsTargetModifiers::is_target_modifier(flag_name) || +/// UnstableOptionsTargetModifiers::is_target_modifier(flag_name) +/// } +/// } +/// ``` +macro_rules! top_level_tmod_enum { + ($( {$($optinfo:tt)*} ),* $(,)*) => { + top_level_tmod_enum! { @parse {}, (user_value){}; $($($optinfo)*|)* } + }; + // Termination + ( + @parse + {$($variant:tt($substruct_enum:tt))*}, + ($user_value:ident){$($pout:tt)*}; + ) => { + #[allow(non_camel_case_types)] + #[derive(PartialEq, Eq, PartialOrd, Ord, Debug, Copy, Clone, Encodable, Decodable)] + pub enum OptionsTargetModifiers { + $($variant($substruct_enum)),* + } + impl OptionsTargetModifiers { + #[allow(unused_variables)] + pub fn reparse(&self, $user_value: &str) -> ExtendedTargetModifierInfo { + #[allow(unreachable_patterns)] + match self { + $($pout)* + _ => panic!("unknown target modifier option: {:?}", *self) + } + } + pub fn is_target_modifier(flag_name: &str) -> bool { + $($substruct_enum::is_target_modifier(flag_name))||* + } + } + }; + // Adding SUBSTRUCT option group into $eout + ( + @parse {$($eout:tt)*}, ($puser_value:ident){$($pout:tt)*}; + [SUBSTRUCT $substruct_enum:ident $variant:ident] | + $($tail:tt)* + ) => { + top_level_tmod_enum! { + @parse + { + $($eout)* + $variant($substruct_enum) + }, + ($puser_value){ + $($pout)* + Self::$variant(v) => v.reparse($puser_value), + }; + $($tail)* + } + }; + // Skipping non-target-modifier and non-substruct + ( + @parse {$($eout:tt)*}, ($puser_value:ident){$($pout:tt)*}; + [$non_substruct:ident] | + $($tail:tt)* + ) => { + top_level_tmod_enum! { + @parse + { + $($eout)* + }, + ($puser_value){ + $($pout)* + }; + $($tail)* + } + }; +} + macro_rules! top_level_options { ( $( #[$top_level_attr:meta] )* pub struct Options { $( $( #[$attr:meta] )* - $opt:ident : $t:ty [$dep_tracking_marker:ident], + $opt:ident : $t:ty [$dep_tracking_marker:ident $( $tmod:ident $variant:ident )?], )* } ) => ( + top_level_tmod_enum!( {$([$dep_tracking_marker $($tmod $variant),*])|*} ); + #[derive(Clone)] $( #[$top_level_attr] )* pub struct Options { $( $( #[$attr] )* pub $opt: $t - ),* + ),*, + pub target_modifiers: BTreeMap<OptionsTargetModifiers, String>, } impl Options { @@ -98,6 +275,17 @@ macro_rules! top_level_options { })* hasher.finish() } + + pub fn gather_target_modifiers(&self) -> Vec<TargetModifier> { + let mut mods = Vec::<TargetModifier>::new(); + $({ + gather_tmods_top_level!($opt, + &self.$opt, &mut mods, &self.target_modifiers, + [$dep_tracking_marker $($tmod),*]); + })* + mods.sort_by(|a, b| a.opt.cmp(&b.opt)); + mods + } } ); } @@ -165,9 +353,9 @@ top_level_options!( #[rustc_lint_opt_deny_field_access("should only be used via `Config::hash_untracked_state`")] untracked_state_hash: Hash64 [TRACKED_NO_CRATE_HASH], - unstable_opts: UnstableOptions [SUBSTRUCT], + unstable_opts: UnstableOptions [SUBSTRUCT UnstableOptionsTargetModifiers UnstableOptions], prints: Vec<PrintRequest> [UNTRACKED], - cg: CodegenOptions [SUBSTRUCT], + cg: CodegenOptions [SUBSTRUCT CodegenOptionsTargetModifiers CodegenOptions], externs: Externs [UNTRACKED], crate_name: Option<String> [TRACKED], /// Indicates how the compiler should treat unstable features. @@ -226,6 +414,98 @@ top_level_options!( } ); +macro_rules! tmod_enum_opt { + ($struct_name:ident, $tmod_enum_name:ident, $opt:ident, $v:ident) => { + Some(OptionsTargetModifiers::$struct_name($tmod_enum_name::$opt)) + }; + ($struct_name:ident, $tmod_enum_name:ident, $opt:ident, ) => { + None + }; +} + +macro_rules! tmod_enum { + ($tmod_enum_name:ident, $prefix:expr, $( {$($optinfo:tt)*} ),* $(,)*) => { + tmod_enum! { $tmod_enum_name, $prefix, @parse {}, (user_value){}; $($($optinfo)*|)* } + }; + // Termination + ( + $tmod_enum_name:ident, $prefix:expr, + @parse + {$($eout:tt)*}, + ($user_value:ident){$($pout:tt)*}; + ) => { + #[allow(non_camel_case_types)] + #[derive(PartialEq, Eq, PartialOrd, Ord, Debug, Copy, Clone, Encodable, Decodable)] + pub enum $tmod_enum_name { + $($eout),* + } + impl $tmod_enum_name { + #[allow(unused_variables)] + pub fn reparse(&self, $user_value: &str) -> ExtendedTargetModifierInfo { + #[allow(unreachable_patterns)] + match self { + $($pout)* + _ => panic!("unknown target modifier option: {:?}", *self) + } + } + pub fn is_target_modifier(flag_name: &str) -> bool { + match flag_name.replace('-', "_").as_str() { + $(stringify!($eout) => true,)* + _ => false, + } + } + } + }; + // Adding target-modifier option into $eout + ( + $tmod_enum_name:ident, $prefix:expr, + @parse {$($eout:tt)*}, ($puser_value:ident){$($pout:tt)*}; + $opt:ident, $parse:ident, $t:ty, [TARGET_MODIFIER] | + $($tail:tt)* + ) => { + tmod_enum! { + $tmod_enum_name, $prefix, + @parse + { + $($eout)* + $opt + }, + ($puser_value){ + $($pout)* + Self::$opt => { + let mut parsed : $t = Default::default(); + parse::$parse(&mut parsed, Some($puser_value)); + ExtendedTargetModifierInfo { + prefix: $prefix.to_string(), + name: stringify!($opt).to_string().replace('_', "-"), + tech_value: format!("{:?}", parsed), + } + }, + }; + $($tail)* + } + }; + // Skipping non-target-modifier + ( + $tmod_enum_name:ident, $prefix:expr, + @parse {$($eout:tt)*}, ($puser_value:ident){$($pout:tt)*}; + $opt:ident, $parse:ident, $t:ty, [] | + $($tail:tt)* + ) => { + tmod_enum! { + $tmod_enum_name, $prefix, + @parse + { + $($eout)* + }, + ($puser_value){ + $($pout)* + }; + $($tail)* + } + }; +} + /// Defines all `CodegenOptions`/`DebuggingOptions` fields and parsers all at once. The goal of this /// macro is to define an interface that can be programmatically used by the option parser /// to initialize the struct without hardcoding field names all over the place. @@ -235,11 +515,11 @@ top_level_options!( /// generated code to parse an option into its respective field in the struct. There are a few /// hand-written parsers for parsing specific types of values in this module. macro_rules! options { - ($struct_name:ident, $stat:ident, $optmod:ident, $prefix:expr, $outputname:expr, + ($struct_name:ident, $tmod_enum_name:ident, $stat:ident, $optmod:ident, $prefix:expr, $outputname:expr, $($( #[$attr:meta] )* $opt:ident : $t:ty = ( $init:expr, $parse:ident, - [$dep_tracking_marker:ident], + [$dep_tracking_marker:ident $( $tmod:ident )?], $desc:expr $(, deprecated_do_nothing: $dnn:literal )?) ),* ,) => @@ -248,6 +528,8 @@ macro_rules! options { #[rustc_lint_opt_ty] pub struct $struct_name { $( $( #[$attr] )* pub $opt: $t),* } + tmod_enum!( $tmod_enum_name, $prefix, {$($opt, $parse, $t, [$($tmod),*])|*} ); + impl Default for $struct_name { fn default() -> $struct_name { $struct_name { $($opt: $init),* } @@ -258,8 +540,9 @@ macro_rules! options { pub fn build( early_dcx: &EarlyDiagCtxt, matches: &getopts::Matches, + target_modifiers: &mut BTreeMap<OptionsTargetModifiers, String>, ) -> $struct_name { - build_options(early_dcx, matches, $stat, $prefix, $outputname) + build_options(early_dcx, matches, target_modifiers, $stat, $prefix, $outputname) } fn dep_tracking_hash(&self, for_crate_hash: bool, error_format: ErrorOutputType) -> u64 { @@ -279,11 +562,23 @@ macro_rules! options { ); hasher.finish() } + + pub fn gather_target_modifiers( + &self, + _mods: &mut Vec<TargetModifier>, + _tmod_vals: &BTreeMap<OptionsTargetModifiers, String>, + ) { + $({ + gather_tmods!($struct_name, $tmod_enum_name, $opt, &self.$opt, _mods, _tmod_vals, + [$dep_tracking_marker], [$($tmod),*]); + })* + } } pub const $stat: OptionDescrs<$struct_name> = &[ $( OptionDesc{ name: stringify!($opt), setter: $optmod::$opt, - type_desc: desc::$parse, desc: $desc, is_deprecated_and_do_nothing: false $( || $dnn )? } ),* ]; + type_desc: desc::$parse, desc: $desc, is_deprecated_and_do_nothing: false $( || $dnn )?, + tmod: tmod_enum_opt!($struct_name, $tmod_enum_name, $opt, $($tmod),*) } ),* ]; mod $optmod { $( @@ -328,6 +623,7 @@ pub struct OptionDesc<O> { // description for option from options table desc: &'static str, is_deprecated_and_do_nothing: bool, + tmod: Option<OptionsTargetModifiers>, } impl<O> OptionDesc<O> { @@ -344,6 +640,7 @@ impl<O> OptionDesc<O> { fn build_options<O: Default>( early_dcx: &EarlyDiagCtxt, matches: &getopts::Matches, + target_modifiers: &mut BTreeMap<OptionsTargetModifiers, String>, descrs: OptionDescrs<O>, prefix: &str, outputname: &str, @@ -357,7 +654,14 @@ fn build_options<O: Default>( let option_to_lookup = key.replace('-', "_"); match descrs.iter().find(|opt_desc| opt_desc.name == option_to_lookup) { - Some(OptionDesc { name: _, setter, type_desc, desc, is_deprecated_and_do_nothing }) => { + Some(OptionDesc { + name: _, + setter, + type_desc, + desc, + is_deprecated_and_do_nothing, + tmod, + }) => { if *is_deprecated_and_do_nothing { // deprecation works for prefixed options only assert!(!prefix.is_empty()); @@ -377,6 +681,11 @@ fn build_options<O: Default>( ), } } + if let Some(tmod) = *tmod + && let Some(value) = value + { + target_modifiers.insert(tmod, value.to_string()); + } } None => early_dcx.early_fatal(format!("unknown {outputname} option: `{key}`")), } @@ -1614,7 +1923,7 @@ pub mod parse { } options! { - CodegenOptions, CG_OPTIONS, cgopts, "C", "codegen", + CodegenOptions, CodegenOptionsTargetModifiers, CG_OPTIONS, cgopts, "C", "codegen", // If you add a new option, please update: // - compiler/rustc_interface/src/tests.rs @@ -1745,6 +2054,8 @@ options! { target_feature: String = (String::new(), parse_target_feature, [TRACKED], "target specific attributes. (`rustc --print target-features` for details). \ This feature is unsafe."), + unsafe_allow_abi_mismatch: Vec<String> = (Vec::new(), parse_comma_list, [UNTRACKED], + "Allow incompatible target modifiers in dependency crates (comma separated list)"), // tidy-alphabetical-end // If you add a new option, please update: @@ -1753,7 +2064,7 @@ options! { } options! { - UnstableOptions, Z_OPTIONS, dbopts, "Z", "unstable", + UnstableOptions, UnstableOptionsTargetModifiers, Z_OPTIONS, dbopts, "Z", "unstable", // If you add a new option, please update: // - compiler/rustc_interface/src/tests.rs @@ -2098,10 +2409,10 @@ options! { "enable queries of the dependency graph for regression testing (default: no)"), randomize_layout: bool = (false, parse_bool, [TRACKED], "randomize the layout of types (default: no)"), - reg_struct_return: bool = (false, parse_bool, [TRACKED], + reg_struct_return: bool = (false, parse_bool, [TRACKED TARGET_MODIFIER], "On x86-32 targets, it overrides the default ABI to return small structs in registers. It is UNSOUND to link together crates that use different values for this flag!"), - regparm: Option<u32> = (None, parse_opt_number, [TRACKED], + regparm: Option<u32> = (None, parse_opt_number, [TRACKED TARGET_MODIFIER], "On x86-32 targets, setting this to N causes the compiler to pass N arguments \ in registers EAX, EDX, and ECX instead of on the stack for\ \"C\", \"cdecl\", and \"stdcall\" fn.\ diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index b23cc909911..c6233febd95 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -294,9 +294,12 @@ symbols! { ProceduralMasqueradeDummyType, Range, RangeBounds, + RangeCopy, RangeFrom, + RangeFromCopy, RangeFull, RangeInclusive, + RangeInclusiveCopy, RangeTo, RangeToInclusive, Rc, @@ -1148,6 +1151,7 @@ symbols! { iterator, iterator_collect_fn, kcfi, + keylocker_x86, keyword, kind, kreg, @@ -1363,6 +1367,7 @@ symbols! { new_lower_hex, new_octal, new_pointer, + new_range, new_unchecked, new_upper_exp, new_upper_hex, diff --git a/compiler/rustc_symbol_mangling/src/v0.rs b/compiler/rustc_symbol_mangling/src/v0.rs index 7b040a8b2c4..0ac6f17b97b 100644 --- a/compiler/rustc_symbol_mangling/src/v0.rs +++ b/compiler/rustc_symbol_mangling/src/v0.rs @@ -649,7 +649,8 @@ impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> { // HACK(jaic1): hide the `str` type behind a reference // for the following transformation from valtree to raw bytes let ref_ty = Ty::new_imm_ref(tcx, tcx.lifetimes.re_static, ct_ty); - let slice = valtree.try_to_raw_bytes(tcx, ref_ty).unwrap_or_else(|| { + let cv = ty::Value { ty: ref_ty, valtree }; + let slice = cv.try_to_raw_bytes(tcx).unwrap_or_else(|| { bug!("expected to get raw bytes from valtree {:?} for type {:}", valtree, ct_ty) }); let s = std::str::from_utf8(slice).expect("non utf8 str from MIR interpreter"); diff --git a/compiler/rustc_target/src/spec/json.rs b/compiler/rustc_target/src/spec/json.rs index 015ea97f2ac..a6b0ec072e8 100644 --- a/compiler/rustc_target/src/spec/json.rs +++ b/compiler/rustc_target/src/spec/json.rs @@ -128,6 +128,19 @@ impl Target { Some(Ok(())) })).unwrap_or(Ok(())) } ); + ($key_name:ident, RustcAbi) => ( { + let name = (stringify!($key_name)).replace("_", "-"); + obj.remove(&name).and_then(|o| o.as_str().and_then(|s| { + match s.parse::<super::RustcAbi>() { + Ok(rustc_abi) => base.$key_name = Some(rustc_abi), + _ => return Some(Err(format!( + "'{s}' is not a valid value for rustc-abi. \ + Use 'x86-softfloat' or leave the field unset." + ))), + } + Some(Ok(())) + })).unwrap_or(Ok(())) + } ); ($key_name:ident, RelocModel) => ( { let name = (stringify!($key_name)).replace("_", "-"); obj.remove(&name).and_then(|o| o.as_str().and_then(|s| { @@ -612,6 +625,7 @@ impl Target { key!(llvm_mcount_intrinsic, optional); key!(llvm_abiname); key!(llvm_floatabi, FloatAbi)?; + key!(rustc_abi, RustcAbi)?; key!(relax_elf_relocations, bool); key!(llvm_args, list); key!(use_ctors_section, bool); @@ -788,6 +802,7 @@ impl ToJson for Target { target_option_val!(llvm_mcount_intrinsic); target_option_val!(llvm_abiname); target_option_val!(llvm_floatabi); + target_option_val!(rustc_abi); target_option_val!(relax_elf_relocations); target_option_val!(llvm_args); target_option_val!(use_ctors_section); diff --git a/compiler/rustc_target/src/spec/mod.rs b/compiler/rustc_target/src/spec/mod.rs index 3fc7a07fb91..72600225e7a 100644 --- a/compiler/rustc_target/src/spec/mod.rs +++ b/compiler/rustc_target/src/spec/mod.rs @@ -1114,6 +1114,33 @@ impl ToJson for FloatAbi { } } +/// The Rustc-specific variant of the ABI used for this target. +#[derive(Clone, Copy, PartialEq, Hash, Debug)] +pub enum RustcAbi { + /// On x86-32/64 only: do not use any FPU or SIMD registers for the ABI. + X86Softfloat, +} + +impl FromStr for RustcAbi { + type Err = (); + + fn from_str(s: &str) -> Result<RustcAbi, ()> { + Ok(match s { + "x86-softfloat" => RustcAbi::X86Softfloat, + _ => return Err(()), + }) + } +} + +impl ToJson for RustcAbi { + fn to_json(&self) -> Json { + match *self { + RustcAbi::X86Softfloat => "x86-softfloat", + } + .to_json() + } +} + #[derive(Clone, Copy, PartialEq, Hash, Debug)] pub enum TlsModel { GeneralDynamic, @@ -2505,6 +2532,12 @@ pub struct TargetOptions { /// If not provided, LLVM will infer the float ABI from the target triple (`llvm_target`). pub llvm_floatabi: Option<FloatAbi>, + /// Picks a specific ABI for this target. This is *not* just for "Rust" ABI functions, + /// it can also affect "C" ABI functions; the point is that this flag is interpreted by + /// rustc and not forwarded to LLVM. + /// So far, this is only used on x86. + pub rustc_abi: Option<RustcAbi>, + /// Whether or not RelaxElfRelocation flag will be passed to the linker pub relax_elf_relocations: bool, @@ -2664,10 +2697,6 @@ impl TargetOptions { .collect(); } } - - pub(crate) fn has_feature(&self, search_feature: &str) -> bool { - self.features.split(',').any(|f| f.strip_prefix('+').is_some_and(|f| f == search_feature)) - } } impl Default for TargetOptions { @@ -2774,6 +2803,7 @@ impl Default for TargetOptions { llvm_mcount_intrinsic: None, llvm_abiname: "".into(), llvm_floatabi: None, + rustc_abi: None, relax_elf_relocations: false, llvm_args: cvs![], use_ctors_section: false, @@ -3240,6 +3270,17 @@ impl Target { _ => {} } + // Check consistency of Rust ABI declaration. + if let Some(rust_abi) = self.rustc_abi { + match rust_abi { + RustcAbi::X86Softfloat => check_matches!( + &*self.arch, + "x86" | "x86_64", + "`x86-softfloat` ABI is only valid for x86 targets" + ), + } + } + // Check that the given target-features string makes some basic sense. if !self.features.is_empty() { let mut features_enabled = FxHashSet::default(); diff --git a/compiler/rustc_target/src/spec/targets/i686_unknown_uefi.rs b/compiler/rustc_target/src/spec/targets/i686_unknown_uefi.rs index 39d3a5a4633..c1ed565f0fe 100644 --- a/compiler/rustc_target/src/spec/targets/i686_unknown_uefi.rs +++ b/compiler/rustc_target/src/spec/targets/i686_unknown_uefi.rs @@ -5,7 +5,7 @@ // The cdecl ABI is used. It differs from the stdcall or fastcall ABI. // "i686-unknown-windows" is used to get the minimal subset of windows-specific features. -use crate::spec::{Target, base}; +use crate::spec::{RustcAbi, Target, base}; pub(crate) fn target() -> Target { let mut base = base::uefi_msvc::opts(); @@ -22,6 +22,7 @@ pub(crate) fn target() -> Target { // If you initialize FP units yourself, you can override these flags with custom linker // arguments, thus giving you access to full MMX/SSE acceleration. base.features = "-mmx,-sse,+soft-float".into(); + base.rustc_abi = Some(RustcAbi::X86Softfloat); // Use -GNU here, because of the reason below: // Background and Problem: diff --git a/compiler/rustc_target/src/spec/targets/x86_64_unknown_none.rs b/compiler/rustc_target/src/spec/targets/x86_64_unknown_none.rs index cfefb1de993..e14a3673589 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_unknown_none.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_unknown_none.rs @@ -5,8 +5,8 @@ // features. use crate::spec::{ - Cc, CodeModel, LinkerFlavor, Lld, PanicStrategy, RelroLevel, SanitizerSet, StackProbeType, - Target, TargetOptions, + Cc, CodeModel, LinkerFlavor, Lld, PanicStrategy, RelroLevel, RustcAbi, SanitizerSet, + StackProbeType, Target, TargetOptions, }; pub(crate) fn target() -> Target { @@ -20,6 +20,7 @@ pub(crate) fn target() -> Target { relro_level: RelroLevel::Full, linker_flavor: LinkerFlavor::Gnu(Cc::No, Lld::Yes), linker: Some("rust-lld".into()), + rustc_abi: Some(RustcAbi::X86Softfloat), features: "-mmx,-sse,-sse2,-sse3,-ssse3,-sse4.1,-sse4.2,-avx,-avx2,+soft-float".into(), supported_sanitizers: SanitizerSet::KCFI | SanitizerSet::KERNELADDRESS, disable_redzone: true, diff --git a/compiler/rustc_target/src/spec/targets/x86_64_unknown_uefi.rs b/compiler/rustc_target/src/spec/targets/x86_64_unknown_uefi.rs index a11a79ff41a..8fd92e8123b 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_unknown_uefi.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_unknown_uefi.rs @@ -6,7 +6,7 @@ // LLVM. "x86_64-unknown-windows" is used to get the minimal subset of windows-specific features. use crate::abi::call::Conv; -use crate::spec::{Target, base}; +use crate::spec::{RustcAbi, Target, base}; pub(crate) fn target() -> Target { let mut base = base::uefi_msvc::opts(); @@ -26,6 +26,7 @@ pub(crate) fn target() -> Target { // If you initialize FP units yourself, you can override these flags with custom linker // arguments, thus giving you access to full MMX/SSE acceleration. base.features = "-mmx,-sse,+soft-float".into(); + base.rustc_abi = Some(RustcAbi::X86Softfloat); Target { llvm_target: "x86_64-unknown-windows".into(), diff --git a/compiler/rustc_target/src/target_features.rs b/compiler/rustc_target/src/target_features.rs index 0d8a4988dce..eb2417e0a20 100644 --- a/compiler/rustc_target/src/target_features.rs +++ b/compiler/rustc_target/src/target_features.rs @@ -5,7 +5,7 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_span::{Symbol, sym}; -use crate::spec::{FloatAbi, Target}; +use crate::spec::{FloatAbi, RustcAbi, Target}; /// Features that control behaviour of rustc, rather than the codegen. /// These exist globally and are not in the target-specific lists below. @@ -409,6 +409,7 @@ const X86_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ ("fma", Stable, &["avx"]), ("fxsr", Stable, &[]), ("gfni", Unstable(sym::avx512_target_feature), &["sse2"]), + ("kl", Unstable(sym::keylocker_x86), &["sse2"]), ("lahfsahf", Unstable(sym::lahfsahf_target_feature), &[]), ("lzcnt", Stable, &[]), ("movbe", Stable, &[]), @@ -422,7 +423,9 @@ const X86_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ ("sha512", Unstable(sym::sha512_sm_x86), &["avx2"]), ("sm3", Unstable(sym::sha512_sm_x86), &["avx"]), ("sm4", Unstable(sym::sha512_sm_x86), &["avx2"]), - ("soft-float", Stability::Forbidden { reason: "unsound because it changes float ABI" }, &[]), + // This cannot actually be toggled, the ABI always fixes it, so it'd make little sense to + // stabilize. It must be in this list for the ABI check to be able to use it. + ("soft-float", Stability::Unstable(sym::x87_target_feature), &[]), ("sse", Stable, &[]), ("sse2", Stable, &["sse"]), ("sse3", Stable, &["sse2"]), @@ -433,6 +436,7 @@ const X86_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ ("tbm", Unstable(sym::tbm_target_feature), &[]), ("vaes", Unstable(sym::avx512_target_feature), &["avx2", "aes"]), ("vpclmulqdq", Unstable(sym::avx512_target_feature), &["avx", "pclmulqdq"]), + ("widekl", Unstable(sym::keylocker_x86), &["kl"]), ("x87", Unstable(sym::x87_target_feature), &[]), ("xop", Unstable(sym::xop_target_feature), &[/*"fma4", */ "avx", "sse4a"]), ("xsave", Stable, &[]), @@ -773,23 +777,41 @@ impl Target { // questions "which ABI is used". match &*self.arch { "x86" => { - // We support 2 ABIs, hardfloat (default) and softfloat. - // x86 has no sane ABI indicator so we have to use the target feature. - if self.has_feature("soft-float") { - NOTHING - } else { - // Hardfloat ABI. x87 must be enabled. - FeatureConstraints { required: &["x87"], incompatible: &[] } + // We use our own ABI indicator here; LLVM does not have anything native. + // Every case should require or forbid `soft-float`! + match self.rustc_abi { + None => { + // Default hardfloat ABI. + // x87 must be enabled, soft-float must be disabled. + FeatureConstraints { required: &["x87"], incompatible: &["soft-float"] } + } + Some(RustcAbi::X86Softfloat) => { + // Softfloat ABI, requires corresponding target feature. That feature trumps + // `x87` and all other FPU features so those do not matter. + // Note that this one requirement is the entire implementation of the ABI! + // LLVM handles the rest. + FeatureConstraints { required: &["soft-float"], incompatible: &[] } + } } } "x86_64" => { - // We support 2 ABIs, hardfloat (default) and softfloat. - // x86 has no sane ABI indicator so we have to use the target feature. - if self.has_feature("soft-float") { - NOTHING - } else { - // Hardfloat ABI. x87 and SSE2 must be enabled. - FeatureConstraints { required: &["x87", "sse2"], incompatible: &[] } + // We use our own ABI indicator here; LLVM does not have anything native. + // Every case should require or forbid `soft-float`! + match self.rustc_abi { + None => { + // Default hardfloat ABI. On x86-64, this always includes SSE2. + FeatureConstraints { + required: &["x87", "sse2"], + incompatible: &["soft-float"], + } + } + Some(RustcAbi::X86Softfloat) => { + // Softfloat ABI, requires corresponding target feature. That feature trumps + // `x87` and all other FPU features so those do not matter. + // Note that this one requirement is the entire implementation of the ABI! + // LLVM handles the rest. + FeatureConstraints { required: &["soft-float"], incompatible: &[] } + } } } "arm" => { diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs index 87dcdcfd665..3128577776a 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs @@ -703,7 +703,6 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { }; self.note_obligation_cause(&mut err, &obligation); - self.point_at_returns_when_relevant(&mut err, &obligation); err.emit() } } @@ -806,7 +805,6 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { "Async", ); self.note_obligation_cause(&mut err, &obligation); - self.point_at_returns_when_relevant(&mut err, &obligation); return Some(err.emit()); } } @@ -852,7 +850,6 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { "", ); self.note_obligation_cause(&mut err, &obligation); - self.point_at_returns_when_relevant(&mut err, &obligation); return Some(err.emit()); } @@ -868,7 +865,6 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { kind: expected_kind.as_str(), }); self.note_obligation_cause(&mut err, &obligation); - self.point_at_returns_when_relevant(&mut err, &obligation); return Some(err.emit()); } } @@ -2826,7 +2822,6 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { err.span_note(self.tcx.def_span(def_id), "opaque type is declared here"); self.note_obligation_cause(&mut err, &obligation); - self.point_at_returns_when_relevant(&mut err, &obligation); self.dcx().try_steal_replace_and_emit_err(self.tcx.def_span(def_id), StashKey::Cycle, err) } diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/overflow.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/overflow.rs index fad03b5e9bf..c5ed74420d4 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/overflow.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/overflow.rs @@ -185,7 +185,6 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { suggest_increasing_limit, ); self.note_obligation_cause(&mut err, &obligation); - self.point_at_returns_when_relevant(&mut err, &obligation); err.emit() } } diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs index 24ca7bb7fc2..c194cc11727 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs @@ -1765,7 +1765,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { }; err.code(E0746); - err.primary_message("return type cannot have an unboxed trait object"); + err.primary_message("return type cannot be a trait object without pointer indirection"); err.children.clear(); let span = obligation.cause.span; @@ -1781,25 +1781,13 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } else { ("dyn ", span.shrink_to_lo()) }; - let alternatively = if visitor - .returns - .iter() - .map(|expr| self.typeck_results.as_ref().unwrap().expr_ty_adjusted_opt(expr)) - .collect::<FxHashSet<_>>() - .len() - <= 1 - { - err.span_suggestion_verbose( - impl_span, - "consider returning an `impl Trait` instead of a `dyn Trait`", - "impl ", - Applicability::MaybeIncorrect, - ); - "alternatively, " - } else { - err.help("if there were a single returned type, you could use `impl Trait` instead"); - "" - }; + + err.span_suggestion_verbose( + impl_span, + "consider returning an `impl Trait` instead of a `dyn Trait`", + "impl ", + Applicability::MaybeIncorrect, + ); let mut sugg = vec![ (span.shrink_to_lo(), format!("Box<{pre}")), @@ -1831,7 +1819,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { err.multipart_suggestion( format!( - "{alternatively}box the return type, and wrap all of the returned values in \ + "alternatively, box the return type, and wrap all of the returned values in \ `Box::new`", ), sugg, @@ -1841,41 +1829,6 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { true } - pub(super) fn point_at_returns_when_relevant( - &self, - err: &mut Diag<'_>, - obligation: &PredicateObligation<'tcx>, - ) { - match obligation.cause.code().peel_derives() { - ObligationCauseCode::SizedReturnType => {} - _ => return, - } - - let hir = self.tcx.hir(); - let node = self.tcx.hir_node_by_def_id(obligation.cause.body_id); - if let hir::Node::Item(hir::Item { - kind: hir::ItemKind::Fn { body: body_id, .. }, .. - }) = node - { - let body = hir.body(*body_id); - // Point at all the `return`s in the function as they have failed trait bounds. - let mut visitor = ReturnsVisitor::default(); - visitor.visit_body(body); - let typeck_results = self.typeck_results.as_ref().unwrap(); - for expr in &visitor.returns { - if let Some(returned_ty) = typeck_results.node_type_opt(expr.hir_id) { - let ty = self.resolve_vars_if_possible(returned_ty); - if ty.references_error() { - // don't print out the [type error] here - err.downgrade_to_delayed_bug(); - } else { - err.span_label(expr.span, format!("this returned value is of type `{ty}`")); - } - } - } - } - } - pub(super) fn report_closure_arg_mismatch( &self, span: Span, diff --git a/compiler/rustc_type_ir/src/fold.rs b/compiler/rustc_type_ir/src/fold.rs index d337a1a8ad9..711e42ff055 100644 --- a/compiler/rustc_type_ir/src/fold.rs +++ b/compiler/rustc_type_ir/src/fold.rs @@ -73,7 +73,7 @@ type Never = std::convert::Infallible; /// which means in practice almost every foldable type needs to also be /// visitable. (However, there are some types that are visitable without being /// foldable.) -pub trait TypeFoldable<I: Interner>: TypeVisitable<I> { +pub trait TypeFoldable<I: Interner>: TypeVisitable<I> + Clone { /// The entry point for folding. To fold a value `t` with a folder `f` /// call: `t.try_fold_with(f)`. /// diff --git a/compiler/rustc_type_ir/src/visit.rs b/compiler/rustc_type_ir/src/visit.rs index 3213638afb2..0a074942170 100644 --- a/compiler/rustc_type_ir/src/visit.rs +++ b/compiler/rustc_type_ir/src/visit.rs @@ -59,7 +59,7 @@ use crate::{self as ty, Interner, TypeFlags}; /// /// To implement this conveniently, use the derive macro located in /// `rustc_macros`. -pub trait TypeVisitable<I: Interner>: fmt::Debug + Clone { +pub trait TypeVisitable<I: Interner>: fmt::Debug { /// The entry point for visiting. To visit a value `t` with a visitor `v` /// call: `t.visit_with(v)`. /// diff --git a/library/core/src/cell.rs b/library/core/src/cell.rs index 20187e478aa..320d8176011 100644 --- a/library/core/src/cell.rs +++ b/library/core/src/cell.rs @@ -2118,6 +2118,35 @@ impl<T> UnsafeCell<T> { pub const fn into_inner(self) -> T { self.value } + + /// Replace the value in this `UnsafeCell` and return the old value. + /// + /// # Safety + /// + /// The caller must take care to avoid aliasing and data races. + /// + /// - It is Undefined Behavior to allow calls to race with + /// any other access to the wrapped value. + /// - It is Undefined Behavior to call this while any other + /// reference(s) to the wrapped value are alive. + /// + /// # Examples + /// + /// ``` + /// #![feature(unsafe_cell_access)] + /// use std::cell::UnsafeCell; + /// + /// let uc = UnsafeCell::new(5); + /// + /// let old = unsafe { uc.replace(10) }; + /// assert_eq!(old, 5); + /// ``` + #[inline] + #[unstable(feature = "unsafe_cell_access", issue = "136327")] + pub const unsafe fn replace(&self, value: T) -> T { + // SAFETY: pointer comes from `&self` so naturally satisfies invariants. + unsafe { ptr::replace(self.get(), value) } + } } impl<T: ?Sized> UnsafeCell<T> { @@ -2230,6 +2259,61 @@ impl<T: ?Sized> UnsafeCell<T> { // no guarantee for user code that this will work in future versions of the compiler! this as *const T as *mut T } + + /// Get a shared reference to the value within the `UnsafeCell`. + /// + /// # Safety + /// + /// - It is Undefined Behavior to call this while any mutable + /// reference to the wrapped value is alive. + /// - Mutating the wrapped value while the returned + /// reference is alive is Undefined Behavior. + /// + /// # Examples + /// + /// ``` + /// #![feature(unsafe_cell_access)] + /// use std::cell::UnsafeCell; + /// + /// let uc = UnsafeCell::new(5); + /// + /// let val = unsafe { uc.as_ref_unchecked() }; + /// assert_eq!(val, &5); + /// ``` + #[inline] + #[unstable(feature = "unsafe_cell_access", issue = "136327")] + pub const unsafe fn as_ref_unchecked(&self) -> &T { + // SAFETY: pointer comes from `&self` so naturally satisfies ptr-to-ref invariants. + unsafe { self.get().as_ref_unchecked() } + } + + /// Get an exclusive reference to the value within the `UnsafeCell`. + /// + /// # Safety + /// + /// - It is Undefined Behavior to call this while any other + /// reference(s) to the wrapped value are alive. + /// - Mutating the wrapped value through other means while the + /// returned reference is alive is Undefined Behavior. + /// + /// # Examples + /// + /// ``` + /// #![feature(unsafe_cell_access)] + /// use std::cell::UnsafeCell; + /// + /// let uc = UnsafeCell::new(5); + /// + /// unsafe { *uc.as_mut_unchecked() += 1; } + /// assert_eq!(uc.into_inner(), 6); + /// ``` + #[inline] + #[unstable(feature = "unsafe_cell_access", issue = "136327")] + #[allow(clippy::mut_from_ref)] + pub const unsafe fn as_mut_unchecked(&self) -> &mut T { + // SAFETY: pointer comes from `&self` so naturally satisfies ptr-to-ref invariants. + unsafe { self.get().as_mut_unchecked() } + } } #[stable(feature = "unsafe_cell_default", since = "1.10.0")] diff --git a/library/core/src/cell/once.rs b/library/core/src/cell/once.rs index 6a85791916a..c6c96571d33 100644 --- a/library/core/src/cell/once.rs +++ b/library/core/src/cell/once.rs @@ -8,6 +8,9 @@ use crate::{fmt, mem}; /// only immutable references can be obtained unless one has a mutable reference to the cell /// itself. In the same vein, the cell can only be re-initialized with such a mutable reference. /// +/// A `OnceCell` can be thought of as a safe abstraction over uninitialized data that becomes +/// initialized once written. +/// /// For a thread-safe version of this struct, see [`std::sync::OnceLock`]. /// /// [`RefCell`]: crate::cell::RefCell @@ -35,7 +38,7 @@ pub struct OnceCell<T> { } impl<T> OnceCell<T> { - /// Creates a new empty cell. + /// Creates a new uninitialized cell. #[inline] #[must_use] #[stable(feature = "once_cell", since = "1.70.0")] @@ -46,7 +49,7 @@ impl<T> OnceCell<T> { /// Gets the reference to the underlying value. /// - /// Returns `None` if the cell is empty. + /// Returns `None` if the cell is uninitialized. #[inline] #[stable(feature = "once_cell", since = "1.70.0")] pub fn get(&self) -> Option<&T> { @@ -56,19 +59,19 @@ impl<T> OnceCell<T> { /// Gets the mutable reference to the underlying value. /// - /// Returns `None` if the cell is empty. + /// Returns `None` if the cell is uninitialized. #[inline] #[stable(feature = "once_cell", since = "1.70.0")] pub fn get_mut(&mut self) -> Option<&mut T> { self.inner.get_mut().as_mut() } - /// Sets the contents of the cell to `value`. + /// Initializes the contents of the cell to `value`. /// /// # Errors /// - /// This method returns `Ok(())` if the cell was empty and `Err(value)` if - /// it was full. + /// This method returns `Ok(())` if the cell was uninitialized + /// and `Err(value)` if it was already initialized. /// /// # Examples /// @@ -92,13 +95,13 @@ impl<T> OnceCell<T> { } } - /// Sets the contents of the cell to `value` if the cell was empty, then - /// returns a reference to it. + /// Initializes the contents of the cell to `value` if the cell was + /// uninitialized, then returns a reference to it. /// /// # Errors /// - /// This method returns `Ok(&value)` if the cell was empty and - /// `Err(¤t_value, value)` if it was full. + /// This method returns `Ok(&value)` if the cell was uninitialized + /// and `Err((¤t_value, value))` if it was already initialized. /// /// # Examples /// @@ -130,12 +133,12 @@ impl<T> OnceCell<T> { Ok(slot.insert(value)) } - /// Gets the contents of the cell, initializing it with `f` - /// if the cell was empty. + /// Gets the contents of the cell, initializing it to `f()` + /// if the cell was uninitialized. /// /// # Panics /// - /// If `f` panics, the panic is propagated to the caller, and the cell + /// If `f()` panics, the panic is propagated to the caller, and the cell /// remains uninitialized. /// /// It is an error to reentrantly initialize the cell from `f`. Doing @@ -164,11 +167,11 @@ impl<T> OnceCell<T> { } /// Gets the mutable reference of the contents of the cell, - /// initializing it with `f` if the cell was empty. + /// initializing it to `f()` if the cell was uninitialized. /// /// # Panics /// - /// If `f` panics, the panic is propagated to the caller, and the cell + /// If `f()` panics, the panic is propagated to the caller, and the cell /// remains uninitialized. /// /// # Examples @@ -199,13 +202,13 @@ impl<T> OnceCell<T> { } } - /// Gets the contents of the cell, initializing it with `f` if - /// the cell was empty. If the cell was empty and `f` failed, an - /// error is returned. + /// Gets the contents of the cell, initializing it to `f()` if + /// the cell was uninitialized. If the cell was uninitialized + /// and `f()` failed, an error is returned. /// /// # Panics /// - /// If `f` panics, the panic is propagated to the caller, and the cell + /// If `f()` panics, the panic is propagated to the caller, and the cell /// remains uninitialized. /// /// It is an error to reentrantly initialize the cell from `f`. Doing @@ -239,12 +242,12 @@ impl<T> OnceCell<T> { } /// Gets the mutable reference of the contents of the cell, initializing - /// it with `f` if the cell was empty. If the cell was empty and `f` failed, - /// an error is returned. + /// it to `f()` if the cell was uninitialized. If the cell was uninitialized + /// and `f()` failed, an error is returned. /// /// # Panics /// - /// If `f` panics, the panic is propagated to the caller, and the cell + /// If `f()` panics, the panic is propagated to the caller, and the cell /// remains uninitialized. /// /// # Examples @@ -256,7 +259,7 @@ impl<T> OnceCell<T> { /// /// let mut cell: OnceCell<u32> = OnceCell::new(); /// - /// // Failed initializers do not change the value + /// // Failed attempts to initialize the cell do not change its contents /// assert!(cell.get_mut_or_try_init(|| "not a number!".parse()).is_err()); /// assert!(cell.get().is_none()); /// @@ -295,7 +298,7 @@ impl<T> OnceCell<T> { /// Consumes the cell, returning the wrapped value. /// - /// Returns `None` if the cell was empty. + /// Returns `None` if the cell was uninitialized. /// /// # Examples /// @@ -321,7 +324,7 @@ impl<T> OnceCell<T> { /// Takes the value out of this `OnceCell`, moving it back to an uninitialized state. /// - /// Has no effect and returns `None` if the `OnceCell` hasn't been initialized. + /// Has no effect and returns `None` if the `OnceCell` is uninitialized. /// /// Safety is guaranteed by requiring a mutable reference. /// diff --git a/library/core/src/ffi/mod.rs b/library/core/src/ffi/mod.rs index 51687a3adcd..50968c57adc 100644 --- a/library/core/src/ffi/mod.rs +++ b/library/core/src/ffi/mod.rs @@ -37,175 +37,14 @@ pub use self::va_list::{VaList, VaListImpl}; )] pub mod va_list; -macro_rules! type_alias { - { - $Docfile:tt, $Alias:ident = $Real:ty; - $( $Cfg:tt )* - } => { - #[doc = include_str!($Docfile)] - $( $Cfg )* - #[stable(feature = "core_ffi_c", since = "1.64.0")] - pub type $Alias = $Real; - } -} - -type_alias! { "c_char.md", c_char = c_char_definition::c_char; #[doc(cfg(all()))] } - -type_alias! { "c_schar.md", c_schar = i8; } -type_alias! { "c_uchar.md", c_uchar = u8; } -type_alias! { "c_short.md", c_short = i16; } -type_alias! { "c_ushort.md", c_ushort = u16; } - -type_alias! { "c_int.md", c_int = c_int_definition::c_int; #[doc(cfg(all()))] } -type_alias! { "c_uint.md", c_uint = c_int_definition::c_uint; #[doc(cfg(all()))] } - -type_alias! { "c_long.md", c_long = c_long_definition::c_long; #[doc(cfg(all()))] } -type_alias! { "c_ulong.md", c_ulong = c_long_definition::c_ulong; #[doc(cfg(all()))] } - -type_alias! { "c_longlong.md", c_longlong = i64; } -type_alias! { "c_ulonglong.md", c_ulonglong = u64; } - -type_alias! { "c_float.md", c_float = f32; } -type_alias! { "c_double.md", c_double = f64; } - -/// Equivalent to C's `size_t` type, from `stddef.h` (or `cstddef` for C++). -/// -/// This type is currently always [`usize`], however in the future there may be -/// platforms where this is not the case. -#[unstable(feature = "c_size_t", issue = "88345")] -pub type c_size_t = usize; - -/// Equivalent to C's `ptrdiff_t` type, from `stddef.h` (or `cstddef` for C++). -/// -/// This type is currently always [`isize`], however in the future there may be -/// platforms where this is not the case. +mod primitives; +#[stable(feature = "core_ffi_c", since = "1.64.0")] +pub use self::primitives::{ + c_char, c_double, c_float, c_int, c_long, c_longlong, c_schar, c_short, c_uchar, c_uint, + c_ulong, c_ulonglong, c_ushort, +}; #[unstable(feature = "c_size_t", issue = "88345")] -pub type c_ptrdiff_t = isize; - -/// Equivalent to C's `ssize_t` (on POSIX) or `SSIZE_T` (on Windows) type. -/// -/// This type is currently always [`isize`], however in the future there may be -/// platforms where this is not the case. -#[unstable(feature = "c_size_t", issue = "88345")] -pub type c_ssize_t = isize; - -mod c_char_definition { - cfg_if! { - // These are the targets on which c_char is unsigned. Usually the - // signedness is the same for all target_os values on a given architecture - // but there are some exceptions (see isSignedCharDefault() in clang). - // - // aarch64: - // Section 10 "Arm C and C++ language mappings" in Procedure Call Standard for the Arm® - // 64-bit Architecture (AArch64) says C/C++ char is unsigned byte. - // https://github.com/ARM-software/abi-aa/blob/2024Q3/aapcs64/aapcs64.rst#arm-c-and-c-language-mappings - // arm: - // Section 8 "Arm C and C++ Language Mappings" in Procedure Call Standard for the Arm® - // Architecture says C/C++ char is unsigned byte. - // https://github.com/ARM-software/abi-aa/blob/2024Q3/aapcs32/aapcs32.rst#arm-c-and-c-language-mappings - // csky: - // Section 2.1.2 "Primary Data Type" in C-SKY V2 CPU Applications Binary Interface - // Standards Manual says ANSI C char is unsigned byte. - // https://github.com/c-sky/csky-doc/blob/9f7121f7d40970ba5cc0f15716da033db2bb9d07/C-SKY_V2_CPU_Applications_Binary_Interface_Standards_Manual.pdf - // Note: this doesn't seem to match Clang's default (https://github.com/rust-lang/rust/issues/129945). - // hexagon: - // Section 3.1 "Basic data type" in Qualcomm Hexagon™ Application - // Binary Interface User Guide says "By default, the `char` data type is unsigned." - // https://docs.qualcomm.com/bundle/publicresource/80-N2040-23_REV_K_Qualcomm_Hexagon_Application_Binary_Interface_User_Guide.pdf - // msp430: - // Section 2.1 "Basic Types" in MSP430 Embedded Application Binary - // Interface says "The char type is unsigned by default". - // https://www.ti.com/lit/an/slaa534a/slaa534a.pdf - // powerpc/powerpc64: - // - PPC32 SysV: "Table 3-1 Scalar Types" in System V Application Binary Interface PowerPC - // Processor Supplement says ANSI C char is unsigned byte - // https://refspecs.linuxfoundation.org/elf/elfspec_ppc.pdf - // - PPC64 ELFv1: Section 3.1.4 "Fundamental Types" in 64-bit PowerPC ELF Application - // Binary Interface Supplement 1.9 says ANSI C is unsigned byte - // https://refspecs.linuxfoundation.org/ELF/ppc64/PPC-elf64abi.html#FUND-TYPE - // - PPC64 ELFv2: Section 2.1.2.2 "Fundamental Types" in 64-Bit ELF V2 ABI Specification - // says char is unsigned byte - // https://openpowerfoundation.org/specifications/64bitelfabi/ - // - AIX: XL C for AIX Language Reference says "By default, char behaves like an unsigned char." - // https://www.ibm.com/docs/en/xl-c-aix/13.1.3?topic=specifiers-character-types - // riscv32/riscv64: - // C/C++ type representations section in RISC-V Calling Conventions - // page in RISC-V ELF psABI Document says "char is unsigned." - // https://github.com/riscv-non-isa/riscv-elf-psabi-doc/blob/draft-20240829-13bfa9f54634cb60d86b9b333e109f077805b4b3/riscv-cc.adoc#cc-type-representations - // s390x: - // - ELF: "Table 1.1.: Scalar types" in ELF Application Binary Interface s390x Supplement - // Version 1.6.1 categorize ISO C char in unsigned integer - // https://github.com/IBM/s390x-abi/releases/tag/v1.6.1 - // - z/OS: XL C/C++ Language Reference says: "By default, char behaves like an unsigned char." - // https://www.ibm.com/docs/en/zos/3.1.0?topic=specifiers-character-types - // xtensa: - // Section 2.17.1 "Data Types and Alignment" of Xtensa LX Microprocessor Overview handbook - // says "`char` type is unsigned by default". - // https://loboris.eu/ESP32/Xtensa_lx%20Overview%20handbook.pdf - // - // On the following operating systems, c_char is signed by default, regardless of architecture. - // Darwin (macOS, iOS, etc.): - // Apple targets' c_char is signed by default even on arm - // https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Handle-data-types-and-data-alignment-properly - // Windows: - // Windows MSVC C++ Language Reference says "Microsoft-specific: Variables of type char - // are promoted to int as if from type signed char by default, unless the /J compilation - // option is used." - // https://learn.microsoft.com/en-us/cpp/cpp/fundamental-types-cpp?view=msvc-170#character-types - // L4Re: - // The kernel builds with -funsigned-char on all targets (but useserspace follows the - // architecture defaults). As we only have a target for userspace apps so there are no - // special cases for L4Re below. - // https://github.com/rust-lang/rust/pull/132975#issuecomment-2484645240 - if #[cfg(all( - not(windows), - not(target_vendor = "apple"), - any( - target_arch = "aarch64", - target_arch = "arm", - target_arch = "csky", - target_arch = "hexagon", - target_arch = "msp430", - target_arch = "powerpc", - target_arch = "powerpc64", - target_arch = "riscv32", - target_arch = "riscv64", - target_arch = "s390x", - target_arch = "xtensa", - ) - ))] { - pub(super) type c_char = u8; - } else { - // On every other target, c_char is signed. - pub(super) type c_char = i8; - } - } -} - -mod c_int_definition { - cfg_if! { - if #[cfg(any(target_arch = "avr", target_arch = "msp430"))] { - pub(super) type c_int = i16; - pub(super) type c_uint = u16; - } else { - pub(super) type c_int = i32; - pub(super) type c_uint = u32; - } - } -} - -mod c_long_definition { - cfg_if! { - if #[cfg(all(target_pointer_width = "64", not(windows)))] { - pub(super) type c_long = i64; - pub(super) type c_ulong = u64; - } else { - // The minimal size of `long` in the C standard is 32 bits - pub(super) type c_long = i32; - pub(super) type c_ulong = u32; - } - } -} +pub use self::primitives::{c_ptrdiff_t, c_size_t, c_ssize_t}; // N.B., for LLVM to recognize the void pointer type and by extension // functions like malloc(), we need to have it represented as i8* in diff --git a/library/core/src/ffi/primitives.rs b/library/core/src/ffi/primitives.rs new file mode 100644 index 00000000000..ece3c7538da --- /dev/null +++ b/library/core/src/ffi/primitives.rs @@ -0,0 +1,174 @@ +//! Defines primitive types that match C's type definitions for FFI compatibility. +//! +//! This module is intentionally standalone to facilitate parsing when retrieving +//! core C types. + +macro_rules! type_alias { + { + $Docfile:tt, $Alias:ident = $Real:ty; + $( $Cfg:tt )* + } => { + #[doc = include_str!($Docfile)] + $( $Cfg )* + #[stable(feature = "core_ffi_c", since = "1.64.0")] + pub type $Alias = $Real; + } +} + +type_alias! { "c_char.md", c_char = c_char_definition::c_char; #[doc(cfg(all()))] } + +type_alias! { "c_schar.md", c_schar = i8; } +type_alias! { "c_uchar.md", c_uchar = u8; } +type_alias! { "c_short.md", c_short = i16; } +type_alias! { "c_ushort.md", c_ushort = u16; } + +type_alias! { "c_int.md", c_int = c_int_definition::c_int; #[doc(cfg(all()))] } +type_alias! { "c_uint.md", c_uint = c_int_definition::c_uint; #[doc(cfg(all()))] } + +type_alias! { "c_long.md", c_long = c_long_definition::c_long; #[doc(cfg(all()))] } +type_alias! { "c_ulong.md", c_ulong = c_long_definition::c_ulong; #[doc(cfg(all()))] } + +type_alias! { "c_longlong.md", c_longlong = i64; } +type_alias! { "c_ulonglong.md", c_ulonglong = u64; } + +type_alias! { "c_float.md", c_float = f32; } +type_alias! { "c_double.md", c_double = f64; } + +mod c_char_definition { + cfg_if! { + // These are the targets on which c_char is unsigned. Usually the + // signedness is the same for all target_os values on a given architecture + // but there are some exceptions (see isSignedCharDefault() in clang). + // + // aarch64: + // Section 10 "Arm C and C++ language mappings" in Procedure Call Standard for the Arm® + // 64-bit Architecture (AArch64) says C/C++ char is unsigned byte. + // https://github.com/ARM-software/abi-aa/blob/2024Q3/aapcs64/aapcs64.rst#arm-c-and-c-language-mappings + // arm: + // Section 8 "Arm C and C++ Language Mappings" in Procedure Call Standard for the Arm® + // Architecture says C/C++ char is unsigned byte. + // https://github.com/ARM-software/abi-aa/blob/2024Q3/aapcs32/aapcs32.rst#arm-c-and-c-language-mappings + // csky: + // Section 2.1.2 "Primary Data Type" in C-SKY V2 CPU Applications Binary Interface + // Standards Manual says ANSI C char is unsigned byte. + // https://github.com/c-sky/csky-doc/blob/9f7121f7d40970ba5cc0f15716da033db2bb9d07/C-SKY_V2_CPU_Applications_Binary_Interface_Standards_Manual.pdf + // Note: this doesn't seem to match Clang's default (https://github.com/rust-lang/rust/issues/129945). + // hexagon: + // Section 3.1 "Basic data type" in Qualcomm Hexagon™ Application + // Binary Interface User Guide says "By default, the `char` data type is unsigned." + // https://docs.qualcomm.com/bundle/publicresource/80-N2040-23_REV_K_Qualcomm_Hexagon_Application_Binary_Interface_User_Guide.pdf + // msp430: + // Section 2.1 "Basic Types" in MSP430 Embedded Application Binary + // Interface says "The char type is unsigned by default". + // https://www.ti.com/lit/an/slaa534a/slaa534a.pdf + // powerpc/powerpc64: + // - PPC32 SysV: "Table 3-1 Scalar Types" in System V Application Binary Interface PowerPC + // Processor Supplement says ANSI C char is unsigned byte + // https://refspecs.linuxfoundation.org/elf/elfspec_ppc.pdf + // - PPC64 ELFv1: Section 3.1.4 "Fundamental Types" in 64-bit PowerPC ELF Application + // Binary Interface Supplement 1.9 says ANSI C is unsigned byte + // https://refspecs.linuxfoundation.org/ELF/ppc64/PPC-elf64abi.html#FUND-TYPE + // - PPC64 ELFv2: Section 2.1.2.2 "Fundamental Types" in 64-Bit ELF V2 ABI Specification + // says char is unsigned byte + // https://openpowerfoundation.org/specifications/64bitelfabi/ + // - AIX: XL C for AIX Language Reference says "By default, char behaves like an unsigned char." + // https://www.ibm.com/docs/en/xl-c-aix/13.1.3?topic=specifiers-character-types + // riscv32/riscv64: + // C/C++ type representations section in RISC-V Calling Conventions + // page in RISC-V ELF psABI Document says "char is unsigned." + // https://github.com/riscv-non-isa/riscv-elf-psabi-doc/blob/draft-20240829-13bfa9f54634cb60d86b9b333e109f077805b4b3/riscv-cc.adoc#cc-type-representations + // s390x: + // - ELF: "Table 1.1.: Scalar types" in ELF Application Binary Interface s390x Supplement + // Version 1.6.1 categorize ISO C char in unsigned integer + // https://github.com/IBM/s390x-abi/releases/tag/v1.6.1 + // - z/OS: XL C/C++ Language Reference says: "By default, char behaves like an unsigned char." + // https://www.ibm.com/docs/en/zos/3.1.0?topic=specifiers-character-types + // xtensa: + // Section 2.17.1 "Data Types and Alignment" of Xtensa LX Microprocessor Overview handbook + // says "`char` type is unsigned by default". + // https://loboris.eu/ESP32/Xtensa_lx%20Overview%20handbook.pdf + // + // On the following operating systems, c_char is signed by default, regardless of architecture. + // Darwin (macOS, iOS, etc.): + // Apple targets' c_char is signed by default even on arm + // https://developer.apple.com/documentation/xcode/writing-arm64-code-for-apple-platforms#Handle-data-types-and-data-alignment-properly + // Windows: + // Windows MSVC C++ Language Reference says "Microsoft-specific: Variables of type char + // are promoted to int as if from type signed char by default, unless the /J compilation + // option is used." + // https://learn.microsoft.com/en-us/cpp/cpp/fundamental-types-cpp?view=msvc-170#character-types + // L4Re: + // The kernel builds with -funsigned-char on all targets (but useserspace follows the + // architecture defaults). As we only have a target for userspace apps so there are no + // special cases for L4Re below. + // https://github.com/rust-lang/rust/pull/132975#issuecomment-2484645240 + if #[cfg(all( + not(windows), + not(target_vendor = "apple"), + any( + target_arch = "aarch64", + target_arch = "arm", + target_arch = "csky", + target_arch = "hexagon", + target_arch = "msp430", + target_arch = "powerpc", + target_arch = "powerpc64", + target_arch = "riscv32", + target_arch = "riscv64", + target_arch = "s390x", + target_arch = "xtensa", + ) + ))] { + pub(super) type c_char = u8; + } else { + // On every other target, c_char is signed. + pub(super) type c_char = i8; + } + } +} + +mod c_long_definition { + cfg_if! { + if #[cfg(all(target_pointer_width = "64", not(windows)))] { + pub(super) type c_long = i64; + pub(super) type c_ulong = u64; + } else { + // The minimal size of `long` in the C standard is 32 bits + pub(super) type c_long = i32; + pub(super) type c_ulong = u32; + } + } +} + +/// Equivalent to C's `size_t` type, from `stddef.h` (or `cstddef` for C++). +/// +/// This type is currently always [`usize`], however in the future there may be +/// platforms where this is not the case. +#[unstable(feature = "c_size_t", issue = "88345")] +pub type c_size_t = usize; + +/// Equivalent to C's `ptrdiff_t` type, from `stddef.h` (or `cstddef` for C++). +/// +/// This type is currently always [`isize`], however in the future there may be +/// platforms where this is not the case. +#[unstable(feature = "c_size_t", issue = "88345")] +pub type c_ptrdiff_t = isize; + +/// Equivalent to C's `ssize_t` (on POSIX) or `SSIZE_T` (on Windows) type. +/// +/// This type is currently always [`isize`], however in the future there may be +/// platforms where this is not the case. +#[unstable(feature = "c_size_t", issue = "88345")] +pub type c_ssize_t = isize; + +mod c_int_definition { + cfg_if! { + if #[cfg(any(target_arch = "avr", target_arch = "msp430"))] { + pub(super) type c_int = i16; + pub(super) type c_uint = u16; + } else { + pub(super) type c_int = i32; + pub(super) type c_uint = u32; + } + } +} diff --git a/library/core/src/fmt/num.rs b/library/core/src/fmt/num.rs index 683e45b35f7..7166f106b8d 100644 --- a/library/core/src/fmt/num.rs +++ b/library/core/src/fmt/num.rs @@ -192,7 +192,8 @@ macro_rules! impl_Debug { } // 2 digit decimal look up table -static DEC_DIGITS_LUT: &[u8; 200] = b"0001020304050607080910111213141516171819\ +static DEC_DIGITS_LUT: &[u8; 200] = b"\ + 0001020304050607080910111213141516171819\ 2021222324252627282930313233343536373839\ 4041424344454647484950515253545556575859\ 6061626364656667686970717273747576777879\ @@ -232,83 +233,89 @@ macro_rules! impl_Display { #[cfg(not(feature = "optimize_for_size"))] impl $unsigned { - fn _fmt(mut self, is_nonnegative: bool, f: &mut fmt::Formatter<'_>) -> fmt::Result { - const SIZE: usize = $unsigned::MAX.ilog(10) as usize + 1; - let mut buf = [MaybeUninit::<u8>::uninit(); SIZE]; - let mut curr = SIZE; - let buf_ptr = MaybeUninit::slice_as_mut_ptr(&mut buf); - let lut_ptr = DEC_DIGITS_LUT.as_ptr(); - - // SAFETY: Since `d1` and `d2` are always less than or equal to `198`, we - // can copy from `lut_ptr[d1..d1 + 1]` and `lut_ptr[d2..d2 + 1]`. To show - // that it's OK to copy into `buf_ptr`, notice that at the beginning - // `curr == buf.len() == 39 > log(n)` since `n < 2^128 < 10^39`, and at - // each step this is kept the same as `n` is divided. Since `n` is always - // non-negative, this means that `curr > 0` so `buf_ptr[curr..curr + 1]` - // is safe to access. - unsafe { - // need at least 16 bits for the 4-characters-at-a-time to work. - #[allow(overflowing_literals)] - #[allow(unused_comparisons)] - // This block will be removed for smaller types at compile time and in the worst - // case, it will prevent to have the `10000` literal to overflow for `i8` and `u8`. - if core::mem::size_of::<$unsigned>() >= 2 { - // eagerly decode 4 characters at a time - while self >= 10000 { - let rem = (self % 10000) as usize; - self /= 10000; - - let d1 = (rem / 100) << 1; - let d2 = (rem % 100) << 1; - curr -= 4; - - // We are allowed to copy to `buf_ptr[curr..curr + 3]` here since - // otherwise `curr < 0`. But then `n` was originally at least `10000^10` - // which is `10^40 > 2^128 > n`. - ptr::copy_nonoverlapping(lut_ptr.add(d1 as usize), buf_ptr.add(curr), 2); - ptr::copy_nonoverlapping(lut_ptr.add(d2 as usize), buf_ptr.add(curr + 2), 2); - } - } - - // if we reach here numbers are <= 9999, so at most 4 chars long - let mut n = self as usize; // possibly reduce 64bit math + fn _fmt(self, is_nonnegative: bool, f: &mut fmt::Formatter<'_>) -> fmt::Result { + const MAX_DEC_N: usize = $unsigned::MAX.ilog(10) as usize + 1; + // Buffer decimals for $unsigned with right alignment. + let mut buf = [MaybeUninit::<u8>::uninit(); MAX_DEC_N]; + // Count the number of bytes in buf that are not initialized. + let mut offset = buf.len(); + // Consume the least-significant decimals from a working copy. + let mut remain = self; + + // Format per four digits from the lookup table. + // Four digits need a 16-bit $unsigned or wider. + while size_of::<Self>() > 1 && remain > 999.try_into().expect("branch is not hit for types that cannot fit 999 (u8)") { + // SAFETY: All of the decimals fit in buf due to MAX_DEC_N + // and the while condition ensures at least 4 more decimals. + unsafe { core::hint::assert_unchecked(offset >= 4) } + // SAFETY: The offset counts down from its initial buf.len() + // without underflow due to the previous precondition. + unsafe { core::hint::assert_unchecked(offset <= buf.len()) } + offset -= 4; + + // pull two pairs + let scale: Self = 1_00_00.try_into().expect("branch is not hit for types that cannot fit 1E4 (u8)"); + let quad = remain % scale; + remain /= scale; + let pair1 = (quad / 100) as usize; + let pair2 = (quad % 100) as usize; + buf[offset + 0].write(DEC_DIGITS_LUT[pair1 * 2 + 0]); + buf[offset + 1].write(DEC_DIGITS_LUT[pair1 * 2 + 1]); + buf[offset + 2].write(DEC_DIGITS_LUT[pair2 * 2 + 0]); + buf[offset + 3].write(DEC_DIGITS_LUT[pair2 * 2 + 1]); + } - // decode 2 more chars, if > 2 chars - if n >= 100 { - let d1 = (n % 100) << 1; - n /= 100; - curr -= 2; - ptr::copy_nonoverlapping(lut_ptr.add(d1), buf_ptr.add(curr), 2); - } + // Format per two digits from the lookup table. + if remain > 9 { + // SAFETY: All of the decimals fit in buf due to MAX_DEC_N + // and the while condition ensures at least 2 more decimals. + unsafe { core::hint::assert_unchecked(offset >= 2) } + // SAFETY: The offset counts down from its initial buf.len() + // without underflow due to the previous precondition. + unsafe { core::hint::assert_unchecked(offset <= buf.len()) } + offset -= 2; + + let pair = (remain % 100) as usize; + remain /= 100; + buf[offset + 0].write(DEC_DIGITS_LUT[pair * 2 + 0]); + buf[offset + 1].write(DEC_DIGITS_LUT[pair * 2 + 1]); + } - // if we reach here numbers are <= 100, so at most 2 chars long - // The biggest it can be is 99, and 99 << 1 == 198, so a `u8` is enough. - // decode last 1 or 2 chars - if n < 10 { - curr -= 1; - *buf_ptr.add(curr) = (n as u8) + b'0'; - } else { - let d1 = n << 1; - curr -= 2; - ptr::copy_nonoverlapping(lut_ptr.add(d1), buf_ptr.add(curr), 2); - } + // Format the last remaining digit, if any. + if remain != 0 || self == 0 { + // SAFETY: All of the decimals fit in buf due to MAX_DEC_N + // and the if condition ensures (at least) 1 more decimals. + unsafe { core::hint::assert_unchecked(offset >= 1) } + // SAFETY: The offset counts down from its initial buf.len() + // without underflow due to the previous precondition. + unsafe { core::hint::assert_unchecked(offset <= buf.len()) } + offset -= 1; + + // Either the compiler sees that remain < 10, or it prevents + // a boundary check up next. + let last = (remain & 15) as usize; + buf[offset].write(DEC_DIGITS_LUT[last * 2 + 1]); + // not used: remain = 0; } - // SAFETY: `curr` > 0 (since we made `buf` large enough), and all the chars are valid - // UTF-8 since `DEC_DIGITS_LUT` is - let buf_slice = unsafe { - str::from_utf8_unchecked( - slice::from_raw_parts(buf_ptr.add(curr), buf.len() - curr)) + // SAFETY: All buf content since offset is set. + let written = unsafe { buf.get_unchecked(offset..) }; + // SAFETY: Writes use ASCII from the lookup table exclusively. + let as_str = unsafe { + str::from_utf8_unchecked(slice::from_raw_parts( + MaybeUninit::slice_as_ptr(written), + written.len(), + )) }; - f.pad_integral(is_nonnegative, "", buf_slice) + f.pad_integral(is_nonnegative, "", as_str) } })* #[cfg(feature = "optimize_for_size")] fn $gen_name(mut n: $u, is_nonnegative: bool, f: &mut fmt::Formatter<'_>) -> fmt::Result { - const SIZE: usize = $u::MAX.ilog(10) as usize + 1; - let mut buf = [MaybeUninit::<u8>::uninit(); SIZE]; - let mut curr = buf.len(); + const MAX_DEC_N: usize = $u::MAX.ilog(10) as usize + 1; + let mut buf = [MaybeUninit::<u8>::uninit(); MAX_DEC_N]; + let mut curr = MAX_DEC_N; let buf_ptr = MaybeUninit::slice_as_mut_ptr(&mut buf); // SAFETY: To show that it's OK to copy into `buf_ptr`, notice that at the beginning diff --git a/library/core/src/marker.rs b/library/core/src/marker.rs index 18ada14d101..1a8ef20dd7b 100644 --- a/library/core/src/marker.rs +++ b/library/core/src/marker.rs @@ -1077,6 +1077,9 @@ marker_impls! { } /// A common trait implemented by all function pointers. +// +// Note that while the trait is internal and unstable it is nevertheless +// exposed as a public bound of the stable `core::ptr::fn_addr_eq` function. #[unstable( feature = "fn_ptr_trait", issue = "none", diff --git a/library/core/src/num/nonzero.rs b/library/core/src/num/nonzero.rs index 61e83ebfad7..a115acf42b1 100644 --- a/library/core/src/num/nonzero.rs +++ b/library/core/src/num/nonzero.rs @@ -474,6 +474,7 @@ macro_rules! nonzero_integer { #[$stability:meta] Self = $Ty:ident, Primitive = $signedness:ident $Int:ident, + SignedPrimitive = $Sint:ty, UnsignedPrimitive = $Uint:ty, // Used in doc comments. @@ -905,6 +906,7 @@ macro_rules! nonzero_integer { nonzero_integer_signedness_dependent_methods! { Primitive = $signedness $Int, + SignedPrimitive = $Sint, UnsignedPrimitive = $Uint, } @@ -1128,6 +1130,7 @@ macro_rules! nonzero_integer { ( Self = $Ty:ident, Primitive = unsigned $Int:ident, + SignedPrimitive = $Sint:ident, rot = $rot:literal, rot_op = $rot_op:literal, rot_result = $rot_result:literal, @@ -1140,6 +1143,7 @@ macro_rules! nonzero_integer { #[stable(feature = "nonzero", since = "1.28.0")] Self = $Ty, Primitive = unsigned $Int, + SignedPrimitive = $Sint, UnsignedPrimitive = $Int, rot = $rot, rot_op = $rot_op, @@ -1154,7 +1158,7 @@ macro_rules! nonzero_integer { ( Self = $Ty:ident, Primitive = signed $Int:ident, - UnsignedPrimitive = $UInt:ident, + UnsignedPrimitive = $Uint:ident, rot = $rot:literal, rot_op = $rot_op:literal, rot_result = $rot_result:literal, @@ -1166,7 +1170,8 @@ macro_rules! nonzero_integer { #[stable(feature = "signed_nonzero", since = "1.34.0")] Self = $Ty, Primitive = signed $Int, - UnsignedPrimitive = $UInt, + SignedPrimitive = $Int, + UnsignedPrimitive = $Uint, rot = $rot, rot_op = $rot_op, rot_result = $rot_result, @@ -1286,6 +1291,7 @@ macro_rules! nonzero_integer_signedness_dependent_methods { // Associated items for unsigned nonzero types only. ( Primitive = unsigned $Int:ident, + SignedPrimitive = $Sint:ty, UnsignedPrimitive = $Uint:ty, ) => { /// The smallest value that can be represented by this non-zero @@ -1620,11 +1626,35 @@ macro_rules! nonzero_integer_signedness_dependent_methods { // results will be sqrt(1), which is 1, so a result can't be zero. unsafe { Self::new_unchecked(result) } } + + /// Returns the bit pattern of `self` reinterpreted as a signed integer of the same size. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(integer_sign_cast)] + /// # use std::num::NonZero; + /// + #[doc = concat!("let n = NonZero::<", stringify!($Int), ">::MAX;")] + /// + #[doc = concat!("assert_eq!(n.cast_signed(), NonZero::new(-1", stringify!($Sint), ").unwrap());")] + /// ``` + #[unstable(feature = "integer_sign_cast", issue = "125882")] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline(always)] + pub const fn cast_signed(self) -> NonZero<$Sint> { + // SAFETY: `self.get()` can't be zero + unsafe { NonZero::new_unchecked(self.get().cast_signed()) } + } }; // Associated items for signed nonzero types only. ( Primitive = signed $Int:ident, + SignedPrimitive = $Sint:ty, UnsignedPrimitive = $Uint:ty, ) => { /// The smallest value that can be represented by this non-zero @@ -2035,12 +2065,37 @@ macro_rules! nonzero_integer_signedness_dependent_methods { // SAFETY: negation of nonzero cannot yield zero values. unsafe { Self::new_unchecked(result) } } + + /// Returns the bit pattern of `self` reinterpreted as an unsigned integer of the same size. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(integer_sign_cast)] + /// # use std::num::NonZero; + /// + #[doc = concat!("let n = NonZero::new(-1", stringify!($Int), ").unwrap();")] + /// + #[doc = concat!("assert_eq!(n.cast_unsigned(), NonZero::<", stringify!($Uint), ">::MAX);")] + /// ``` + #[unstable(feature = "integer_sign_cast", issue = "125882")] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline(always)] + pub const fn cast_unsigned(self) -> NonZero<$Uint> { + // SAFETY: `self.get()` can't be zero + unsafe { NonZero::new_unchecked(self.get().cast_unsigned()) } + } + }; } nonzero_integer! { Self = NonZeroU8, Primitive = unsigned u8, + SignedPrimitive = i8, rot = 2, rot_op = "0x82", rot_result = "0xa", @@ -2052,6 +2107,7 @@ nonzero_integer! { nonzero_integer! { Self = NonZeroU16, Primitive = unsigned u16, + SignedPrimitive = i16, rot = 4, rot_op = "0xa003", rot_result = "0x3a", @@ -2063,6 +2119,7 @@ nonzero_integer! { nonzero_integer! { Self = NonZeroU32, Primitive = unsigned u32, + SignedPrimitive = i32, rot = 8, rot_op = "0x10000b3", rot_result = "0xb301", @@ -2074,6 +2131,7 @@ nonzero_integer! { nonzero_integer! { Self = NonZeroU64, Primitive = unsigned u64, + SignedPrimitive = i64, rot = 12, rot_op = "0xaa00000000006e1", rot_result = "0x6e10aa", @@ -2085,6 +2143,7 @@ nonzero_integer! { nonzero_integer! { Self = NonZeroU128, Primitive = unsigned u128, + SignedPrimitive = i128, rot = 16, rot_op = "0x13f40000000000000000000000004f76", rot_result = "0x4f7613f4", @@ -2097,6 +2156,7 @@ nonzero_integer! { nonzero_integer! { Self = NonZeroUsize, Primitive = unsigned usize, + SignedPrimitive = isize, rot = 4, rot_op = "0xa003", rot_result = "0x3a", @@ -2109,6 +2169,7 @@ nonzero_integer! { nonzero_integer! { Self = NonZeroUsize, Primitive = unsigned usize, + SignedPrimitive = isize, rot = 8, rot_op = "0x10000b3", rot_result = "0xb301", @@ -2121,6 +2182,7 @@ nonzero_integer! { nonzero_integer! { Self = NonZeroUsize, Primitive = unsigned usize, + SignedPrimitive = isize, rot = 12, rot_op = "0xaa00000000006e1", rot_result = "0x6e10aa", diff --git a/library/core/src/primitive_docs.rs b/library/core/src/primitive_docs.rs index c5f029363e5..bbf5939fe1b 100644 --- a/library/core/src/primitive_docs.rs +++ b/library/core/src/primitive_docs.rs @@ -1160,9 +1160,9 @@ impl<T> (T,) {} /// /// Note that most common platforms will not support `f16` in hardware without enabling extra target /// features, with the notable exception of Apple Silicon (also known as M1, M2, etc.) processors. -/// Hardware support on x86-64 requires the avx512fp16 feature, while RISC-V requires Zhf. -/// Usually the fallback implementation will be to use `f32` hardware if it exists, and convert -/// between `f16` and `f32` when performing math. +/// Hardware support on x86/x86-64 requires the avx512fp16 or avx10.1 features, while RISC-V requires +/// Zfh, and Arm/AArch64 requires FEAT_FP16. Usually the fallback implementation will be to use `f32` +/// hardware if it exists, and convert between `f16` and `f32` when performing math. /// /// *[See also the `std::f16::consts` module](crate::f16::consts).* /// @@ -1344,10 +1344,10 @@ mod prim_f64 {} /// quad-precision values][wikipedia] for more information. /// /// Note that no platforms have hardware support for `f128` without enabling target specific features, -/// as for all instruction set architectures `f128` is considered an optional feature. -/// Only Power ISA ("PowerPC") and RISC-V specify it, and only certain microarchitectures -/// actually implement it. For x86-64 and AArch64, ISA support is not even specified, -/// so it will always be a software implementation significantly slower than `f64`. +/// as for all instruction set architectures `f128` is considered an optional feature. Only Power ISA +/// ("PowerPC") and RISC-V (via the Q extension) specify it, and only certain microarchitectures +/// actually implement it. For x86-64 and AArch64, ISA support is not even specified, so it will always +/// be a software implementation significantly slower than `f64`. /// /// _Note: `f128` support is incomplete. Many platforms will not be able to link math functions. On /// x86 in particular, these functions do link but their results are always incorrect._ diff --git a/library/core/src/range.rs b/library/core/src/range.rs index 427526fd14b..6a62928873f 100644 --- a/library/core/src/range.rs +++ b/library/core/src/range.rs @@ -48,6 +48,7 @@ pub use crate::ops::{Bound, OneSidedRange, RangeBounds, RangeFull, RangeTo, Rang /// assert_eq!(Range::from(3..5), Range { start: 3, end: 5 }); /// assert_eq!(3 + 4 + 5, Range::from(3..6).into_iter().sum()); /// ``` +#[cfg_attr(not(bootstrap), lang = "RangeCopy")] #[derive(Clone, Copy, Default, PartialEq, Eq, Hash)] #[unstable(feature = "new_range_api", issue = "125687")] pub struct Range<Idx> { @@ -205,6 +206,7 @@ impl<T> From<legacy::Range<T>> for Range<T> { /// assert_eq!(RangeInclusive::from(3..=5), RangeInclusive { start: 3, end: 5 }); /// assert_eq!(3 + 4 + 5, RangeInclusive::from(3..=5).into_iter().sum()); /// ``` +#[cfg_attr(not(bootstrap), lang = "RangeInclusiveCopy")] #[derive(Clone, Copy, PartialEq, Eq, Hash)] #[unstable(feature = "new_range_api", issue = "125687")] pub struct RangeInclusive<Idx> { @@ -388,6 +390,7 @@ impl<T> From<legacy::RangeInclusive<T>> for RangeInclusive<T> { /// assert_eq!(RangeFrom::from(2..), core::range::RangeFrom { start: 2 }); /// assert_eq!(2 + 3 + 4, RangeFrom::from(2..).into_iter().take(3).sum()); /// ``` +#[cfg_attr(not(bootstrap), lang = "RangeFromCopy")] #[derive(Clone, Copy, PartialEq, Eq, Hash)] #[unstable(feature = "new_range_api", issue = "125687")] pub struct RangeFrom<Idx> { diff --git a/library/coretests/benches/fmt.rs b/library/coretests/benches/fmt.rs index ed478b0f1e0..ee8e981b46b 100644 --- a/library/coretests/benches/fmt.rs +++ b/library/coretests/benches/fmt.rs @@ -124,42 +124,41 @@ fn write_str_macro_debug_ascii(bh: &mut Bencher) { #[bench] fn write_u128_max(bh: &mut Bencher) { bh.iter(|| { - test::black_box(format!("{}", u128::MAX)); + black_box(format!("{}", black_box(u128::MAX))); }); } #[bench] fn write_u128_min(bh: &mut Bencher) { bh.iter(|| { - let s = format!("{}", 0u128); - test::black_box(s); + black_box(format!("{}", black_box(u128::MIN))); }); } #[bench] fn write_u64_max(bh: &mut Bencher) { bh.iter(|| { - test::black_box(format!("{}", u64::MAX)); + black_box(format!("{}", black_box(u64::MAX))); }); } #[bench] fn write_u64_min(bh: &mut Bencher) { bh.iter(|| { - test::black_box(format!("{}", 0u64)); + black_box(format!("{}", black_box(u64::MIN))); }); } #[bench] fn write_u8_max(bh: &mut Bencher) { bh.iter(|| { - test::black_box(format!("{}", u8::MAX)); + black_box(format!("{}", black_box(u8::MAX))); }); } #[bench] fn write_u8_min(bh: &mut Bencher) { bh.iter(|| { - test::black_box(format!("{}", 0u8)); + black_box(format!("{}", black_box(u8::MIN))); }); } diff --git a/library/std/Cargo.toml b/library/std/Cargo.toml index 9eab75b0696..944c3438557 100644 --- a/library/std/Cargo.toml +++ b/library/std/Cargo.toml @@ -7,6 +7,7 @@ license = "MIT OR Apache-2.0" repository = "https://github.com/rust-lang/rust.git" description = "The Rust Standard Library" edition = "2021" +autobenches = false [lib] crate-type = ["dylib", "rlib"] @@ -130,6 +131,18 @@ name = "pipe-subprocess" path = "tests/pipe_subprocess.rs" harness = false +[[test]] +name = "sync" +path = "tests/sync/lib.rs" + +[[test]] +name = "floats" +path = "tests/floats/lib.rs" + +[[test]] +name = "thread_local" +path = "tests/thread_local/lib.rs" + [[bench]] name = "stdbenches" path = "benches/lib.rs" diff --git a/library/std/benches/lib.rs b/library/std/benches/lib.rs index 1b21c230a0b..e749d9c0f79 100644 --- a/library/std/benches/lib.rs +++ b/library/std/benches/lib.rs @@ -5,3 +5,5 @@ extern crate test; mod hash; +mod path; +mod time; diff --git a/library/std/benches/path.rs b/library/std/benches/path.rs new file mode 100644 index 00000000000..094c00894a8 --- /dev/null +++ b/library/std/benches/path.rs @@ -0,0 +1,114 @@ +use core::hint::black_box; +use std::collections::{BTreeSet, HashSet}; +use std::hash::{DefaultHasher, Hash, Hasher}; +use std::path::*; + +#[bench] +#[cfg_attr(miri, ignore)] // Miri isn't fast... +fn bench_path_cmp_fast_path_buf_sort(b: &mut test::Bencher) { + let prefix = "my/home"; + let mut paths: Vec<_> = + (0..1000).map(|num| PathBuf::from(prefix).join(format!("file {num}.rs"))).collect(); + + paths.sort(); + + b.iter(|| { + black_box(paths.as_mut_slice()).sort_unstable(); + }); +} + +#[bench] +#[cfg_attr(miri, ignore)] // Miri isn't fast... +fn bench_path_cmp_fast_path_long(b: &mut test::Bencher) { + let prefix = "/my/home/is/my/castle/and/my/castle/has/a/rusty/workbench/"; + let paths: Vec<_> = + (0..1000).map(|num| PathBuf::from(prefix).join(format!("file {num}.rs"))).collect(); + + let mut set = BTreeSet::new(); + + paths.iter().for_each(|p| { + set.insert(p.as_path()); + }); + + b.iter(|| { + set.remove(paths[500].as_path()); + set.insert(paths[500].as_path()); + }); +} + +#[bench] +#[cfg_attr(miri, ignore)] // Miri isn't fast... +fn bench_path_cmp_fast_path_short(b: &mut test::Bencher) { + let prefix = "my/home"; + let paths: Vec<_> = + (0..1000).map(|num| PathBuf::from(prefix).join(format!("file {num}.rs"))).collect(); + + let mut set = BTreeSet::new(); + + paths.iter().for_each(|p| { + set.insert(p.as_path()); + }); + + b.iter(|| { + set.remove(paths[500].as_path()); + set.insert(paths[500].as_path()); + }); +} + +#[bench] +#[cfg_attr(miri, ignore)] // Miri isn't fast... +fn bench_path_hashset(b: &mut test::Bencher) { + let prefix = "/my/home/is/my/castle/and/my/castle/has/a/rusty/workbench/"; + let paths: Vec<_> = + (0..1000).map(|num| PathBuf::from(prefix).join(format!("file {num}.rs"))).collect(); + + let mut set = HashSet::new(); + + paths.iter().for_each(|p| { + set.insert(p.as_path()); + }); + + b.iter(|| { + set.remove(paths[500].as_path()); + set.insert(black_box(paths[500].as_path())) + }); +} + +#[bench] +#[cfg_attr(miri, ignore)] // Miri isn't fast... +fn bench_path_hashset_miss(b: &mut test::Bencher) { + let prefix = "/my/home/is/my/castle/and/my/castle/has/a/rusty/workbench/"; + let paths: Vec<_> = + (0..1000).map(|num| PathBuf::from(prefix).join(format!("file {num}.rs"))).collect(); + + let mut set = HashSet::new(); + + paths.iter().for_each(|p| { + set.insert(p.as_path()); + }); + + let probe = PathBuf::from(prefix).join("other"); + + b.iter(|| set.remove(black_box(probe.as_path()))); +} + +#[bench] +fn bench_hash_path_short(b: &mut test::Bencher) { + let mut hasher = DefaultHasher::new(); + let path = Path::new("explorer.exe"); + + b.iter(|| black_box(path).hash(&mut hasher)); + + black_box(hasher.finish()); +} + +#[bench] +fn bench_hash_path_long(b: &mut test::Bencher) { + let mut hasher = DefaultHasher::new(); + let path = + Path::new("/aaaaa/aaaaaa/./../aaaaaaaa/bbbbbbbbbbbbb/ccccccccccc/ddddddddd/eeeeeee.fff"); + + b.iter(|| black_box(path).hash(&mut hasher)); + + black_box(hasher.finish()); +} diff --git a/library/std/benches/time.rs b/library/std/benches/time.rs new file mode 100644 index 00000000000..552481cad92 --- /dev/null +++ b/library/std/benches/time.rs @@ -0,0 +1,47 @@ +use std::time::Instant; + +#[cfg(not(target_arch = "wasm32"))] +use test::{Bencher, black_box}; + +macro_rules! bench_instant_threaded { + ($bench_name:ident, $thread_count:expr) => { + #[bench] + #[cfg(not(target_arch = "wasm32"))] + fn $bench_name(b: &mut Bencher) -> std::thread::Result<()> { + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, Ordering}; + + let running = Arc::new(AtomicBool::new(true)); + + let threads: Vec<_> = (0..$thread_count) + .map(|_| { + let flag = Arc::clone(&running); + std::thread::spawn(move || { + while flag.load(Ordering::Relaxed) { + black_box(Instant::now()); + } + }) + }) + .collect(); + + b.iter(|| { + let a = Instant::now(); + let b = Instant::now(); + assert!(b >= a); + }); + + running.store(false, Ordering::Relaxed); + + for t in threads { + t.join()?; + } + Ok(()) + } + }; +} + +bench_instant_threaded!(instant_contention_01_threads, 0); +bench_instant_threaded!(instant_contention_02_threads, 1); +bench_instant_threaded!(instant_contention_04_threads, 3); +bench_instant_threaded!(instant_contention_08_threads, 7); +bench_instant_threaded!(instant_contention_16_threads, 15); diff --git a/library/std/src/env.rs b/library/std/src/env.rs index bbd506127fb..c665dfd3624 100644 --- a/library/std/src/env.rs +++ b/library/std/src/env.rs @@ -10,9 +10,6 @@ #![stable(feature = "env", since = "1.0.0")] -#[cfg(test)] -mod tests; - use crate::error::Error; use crate::ffi::{OsStr, OsString}; use crate::path::{Path, PathBuf}; diff --git a/library/std/src/env/tests.rs b/library/std/src/env/tests.rs deleted file mode 100644 index d0217261068..00000000000 --- a/library/std/src/env/tests.rs +++ /dev/null @@ -1,120 +0,0 @@ -use super::*; - -#[test] -#[cfg_attr(any(target_os = "emscripten", target_os = "wasi", target_env = "sgx"), ignore)] -fn test_self_exe_path() { - let path = current_exe(); - assert!(path.is_ok()); - let path = path.unwrap(); - - // Hard to test this function - assert!(path.is_absolute()); -} - -#[test] -fn test() { - assert!((!Path::new("test-path").is_absolute())); - - #[cfg(not(target_env = "sgx"))] - current_dir().unwrap(); -} - -#[test] -#[cfg(windows)] -fn split_paths_windows() { - use crate::path::PathBuf; - - fn check_parse(unparsed: &str, parsed: &[&str]) -> bool { - split_paths(unparsed).collect::<Vec<_>>() - == parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>() - } - - assert!(check_parse("", &mut [""])); - assert!(check_parse(r#""""#, &mut [""])); - assert!(check_parse(";;", &mut ["", "", ""])); - assert!(check_parse(r"c:\", &mut [r"c:\"])); - assert!(check_parse(r"c:\;", &mut [r"c:\", ""])); - assert!(check_parse(r"c:\;c:\Program Files\", &mut [r"c:\", r"c:\Program Files\"])); - assert!(check_parse(r#"c:\;c:\"foo"\"#, &mut [r"c:\", r"c:\foo\"])); - assert!(check_parse(r#"c:\;c:\"foo;bar"\;c:\baz"#, &mut [r"c:\", r"c:\foo;bar\", r"c:\baz"])); -} - -#[test] -#[cfg(unix)] -fn split_paths_unix() { - use crate::path::PathBuf; - - fn check_parse(unparsed: &str, parsed: &[&str]) -> bool { - split_paths(unparsed).collect::<Vec<_>>() - == parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>() - } - - assert!(check_parse("", &mut [""])); - assert!(check_parse("::", &mut ["", "", ""])); - assert!(check_parse("/", &mut ["/"])); - assert!(check_parse("/:", &mut ["/", ""])); - assert!(check_parse("/:/usr/local", &mut ["/", "/usr/local"])); -} - -#[test] -#[cfg(unix)] -fn join_paths_unix() { - use crate::ffi::OsStr; - - fn test_eq(input: &[&str], output: &str) -> bool { - &*join_paths(input.iter().cloned()).unwrap() == OsStr::new(output) - } - - assert!(test_eq(&[], "")); - assert!(test_eq(&["/bin", "/usr/bin", "/usr/local/bin"], "/bin:/usr/bin:/usr/local/bin")); - assert!(test_eq(&["", "/bin", "", "", "/usr/bin", ""], ":/bin:::/usr/bin:")); - assert!(join_paths(["/te:st"].iter().cloned()).is_err()); -} - -#[test] -#[cfg(windows)] -fn join_paths_windows() { - use crate::ffi::OsStr; - - fn test_eq(input: &[&str], output: &str) -> bool { - &*join_paths(input.iter().cloned()).unwrap() == OsStr::new(output) - } - - assert!(test_eq(&[], "")); - assert!(test_eq(&[r"c:\windows", r"c:\"], r"c:\windows;c:\")); - assert!(test_eq(&["", r"c:\windows", "", "", r"c:\", ""], r";c:\windows;;;c:\;")); - assert!(test_eq(&[r"c:\te;st", r"c:\"], r#""c:\te;st";c:\"#)); - assert!(join_paths([r#"c:\te"st"#].iter().cloned()).is_err()); -} - -#[test] -fn args_debug() { - assert_eq!( - format!("Args {{ inner: {:?} }}", args().collect::<Vec<_>>()), - format!("{:?}", args()) - ); -} - -#[test] -fn args_os_debug() { - assert_eq!( - format!("ArgsOs {{ inner: {:?} }}", args_os().collect::<Vec<_>>()), - format!("{:?}", args_os()) - ); -} - -#[test] -fn vars_debug() { - assert_eq!( - format!("Vars {{ inner: {:?} }}", vars().collect::<Vec<_>>()), - format!("{:?}", vars()) - ); -} - -#[test] -fn vars_os_debug() { - assert_eq!( - format!("VarsOs {{ inner: {:?} }}", vars_os().collect::<Vec<_>>()), - format!("{:?}", vars_os()) - ); -} diff --git a/library/std/src/error.rs b/library/std/src/error.rs index b3e63aaf1c5..def5f984c88 100644 --- a/library/std/src/error.rs +++ b/library/std/src/error.rs @@ -1,9 +1,6 @@ #![doc = include_str!("../../core/src/error.md")] #![stable(feature = "rust1", since = "1.0.0")] -#[cfg(test)] -mod tests; - #[stable(feature = "rust1", since = "1.0.0")] pub use core::error::Error; #[unstable(feature = "error_generic_member_access", issue = "99301")] diff --git a/library/std/src/f128.rs b/library/std/src/f128.rs index d65f5ed61cf..89612fa7475 100644 --- a/library/std/src/f128.rs +++ b/library/std/src/f128.rs @@ -4,9 +4,6 @@ //! //! Mathematically significant numbers are provided in the `consts` sub-module. -#[cfg(test)] -mod tests; - #[unstable(feature = "f128", issue = "116909")] pub use core::f128::consts; diff --git a/library/std/src/f16.rs b/library/std/src/f16.rs index 5b0903bceab..cc523c93b4d 100644 --- a/library/std/src/f16.rs +++ b/library/std/src/f16.rs @@ -4,9 +4,6 @@ //! //! Mathematically significant numbers are provided in the `consts` sub-module. -#[cfg(test)] -mod tests; - #[unstable(feature = "f16", issue = "116909")] pub use core::f16::consts; diff --git a/library/std/src/f32.rs b/library/std/src/f32.rs index f9b6723788a..260c499b7f4 100644 --- a/library/std/src/f32.rs +++ b/library/std/src/f32.rs @@ -12,9 +12,6 @@ #![stable(feature = "rust1", since = "1.0.0")] #![allow(missing_docs)] -#[cfg(test)] -mod tests; - #[stable(feature = "rust1", since = "1.0.0")] #[allow(deprecated, deprecated_in_future)] pub use core::f32::{ diff --git a/library/std/src/f64.rs b/library/std/src/f64.rs index 0de55a15d48..7af646f8cfd 100644 --- a/library/std/src/f64.rs +++ b/library/std/src/f64.rs @@ -12,9 +12,6 @@ #![stable(feature = "rust1", since = "1.0.0")] #![allow(missing_docs)] -#[cfg(test)] -mod tests; - #[stable(feature = "rust1", since = "1.0.0")] #[allow(deprecated, deprecated_in_future)] pub use core::f64::{ diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index acb3a0578e5..7c18226874c 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -530,6 +530,8 @@ pub use core::option; pub use core::pin; #[stable(feature = "rust1", since = "1.0.0")] pub use core::ptr; +#[unstable(feature = "new_range_api", issue = "125687")] +pub use core::range; #[stable(feature = "rust1", since = "1.0.0")] pub use core::result; #[stable(feature = "rust1", since = "1.0.0")] diff --git a/library/std/src/macros.rs b/library/std/src/macros.rs index 1b0d7f3dbf2..e0f9f0bb5ce 100644 --- a/library/std/src/macros.rs +++ b/library/std/src/macros.rs @@ -372,18 +372,3 @@ macro_rules! dbg { ($($crate::dbg!($val)),+,) }; } - -/// Verify that floats are within a tolerance of each other, 1.0e-6 by default. -#[cfg(test)] -macro_rules! assert_approx_eq { - ($a:expr, $b:expr) => {{ assert_approx_eq!($a, $b, 1.0e-6) }}; - ($a:expr, $b:expr, $lim:expr) => {{ - let (a, b) = (&$a, &$b); - let diff = (*a - *b).abs(); - assert!( - diff < $lim, - "{a:?} is not approximately equal to {b:?} (threshold {lim:?}, difference {diff:?})", - lim = $lim - ); - }}; -} diff --git a/library/std/src/num.rs b/library/std/src/num.rs index d2f679e7dde..ffb8789c906 100644 --- a/library/std/src/num.rs +++ b/library/std/src/num.rs @@ -6,9 +6,6 @@ #![stable(feature = "rust1", since = "1.0.0")] #![allow(missing_docs)] -#[cfg(test)] -mod tests; - #[stable(feature = "int_error_matching", since = "1.55.0")] pub use core::num::IntErrorKind; #[stable(feature = "generic_nonzero", since = "1.79.0")] @@ -29,28 +26,3 @@ pub use core::num::{FpCategory, ParseFloatError, ParseIntError, TryFromIntError} pub use core::num::{NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI128, NonZeroIsize}; #[stable(feature = "nonzero", since = "1.28.0")] pub use core::num::{NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128, NonZeroUsize}; - -#[cfg(test)] -use crate::fmt; -#[cfg(test)] -use crate::ops::{Add, Div, Mul, Rem, Sub}; - -/// Helper function for testing numeric operations -#[cfg(test)] -pub fn test_num<T>(ten: T, two: T) -where - T: PartialEq - + Add<Output = T> - + Sub<Output = T> - + Mul<Output = T> - + Div<Output = T> - + Rem<Output = T> - + fmt::Debug - + Copy, -{ - assert_eq!(ten.add(two), ten + two); - assert_eq!(ten.sub(two), ten - two); - assert_eq!(ten.mul(two), ten * two); - assert_eq!(ten.div(two), ten / two); - assert_eq!(ten.rem(two), ten % two); -} diff --git a/library/std/src/panic.rs b/library/std/src/panic.rs index d649357a56d..153189b8b03 100644 --- a/library/std/src/panic.rs +++ b/library/std/src/panic.rs @@ -529,6 +529,3 @@ pub fn get_backtrace_style() -> Option<BacktraceStyle> { Err(new) => BacktraceStyle::from_u8(new), } } - -#[cfg(test)] -mod tests; diff --git a/library/std/src/path.rs b/library/std/src/path.rs index 7fd08a97f1f..97e17acadea 100644 --- a/library/std/src/path.rs +++ b/library/std/src/path.rs @@ -67,9 +67,6 @@ #![stable(feature = "rust1", since = "1.0.0")] #![deny(unsafe_op_in_unsafe_fn)] -#[cfg(test)] -mod tests; - use core::clone::CloneToUninit; use crate::borrow::{Borrow, Cow}; diff --git a/library/std/src/sync/barrier.rs b/library/std/src/sync/barrier.rs index 862753e4765..067ff66d9af 100644 --- a/library/std/src/sync/barrier.rs +++ b/library/std/src/sync/barrier.rs @@ -1,6 +1,3 @@ -#[cfg(test)] -mod tests; - use crate::fmt; // FIXME(nonpoison_mutex,nonpoison_condvar): switch to nonpoison versions once they are available use crate::sync::{Condvar, Mutex}; diff --git a/library/std/src/sync/lazy_lock.rs b/library/std/src/sync/lazy_lock.rs index 98c83d8d326..78cf8841efe 100644 --- a/library/std/src/sync/lazy_lock.rs +++ b/library/std/src/sync/lazy_lock.rs @@ -350,6 +350,3 @@ unsafe impl<T: Sync + Send, F: Send> Sync for LazyLock<T, F> {} impl<T: RefUnwindSafe + UnwindSafe, F: UnwindSafe> RefUnwindSafe for LazyLock<T, F> {} #[stable(feature = "lazy_cell", since = "1.80.0")] impl<T: UnwindSafe, F: UnwindSafe> UnwindSafe for LazyLock<T, F> {} - -#[cfg(test)] -mod tests; diff --git a/library/std/src/sync/mpsc/mod.rs b/library/std/src/sync/mpsc.rs index c86b546e011..f942937c14d 100644 --- a/library/std/src/sync/mpsc/mod.rs +++ b/library/std/src/sync/mpsc.rs @@ -137,12 +137,6 @@ #![stable(feature = "rust1", since = "1.0.0")] -#[cfg(all(test, not(any(target_os = "emscripten", target_os = "wasi"))))] -mod tests; - -#[cfg(all(test, not(any(target_os = "emscripten", target_os = "wasi"))))] -mod sync_tests; - // MPSC channels are built as a wrapper around MPMC channels, which // were ported from the `crossbeam-channel` crate. MPMC channels are // not exposed publicly, but if you are curious about the implementation, @@ -737,9 +731,10 @@ impl<T> SyncSender<T> { // Attempts to send for a value on this receiver, returning an error if the // corresponding channel has hung up, or if it waits more than `timeout`. // - // This method is currently private and only used for tests. - #[allow(unused)] - fn send_timeout(&self, t: T, timeout: Duration) -> Result<(), mpmc::SendTimeoutError<T>> { + // This method is currently only used for tests. + #[unstable(issue = "none", feature = "std_internals")] + #[doc(hidden)] + pub fn send_timeout(&self, t: T, timeout: Duration) -> Result<(), mpmc::SendTimeoutError<T>> { self.inner.send_timeout(t, timeout) } } diff --git a/library/std/src/sync/once_lock.rs b/library/std/src/sync/once_lock.rs index 6fc0abbed9e..21e6b65a744 100644 --- a/library/std/src/sync/once_lock.rs +++ b/library/std/src/sync/once_lock.rs @@ -13,6 +13,9 @@ use crate::sync::Once; /// Where OnceLock shines is when LazyLock is too simple to support a given case, as LazyLock /// doesn't allow additional inputs to its function after you call [`LazyLock::new(|| ...)`]. /// +/// A `OnceLock` can be thought of as a safe abstraction over uninitialized data that becomes +/// initialized once written. +/// /// [`OnceCell`]: crate::cell::OnceCell /// [`LazyLock<T, F>`]: crate::sync::LazyLock /// [`LazyLock::new(|| ...)`]: crate::sync::LazyLock::new @@ -126,7 +129,7 @@ pub struct OnceLock<T> { } impl<T> OnceLock<T> { - /// Creates a new empty cell. + /// Creates a new uninitialized cell. #[inline] #[must_use] #[stable(feature = "once_cell", since = "1.70.0")] @@ -141,8 +144,8 @@ impl<T> OnceLock<T> { /// Gets the reference to the underlying value. /// - /// Returns `None` if the cell is empty, or being initialized. This - /// method never blocks. + /// Returns `None` if the cell is uninitialized, or being initialized. + /// This method never blocks. #[inline] #[stable(feature = "once_cell", since = "1.70.0")] pub fn get(&self) -> Option<&T> { @@ -156,7 +159,8 @@ impl<T> OnceLock<T> { /// Gets the mutable reference to the underlying value. /// - /// Returns `None` if the cell is empty. This method never blocks. + /// Returns `None` if the cell is uninitialized, or being initialized. + /// This method never blocks. #[inline] #[stable(feature = "once_cell", since = "1.70.0")] pub fn get_mut(&mut self) -> Option<&mut T> { @@ -194,12 +198,13 @@ impl<T> OnceLock<T> { unsafe { self.get_unchecked() } } - /// Sets the contents of this cell to `value`. + /// Initializes the contents of the cell to `value`. /// /// May block if another thread is currently attempting to initialize the cell. The cell is - /// guaranteed to contain a value when set returns, though not necessarily the one provided. + /// guaranteed to contain a value when `set` returns, though not necessarily the one provided. /// - /// Returns `Ok(())` if the cell's value was set by this call. + /// Returns `Ok(())` if the cell was uninitialized and + /// `Err(value)` if the cell was already initialized. /// /// # Examples /// @@ -228,13 +233,15 @@ impl<T> OnceLock<T> { } } - /// Sets the contents of this cell to `value` if the cell was empty, then - /// returns a reference to it. + /// Initializes the contents of the cell to `value` if the cell was uninitialized, + /// then returns a reference to it. /// /// May block if another thread is currently attempting to initialize the cell. The cell is - /// guaranteed to contain a value when set returns, though not necessarily the one provided. + /// guaranteed to contain a value when `try_insert` returns, though not necessarily the + /// one provided. /// - /// Returns `Ok(&value)` if the cell was empty and `Err(¤t_value, value)` if it was full. + /// Returns `Ok(&value)` if the cell was uninitialized and + /// `Err((¤t_value, value))` if it was already initialized. /// /// # Examples /// @@ -267,8 +274,8 @@ impl<T> OnceLock<T> { } } - /// Gets the contents of the cell, initializing it with `f` if the cell - /// was empty. + /// Gets the contents of the cell, initializing it to `f()` if the cell + /// was uninitialized. /// /// Many threads may call `get_or_init` concurrently with different /// initializing functions, but it is guaranteed that only one function @@ -276,7 +283,7 @@ impl<T> OnceLock<T> { /// /// # Panics /// - /// If `f` panics, the panic is propagated to the caller, and the cell + /// If `f()` panics, the panic is propagated to the caller, and the cell /// remains uninitialized. /// /// It is an error to reentrantly initialize the cell from `f`. The @@ -306,13 +313,13 @@ impl<T> OnceLock<T> { } /// Gets the mutable reference of the contents of the cell, initializing - /// it with `f` if the cell was empty. + /// it to `f()` if the cell was uninitialized. /// /// This method never blocks. /// /// # Panics /// - /// If `f` panics, the panic is propagated to the caller, and the cell + /// If `f()` panics, the panic is propagated to the caller, and the cell /// remains uninitialized. /// /// # Examples @@ -343,13 +350,13 @@ impl<T> OnceLock<T> { } } - /// Gets the contents of the cell, initializing it with `f` if - /// the cell was empty. If the cell was empty and `f` failed, an - /// error is returned. + /// Gets the contents of the cell, initializing it to `f()` if + /// the cell was uninitialized. If the cell was uninitialized + /// and `f()` failed, an error is returned. /// /// # Panics /// - /// If `f` panics, the panic is propagated to the caller, and + /// If `f()` panics, the panic is propagated to the caller, and /// the cell remains uninitialized. /// /// It is an error to reentrantly initialize the cell from `f`. @@ -395,14 +402,14 @@ impl<T> OnceLock<T> { } /// Gets the mutable reference of the contents of the cell, initializing - /// it with `f` if the cell was empty. If the cell was empty and `f` failed, - /// an error is returned. + /// it to `f()` if the cell was uninitialized. If the cell was uninitialized + /// and `f()` failed, an error is returned. /// /// This method never blocks. /// /// # Panics /// - /// If `f` panics, the panic is propagated to the caller, and + /// If `f()` panics, the panic is propagated to the caller, and /// the cell remains uninitialized. /// /// # Examples @@ -414,7 +421,7 @@ impl<T> OnceLock<T> { /// /// let mut cell: OnceLock<u32> = OnceLock::new(); /// - /// // Failed initializers do not change the value + /// // Failed attempts to initialize the cell do not change its contents /// assert!(cell.get_mut_or_try_init(|| "not a number!".parse()).is_err()); /// assert!(cell.get().is_none()); /// @@ -438,7 +445,7 @@ impl<T> OnceLock<T> { } /// Consumes the `OnceLock`, returning the wrapped value. Returns - /// `None` if the cell was empty. + /// `None` if the cell was uninitialized. /// /// # Examples /// @@ -460,7 +467,7 @@ impl<T> OnceLock<T> { /// Takes the value out of this `OnceLock`, moving it back to an uninitialized state. /// - /// Has no effect and returns `None` if the `OnceLock` hasn't been initialized. + /// Has no effect and returns `None` if the `OnceLock` was uninitialized. /// /// Safety is guaranteed by requiring a mutable reference. /// @@ -526,7 +533,7 @@ impl<T> OnceLock<T> { /// # Safety /// - /// The value must be initialized + /// The cell must be initialized #[inline] unsafe fn get_unchecked(&self) -> &T { debug_assert!(self.is_initialized()); @@ -535,7 +542,7 @@ impl<T> OnceLock<T> { /// # Safety /// - /// The value must be initialized + /// The cell must be initialized #[inline] unsafe fn get_unchecked_mut(&mut self) -> &mut T { debug_assert!(self.is_initialized()); @@ -560,7 +567,7 @@ impl<T: UnwindSafe> UnwindSafe for OnceLock<T> {} #[stable(feature = "once_cell", since = "1.70.0")] impl<T> Default for OnceLock<T> { - /// Creates a new empty cell. + /// Creates a new uninitialized cell. /// /// # Example /// @@ -674,6 +681,3 @@ unsafe impl<#[may_dangle] T> Drop for OnceLock<T> { } } } - -#[cfg(test)] -mod tests; diff --git a/library/std/src/sync/poison/condvar.rs b/library/std/src/sync/poison/condvar.rs index a6e2389c93b..7f0f3f652bc 100644 --- a/library/std/src/sync/poison/condvar.rs +++ b/library/std/src/sync/poison/condvar.rs @@ -1,6 +1,3 @@ -#[cfg(test)] -mod tests; - use crate::fmt; use crate::sync::poison::{self, LockResult, MutexGuard, PoisonError, mutex}; use crate::sys::sync as sys; diff --git a/library/std/src/sync/poison/mutex.rs b/library/std/src/sync/poison/mutex.rs index fb43ada6375..9362c764173 100644 --- a/library/std/src/sync/poison/mutex.rs +++ b/library/std/src/sync/poison/mutex.rs @@ -1,6 +1,3 @@ -#[cfg(all(test, not(any(target_os = "emscripten", target_os = "wasi"))))] -mod tests; - use crate::cell::UnsafeCell; use crate::fmt; use crate::marker::PhantomData; diff --git a/library/std/src/sync/poison/once.rs b/library/std/src/sync/poison/once.rs index 528b11ca0c1..d2938b7a0c1 100644 --- a/library/std/src/sync/poison/once.rs +++ b/library/std/src/sync/poison/once.rs @@ -3,9 +3,6 @@ //! This primitive is meant to be used to run one-time initialization. An //! example use case would be for initializing an FFI library. -#[cfg(all(test, not(any(target_os = "emscripten", target_os = "wasi"))))] -mod tests; - use crate::fmt; use crate::panic::{RefUnwindSafe, UnwindSafe}; use crate::sys::sync as sys; diff --git a/library/std/src/sync/poison/rwlock.rs b/library/std/src/sync/poison/rwlock.rs index 1519baf99a8..f9d9321f5f2 100644 --- a/library/std/src/sync/poison/rwlock.rs +++ b/library/std/src/sync/poison/rwlock.rs @@ -1,6 +1,3 @@ -#[cfg(all(test, not(any(target_os = "emscripten", target_os = "wasi"))))] -mod tests; - use crate::cell::UnsafeCell; use crate::fmt; use crate::marker::PhantomData; diff --git a/library/std/src/sync/reentrant_lock.rs b/library/std/src/sync/reentrant_lock.rs index 0140e0d2129..e009eb410ef 100644 --- a/library/std/src/sync/reentrant_lock.rs +++ b/library/std/src/sync/reentrant_lock.rs @@ -1,6 +1,3 @@ -#[cfg(all(test, not(any(target_os = "emscripten", target_os = "wasi"))))] -mod tests; - use cfg_if::cfg_if; use crate::cell::UnsafeCell; @@ -324,7 +321,10 @@ impl<T: ?Sized> ReentrantLock<T> { /// Otherwise, an RAII guard is returned. /// /// This function does not block. - pub(crate) fn try_lock(&self) -> Option<ReentrantLockGuard<'_, T>> { + // FIXME maybe make it a public part of the API? + #[unstable(issue = "none", feature = "std_internals")] + #[doc(hidden)] + pub fn try_lock(&self) -> Option<ReentrantLockGuard<'_, T>> { let this_thread = current_id(); // Safety: We only touch lock_count when we own the inner mutex. // Additionally, we only call `self.owner.set()` while holding diff --git a/library/std/src/sys/pal/unix/fs.rs b/library/std/src/sys/pal/unix/fs.rs index fdf011c1948..6c41781fe85 100644 --- a/library/std/src/sys/pal/unix/fs.rs +++ b/library/std/src/sys/pal/unix/fs.rs @@ -740,29 +740,27 @@ impl Iterator for ReadDir { // to `byte_offset` and thus does not require the full extent of `*entry_ptr` // to be in bounds of the same allocation, only the offset of the field // being referenced. - macro_rules! entry_field_ptr { - ($field:ident) => { - &raw const (*entry_ptr).$field - }; - } // d_name is guaranteed to be null-terminated. - let name = CStr::from_ptr(entry_field_ptr!(d_name).cast()); + let name = CStr::from_ptr((&raw const (*entry_ptr).d_name).cast()); let name_bytes = name.to_bytes(); if name_bytes == b"." || name_bytes == b".." { continue; } + // When loading from a field, we can skip the `&raw const`; `(*entry_ptr).d_ino` as + // a value expression will do the right thing: `byte_offset` to the field and then + // only access those bytes. #[cfg(not(target_os = "vita"))] let entry = dirent64_min { - d_ino: *entry_field_ptr!(d_ino) as u64, + d_ino: (*entry_ptr).d_ino as u64, #[cfg(not(any( target_os = "solaris", target_os = "illumos", target_os = "aix", target_os = "nto", )))] - d_type: *entry_field_ptr!(d_type) as u8, + d_type: (*entry_ptr).d_type as u8, }; #[cfg(target_os = "vita")] diff --git a/library/std/src/thread/local.rs b/library/std/src/thread/local.rs index c003503ca8b..ca04aa4ada4 100644 --- a/library/std/src/thread/local.rs +++ b/library/std/src/thread/local.rs @@ -2,12 +2,6 @@ #![unstable(feature = "thread_local_internals", issue = "none")] -#[cfg(all(test, not(any(target_os = "emscripten", target_os = "wasi"))))] -mod tests; - -#[cfg(test)] -mod dynamic_tests; - use crate::cell::{Cell, RefCell}; use crate::error::Error; use crate::fmt; diff --git a/library/std/src/time.rs b/library/std/src/time.rs index 9f4f8a0d088..88b3e9e0ceb 100644 --- a/library/std/src/time.rs +++ b/library/std/src/time.rs @@ -31,9 +31,6 @@ #![stable(feature = "time", since = "1.3.0")] -#[cfg(test)] -mod tests; - #[stable(feature = "time", since = "1.3.0")] pub use core::time::Duration; #[stable(feature = "duration_checked_float", since = "1.66.0")] diff --git a/library/std/tests/env.rs b/library/std/tests/env.rs index 44fe84c989f..e754cf8263b 100644 --- a/library/std/tests/env.rs +++ b/library/std/tests/env.rs @@ -1,163 +1,123 @@ use std::env::*; -use std::ffi::{OsStr, OsString}; - -use rand::distributions::{Alphanumeric, DistString}; +use std::path::Path; mod common; -use std::thread; - -use common::test_rng; - -#[track_caller] -fn make_rand_name() -> OsString { - let n = format!("TEST{}", Alphanumeric.sample_string(&mut test_rng(), 10)); - let n = OsString::from(n); - assert!(var_os(&n).is_none()); - n -} - -fn eq(a: Option<OsString>, b: Option<&str>) { - assert_eq!(a.as_ref().map(|s| &**s), b.map(OsStr::new).map(|s| &*s)); -} #[test] -fn test_set_var() { - let n = make_rand_name(); - set_var(&n, "VALUE"); - eq(var_os(&n), Some("VALUE")); +#[cfg_attr(any(target_os = "emscripten", target_os = "wasi", target_env = "sgx"), ignore)] +fn test_self_exe_path() { + let path = current_exe(); + assert!(path.is_ok()); + let path = path.unwrap(); + + // Hard to test this function + assert!(path.is_absolute()); } #[test] -fn test_remove_var() { - let n = make_rand_name(); - set_var(&n, "VALUE"); - remove_var(&n); - eq(var_os(&n), None); -} +fn test() { + assert!((!Path::new("test-path").is_absolute())); -#[test] -fn test_set_var_overwrite() { - let n = make_rand_name(); - set_var(&n, "1"); - set_var(&n, "2"); - eq(var_os(&n), Some("2")); - set_var(&n, ""); - eq(var_os(&n), Some("")); + #[cfg(not(target_env = "sgx"))] + current_dir().unwrap(); } #[test] -#[cfg_attr(target_os = "emscripten", ignore)] -fn test_var_big() { - let mut s = "".to_string(); - let mut i = 0; - while i < 100 { - s.push_str("aaaaaaaaaa"); - i += 1; +#[cfg(windows)] +fn split_paths_windows() { + use std::path::PathBuf; + + fn check_parse(unparsed: &str, parsed: &[&str]) -> bool { + split_paths(unparsed).collect::<Vec<_>>() + == parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>() } - let n = make_rand_name(); - set_var(&n, &s); - eq(var_os(&n), Some(&s)); -} -#[test] -#[cfg_attr(target_os = "emscripten", ignore)] -fn test_env_set_get_huge() { - let n = make_rand_name(); - let s = "x".repeat(10000); - set_var(&n, &s); - eq(var_os(&n), Some(&s)); - remove_var(&n); - eq(var_os(&n), None); + assert!(check_parse("", &mut [""])); + assert!(check_parse(r#""""#, &mut [""])); + assert!(check_parse(";;", &mut ["", "", ""])); + assert!(check_parse(r"c:\", &mut [r"c:\"])); + assert!(check_parse(r"c:\;", &mut [r"c:\", ""])); + assert!(check_parse(r"c:\;c:\Program Files\", &mut [r"c:\", r"c:\Program Files\"])); + assert!(check_parse(r#"c:\;c:\"foo"\"#, &mut [r"c:\", r"c:\foo\"])); + assert!(check_parse(r#"c:\;c:\"foo;bar"\;c:\baz"#, &mut [r"c:\", r"c:\foo;bar\", r"c:\baz"])); } #[test] -fn test_env_set_var() { - let n = make_rand_name(); +#[cfg(unix)] +fn split_paths_unix() { + use std::path::PathBuf; - let mut e = vars_os(); - set_var(&n, "VALUE"); - assert!(!e.any(|(k, v)| { &*k == &*n && &*v == "VALUE" })); + fn check_parse(unparsed: &str, parsed: &[&str]) -> bool { + split_paths(unparsed).collect::<Vec<_>>() + == parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>() + } - assert!(vars_os().any(|(k, v)| { &*k == &*n && &*v == "VALUE" })); + assert!(check_parse("", &mut [""])); + assert!(check_parse("::", &mut ["", "", ""])); + assert!(check_parse("/", &mut ["/"])); + assert!(check_parse("/:", &mut ["/", ""])); + assert!(check_parse("/:/usr/local", &mut ["/", "/usr/local"])); } #[test] -#[cfg_attr(not(any(unix, windows)), ignore, allow(unused))] -#[allow(deprecated)] -fn env_home_dir() { - use std::path::PathBuf; +#[cfg(unix)] +fn join_paths_unix() { + use std::ffi::OsStr; - fn var_to_os_string(var: Result<String, VarError>) -> Option<OsString> { - match var { - Ok(var) => Some(OsString::from(var)), - Err(VarError::NotUnicode(var)) => Some(var), - _ => None, - } + fn test_eq(input: &[&str], output: &str) -> bool { + &*join_paths(input.iter().cloned()).unwrap() == OsStr::new(output) } - cfg_if::cfg_if! { - if #[cfg(unix)] { - let oldhome = var_to_os_string(var("HOME")); - - set_var("HOME", "/home/MountainView"); - assert_eq!(home_dir(), Some(PathBuf::from("/home/MountainView"))); - - remove_var("HOME"); - if cfg!(target_os = "android") { - assert!(home_dir().is_none()); - } else { - // When HOME is not set, some platforms return `None`, - // but others return `Some` with a default. - // Just check that it is not "/home/MountainView". - assert_ne!(home_dir(), Some(PathBuf::from("/home/MountainView"))); - } - - if let Some(oldhome) = oldhome { set_var("HOME", oldhome); } - } else if #[cfg(windows)] { - let oldhome = var_to_os_string(var("HOME")); - let olduserprofile = var_to_os_string(var("USERPROFILE")); - - remove_var("HOME"); - remove_var("USERPROFILE"); - - assert!(home_dir().is_some()); - - set_var("HOME", "/home/PaloAlto"); - assert_ne!(home_dir(), Some(PathBuf::from("/home/PaloAlto")), "HOME must not be used"); + assert!(test_eq(&[], "")); + assert!(test_eq(&["/bin", "/usr/bin", "/usr/local/bin"], "/bin:/usr/bin:/usr/local/bin")); + assert!(test_eq(&["", "/bin", "", "", "/usr/bin", ""], ":/bin:::/usr/bin:")); + assert!(join_paths(["/te:st"].iter().cloned()).is_err()); +} - set_var("USERPROFILE", "/home/MountainView"); - assert_eq!(home_dir(), Some(PathBuf::from("/home/MountainView"))); +#[test] +#[cfg(windows)] +fn join_paths_windows() { + use std::ffi::OsStr; - remove_var("HOME"); + fn test_eq(input: &[&str], output: &str) -> bool { + &*join_paths(input.iter().cloned()).unwrap() == OsStr::new(output) + } - assert_eq!(home_dir(), Some(PathBuf::from("/home/MountainView"))); + assert!(test_eq(&[], "")); + assert!(test_eq(&[r"c:\windows", r"c:\"], r"c:\windows;c:\")); + assert!(test_eq(&["", r"c:\windows", "", "", r"c:\", ""], r";c:\windows;;;c:\;")); + assert!(test_eq(&[r"c:\te;st", r"c:\"], r#""c:\te;st";c:\"#)); + assert!(join_paths([r#"c:\te"st"#].iter().cloned()).is_err()); +} - set_var("USERPROFILE", ""); - assert_ne!(home_dir(), Some(PathBuf::from("")), "Empty USERPROFILE must be ignored"); +#[test] +fn args_debug() { + assert_eq!( + format!("Args {{ inner: {:?} }}", args().collect::<Vec<_>>()), + format!("{:?}", args()) + ); +} - remove_var("USERPROFILE"); +#[test] +fn args_os_debug() { + assert_eq!( + format!("ArgsOs {{ inner: {:?} }}", args_os().collect::<Vec<_>>()), + format!("{:?}", args_os()) + ); +} - if let Some(oldhome) = oldhome { set_var("HOME", oldhome); } - if let Some(olduserprofile) = olduserprofile { set_var("USERPROFILE", olduserprofile); } - } - } +#[test] +fn vars_debug() { + assert_eq!( + format!("Vars {{ inner: {:?} }}", vars().collect::<Vec<_>>()), + format!("{:?}", vars()) + ); } -#[test] // miri shouldn't detect any data race in this fn -#[cfg_attr(any(not(miri), target_os = "emscripten"), ignore)] -fn test_env_get_set_multithreaded() { - let getter = thread::spawn(|| { - for _ in 0..100 { - let _ = var_os("foo"); - } - }); - - let setter = thread::spawn(|| { - for _ in 0..100 { - set_var("foo", "bar"); - } - }); - - let _ = getter.join(); - let _ = setter.join(); +#[test] +fn vars_os_debug() { + assert_eq!( + format!("VarsOs {{ inner: {:?} }}", vars_os().collect::<Vec<_>>()), + format!("{:?}", vars_os()) + ); } diff --git a/library/std/tests/env_modify.rs b/library/std/tests/env_modify.rs new file mode 100644 index 00000000000..60747447350 --- /dev/null +++ b/library/std/tests/env_modify.rs @@ -0,0 +1,166 @@ +// These tests are in a separate integration test as they modify the environment, +// and would otherwise cause some other tests to fail. + +use std::env::*; +use std::ffi::{OsStr, OsString}; + +use rand::distributions::{Alphanumeric, DistString}; + +mod common; +use std::thread; + +use common::test_rng; + +#[track_caller] +fn make_rand_name() -> OsString { + let n = format!("TEST{}", Alphanumeric.sample_string(&mut test_rng(), 10)); + let n = OsString::from(n); + assert!(var_os(&n).is_none()); + n +} + +fn eq(a: Option<OsString>, b: Option<&str>) { + assert_eq!(a.as_ref().map(|s| &**s), b.map(OsStr::new).map(|s| &*s)); +} + +#[test] +fn test_set_var() { + let n = make_rand_name(); + set_var(&n, "VALUE"); + eq(var_os(&n), Some("VALUE")); +} + +#[test] +fn test_remove_var() { + let n = make_rand_name(); + set_var(&n, "VALUE"); + remove_var(&n); + eq(var_os(&n), None); +} + +#[test] +fn test_set_var_overwrite() { + let n = make_rand_name(); + set_var(&n, "1"); + set_var(&n, "2"); + eq(var_os(&n), Some("2")); + set_var(&n, ""); + eq(var_os(&n), Some("")); +} + +#[test] +#[cfg_attr(target_os = "emscripten", ignore)] +fn test_var_big() { + let mut s = "".to_string(); + let mut i = 0; + while i < 100 { + s.push_str("aaaaaaaaaa"); + i += 1; + } + let n = make_rand_name(); + set_var(&n, &s); + eq(var_os(&n), Some(&s)); +} + +#[test] +#[cfg_attr(target_os = "emscripten", ignore)] +fn test_env_set_get_huge() { + let n = make_rand_name(); + let s = "x".repeat(10000); + set_var(&n, &s); + eq(var_os(&n), Some(&s)); + remove_var(&n); + eq(var_os(&n), None); +} + +#[test] +fn test_env_set_var() { + let n = make_rand_name(); + + let mut e = vars_os(); + set_var(&n, "VALUE"); + assert!(!e.any(|(k, v)| { &*k == &*n && &*v == "VALUE" })); + + assert!(vars_os().any(|(k, v)| { &*k == &*n && &*v == "VALUE" })); +} + +#[test] +#[cfg_attr(not(any(unix, windows)), ignore, allow(unused))] +#[allow(deprecated)] +fn env_home_dir() { + use std::path::PathBuf; + + fn var_to_os_string(var: Result<String, VarError>) -> Option<OsString> { + match var { + Ok(var) => Some(OsString::from(var)), + Err(VarError::NotUnicode(var)) => Some(var), + _ => None, + } + } + + cfg_if::cfg_if! { + if #[cfg(unix)] { + let oldhome = var_to_os_string(var("HOME")); + + set_var("HOME", "/home/MountainView"); + assert_eq!(home_dir(), Some(PathBuf::from("/home/MountainView"))); + + remove_var("HOME"); + if cfg!(target_os = "android") { + assert!(home_dir().is_none()); + } else { + // When HOME is not set, some platforms return `None`, + // but others return `Some` with a default. + // Just check that it is not "/home/MountainView". + assert_ne!(home_dir(), Some(PathBuf::from("/home/MountainView"))); + } + + if let Some(oldhome) = oldhome { set_var("HOME", oldhome); } + } else if #[cfg(windows)] { + let oldhome = var_to_os_string(var("HOME")); + let olduserprofile = var_to_os_string(var("USERPROFILE")); + + remove_var("HOME"); + remove_var("USERPROFILE"); + + assert!(home_dir().is_some()); + + set_var("HOME", "/home/PaloAlto"); + assert_ne!(home_dir(), Some(PathBuf::from("/home/PaloAlto")), "HOME must not be used"); + + set_var("USERPROFILE", "/home/MountainView"); + assert_eq!(home_dir(), Some(PathBuf::from("/home/MountainView"))); + + remove_var("HOME"); + + assert_eq!(home_dir(), Some(PathBuf::from("/home/MountainView"))); + + set_var("USERPROFILE", ""); + assert_ne!(home_dir(), Some(PathBuf::from("")), "Empty USERPROFILE must be ignored"); + + remove_var("USERPROFILE"); + + if let Some(oldhome) = oldhome { set_var("HOME", oldhome); } + if let Some(olduserprofile) = olduserprofile { set_var("USERPROFILE", olduserprofile); } + } + } +} + +#[test] // miri shouldn't detect any data race in this fn +#[cfg_attr(any(not(miri), target_os = "emscripten"), ignore)] +fn test_env_get_set_multithreaded() { + let getter = thread::spawn(|| { + for _ in 0..100 { + let _ = var_os("foo"); + } + }); + + let setter = thread::spawn(|| { + for _ in 0..100 { + set_var("foo", "bar"); + } + }); + + let _ = getter.join(); + let _ = setter.join(); +} diff --git a/library/std/src/error/tests.rs b/library/std/tests/error.rs index 88a9f33c079..8fd6eb3c020 100644 --- a/library/std/src/error/tests.rs +++ b/library/std/tests/error.rs @@ -1,7 +1,8 @@ -use core::error::Request; +#![feature(error_generic_member_access, error_reporter)] -use super::Error; -use crate::fmt; +use std::backtrace::Backtrace; +use std::error::{Error, Report, Request}; +use std::fmt; #[derive(Debug, PartialEq)] struct A; @@ -38,9 +39,6 @@ fn downcasting() { } } -use crate::backtrace::Backtrace; -use crate::error::Report; - #[derive(Debug)] struct SuperError { source: SuperErrorSideKick, diff --git a/library/std/src/f128/tests.rs b/library/std/tests/floats/f128.rs index cbcf9f96239..d0e8b157e6b 100644 --- a/library/std/src/f128/tests.rs +++ b/library/std/tests/floats/f128.rs @@ -1,11 +1,11 @@ // FIXME(f16_f128): only tested on platforms that have symbols and aren't buggy #![cfg(reliable_f128)] -use crate::f128::consts; -use crate::num::FpCategory as Fp; +use std::f128::consts; +use std::num::FpCategory as Fp; #[cfg(reliable_f128_math)] -use crate::ops::Rem; -use crate::ops::{Add, Div, Mul, Sub}; +use std::ops::Rem; +use std::ops::{Add, Div, Mul, Sub}; // Note these tolerances make sense around zero, but not for more extreme exponents. @@ -762,8 +762,6 @@ fn test_ln_gamma() { #[test] fn test_real_consts() { - use super::consts; - let pi: f128 = consts::PI; let frac_pi_2: f128 = consts::FRAC_PI_2; let frac_pi_3: f128 = consts::FRAC_PI_3; diff --git a/library/std/src/f16/tests.rs b/library/std/tests/floats/f16.rs index 684ee3f3855..5180f3d40f3 100644 --- a/library/std/src/f16/tests.rs +++ b/library/std/tests/floats/f16.rs @@ -1,8 +1,8 @@ // FIXME(f16_f128): only tested on platforms that have symbols and aren't buggy #![cfg(reliable_f16)] -use crate::f16::consts; -use crate::num::{FpCategory as Fp, *}; +use std::f16::consts; +use std::num::FpCategory as Fp; /// Tolerance for results on the order of 10.0e-2 #[allow(unused)] @@ -54,7 +54,7 @@ macro_rules! assert_f16_biteq { #[test] fn test_num_f16() { - test_num(10f16, 2f16); + crate::test_num(10f16, 2f16); } #[test] @@ -734,7 +734,6 @@ fn test_ln_gamma() { #[test] fn test_real_consts() { // FIXME(f16_f128): add math tests when available - use super::consts; let pi: f16 = consts::PI; let frac_pi_2: f16 = consts::FRAC_PI_2; diff --git a/library/std/src/f32/tests.rs b/library/std/tests/floats/f32.rs index 99cfcfb231d..bf7641986ad 100644 --- a/library/std/src/f32/tests.rs +++ b/library/std/tests/floats/f32.rs @@ -1,5 +1,5 @@ -use crate::f32::consts; -use crate::num::{FpCategory as Fp, *}; +use std::f32::consts; +use std::num::FpCategory as Fp; /// Smallest number const TINY_BITS: u32 = 0x1; @@ -35,7 +35,7 @@ macro_rules! assert_f32_biteq { #[test] fn test_num_f32() { - test_num(10f32, 2f32); + crate::test_num(10f32, 2f32); } #[test] @@ -700,8 +700,6 @@ fn test_ln_gamma() { #[test] fn test_real_consts() { - use super::consts; - let pi: f32 = consts::PI; let frac_pi_2: f32 = consts::FRAC_PI_2; let frac_pi_3: f32 = consts::FRAC_PI_3; diff --git a/library/std/src/f64/tests.rs b/library/std/tests/floats/f64.rs index f5ba2c7b594..cbbfcd15efd 100644 --- a/library/std/src/f64/tests.rs +++ b/library/std/tests/floats/f64.rs @@ -1,5 +1,5 @@ -use crate::f64::consts; -use crate::num::{FpCategory as Fp, *}; +use std::f64::consts; +use std::num::FpCategory as Fp; /// Smallest number const TINY_BITS: u64 = 0x1; @@ -35,7 +35,7 @@ macro_rules! assert_f64_biteq { #[test] fn test_num_f64() { - test_num(10f64, 2f64); + crate::test_num(10f64, 2f64); } #[test] @@ -680,7 +680,6 @@ fn test_ln_gamma() { #[test] fn test_real_consts() { - use super::consts; let pi: f64 = consts::PI; let frac_pi_2: f64 = consts::FRAC_PI_2; let frac_pi_3: f64 = consts::FRAC_PI_3; diff --git a/library/std/tests/floats/lib.rs b/library/std/tests/floats/lib.rs new file mode 100644 index 00000000000..ad82f1a44e7 --- /dev/null +++ b/library/std/tests/floats/lib.rs @@ -0,0 +1,42 @@ +#![feature(f16, f128, float_gamma, float_minimum_maximum)] + +use std::fmt; +use std::ops::{Add, Div, Mul, Rem, Sub}; + +/// Verify that floats are within a tolerance of each other, 1.0e-6 by default. +macro_rules! assert_approx_eq { + ($a:expr, $b:expr) => {{ assert_approx_eq!($a, $b, 1.0e-6) }}; + ($a:expr, $b:expr, $lim:expr) => {{ + let (a, b) = (&$a, &$b); + let diff = (*a - *b).abs(); + assert!( + diff < $lim, + "{a:?} is not approximately equal to {b:?} (threshold {lim:?}, difference {diff:?})", + lim = $lim + ); + }}; +} + +/// Helper function for testing numeric operations +pub fn test_num<T>(ten: T, two: T) +where + T: PartialEq + + Add<Output = T> + + Sub<Output = T> + + Mul<Output = T> + + Div<Output = T> + + Rem<Output = T> + + fmt::Debug + + Copy, +{ + assert_eq!(ten.add(two), ten + two); + assert_eq!(ten.sub(two), ten - two); + assert_eq!(ten.mul(two), ten * two); + assert_eq!(ten.div(two), ten / two); + assert_eq!(ten.rem(two), ten % two); +} + +mod f128; +mod f16; +mod f32; +mod f64; diff --git a/library/std/src/num/tests.rs b/library/std/tests/num.rs index df0df3f23f7..a7400f1c02d 100644 --- a/library/std/src/num/tests.rs +++ b/library/std/tests/num.rs @@ -1,4 +1,4 @@ -use crate::ops::Mul; +use std::ops::Mul; #[test] fn test_saturating_add_uint() { @@ -190,8 +190,8 @@ fn test_uint_to_str_overflow() { assert_eq!(u64_val.to_string(), "0"); } -fn from_str<T: crate::str::FromStr>(t: &str) -> Option<T> { - crate::str::FromStr::from_str(t).ok() +fn from_str<T: std::str::FromStr>(t: &str) -> Option<T> { + std::str::FromStr::from_str(t).ok() } #[test] diff --git a/library/std/src/panic/tests.rs b/library/std/tests/panic.rs index b37d74011cc..f13b931dd22 100644 --- a/library/std/src/panic/tests.rs +++ b/library/std/tests/panic.rs @@ -1,9 +1,9 @@ #![allow(dead_code)] -use crate::cell::RefCell; -use crate::panic::{AssertUnwindSafe, UnwindSafe}; -use crate::rc::Rc; -use crate::sync::{Arc, Mutex, RwLock}; +use std::cell::RefCell; +use std::panic::{AssertUnwindSafe, UnwindSafe}; +use std::rc::Rc; +use std::sync::{Arc, Mutex, RwLock}; struct Foo { a: i32, diff --git a/library/std/src/path/tests.rs b/library/std/tests/path.rs index 3f96ac4672a..978402b6fda 100644 --- a/library/std/src/path/tests.rs +++ b/library/std/tests/path.rs @@ -1,10 +1,19 @@ -use core::hint::black_box; - -use super::*; -use crate::collections::{BTreeSet, HashSet}; -use crate::hash::DefaultHasher; -use crate::mem::MaybeUninit; -use crate::ptr; +#![feature( + clone_to_uninit, + path_add_extension, + path_file_prefix, + maybe_uninit_slice, + os_string_pathbuf_leak +)] + +use std::clone::CloneToUninit; +use std::ffi::OsStr; +use std::hash::{DefaultHasher, Hash, Hasher}; +use std::mem::MaybeUninit; +use std::path::*; +use std::ptr; +use std::rc::Rc; +use std::sync::Arc; #[allow(unknown_lints, unused_macro_rules)] macro_rules! t ( @@ -110,7 +119,7 @@ macro_rules! t ( #[test] fn into() { - use crate::borrow::Cow; + use std::borrow::Cow; let static_path = Path::new("/home/foo"); let static_cow_path: Cow<'static, Path> = static_path.into(); @@ -1525,7 +1534,7 @@ pub fn test_with_added_extension() { #[test] fn test_eq_receivers() { - use crate::borrow::Cow; + use std::borrow::Cow; let borrowed: &Path = Path::new("foo/bar"); let mut owned: PathBuf = PathBuf::new(); @@ -1550,7 +1559,7 @@ fn test_eq_receivers() { #[test] pub fn test_compare() { - use crate::hash::{DefaultHasher, Hash, Hasher}; + use std::hash::{DefaultHasher, Hash, Hasher}; fn hash<T: Hash>(t: T) -> u64 { let mut s = DefaultHasher::new(); @@ -1867,12 +1876,12 @@ fn test_ord() { #[test] #[cfg(any(unix, target_os = "wasi"))] fn test_unix_absolute() { - use crate::path::absolute; + use std::path::absolute; assert!(absolute("").is_err()); let relative = "a/b"; - let mut expected = crate::env::current_dir().unwrap(); + let mut expected = std::env::current_dir().unwrap(); expected.push(relative); assert_eq!(absolute(relative).unwrap().as_os_str(), expected.as_os_str()); @@ -1888,7 +1897,7 @@ fn test_unix_absolute() { ); // Test leading `.` and `..` components - let curdir = crate::env::current_dir().unwrap(); + let curdir = std::env::current_dir().unwrap(); assert_eq!(absolute("./a").unwrap().as_os_str(), curdir.join("a").as_os_str()); assert_eq!(absolute("../a").unwrap().as_os_str(), curdir.join("../a").as_os_str()); // return /pwd/../a } @@ -1896,12 +1905,12 @@ fn test_unix_absolute() { #[test] #[cfg(windows)] fn test_windows_absolute() { - use crate::path::absolute; + use std::path::absolute; // An empty path is an error. assert!(absolute("").is_err()); let relative = r"a\b"; - let mut expected = crate::env::current_dir().unwrap(); + let mut expected = std::env::current_dir().unwrap(); expected.push(relative); assert_eq!(absolute(relative).unwrap().as_os_str(), expected.as_os_str()); @@ -1953,116 +1962,6 @@ fn test_extension_path_sep_alternate() { assert_eq!(path, Path::new("path/to/file.d\\test")); } -#[bench] -#[cfg_attr(miri, ignore)] // Miri isn't fast... -fn bench_path_cmp_fast_path_buf_sort(b: &mut test::Bencher) { - let prefix = "my/home"; - let mut paths: Vec<_> = - (0..1000).map(|num| PathBuf::from(prefix).join(format!("file {num}.rs"))).collect(); - - paths.sort(); - - b.iter(|| { - black_box(paths.as_mut_slice()).sort_unstable(); - }); -} - -#[bench] -#[cfg_attr(miri, ignore)] // Miri isn't fast... -fn bench_path_cmp_fast_path_long(b: &mut test::Bencher) { - let prefix = "/my/home/is/my/castle/and/my/castle/has/a/rusty/workbench/"; - let paths: Vec<_> = - (0..1000).map(|num| PathBuf::from(prefix).join(format!("file {num}.rs"))).collect(); - - let mut set = BTreeSet::new(); - - paths.iter().for_each(|p| { - set.insert(p.as_path()); - }); - - b.iter(|| { - set.remove(paths[500].as_path()); - set.insert(paths[500].as_path()); - }); -} - -#[bench] -#[cfg_attr(miri, ignore)] // Miri isn't fast... -fn bench_path_cmp_fast_path_short(b: &mut test::Bencher) { - let prefix = "my/home"; - let paths: Vec<_> = - (0..1000).map(|num| PathBuf::from(prefix).join(format!("file {num}.rs"))).collect(); - - let mut set = BTreeSet::new(); - - paths.iter().for_each(|p| { - set.insert(p.as_path()); - }); - - b.iter(|| { - set.remove(paths[500].as_path()); - set.insert(paths[500].as_path()); - }); -} - -#[bench] -#[cfg_attr(miri, ignore)] // Miri isn't fast... -fn bench_path_hashset(b: &mut test::Bencher) { - let prefix = "/my/home/is/my/castle/and/my/castle/has/a/rusty/workbench/"; - let paths: Vec<_> = - (0..1000).map(|num| PathBuf::from(prefix).join(format!("file {num}.rs"))).collect(); - - let mut set = HashSet::new(); - - paths.iter().for_each(|p| { - set.insert(p.as_path()); - }); - - b.iter(|| { - set.remove(paths[500].as_path()); - set.insert(black_box(paths[500].as_path())) - }); -} - -#[bench] -#[cfg_attr(miri, ignore)] // Miri isn't fast... -fn bench_path_hashset_miss(b: &mut test::Bencher) { - let prefix = "/my/home/is/my/castle/and/my/castle/has/a/rusty/workbench/"; - let paths: Vec<_> = - (0..1000).map(|num| PathBuf::from(prefix).join(format!("file {num}.rs"))).collect(); - - let mut set = HashSet::new(); - - paths.iter().for_each(|p| { - set.insert(p.as_path()); - }); - - let probe = PathBuf::from(prefix).join("other"); - - b.iter(|| set.remove(black_box(probe.as_path()))); -} - -#[bench] -fn bench_hash_path_short(b: &mut test::Bencher) { - let mut hasher = DefaultHasher::new(); - let path = Path::new("explorer.exe"); - - b.iter(|| black_box(path).hash(&mut hasher)); - - black_box(hasher.finish()); -} - -#[bench] -fn bench_hash_path_long(b: &mut test::Bencher) { - let mut hasher = DefaultHasher::new(); - let path = - Path::new("/aaaaa/aaaaaa/./../aaaaaaaa/bbbbbbbbbbbbb/ccccccccccc/ddddddddd/eeeeeee.fff"); - - b.iter(|| black_box(path).hash(&mut hasher)); - - black_box(hasher.finish()); -} - #[test] fn clone_to_uninit() { let a = Path::new("hello.txt"); diff --git a/library/std/src/sync/barrier/tests.rs b/library/std/tests/sync/barrier.rs index 0fbcd998812..8aefff9d507 100644 --- a/library/std/src/sync/barrier/tests.rs +++ b/library/std/tests/sync/barrier.rs @@ -1,6 +1,6 @@ -use crate::sync::mpsc::{TryRecvError, channel}; -use crate::sync::{Arc, Barrier}; -use crate::thread; +use std::sync::mpsc::{TryRecvError, channel}; +use std::sync::{Arc, Barrier}; +use std::thread; #[test] #[cfg_attr(any(target_os = "emscripten", target_os = "wasi"), ignore)] // no threads diff --git a/library/std/src/sync/poison/condvar/tests.rs b/library/std/tests/sync/condvar.rs index f9e9066bc92..834de6bb1c2 100644 --- a/library/std/src/sync/poison/condvar/tests.rs +++ b/library/std/tests/sync/condvar.rs @@ -1,8 +1,8 @@ -use crate::sync::atomic::{AtomicBool, Ordering}; -use crate::sync::mpsc::channel; -use crate::sync::{Arc, Condvar, Mutex}; -use crate::thread; -use crate::time::Duration; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::channel; +use std::sync::{Arc, Condvar, Mutex}; +use std::thread; +use std::time::Duration; #[test] fn smoke() { diff --git a/library/std/src/sync/lazy_lock/tests.rs b/library/std/tests/sync/lazy_lock.rs index 7d7dde54349..6c14b79f2ce 100644 --- a/library/std/src/sync/lazy_lock/tests.rs +++ b/library/std/tests/sync/lazy_lock.rs @@ -1,8 +1,8 @@ -use crate::cell::LazyCell; -use crate::sync::atomic::AtomicUsize; -use crate::sync::atomic::Ordering::SeqCst; -use crate::sync::{LazyLock, Mutex, OnceLock}; -use crate::{panic, thread}; +use std::cell::LazyCell; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering::SeqCst; +use std::sync::{LazyLock, Mutex, OnceLock}; +use std::{panic, thread}; fn spawn_and_wait<R: Send + 'static>(f: impl FnOnce() -> R + Send + 'static) -> R { thread::spawn(f).join().unwrap() @@ -149,7 +149,7 @@ fn is_sync_send() { #[should_panic = "has previously been poisoned"] fn lazy_force_mut_panic() { let mut lazy = LazyLock::<String>::new(|| panic!()); - crate::panic::catch_unwind(crate::panic::AssertUnwindSafe(|| { + panic::catch_unwind(panic::AssertUnwindSafe(|| { let _ = LazyLock::force_mut(&mut lazy); })) .unwrap_err(); diff --git a/library/std/tests/sync/lib.rs b/library/std/tests/sync/lib.rs new file mode 100644 index 00000000000..51190f0894f --- /dev/null +++ b/library/std/tests/sync/lib.rs @@ -0,0 +1,31 @@ +#![feature(lazy_get)] +#![feature(mapped_lock_guards)] +#![feature(mpmc_channel)] +#![feature(once_cell_try)] +#![feature(lock_value_accessors)] +#![feature(reentrant_lock)] +#![feature(rwlock_downgrade)] +#![feature(std_internals)] +#![allow(internal_features)] + +mod barrier; +mod condvar; +mod lazy_lock; +#[cfg(not(any(target_os = "emscripten", target_os = "wasi")))] +mod mpmc; +#[cfg(not(any(target_os = "emscripten", target_os = "wasi")))] +mod mpsc; +#[cfg(not(any(target_os = "emscripten", target_os = "wasi")))] +mod mpsc_sync; +#[cfg(not(any(target_os = "emscripten", target_os = "wasi")))] +mod mutex; +#[cfg(not(any(target_os = "emscripten", target_os = "wasi")))] +mod once; +mod once_lock; +#[cfg(not(any(target_os = "emscripten", target_os = "wasi")))] +mod reentrant_lock; +#[cfg(not(any(target_os = "emscripten", target_os = "wasi")))] +mod rwlock; + +#[path = "../common/mod.rs"] +mod common; diff --git a/library/std/src/sync/mpmc/tests.rs b/library/std/tests/sync/mpmc.rs index ab14050df6c..81b92297f76 100644 --- a/library/std/src/sync/mpmc/tests.rs +++ b/library/std/tests/sync/mpmc.rs @@ -1,5 +1,6 @@ -use super::*; -use crate::{env, thread}; +use std::sync::mpmc::*; +use std::time::{Duration, Instant}; +use std::{env, thread}; pub fn stress_factor() -> usize { match env::var("RUST_TEST_STRESS") { diff --git a/library/std/src/sync/mpsc/tests.rs b/library/std/tests/sync/mpsc.rs index 13892fa0d18..1d8edfde44b 100644 --- a/library/std/src/sync/mpsc/tests.rs +++ b/library/std/tests/sync/mpsc.rs @@ -1,5 +1,6 @@ -use super::*; -use crate::{env, thread}; +use std::sync::mpsc::*; +use std::time::{Duration, Instant}; +use std::{env, thread}; pub fn stress_factor() -> usize { match env::var("RUST_TEST_STRESS") { diff --git a/library/std/src/sync/mpsc/sync_tests.rs b/library/std/tests/sync/mpsc_sync.rs index 49b65c8efe6..a7f326d201b 100644 --- a/library/std/src/sync/mpsc/sync_tests.rs +++ b/library/std/tests/sync/mpsc_sync.rs @@ -1,7 +1,8 @@ -use super::*; -use crate::rc::Rc; -use crate::sync::mpmc::SendTimeoutError; -use crate::{env, thread}; +use std::rc::Rc; +use std::sync::mpmc::SendTimeoutError; +use std::sync::mpsc::*; +use std::time::Duration; +use std::{env, thread}; pub fn stress_factor() -> usize { match env::var("RUST_TEST_STRESS") { diff --git a/library/std/src/sync/poison/mutex/tests.rs b/library/std/tests/sync/mutex.rs index 395c8aada08..74c62720107 100644 --- a/library/std/src/sync/poison/mutex/tests.rs +++ b/library/std/tests/sync/mutex.rs @@ -1,10 +1,10 @@ -use crate::fmt::Debug; -use crate::ops::FnMut; -use crate::panic::{self, AssertUnwindSafe}; -use crate::sync::atomic::{AtomicUsize, Ordering}; -use crate::sync::mpsc::channel; -use crate::sync::{Arc, Condvar, MappedMutexGuard, Mutex, MutexGuard, TryLockError}; -use crate::{hint, mem, thread}; +use std::fmt::Debug; +use std::ops::FnMut; +use std::panic::{self, AssertUnwindSafe}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::mpsc::channel; +use std::sync::{Arc, Condvar, MappedMutexGuard, Mutex, MutexGuard, TryLockError}; +use std::{hint, mem, thread}; struct Packet<T>(Arc<(Mutex<T>, Condvar)>); diff --git a/library/std/src/sync/poison/once/tests.rs b/library/std/tests/sync/once.rs index ce96468aeb6..a3ffc73fe06 100644 --- a/library/std/src/sync/poison/once/tests.rs +++ b/library/std/tests/sync/once.rs @@ -1,9 +1,9 @@ -use super::Once; -use crate::sync::atomic::AtomicBool; -use crate::sync::atomic::Ordering::Relaxed; -use crate::sync::mpsc::channel; -use crate::time::Duration; -use crate::{panic, thread}; +use std::sync::Once; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering::Relaxed; +use std::sync::mpsc::channel; +use std::time::Duration; +use std::{panic, thread}; #[test] fn smoke_once() { diff --git a/library/std/src/sync/once_lock/tests.rs b/library/std/tests/sync/once_lock.rs index 5113d436c3c..ac9aaa8892e 100644 --- a/library/std/src/sync/once_lock/tests.rs +++ b/library/std/tests/sync/once_lock.rs @@ -1,8 +1,8 @@ -use crate::sync::OnceLock; -use crate::sync::atomic::AtomicUsize; -use crate::sync::atomic::Ordering::SeqCst; -use crate::sync::mpsc::channel; -use crate::{panic, thread}; +use std::sync::OnceLock; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering::SeqCst; +use std::sync::mpsc::channel; +use std::{panic, thread}; fn spawn_and_wait<R: Send + 'static>(f: impl FnOnce() -> R + Send + 'static) -> R { thread::spawn(f).join().unwrap() @@ -34,15 +34,6 @@ fn sync_once_cell_get_mut() { } #[test] -fn sync_once_cell_get_unchecked() { - let c = OnceLock::new(); - c.set(92).unwrap(); - unsafe { - assert_eq!(c.get_unchecked(), &92); - } -} - -#[test] #[cfg_attr(any(target_os = "emscripten", target_os = "wasi"), ignore)] // no threads fn sync_once_cell_drop() { static DROP_CNT: AtomicUsize = AtomicUsize::new(0); @@ -88,7 +79,6 @@ fn get_or_try_init() { let res = panic::catch_unwind(|| cell.get_or_try_init(|| -> Result<_, ()> { panic!() })); assert!(res.is_err()); - assert!(!cell.is_initialized()); assert!(cell.get().is_none()); assert_eq!(cell.get_or_try_init(|| Err(())), Err(())); @@ -174,7 +164,7 @@ fn sync_once_cell_does_not_leak_partially_constructed_boxes() { break; } #[cfg(target_env = "sgx")] - crate::thread::yield_now(); + std::thread::yield_now(); } }); } diff --git a/library/std/src/sync/reentrant_lock/tests.rs b/library/std/tests/sync/reentrant_lock.rs index aeef0289d28..2b7b87e3623 100644 --- a/library/std/src/sync/reentrant_lock/tests.rs +++ b/library/std/tests/sync/reentrant_lock.rs @@ -1,7 +1,6 @@ -use super::ReentrantLock; -use crate::cell::RefCell; -use crate::sync::Arc; -use crate::thread; +use std::cell::RefCell; +use std::sync::{Arc, ReentrantLock}; +use std::thread; #[test] fn smoke() { diff --git a/library/std/src/sync/poison/rwlock/tests.rs b/library/std/tests/sync/rwlock.rs index 057c2f1a5d7..bd4bc7a14bc 100644 --- a/library/std/src/sync/poison/rwlock/tests.rs +++ b/library/std/tests/sync/rwlock.rs @@ -1,15 +1,15 @@ -use rand::Rng; - -use crate::fmt::Debug; -use crate::ops::FnMut; -use crate::panic::{self, AssertUnwindSafe}; -use crate::sync::atomic::{AtomicUsize, Ordering}; -use crate::sync::mpsc::channel; -use crate::sync::{ +use std::fmt::Debug; +use std::ops::FnMut; +use std::panic::{self, AssertUnwindSafe}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::mpsc::channel; +use std::sync::{ Arc, MappedRwLockReadGuard, MappedRwLockWriteGuard, RwLock, RwLockReadGuard, RwLockWriteGuard, TryLockError, }; -use crate::{hint, mem, thread}; +use std::{hint, mem, thread}; + +use rand::Rng; #[derive(Eq, PartialEq, Debug)] struct NonCopy(i32); @@ -57,7 +57,7 @@ fn frob() { let tx = tx.clone(); let r = r.clone(); thread::spawn(move || { - let mut rng = crate::test_helpers::test_rng(); + let mut rng = crate::common::test_rng(); for _ in 0..M { if rng.gen_bool(1.0 / (N as f64)) { drop(r.write().unwrap()); @@ -704,7 +704,7 @@ fn test_downgrade_atomic() { // Wait for a good amount of time so that evil threads go to sleep. // Note: this is not strictly necessary... - let eternity = crate::time::Duration::from_millis(42); + let eternity = std::time::Duration::from_millis(42); thread::sleep(eternity); // Once everyone is asleep, set the value to `NEW_VALUE`. diff --git a/library/std/src/thread/local/dynamic_tests.rs b/library/std/tests/thread_local/dynamic_tests.rs index dd180041648..454462b3925 100644 --- a/library/std/src/thread/local/dynamic_tests.rs +++ b/library/std/tests/thread_local/dynamic_tests.rs @@ -1,6 +1,6 @@ -use crate::cell::RefCell; -use crate::collections::HashMap; -use crate::thread_local; +use std::cell::RefCell; +use std::collections::HashMap; +use std::thread_local; #[test] fn smoke() { diff --git a/library/std/tests/thread_local/lib.rs b/library/std/tests/thread_local/lib.rs new file mode 100644 index 00000000000..c5291435425 --- /dev/null +++ b/library/std/tests/thread_local/lib.rs @@ -0,0 +1,4 @@ +#[cfg(not(any(target_os = "emscripten", target_os = "wasi")))] +mod tests; + +mod dynamic_tests; diff --git a/library/std/src/thread/local/tests.rs b/library/std/tests/thread_local/tests.rs index 9d4f52a0921..aa020c2559c 100644 --- a/library/std/src/thread/local/tests.rs +++ b/library/std/tests/thread_local/tests.rs @@ -1,8 +1,8 @@ -use crate::cell::{Cell, UnsafeCell}; -use crate::sync::atomic::{AtomicU8, Ordering}; -use crate::sync::{Arc, Condvar, Mutex}; -use crate::thread::{self, Builder, LocalKey}; -use crate::thread_local; +use std::cell::{Cell, UnsafeCell}; +use std::sync::atomic::{AtomicU8, Ordering}; +use std::sync::{Arc, Condvar, Mutex}; +use std::thread::{self, Builder, LocalKey}; +use std::thread_local; #[derive(Clone, Default)] struct Signal(Arc<(Mutex<bool>, Condvar)>); diff --git a/library/std/src/time/tests.rs b/library/std/tests/time.rs index e88f2d5e806..40709eae37c 100644 --- a/library/std/src/time/tests.rs +++ b/library/std/tests/time.rs @@ -1,9 +1,7 @@ -use core::fmt::Debug; +#![feature(duration_constants)] -#[cfg(not(target_arch = "wasm32"))] -use test::{Bencher, black_box}; - -use super::{Duration, Instant, SystemTime, UNIX_EPOCH}; +use std::fmt::Debug; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; macro_rules! assert_almost_eq { ($a:expr, $b:expr) => {{ @@ -29,10 +27,10 @@ fn instant_monotonic() { #[test] #[cfg(not(target_arch = "wasm32"))] -fn instant_monotonic_concurrent() -> crate::thread::Result<()> { +fn instant_monotonic_concurrent() -> std::thread::Result<()> { let threads: Vec<_> = (0..8) .map(|_| { - crate::thread::spawn(|| { + std::thread::spawn(|| { let mut old = Instant::now(); let count = if cfg!(miri) { 1_000 } else { 5_000_000 }; for _ in 0..count { @@ -229,46 +227,3 @@ fn big_math() { check(instant.checked_add(Duration::from_secs(100)), Instant::checked_sub); check(instant.checked_add(Duration::from_secs(i64::MAX as _)), Instant::checked_sub); } - -macro_rules! bench_instant_threaded { - ($bench_name:ident, $thread_count:expr) => { - #[bench] - #[cfg(not(target_arch = "wasm32"))] - fn $bench_name(b: &mut Bencher) -> crate::thread::Result<()> { - use crate::sync::Arc; - use crate::sync::atomic::{AtomicBool, Ordering}; - - let running = Arc::new(AtomicBool::new(true)); - - let threads: Vec<_> = (0..$thread_count) - .map(|_| { - let flag = Arc::clone(&running); - crate::thread::spawn(move || { - while flag.load(Ordering::Relaxed) { - black_box(Instant::now()); - } - }) - }) - .collect(); - - b.iter(|| { - let a = Instant::now(); - let b = Instant::now(); - assert!(b >= a); - }); - - running.store(false, Ordering::Relaxed); - - for t in threads { - t.join()?; - } - Ok(()) - } - }; -} - -bench_instant_threaded!(instant_contention_01_threads, 0); -bench_instant_threaded!(instant_contention_02_threads, 1); -bench_instant_threaded!(instant_contention_04_threads, 3); -bench_instant_threaded!(instant_contention_08_threads, 7); -bench_instant_threaded!(instant_contention_16_threads, 15); diff --git a/src/bootstrap/src/core/build_steps/check.rs b/src/bootstrap/src/core/build_steps/check.rs index f4a86e26396..21afb031203 100644 --- a/src/bootstrap/src/core/build_steps/check.rs +++ b/src/bootstrap/src/core/build_steps/check.rs @@ -455,6 +455,7 @@ tool_check_step!(Rls { path: "src/tools/rls" }); tool_check_step!(Rustfmt { path: "src/tools/rustfmt" }); tool_check_step!(MiroptTestTools { path: "src/tools/miropt-test-tools" }); tool_check_step!(TestFloatParse { path: "src/etc/test-float-parse" }); +tool_check_step!(FeaturesStatusDump { path: "src/tools/features-status-dump" }); tool_check_step!(Bootstrap { path: "src/bootstrap", default: false }); diff --git a/src/bootstrap/src/core/build_steps/compile.rs b/src/bootstrap/src/core/build_steps/compile.rs index f447d186a52..cd3558ac6a4 100644 --- a/src/bootstrap/src/core/build_steps/compile.rs +++ b/src/bootstrap/src/core/build_steps/compile.rs @@ -339,7 +339,7 @@ fn copy_self_contained_objects( // to using gcc from a glibc-targeting toolchain for linking. // To do that we have to distribute musl startup objects as a part of Rust toolchain // and link with them manually in the self-contained mode. - if target.contains("musl") && !target.contains("unikraft") { + if target.needs_crt_begin_end() { let srcdir = builder.musl_libdir(target).unwrap_or_else(|| { panic!("Target {:?} does not have a \"musl-libdir\" key", target.triple) }); diff --git a/src/bootstrap/src/core/build_steps/llvm.rs b/src/bootstrap/src/core/build_steps/llvm.rs index 3cf25373b89..82779dc6306 100644 --- a/src/bootstrap/src/core/build_steps/llvm.rs +++ b/src/bootstrap/src/core/build_steps/llvm.rs @@ -1295,7 +1295,9 @@ impl Step for CrtBeginEnd { } fn make_run(run: RunConfig<'_>) { - run.builder.ensure(CrtBeginEnd { target: run.target }); + if run.target.needs_crt_begin_end() { + run.builder.ensure(CrtBeginEnd { target: run.target }); + } } /// Build crtbegin.o/crtend.o for musl target. diff --git a/src/bootstrap/src/core/build_steps/run.rs b/src/bootstrap/src/core/build_steps/run.rs index 8513c59808c..167b8a5b168 100644 --- a/src/bootstrap/src/core/build_steps/run.rs +++ b/src/bootstrap/src/core/build_steps/run.rs @@ -311,3 +311,34 @@ impl Step for UnicodeTableGenerator { cmd.run(builder); } } + +#[derive(Debug, PartialOrd, Ord, Clone, Hash, PartialEq, Eq)] +pub struct FeaturesStatusDump; + +impl Step for FeaturesStatusDump { + type Output = (); + const ONLY_HOSTS: bool = true; + + fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { + run.path("src/tools/features-status-dump") + } + + fn make_run(run: RunConfig<'_>) { + run.builder.ensure(FeaturesStatusDump); + } + + fn run(self, builder: &Builder<'_>) { + let mut cmd = builder.tool_cmd(Tool::FeaturesStatusDump); + + cmd.arg("--library-path"); + cmd.arg(builder.src.join("library")); + + cmd.arg("--compiler-path"); + cmd.arg(builder.src.join("compiler")); + + cmd.arg("--output-path"); + cmd.arg(builder.out.join("features-status-dump.json")); + + cmd.run(builder); + } +} diff --git a/src/bootstrap/src/core/build_steps/tool.rs b/src/bootstrap/src/core/build_steps/tool.rs index a0abd439de0..75fac88252b 100644 --- a/src/bootstrap/src/core/build_steps/tool.rs +++ b/src/bootstrap/src/core/build_steps/tool.rs @@ -365,6 +365,7 @@ bootstrap_tool!( RustcPerfWrapper, "src/tools/rustc-perf-wrapper", "rustc-perf-wrapper"; WasmComponentLd, "src/tools/wasm-component-ld", "wasm-component-ld", is_unstable_tool = true, allow_features = "min_specialization"; UnicodeTableGenerator, "src/tools/unicode-table-generator", "unicode-table-generator"; + FeaturesStatusDump, "src/tools/features-status-dump", "features-status-dump"; ); /// These are the submodules that are required for rustbook to work due to diff --git a/src/bootstrap/src/core/builder/cargo.rs b/src/bootstrap/src/core/builder/cargo.rs index f6a03a386d1..2ecab262413 100644 --- a/src/bootstrap/src/core/builder/cargo.rs +++ b/src/bootstrap/src/core/builder/cargo.rs @@ -659,7 +659,10 @@ impl Builder<'_> { // Build proc macros both for the host and the target unless proc-macros are not // supported by the target. if target != compiler.host && cmd_kind != Kind::Check { - let error = command(self.rustc(compiler)) + let mut rustc_cmd = command(self.rustc(compiler)); + self.add_rustc_lib_path(compiler, &mut rustc_cmd); + + let error = rustc_cmd .arg("--target") .arg(target.rustc_target_arg()) .arg("--print=file-names") @@ -667,6 +670,7 @@ impl Builder<'_> { .arg("-") .run_capture(self) .stderr(); + let not_supported = error .lines() .any(|line| line.contains("unsupported crate type `proc-macro`")); diff --git a/src/bootstrap/src/core/builder/mod.rs b/src/bootstrap/src/core/builder/mod.rs index 04a00fde3ab..08421dc1f5b 100644 --- a/src/bootstrap/src/core/builder/mod.rs +++ b/src/bootstrap/src/core/builder/mod.rs @@ -938,6 +938,7 @@ impl<'a> Builder<'a> { check::Bootstrap, check::RunMakeSupport, check::Compiletest, + check::FeaturesStatusDump, ), Kind::Test => describe!( crate::core::build_steps::toolstate::ToolStateCheck, @@ -1089,6 +1090,7 @@ impl<'a> Builder<'a> { run::GenerateWindowsSys, run::GenerateCompletions, run::UnicodeTableGenerator, + run::FeaturesStatusDump, ), Kind::Setup => { describe!(setup::Profile, setup::Hook, setup::Link, setup::Editor) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 98490118f7d..4694dd2ca4e 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -575,6 +575,10 @@ impl TargetSelection { env::var("OSTYPE").is_ok_and(|v| v.to_lowercase().contains("cygwin")) } + pub fn needs_crt_begin_end(&self) -> bool { + self.contains("musl") && !self.contains("unikraft") + } + /// Path to the file defining the custom target, if any. pub fn filepath(&self) -> Option<&Path> { self.file.as_ref().map(Path::new) @@ -700,7 +704,7 @@ trait Merge { impl Merge for TomlConfig { fn merge( &mut self, - TomlConfig { build, install, llvm, rust, dist, target, profile: _, change_id }: Self, + TomlConfig { build, install, llvm, rust, dist, target, profile, change_id }: Self, replace: ReplaceOpt, ) { fn do_merge<T: Merge>(x: &mut Option<T>, y: Option<T>, replace: ReplaceOpt) { @@ -712,7 +716,10 @@ impl Merge for TomlConfig { } } } + self.change_id.inner.merge(change_id.inner, replace); + self.profile.merge(profile, replace); + do_merge(&mut self.build, build, replace); do_merge(&mut self.install, install, replace); do_merge(&mut self.llvm, llvm, replace); @@ -1505,6 +1512,10 @@ impl Config { build.cargo = build.cargo.take().or(std::env::var_os("CARGO").map(|p| p.into())); } + if GitInfo::new(false, &config.src).is_from_tarball() && toml.profile.is_none() { + toml.profile = Some("dist".into()); + } + if let Some(include) = &toml.profile { // Allows creating alias for profile names, allowing // profiles to be renamed while maintaining back compatibility diff --git a/src/ci/docker/scripts/rfl-build.sh b/src/ci/docker/scripts/rfl-build.sh index 8776e0f0be9..3eb85ab215e 100755 --- a/src/ci/docker/scripts/rfl-build.sh +++ b/src/ci/docker/scripts/rfl-build.sh @@ -2,7 +2,7 @@ set -euo pipefail -LINUX_VERSION=v6.13-rc1 +LINUX_VERSION=50e57739141b41f731ab31f8380821c7969f9dc4 # Build rustc, rustdoc, cargo, clippy-driver and rustfmt ../x.py build --stage 2 library rustdoc clippy rustfmt @@ -28,7 +28,7 @@ rm -rf linux || true # Download Linux at a specific commit mkdir -p linux git -C linux init -git -C linux remote add origin https://github.com/Rust-for-Linux/linux.git +git -C linux remote add origin https://github.com/Darksonn/linux.git git -C linux fetch --depth 1 origin ${LINUX_VERSION} git -C linux checkout FETCH_HEAD diff --git a/src/ci/github-actions/jobs.yml b/src/ci/github-actions/jobs.yml index 2bbe3756580..58a9eb69666 100644 --- a/src/ci/github-actions/jobs.yml +++ b/src/ci/github-actions/jobs.yml @@ -558,7 +558,7 @@ auto: SCRIPT: python x.py build --set rust.debug=true opt-dist && PGO_HOST=x86_64-pc-windows-msvc ./build/x86_64-pc-windows-msvc/stage0-tools-bin/opt-dist windows-ci -- python x.py dist bootstrap --include-default-paths DIST_REQUIRE_ALL_TOOLS: 1 CODEGEN_BACKENDS: llvm,cranelift - <<: *job-windows-8c + <<: *job-windows-25-8c - name: dist-i686-msvc env: diff --git a/src/doc/book b/src/doc/book -Subproject fa312a343fbff01bc6cef393e326817f7071981 +Subproject e2fa4316c5a7c0d2499c5d6b799adcfad6ef7a4 diff --git a/src/doc/edition-guide b/src/doc/edition-guide -Subproject 4ed5a1a4a2a7ecc2e529a5baaef04f7bc7917ed +Subproject f56aecc3b036dff16404b525a83b00f911b9bbe diff --git a/src/doc/nomicon b/src/doc/nomicon -Subproject bc2298865544695c63454fc1f9f98a3dc22e994 +Subproject 336f75835a6c0514852cc65aba9a698b699b13c diff --git a/src/doc/reference b/src/doc/reference -Subproject 93b921c7d3213d38d920f7f905a3bec093d2217 +Subproject 4249fb411dd27f945e2881eb0378044b94cee06 diff --git a/src/doc/rust-by-example b/src/doc/rust-by-example -Subproject 054259ed1bf01cdee4309ee764c7e103f6df3de +Subproject 743766929f1e53e72fab74394ae259bbfb4a761 diff --git a/src/doc/rustc/src/platform-support.md b/src/doc/rustc/src/platform-support.md index 8227dfa043e..3b6abdd8483 100644 --- a/src/doc/rustc/src/platform-support.md +++ b/src/doc/rustc/src/platform-support.md @@ -34,9 +34,9 @@ target | notes -------|------- [`aarch64-apple-darwin`](platform-support/apple-darwin.md) | ARM64 macOS (11.0+, Big Sur+) `aarch64-unknown-linux-gnu` | ARM64 Linux (kernel 4.1, glibc 2.17+) -`i686-pc-windows-gnu` | 32-bit MinGW (Windows 10+, Windows Server 2016+) [^x86_32-floats-return-ABI] -`i686-pc-windows-msvc` | 32-bit MSVC (Windows 10+, Windows Server 2016+) [^x86_32-floats-return-ABI] -`i686-unknown-linux-gnu` | 32-bit Linux (kernel 3.2+, glibc 2.17+) [^x86_32-floats-return-ABI] +`i686-pc-windows-gnu` | 32-bit MinGW (Windows 10+, Windows Server 2016+, Pentium 4) [^x86_32-floats-return-ABI] +`i686-pc-windows-msvc` | 32-bit MSVC (Windows 10+, Windows Server 2016+, Pentium 4) [^x86_32-floats-return-ABI] +`i686-unknown-linux-gnu` | 32-bit Linux (kernel 3.2+, glibc 2.17+, Pentium 4) [^x86_32-floats-return-ABI] [`x86_64-apple-darwin`](platform-support/apple-darwin.md) | 64-bit macOS (10.12+, Sierra+) `x86_64-pc-windows-gnu` | 64-bit MinGW (Windows 10+, Windows Server 2016+) `x86_64-pc-windows-msvc` | 64-bit MSVC (Windows 10+, Windows Server 2016+) @@ -162,14 +162,14 @@ target | std | notes [`armv7a-none-eabi`](platform-support/arm-none-eabi.md) | * | Bare Armv7-A [`armv7r-none-eabi`](platform-support/armv7r-none-eabi.md) | * | Bare Armv7-R [`armv7r-none-eabihf`](platform-support/armv7r-none-eabi.md) | * | Bare Armv7-R, hardfloat -`i586-pc-windows-msvc` | * | 32-bit Windows w/o SSE [^x86_32-floats-x87] -`i586-unknown-linux-gnu` | ✓ | 32-bit Linux w/o SSE (kernel 3.2, glibc 2.17) [^x86_32-floats-x87] -`i586-unknown-linux-musl` | ✓ | 32-bit Linux w/o SSE, musl 1.2.3 [^x86_32-floats-x87] -[`i686-linux-android`](platform-support/android.md) | ✓ | 32-bit x86 Android [^x86_32-floats-return-ABI] -[`i686-pc-windows-gnullvm`](platform-support/pc-windows-gnullvm.md) | ✓ | 32-bit x86 MinGW (Windows 10+), LLVM ABI [^x86_32-floats-return-ABI] -[`i686-unknown-freebsd`](platform-support/freebsd.md) | ✓ | 32-bit x86 FreeBSD [^x86_32-floats-return-ABI] -`i686-unknown-linux-musl` | ✓ | 32-bit Linux with musl 1.2.3 [^x86_32-floats-return-ABI] -[`i686-unknown-uefi`](platform-support/unknown-uefi.md) | ? | 32-bit UEFI +`i586-pc-windows-msvc` | * | 32-bit Windows (original Pentium) [^x86_32-floats-x87] +`i586-unknown-linux-gnu` | ✓ | 32-bit Linux (kernel 3.2, glibc 2.17, original Pentium) [^x86_32-floats-x87] +`i586-unknown-linux-musl` | ✓ | 32-bit Linux (musl 1.2.3, original Pentium) [^x86_32-floats-x87] +[`i686-linux-android`](platform-support/android.md) | ✓ | 32-bit x86 Android ([PentiumPro with SSE](https://developer.android.com/ndk/guides/abis.html#x86)) [^x86_32-floats-return-ABI] +[`i686-pc-windows-gnullvm`](platform-support/pc-windows-gnullvm.md) | ✓ | 32-bit x86 MinGW (Windows 10+, Pentium 4), LLVM ABI [^x86_32-floats-return-ABI] +[`i686-unknown-freebsd`](platform-support/freebsd.md) | ✓ | 32-bit x86 FreeBSD (Pentium 4) [^x86_32-floats-return-ABI] +`i686-unknown-linux-musl` | ✓ | 32-bit Linux with musl 1.2.3 (Pentium 4) [^x86_32-floats-return-ABI] +[`i686-unknown-uefi`](platform-support/unknown-uefi.md) | ? (Pentium 4, softfloat) | 32-bit UEFI [`loongarch64-unknown-none`](platform-support/loongarch-none.md) | * | LoongArch64 Bare-metal (LP64D ABI) [`loongarch64-unknown-none-softfloat`](platform-support/loongarch-none.md) | * | LoongArch64 Bare-metal (LP64S ABI) [`nvptx64-nvidia-cuda`](platform-support/nvptx64-nvidia-cuda.md) | * | --emit=asm generates PTX code that [runs on NVIDIA GPUs] @@ -307,15 +307,15 @@ target | std | host | notes `csky-unknown-linux-gnuabiv2hf` | ✓ | | C-SKY abiv2 Linux, hardfloat (little endian) [`hexagon-unknown-linux-musl`](platform-support/hexagon-unknown-linux-musl.md) | ✓ | | Hexagon Linux with musl 1.2.3 [`hexagon-unknown-none-elf`](platform-support/hexagon-unknown-none-elf.md)| * | | Bare Hexagon (v60+, HVX) -[`i386-apple-ios`](platform-support/apple-ios.md) | ✓ | | 32-bit x86 iOS [^x86_32-floats-return-ABI] -[`i586-pc-nto-qnx700`](platform-support/nto-qnx.md) | * | | 32-bit x86 QNX Neutrino 7.0 RTOS [^x86_32-floats-return-ABI] -[`i586-unknown-netbsd`](platform-support/netbsd.md) | ✓ | | 32-bit x86, restricted to Pentium -[`i686-apple-darwin`](platform-support/apple-darwin.md) | ✓ | ✓ | 32-bit macOS (10.12+, Sierra+) [^x86_32-floats-return-ABI] -`i686-unknown-haiku` | ✓ | ✓ | 32-bit Haiku [^x86_32-floats-return-ABI] -[`i686-unknown-hurd-gnu`](platform-support/hurd.md) | ✓ | ✓ | 32-bit GNU/Hurd [^x86_32-floats-return-ABI] -[`i686-unknown-netbsd`](platform-support/netbsd.md) | ✓ | ✓ | NetBSD/i386 with SSE2 [^x86_32-floats-return-ABI] -[`i686-unknown-openbsd`](platform-support/openbsd.md) | ✓ | ✓ | 32-bit OpenBSD [^x86_32-floats-return-ABI] -[`i686-unknown-redox`](platform-support/redox.md) | ✓ | | i686 Redox OS +[`i386-apple-ios`](platform-support/apple-ios.md) | ✓ | | 32-bit x86 iOS (Penryn) [^x86_32-floats-return-ABI] +[`i586-pc-nto-qnx700`](platform-support/nto-qnx.md) | * | | 32-bit x86 QNX Neutrino 7.0 RTOS (Pentium 4) [^x86_32-floats-return-ABI] +[`i586-unknown-netbsd`](platform-support/netbsd.md) | ✓ | | 32-bit x86 (original Pentium) [^x86_32-floats-x87] +[`i686-apple-darwin`](platform-support/apple-darwin.md) | ✓ | ✓ | 32-bit macOS (10.12+, Sierra+, Penryn) [^x86_32-floats-return-ABI] +`i686-unknown-haiku` | ✓ | ✓ | 32-bit Haiku (Pentium 4) [^x86_32-floats-return-ABI] +[`i686-unknown-hurd-gnu`](platform-support/hurd.md) | ✓ | ✓ | 32-bit GNU/Hurd (PentiumPro) [^x86_32-floats-x87] +[`i686-unknown-netbsd`](platform-support/netbsd.md) | ✓ | ✓ | NetBSD/i386 (Pentium 4) [^x86_32-floats-return-ABI] +[`i686-unknown-openbsd`](platform-support/openbsd.md) | ✓ | ✓ | 32-bit OpenBSD (Pentium 4) [^x86_32-floats-return-ABI] +[`i686-unknown-redox`](platform-support/redox.md) | ✓ | | i686 Redox OS (PentiumPro) [^x86_32-floats-x87] `i686-uwp-windows-gnu` | ✓ | | [^x86_32-floats-return-ABI] [`i686-uwp-windows-msvc`](platform-support/uwp-windows-msvc.md) | ✓ | | [^x86_32-floats-return-ABI] [`i686-win7-windows-gnu`](platform-support/win7-windows-gnu.md) | ✓ | | 32-bit Windows 7 support [^x86_32-floats-return-ABI] diff --git a/src/doc/unstable-book/src/language-features/new-range.md b/src/doc/unstable-book/src/language-features/new-range.md new file mode 100644 index 00000000000..e7464f31e53 --- /dev/null +++ b/src/doc/unstable-book/src/language-features/new-range.md @@ -0,0 +1,9 @@ +# `new_range` + +The tracking issue for this feature is: [#123741] + +[#123741]: https://github.com/rust-lang/rust/issues/123741 + +--- + +Switch the syntaxes `a..`, `a..b`, and `a..=b` to resolve the new range types. diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 7853e311a04..55bd7da8816 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1104,17 +1104,29 @@ fn clean_args_from_types_and_names<'tcx>( types: &[hir::Ty<'tcx>], names: &[Ident], ) -> Arguments { + fn nonempty_name(ident: &Ident) -> Option<Symbol> { + if ident.name == kw::Underscore || ident.name == kw::Empty { + None + } else { + Some(ident.name) + } + } + + // If at least one argument has a name, use `_` as the name of unnamed + // arguments. Otherwise omit argument names. + let default_name = if names.iter().any(|ident| nonempty_name(ident).is_some()) { + kw::Underscore + } else { + kw::Empty + }; + Arguments { values: types .iter() .enumerate() .map(|(i, ty)| Argument { type_: clean_ty(ty, cx), - name: names - .get(i) - .map(|ident| ident.name) - .filter(|ident| !ident.is_empty()) - .unwrap_or(kw::Underscore), + name: names.get(i).and_then(nonempty_name).unwrap_or(default_name), is_const: false, }) .collect(), @@ -1934,7 +1946,7 @@ fn can_elide_trait_object_lifetime_bound<'tcx>( preds: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>, tcx: TyCtxt<'tcx>, ) -> bool { - // Below we quote extracts from https://doc.rust-lang.org/reference/lifetime-elision.html#default-trait-object-lifetimes + // Below we quote extracts from https://doc.rust-lang.org/stable/reference/lifetime-elision.html#default-trait-object-lifetimes // > If the trait object is used as a type argument of a generic type then the containing type is // > first used to try to infer a bound. diff --git a/src/librustdoc/clean/utils.rs b/src/librustdoc/clean/utils.rs index 0b4fd9c2258..f1921b90cc6 100644 --- a/src/librustdoc/clean/utils.rs +++ b/src/librustdoc/clean/utils.rs @@ -588,9 +588,9 @@ pub(crate) fn attrs_have_doc_flag<'a>( /// so that the channel is consistent. /// /// Set by `bootstrap::Builder::doc_rust_lang_org_channel` in order to keep tests passing on beta/stable. -pub(crate) const DOC_RUST_LANG_ORG_CHANNEL: &str = env!("DOC_RUST_LANG_ORG_CHANNEL"); -pub(crate) static DOC_CHANNEL: Lazy<&'static str> = - Lazy::new(|| DOC_RUST_LANG_ORG_CHANNEL.rsplit('/').find(|c| !c.is_empty()).unwrap()); +pub(crate) const DOC_RUST_LANG_ORG_VERSION: &str = env!("DOC_RUST_LANG_ORG_CHANNEL"); +pub(crate) static RUSTDOC_VERSION: Lazy<&'static str> = + Lazy::new(|| DOC_RUST_LANG_ORG_VERSION.rsplit('/').find(|c| !c.is_empty()).unwrap()); /// Render a sequence of macro arms in a format suitable for displaying to the user /// as part of an item declaration. diff --git a/src/librustdoc/config.rs b/src/librustdoc/config.rs index cfba7895208..c6fb70eee08 100644 --- a/src/librustdoc/config.rs +++ b/src/librustdoc/config.rs @@ -9,8 +9,8 @@ use rustc_data_structures::fx::FxIndexMap; use rustc_errors::DiagCtxtHandle; use rustc_session::config::{ self, CodegenOptions, CrateType, ErrorOutputType, Externs, Input, JsonUnusedExterns, - UnstableOptions, get_cmd_lint_options, nightly_options, parse_crate_types_from_list, - parse_externs, parse_target_triple, + OptionsTargetModifiers, UnstableOptions, get_cmd_lint_options, nightly_options, + parse_crate_types_from_list, parse_externs, parse_target_triple, }; use rustc_session::lint::Level; use rustc_session::search_paths::SearchPath; @@ -389,8 +389,9 @@ impl Options { config::parse_error_format(early_dcx, matches, color, json_color, json_rendered); let diagnostic_width = matches.opt_get("diagnostic-width").unwrap_or_default(); - let codegen_options = CodegenOptions::build(early_dcx, matches); - let unstable_opts = UnstableOptions::build(early_dcx, matches); + let mut target_modifiers = BTreeMap::<OptionsTargetModifiers, String>::new(); + let codegen_options = CodegenOptions::build(early_dcx, matches, &mut target_modifiers); + let unstable_opts = UnstableOptions::build(early_dcx, matches, &mut target_modifiers); let remap_path_prefix = match parse_remap_path_prefix(matches) { Ok(prefix_mappings) => prefix_mappings, diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs index a072b1256f4..6af35157a43 100644 --- a/src/librustdoc/core.rs +++ b/src/librustdoc/core.rs @@ -387,7 +387,7 @@ pub(crate) fn run_global_ctxt( let help = format!( "The following guide may be of use:\n\ {}/rustdoc/how-to-write-documentation.html", - crate::DOC_RUST_LANG_ORG_CHANNEL + crate::DOC_RUST_LANG_ORG_VERSION ); tcx.node_lint( crate::lint::MISSING_CRATE_LEVEL_DOCS, diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 20a8dc72491..ffd457c8273 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -1408,7 +1408,9 @@ impl clean::Arguments { ) -> impl Display + 'a + Captures<'tcx> { fmt::from_fn(move |f| { for (i, input) in self.values.iter().enumerate() { - write!(f, "{}: ", input.name)?; + if !input.name.is_empty() { + write!(f, "{}: ", input.name)?; + } input.type_.print(cx).fmt(f)?; if i + 1 < self.values.len() { write!(f, ", ")?; diff --git a/src/librustdoc/html/layout.rs b/src/librustdoc/html/layout.rs index b4bc0b80d6c..d957cf1b569 100644 --- a/src/librustdoc/html/layout.rs +++ b/src/librustdoc/html/layout.rs @@ -112,7 +112,7 @@ pub(crate) fn render<T: Print, S: Print>( display_krate_with_trailing_slash, display_krate_version_number, display_krate_version_extra, - rust_channel: *crate::clean::utils::DOC_CHANNEL, + rust_channel: *crate::clean::utils::RUSTDOC_VERSION, rustdoc_version, } .render() diff --git a/src/librustdoc/html/render/context.rs b/src/librustdoc/html/render/context.rs index 5d96dbc0ee6..1cefdf96bbc 100644 --- a/src/librustdoc/html/render/context.rs +++ b/src/librustdoc/html/render/context.rs @@ -32,7 +32,7 @@ use crate::html::render::write_shared::write_shared; use crate::html::url_parts_builder::UrlPartsBuilder; use crate::html::{layout, sources, static_files}; use crate::scrape_examples::AllCallLocations; -use crate::try_err; +use crate::{DOC_RUST_LANG_ORG_VERSION, try_err}; /// Major driving force in all rustdoc rendering. This contains information /// about where in the tree-like hierarchy rendering is occurring and controls @@ -730,7 +730,7 @@ impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> { <noscript>\ <section>\ <p>You need to enable JavaScript to use keyboard commands or search.</p>\ - <p>For more information, browse the <a href=\"https://doc.rust-lang.org/rustdoc/\">rustdoc handbook</a>.</p>\ + <p>For more information, browse the <a href=\"{DOC_RUST_LANG_ORG_VERSION}/rustdoc/\">rustdoc handbook</a>.</p>\ </section>\ </noscript>", ) diff --git a/src/librustdoc/html/render/mod.rs b/src/librustdoc/html/render/mod.rs index a27a9d202eb..f7dcb87e4f3 100644 --- a/src/librustdoc/html/render/mod.rs +++ b/src/librustdoc/html/render/mod.rs @@ -79,7 +79,7 @@ use crate::html::markdown::{ use crate::html::static_files::SCRAPE_EXAMPLES_HELP_MD; use crate::html::{highlight, sources}; use crate::scrape_examples::{CallData, CallLocation}; -use crate::{DOC_RUST_LANG_ORG_CHANNEL, try_none}; +use crate::{DOC_RUST_LANG_ORG_VERSION, try_none}; pub(crate) fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ { fmt::from_fn(move |f| { @@ -480,7 +480,7 @@ fn scrape_examples_help(shared: &SharedContext<'_>) -> String { content.push_str(&format!( "## More information\n\n\ If you want more information about this feature, please read the [corresponding chapter in \ - the Rustdoc book]({DOC_RUST_LANG_ORG_CHANNEL}/rustdoc/scraped-examples.html)." + the Rustdoc book]({DOC_RUST_LANG_ORG_VERSION}/rustdoc/scraped-examples.html)." )); let mut ids = IdMap::default(); diff --git a/src/librustdoc/html/render/print_item.rs b/src/librustdoc/html/render/print_item.rs index 37fea09ace3..c50adf11616 100644 --- a/src/librustdoc/html/render/print_item.rs +++ b/src/librustdoc/html/render/print_item.rs @@ -924,7 +924,7 @@ fn item_trait(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Tra <a href=\"{base}/reference/items/traits.html#dyn-compatibility\">dyn compatible</a>.</p>\ <p><i>In older versions of Rust, dyn compatibility was called \"object safety\", \ so this trait is not object safe.</i></p></div>", - base = crate::clean::utils::DOC_RUST_LANG_ORG_CHANNEL + base = crate::clean::utils::DOC_RUST_LANG_ORG_VERSION ), ); } diff --git a/src/librustdoc/html/static/js/main.js b/src/librustdoc/html/static/js/main.js index ccf4002bb30..bfd5cb7764f 100644 --- a/src/librustdoc/html/static/js/main.js +++ b/src/librustdoc/html/static/js/main.js @@ -1534,10 +1534,10 @@ function preLoadCss(cssUrl) { function buildHelpMenu() { const book_info = document.createElement("span"); - const channel = getVar("channel"); + const drloChannel = `https://doc.rust-lang.org/${getVar("channel")}`; book_info.className = "top"; book_info.innerHTML = `You can find more information in \ -<a href="https://doc.rust-lang.org/${channel}/rustdoc/">the rustdoc book</a>.`; +<a href="${drloChannel}/rustdoc/">the rustdoc book</a>.`; const shortcuts = [ ["?", "Show this help dialog"], @@ -1557,8 +1557,8 @@ function preLoadCss(cssUrl) { div_shortcuts.innerHTML = "<h2>Keyboard Shortcuts</h2><dl>" + shortcuts + "</dl></div>"; const infos = [ - `For a full list of all search features, take a look <a \ -href="https://doc.rust-lang.org/${channel}/rustdoc/read-documentation/search.html">here</a>.`, + `For a full list of all search features, take a look \ + <a href="${drloChannel}/rustdoc/read-documentation/search.html">here</a>.`, "Prefix searches with a type followed by a colon (e.g., <code>fn:</code>) to \ restrict the search to a given item kind.", "Accepted kinds are: <code>fn</code>, <code>mod</code>, <code>struct</code>, \ @@ -1568,10 +1568,10 @@ href="https://doc.rust-lang.org/${channel}/rustdoc/read-documentation/search.htm <code>-> vec</code> or <code>String, enum:Cow -> bool</code>)", "You can look for items with an exact name by putting double quotes around \ your request: <code>\"string\"</code>", - "Look for functions that accept or return \ - <a href=\"https://doc.rust-lang.org/std/primitive.slice.html\">slices</a> and \ - <a href=\"https://doc.rust-lang.org/std/primitive.array.html\">arrays</a> by writing \ - square brackets (e.g., <code>-> [u8]</code> or <code>[] -> Option</code>)", + `Look for functions that accept or return \ + <a href="${drloChannel}/std/primitive.slice.html">slices</a> and \ + <a href="${drloChannel}/std/primitive.array.html">arrays</a> by writing square \ + brackets (e.g., <code>-> [u8]</code> or <code>[] -> Option</code>)`, "Look for items inside another one by searching for a path: <code>vec::Vec</code>", ].map(x => "<p>" + x + "</p>").join(""); const div_infos = document.createElement("div"); diff --git a/src/librustdoc/html/static/js/search.js b/src/librustdoc/html/static/js/search.js index 1ad32721e06..662e9510699 100644 --- a/src/librustdoc/html/static/js/search.js +++ b/src/librustdoc/html/static/js/search.js @@ -1,5 +1,5 @@ // ignore-tidy-filelength -/* global addClass, getNakedUrl, getSettingValue */ +/* global addClass, getNakedUrl, getSettingValue, getVar */ /* global onEachLazy, removeClass, searchState, browserSupportsHistoryApi, exports */ "use strict"; @@ -4923,17 +4923,18 @@ ${item.displayPath}<span class="${type}">${name}</span>\ } }); } else if (query.error === null) { + const dlroChannel = `https://doc.rust-lang.org/${getVar("channel")}`; output.className = "search-failed" + extraClass; output.innerHTML = "No results :(<br/>" + "Try on <a href=\"https://duckduckgo.com/?q=" + encodeURIComponent("rust " + query.userQuery) + "\">DuckDuckGo</a>?<br/><br/>" + "Or try looking in one of these:<ul><li>The <a " + - "href=\"https://doc.rust-lang.org/reference/index.html\">Rust Reference</a> " + + `href="${dlroChannel}/reference/index.html">Rust Reference</a> ` + " for technical details about the language.</li><li><a " + - "href=\"https://doc.rust-lang.org/rust-by-example/index.html\">Rust By " + + `href="${dlroChannel}/rust-by-example/index.html">Rust By ` + "Example</a> for expository code examples.</a></li><li>The <a " + - "href=\"https://doc.rust-lang.org/book/index.html\">Rust Book</a> for " + + `href="${dlroChannel}/book/index.html">Rust Book</a> for ` + "introductions to language features and the language itself.</li><li><a " + "href=\"https://docs.rs\">Docs.rs</a> for documentation of crates released on" + " <a href=\"https://crates.io/\">crates.io</a>.</li></ul>"; diff --git a/src/librustdoc/html/templates/type_layout.html b/src/librustdoc/html/templates/type_layout.html index 9c62826ccc2..0034552bdd3 100644 --- a/src/librustdoc/html/templates/type_layout.html +++ b/src/librustdoc/html/templates/type_layout.html @@ -10,7 +10,7 @@ unstable</strong> and may even differ between compilations. {#+ #} The only exception is types with certain <code>repr(...)</code> {#+ #} attributes. Please see the Rust Reference's {#+ #} - <a href="https://doc.rust-lang.org/reference/type-layout.html">“Type Layout”</a> {#+ #} + <a href="{{ crate::DOC_RUST_LANG_ORG_VERSION }}/reference/type-layout.html">“Type Layout”</a> {#+ #} chapter for details on type layout guarantees. {# #} </p> {# #} </div> {# #} diff --git a/src/librustdoc/html/templates/type_layout_size.html b/src/librustdoc/html/templates/type_layout_size.html index 9c2b39edc9f..5256b6c8f2a 100644 --- a/src/librustdoc/html/templates/type_layout_size.html +++ b/src/librustdoc/html/templates/type_layout_size.html @@ -7,6 +7,6 @@ {{ size +}} bytes {% endif %} {% if is_uninhabited %} - {# +#} (<a href="https://doc.rust-lang.org/stable/reference/glossary.html#uninhabited">uninhabited</a>) + {# +#} (<a href="{{ crate::DOC_RUST_LANG_ORG_VERSION }}/reference/glossary.html#uninhabited">uninhabited</a>) {% endif %} {% endif %} diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index af225c9d68d..96ef400d903 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -82,7 +82,7 @@ use rustc_session::config::{ErrorOutputType, RustcOptGroup, make_crate_type_opti use rustc_session::{EarlyDiagCtxt, getopts}; use tracing::info; -use crate::clean::utils::DOC_RUST_LANG_ORG_CHANNEL; +use crate::clean::utils::DOC_RUST_LANG_ORG_VERSION; /// A macro to create a FxHashMap. /// @@ -709,7 +709,7 @@ fn usage(argv0: &str) { println!("{}", options.usage(&format!("{argv0} [options] <input>"))); println!(" @path Read newline separated options from `path`\n"); println!( - "More information available at {DOC_RUST_LANG_ORG_CHANNEL}/rustdoc/what-is-rustdoc.html", + "More information available at {DOC_RUST_LANG_ORG_VERSION}/rustdoc/what-is-rustdoc.html", ); } diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs index a777b45b807..9fe8b99e8af 100644 --- a/src/librustdoc/passes/collect_intra_doc_links.rs +++ b/src/librustdoc/passes/collect_intra_doc_links.rs @@ -2168,7 +2168,7 @@ fn disambiguator_error( report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, &diag_info, |diag, _sp, _link_range| { let msg = format!( "see {}/rustdoc/write-documentation/linking-to-items-by-name.html#namespaces-and-disambiguators for more info about disambiguators", - crate::DOC_RUST_LANG_ORG_CHANNEL + crate::DOC_RUST_LANG_ORG_VERSION ); diag.note(msg); }); diff --git a/src/tools/compiletest/src/header.rs b/src/tools/compiletest/src/header.rs index 8c96554738e..452a2e9a9d5 100644 --- a/src/tools/compiletest/src/header.rs +++ b/src/tools/compiletest/src/header.rs @@ -882,14 +882,6 @@ fn iter_header( } let ln = ln.trim(); - // Assume that any directives will be found before the first module or function. This - // doesn't seem to be an optimization with a warm page cache. Maybe with a cold one. - // FIXME(jieyouxu): this will cause `//@` directives in the rest of the test file to - // not be checked. - if ln.starts_with("fn") || ln.starts_with("mod") { - return; - } - let Some(directive_line) = line_directive(line_number, comment, ln) else { continue; }; diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index ca48abda5fc..0e2da2b02ca 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -1417,9 +1417,7 @@ impl<'test> TestCx<'test> { } fn is_rustdoc(&self) -> bool { - self.config.src_base.ends_with("rustdoc-ui") - || self.config.src_base.ends_with("rustdoc-js") - || self.config.src_base.ends_with("rustdoc-json") + matches!(self.config.suite.as_str(), "rustdoc-ui" | "rustdoc-js" | "rustdoc-json") } fn get_mir_dump_dir(&self) -> PathBuf { diff --git a/src/tools/compiletest/src/runtest/rustdoc_json.rs b/src/tools/compiletest/src/runtest/rustdoc_json.rs index 31fdb0a5d13..bf7eb2e109a 100644 --- a/src/tools/compiletest/src/runtest/rustdoc_json.rs +++ b/src/tools/compiletest/src/runtest/rustdoc_json.rs @@ -16,13 +16,12 @@ impl TestCx<'_> { self.fatal_proc_rec("rustdoc failed!", &proc_res); } - let root = self.config.find_rust_src_root().unwrap(); let mut json_out = out_dir.join(self.testpaths.file.file_stem().unwrap()); json_out.set_extension("json"); let res = self.run_command_to_procres( Command::new(self.config.jsondocck_path.as_ref().unwrap()) .arg("--doc-dir") - .arg(root.join(&out_dir)) + .arg(&out_dir) .arg("--template") .arg(&self.testpaths.file), ); diff --git a/src/tools/features-status-dump/Cargo.toml b/src/tools/features-status-dump/Cargo.toml new file mode 100644 index 00000000000..35be71a46e5 --- /dev/null +++ b/src/tools/features-status-dump/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "features-status-dump" +version = "0.1.0" +license = "MIT OR Apache-2.0" +edition = "2021" + +[dependencies] +anyhow = { version = "1", features = ["backtrace"] } +clap = { version = "4", features = ["derive"] } +serde = { version = "1.0.125", features = [ "derive" ] } +serde_json = "1.0.59" +tidy = { path = "../tidy", features = ["build-metrics"] } diff --git a/src/tools/features-status-dump/src/main.rs b/src/tools/features-status-dump/src/main.rs new file mode 100644 index 00000000000..1ce98d1506d --- /dev/null +++ b/src/tools/features-status-dump/src/main.rs @@ -0,0 +1,53 @@ +use std::collections::HashMap; +use std::fs::File; +use std::io::BufWriter; +use std::path::PathBuf; + +use anyhow::{Context, Result}; +use clap::Parser; +use tidy::features::{Feature, collect_lang_features, collect_lib_features}; + +#[derive(Debug, Parser)] +struct Cli { + /// Path to `library/` directory. + #[arg(long)] + library_path: PathBuf, + /// Path to `compiler/` directory. + #[arg(long)] + compiler_path: PathBuf, + /// Path to `output/` directory. + #[arg(long)] + output_path: PathBuf, +} + +#[derive(Debug, serde::Serialize)] +struct FeaturesStatus { + lang_features_status: HashMap<String, Feature>, + lib_features_status: HashMap<String, Feature>, +} + +fn main() -> Result<()> { + let Cli { compiler_path, library_path, output_path } = Cli::parse(); + + let lang_features_status = collect_lang_features(&compiler_path, &mut false); + let lib_features_status = collect_lib_features(&library_path) + .into_iter() + .filter(|&(ref name, _)| !lang_features_status.contains_key(name)) + .collect(); + let features_status = FeaturesStatus { lang_features_status, lib_features_status }; + + let output_dir = output_path.parent().with_context(|| { + format!("failed to get parent dir of output path `{}`", output_path.display()) + })?; + std::fs::create_dir_all(output_dir).with_context(|| { + format!("failed to create output directory at `{}`", output_dir.display()) + })?; + + let output_file = File::create(&output_path).with_context(|| { + format!("failed to create file at given output path `{}`", output_path.display()) + })?; + let writer = BufWriter::new(output_file); + serde_json::to_writer_pretty(writer, &features_status) + .context("failed to write json output")?; + Ok(()) +} diff --git a/src/tools/miri/tests/fail/intrinsics/ptr_offset_from_different_allocs.rs b/src/tools/miri/tests/fail/intrinsics/ptr_offset_from_different_allocs.rs new file mode 100644 index 00000000000..5a997ad8ec4 --- /dev/null +++ b/src/tools/miri/tests/fail/intrinsics/ptr_offset_from_different_allocs.rs @@ -0,0 +1,5 @@ +fn main() { + unsafe { + (&1_u8 as *const u8).offset_from(&2_u8); //~ERROR: not both derived from the same allocation + } +} diff --git a/src/tools/miri/tests/fail/intrinsics/ptr_offset_from_different_allocs.stderr b/src/tools/miri/tests/fail/intrinsics/ptr_offset_from_different_allocs.stderr new file mode 100644 index 00000000000..34d7c6a8021 --- /dev/null +++ b/src/tools/miri/tests/fail/intrinsics/ptr_offset_from_different_allocs.stderr @@ -0,0 +1,15 @@ +error: Undefined Behavior: `ptr_offset_from` called on two different pointers that are not both derived from the same allocation + --> tests/fail/intrinsics/ptr_offset_from_different_allocs.rs:LL:CC + | +LL | (&1_u8 as *const u8).offset_from(&2_u8); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `ptr_offset_from` called on two different pointers that are not both derived from the same allocation + | + = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior + = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information + = note: BACKTRACE: + = note: inside `main` at tests/fail/intrinsics/ptr_offset_from_different_allocs.rs:LL:CC + +note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace + +error: aborting due to 1 previous error + diff --git a/src/tools/miri/tests/fail/intrinsics/ptr_offset_from_different_ints.rs b/src/tools/miri/tests/fail/intrinsics/ptr_offset_from_different_ints.rs index 0acda559d3a..0d34e711ca7 100644 --- a/src/tools/miri/tests/fail/intrinsics/ptr_offset_from_different_ints.rs +++ b/src/tools/miri/tests/fail/intrinsics/ptr_offset_from_different_ints.rs @@ -15,6 +15,6 @@ fn main() { let _ = p1.byte_offset_from(p1); // UB because different pointers. - let _ = p1.byte_offset_from(p2); //~ERROR: no provenance + let _ = p1.byte_offset_from(p2); //~ERROR: not both derived from the same allocation } } diff --git a/src/tools/miri/tests/fail/intrinsics/ptr_offset_from_different_ints.stderr b/src/tools/miri/tests/fail/intrinsics/ptr_offset_from_different_ints.stderr index 7ef66390fcd..897945d6d5d 100644 --- a/src/tools/miri/tests/fail/intrinsics/ptr_offset_from_different_ints.stderr +++ b/src/tools/miri/tests/fail/intrinsics/ptr_offset_from_different_ints.stderr @@ -1,8 +1,8 @@ -error: Undefined Behavior: out-of-bounds `offset_from` origin: expected a pointer to the end of 1 byte of memory, but got 0xb[noalloc] which is a dangling pointer (it has no provenance) +error: Undefined Behavior: `ptr_offset_from` called on two different pointers that are not both derived from the same allocation --> tests/fail/intrinsics/ptr_offset_from_different_ints.rs:LL:CC | LL | let _ = p1.byte_offset_from(p2); - | ^^^^^^^^^^^^^^^^^^^^^^^ out-of-bounds `offset_from` origin: expected a pointer to the end of 1 byte of memory, but got 0xb[noalloc] which is a dangling pointer (it has no provenance) + | ^^^^^^^^^^^^^^^^^^^^^^^ `ptr_offset_from` called on two different pointers that are not both derived from the same allocation | = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information diff --git a/src/tools/miri/tests/fail/intrinsics/ptr_offset_from_oob.rs b/src/tools/miri/tests/fail/intrinsics/ptr_offset_from_oob.rs new file mode 100644 index 00000000000..06f6b7a0117 --- /dev/null +++ b/src/tools/miri/tests/fail/intrinsics/ptr_offset_from_oob.rs @@ -0,0 +1,7 @@ +fn main() { + let mem = [0u8; 1]; + let ptr = mem.as_ptr(); + unsafe { + ptr.wrapping_add(4).offset_from(ptr); //~ERROR: the memory range between them is not in-bounds of an allocation + } +} diff --git a/src/tools/miri/tests/fail/intrinsics/ptr_offset_from_oob.stderr b/src/tools/miri/tests/fail/intrinsics/ptr_offset_from_oob.stderr new file mode 100644 index 00000000000..67df633bef5 --- /dev/null +++ b/src/tools/miri/tests/fail/intrinsics/ptr_offset_from_oob.stderr @@ -0,0 +1,15 @@ +error: Undefined Behavior: `ptr_offset_from` called on two different pointers where the memory range between them is not in-bounds of an allocation + --> tests/fail/intrinsics/ptr_offset_from_oob.rs:LL:CC + | +LL | ptr.wrapping_add(4).offset_from(ptr); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `ptr_offset_from` called on two different pointers where the memory range between them is not in-bounds of an allocation + | + = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior + = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information + = note: BACKTRACE: + = note: inside `main` at tests/fail/intrinsics/ptr_offset_from_oob.rs:LL:CC + +note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace + +error: aborting due to 1 previous error + diff --git a/src/tools/tidy/Cargo.toml b/src/tools/tidy/Cargo.toml index 2f424a482b5..9a4d0891b4a 100644 --- a/src/tools/tidy/Cargo.toml +++ b/src/tools/tidy/Cargo.toml @@ -12,11 +12,15 @@ miropt-test-tools = { path = "../miropt-test-tools" } walkdir = "2" ignore = "0.4.18" semver = "1.0" +serde = { version = "1.0.125", features = ["derive"], optional = true } termcolor = "1.1.3" rustc-hash = "2.0.0" fluent-syntax = "0.11.1" similar = "2.5.0" +[features] +build-metrics = ["dep:serde"] + [[bin]] name = "rust-tidy" path = "src/main.rs" diff --git a/src/tools/tidy/src/features.rs b/src/tools/tidy/src/features.rs index 4f24eb21242..fcd7943e6e0 100644 --- a/src/tools/tidy/src/features.rs +++ b/src/tools/tidy/src/features.rs @@ -27,6 +27,7 @@ const FEATURE_GROUP_START_PREFIX: &str = "// feature-group-start"; const FEATURE_GROUP_END_PREFIX: &str = "// feature-group-end"; #[derive(Debug, PartialEq, Clone)] +#[cfg_attr(feature = "build-metrics", derive(serde::Serialize))] pub enum Status { Accepted, Removed, @@ -45,6 +46,7 @@ impl fmt::Display for Status { } #[derive(Debug, Clone)] +#[cfg_attr(feature = "build-metrics", derive(serde::Serialize))] pub struct Feature { pub level: Status, pub since: Option<Version>, diff --git a/src/tools/tidy/src/features/version.rs b/src/tools/tidy/src/features/version.rs index 0830c226caf..6a902e80f8e 100644 --- a/src/tools/tidy/src/features/version.rs +++ b/src/tools/tidy/src/features/version.rs @@ -8,6 +8,7 @@ mod tests; pub const VERSION_PLACEHOLDER: &str = "CURRENT_RUSTC_VERSION"; #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +#[cfg_attr(feature = "build-metrics", derive(serde::Serialize))] pub enum Version { Explicit { parts: [u32; 3] }, CurrentPlaceholder, diff --git a/src/tools/tidy/src/issues.txt b/src/tools/tidy/src/issues.txt index 839d23fb9a7..17786ed6d2f 100644 --- a/src/tools/tidy/src/issues.txt +++ b/src/tools/tidy/src/issues.txt @@ -3146,7 +3146,6 @@ ui/nll/issue-97997.rs ui/nll/issue-98170.rs ui/nll/issue-98589-closures-relate-named-regions.rs ui/nll/issue-98693.rs -ui/nll/polonius/issue-46589.rs ui/nll/relate_tys/issue-48071.rs ui/nll/ty-outlives/issue-53789-1.rs ui/nll/ty-outlives/issue-53789-2.rs diff --git a/src/tools/tidy/src/pal.rs b/src/tools/tidy/src/pal.rs index c650fd0eec6..c708ff7150c 100644 --- a/src/tools/tidy/src/pal.rs +++ b/src/tools/tidy/src/pal.rs @@ -48,8 +48,9 @@ const EXCEPTION_PATHS: &[&str] = &[ // we must use `#[cfg(windows)]` to conditionally compile the // correct `VaList` structure for windows. "library/core/src/ffi/va_list.rs", - // We placed a linkage against Windows libraries here + // core::ffi contains platform-specific type and linkage configuration "library/core/src/ffi/mod.rs", + "library/core/src/ffi/primitives.rs", "library/std/src/sys", // Platform-specific code for std lives here. "library/std/src/os", // Platform-specific public interfaces // Temporary `std` exceptions diff --git a/tests/assembly/small_data_threshold.rs b/tests/assembly/small_data_threshold.rs index d3ba144600e..bed515915b8 100644 --- a/tests/assembly/small_data_threshold.rs +++ b/tests/assembly/small_data_threshold.rs @@ -58,35 +58,35 @@ static mut Z: u64 = 0; // Currently, only MIPS and RISCV successfully put any objects in the small data // sections so the U/V/W/X tests are skipped on Hexagon and M68K -//@ RISCV: .section .sdata -//@ RISCV-NOT: .section -//@ RISCV: U: -//@ RISCV: .section .sbss -//@ RISCV-NOT: .section -//@ RISCV: V: -//@ RISCV: .section .sdata -//@ RISCV-NOT: .section -//@ RISCV: W: -//@ RISCV: .section .sbss -//@ RISCV-NOT: .section -//@ RISCV: X: +// RISCV: .section .sdata +// RISCV-NOT: .section +// RISCV: U: +// RISCV: .section .sbss +// RISCV-NOT: .section +// RISCV: V: +// RISCV: .section .sdata +// RISCV-NOT: .section +// RISCV: W: +// RISCV: .section .sbss +// RISCV-NOT: .section +// RISCV: X: -//@ MIPS: .section .sdata -//@ MIPS-NOT: .section -//@ MIPS: U: -//@ MIPS: .section .sbss -//@ MIPS-NOT: .section -//@ MIPS: V: -//@ MIPS: .section .sdata -//@ MIPS-NOT: .section -//@ MIPS: W: -//@ MIPS: .section .sbss -//@ MIPS-NOT: .section -//@ MIPS: X: +// MIPS: .section .sdata +// MIPS-NOT: .section +// MIPS: U: +// MIPS: .section .sbss +// MIPS-NOT: .section +// MIPS: V: +// MIPS: .section .sdata +// MIPS-NOT: .section +// MIPS: W: +// MIPS: .section .sbss +// MIPS-NOT: .section +// MIPS: X: -//@ CHECK: .section .data.Y, -//@ CHECK-NOT: .section -//@ CHECK: Y: -//@ CHECK: .section .bss.Z, -//@ CHECK-NOT: .section -//@ CHECK: Z: +// CHECK: .section .data.Y, +// CHECK-NOT: .section +// CHECK: Y: +// CHECK: .section .bss.Z, +// CHECK-NOT: .section +// CHECK: Z: diff --git a/tests/codegen/debug-column.rs b/tests/codegen/debug-column.rs index d14a5c29142..2aa0a8a864c 100644 --- a/tests/codegen/debug-column.rs +++ b/tests/codegen/debug-column.rs @@ -1,6 +1,6 @@ // Verify that debuginfo column numbers are 1-based byte offsets. // -//@ ignore-windows +//@ ignore-msvc //@ compile-flags: -C debuginfo=2 #[rustfmt::skip] diff --git a/tests/codegen/force-no-unwind-tables.rs b/tests/codegen/force-no-unwind-tables.rs index e823bedac0f..1de5e0858e0 100644 --- a/tests/codegen/force-no-unwind-tables.rs +++ b/tests/codegen/force-no-unwind-tables.rs @@ -1,5 +1,5 @@ //@ compile-flags: -C no-prepopulate-passes -C panic=abort -C force-unwind-tables=n -//@ ignore-windows +//@ ignore-windows: unwind tables are required for panics on Windows #![crate_type = "lib"] diff --git a/tests/codegen/thread-local.rs b/tests/codegen/thread-local.rs index 2ee15811cc3..3cd81652f5a 100644 --- a/tests/codegen/thread-local.rs +++ b/tests/codegen/thread-local.rs @@ -1,6 +1,6 @@ //@ compile-flags: -O //@ aux-build:thread_local_aux.rs -//@ ignore-windows FIXME(#84933) +//@ ignore-windows FIXME(#134939) //@ ignore-wasm globals are used instead of thread locals //@ ignore-emscripten globals are used instead of thread locals //@ ignore-android does not use #[thread_local] diff --git a/tests/crashes/132981.rs b/tests/crashes/132981.rs index 8ff4fa36fd0..916c1559240 100644 --- a/tests/crashes/132981.rs +++ b/tests/crashes/132981.rs @@ -2,6 +2,10 @@ //@compile-flags: -Clink-dead-code=true --crate-type lib //@ only-x86_64 //@ ignore-windows +// The set of targets this crashes on is really fiddly, because it is deep in our ABI logic. It +// crashes on x86_64-unknown-linux-gnu, and i686-pc-windows-msvc, but not on +// x86_64-pc-windows-msvc. If you are trying to fix this crash, don't pay too much attention to the +// directives. #![feature(rust_cold_cc)] pub extern "rust-cold" fn foo(_: [usize; 3]) {} diff --git a/tests/crashes/134355.rs b/tests/crashes/134355.rs deleted file mode 100644 index b662341e6b1..00000000000 --- a/tests/crashes/134355.rs +++ /dev/null @@ -1,6 +0,0 @@ -//@ known-bug: #134355 - -//@compile-flags: --crate-type=lib -fn digit() -> str { - return { i32::MIN }; -} diff --git a/tests/mir-opt/pre-codegen/range_iter.inclusive_loop.PreCodegen.after.panic-abort.mir b/tests/mir-opt/pre-codegen/range_iter.inclusive_loop.PreCodegen.after.panic-abort.mir index 60c0b8afa53..3f000dcafb0 100644 --- a/tests/mir-opt/pre-codegen/range_iter.inclusive_loop.PreCodegen.after.panic-abort.mir +++ b/tests/mir-opt/pre-codegen/range_iter.inclusive_loop.PreCodegen.after.panic-abort.mir @@ -19,16 +19,16 @@ fn inclusive_loop(_1: u32, _2: u32, _3: impl Fn(u32)) -> () { scope 2 { debug x => _9; } - scope 5 (inlined iter::range::<impl Iterator for RangeInclusive<u32>>::next) { + scope 5 (inlined iter::range::<impl Iterator for std::ops::RangeInclusive<u32>>::next) { } } - scope 3 (inlined RangeInclusive::<u32>::new) { + scope 3 (inlined std::ops::RangeInclusive::<u32>::new) { } - scope 4 (inlined <RangeInclusive<u32> as IntoIterator>::into_iter) { + scope 4 (inlined <std::ops::RangeInclusive<u32> as IntoIterator>::into_iter) { } bb0: { - _4 = RangeInclusive::<u32> { start: copy _1, end: copy _2, exhausted: const false }; + _4 = std::ops::RangeInclusive::<u32> { start: copy _1, end: copy _2, exhausted: const false }; StorageLive(_5); _5 = copy _4; goto -> bb1; @@ -37,7 +37,7 @@ fn inclusive_loop(_1: u32, _2: u32, _3: impl Fn(u32)) -> () { bb1: { StorageLive(_7); _6 = &mut _5; - _7 = <RangeInclusive<u32> as iter::range::RangeInclusiveIteratorImpl>::spec_next(move _6) -> [return: bb2, unwind unreachable]; + _7 = <std::ops::RangeInclusive<u32> as iter::range::RangeInclusiveIteratorImpl>::spec_next(move _6) -> [return: bb2, unwind unreachable]; } bb2: { diff --git a/tests/mir-opt/pre-codegen/range_iter.inclusive_loop.PreCodegen.after.panic-unwind.mir b/tests/mir-opt/pre-codegen/range_iter.inclusive_loop.PreCodegen.after.panic-unwind.mir index 7145da58ce1..23537173627 100644 --- a/tests/mir-opt/pre-codegen/range_iter.inclusive_loop.PreCodegen.after.panic-unwind.mir +++ b/tests/mir-opt/pre-codegen/range_iter.inclusive_loop.PreCodegen.after.panic-unwind.mir @@ -19,16 +19,16 @@ fn inclusive_loop(_1: u32, _2: u32, _3: impl Fn(u32)) -> () { scope 2 { debug x => _9; } - scope 5 (inlined iter::range::<impl Iterator for RangeInclusive<u32>>::next) { + scope 5 (inlined iter::range::<impl Iterator for std::ops::RangeInclusive<u32>>::next) { } } - scope 3 (inlined RangeInclusive::<u32>::new) { + scope 3 (inlined std::ops::RangeInclusive::<u32>::new) { } - scope 4 (inlined <RangeInclusive<u32> as IntoIterator>::into_iter) { + scope 4 (inlined <std::ops::RangeInclusive<u32> as IntoIterator>::into_iter) { } bb0: { - _4 = RangeInclusive::<u32> { start: copy _1, end: copy _2, exhausted: const false }; + _4 = std::ops::RangeInclusive::<u32> { start: copy _1, end: copy _2, exhausted: const false }; StorageLive(_5); _5 = copy _4; goto -> bb1; @@ -37,7 +37,7 @@ fn inclusive_loop(_1: u32, _2: u32, _3: impl Fn(u32)) -> () { bb1: { StorageLive(_7); _6 = &mut _5; - _7 = <RangeInclusive<u32> as iter::range::RangeInclusiveIteratorImpl>::spec_next(move _6) -> [return: bb2, unwind: bb8]; + _7 = <std::ops::RangeInclusive<u32> as iter::range::RangeInclusiveIteratorImpl>::spec_next(move _6) -> [return: bb2, unwind: bb8]; } bb2: { diff --git a/tests/mir-opt/pre-codegen/range_iter.range_inclusive_iter_next.PreCodegen.after.panic-abort.mir b/tests/mir-opt/pre-codegen/range_iter.range_inclusive_iter_next.PreCodegen.after.panic-abort.mir index 8e038246fa2..13969e5d238 100644 --- a/tests/mir-opt/pre-codegen/range_iter.range_inclusive_iter_next.PreCodegen.after.panic-abort.mir +++ b/tests/mir-opt/pre-codegen/range_iter.range_inclusive_iter_next.PreCodegen.after.panic-abort.mir @@ -1,13 +1,13 @@ // MIR for `range_inclusive_iter_next` after PreCodegen -fn range_inclusive_iter_next(_1: &mut RangeInclusive<u32>) -> Option<u32> { +fn range_inclusive_iter_next(_1: &mut std::ops::RangeInclusive<u32>) -> Option<u32> { debug it => _1; let mut _0: std::option::Option<u32>; - scope 1 (inlined iter::range::<impl Iterator for RangeInclusive<u32>>::next) { + scope 1 (inlined iter::range::<impl Iterator for std::ops::RangeInclusive<u32>>::next) { } bb0: { - _0 = <RangeInclusive<u32> as iter::range::RangeInclusiveIteratorImpl>::spec_next(move _1) -> [return: bb1, unwind unreachable]; + _0 = <std::ops::RangeInclusive<u32> as iter::range::RangeInclusiveIteratorImpl>::spec_next(move _1) -> [return: bb1, unwind unreachable]; } bb1: { diff --git a/tests/mir-opt/pre-codegen/range_iter.range_inclusive_iter_next.PreCodegen.after.panic-unwind.mir b/tests/mir-opt/pre-codegen/range_iter.range_inclusive_iter_next.PreCodegen.after.panic-unwind.mir index f54d003c662..98cd58284df 100644 --- a/tests/mir-opt/pre-codegen/range_iter.range_inclusive_iter_next.PreCodegen.after.panic-unwind.mir +++ b/tests/mir-opt/pre-codegen/range_iter.range_inclusive_iter_next.PreCodegen.after.panic-unwind.mir @@ -1,13 +1,13 @@ // MIR for `range_inclusive_iter_next` after PreCodegen -fn range_inclusive_iter_next(_1: &mut RangeInclusive<u32>) -> Option<u32> { +fn range_inclusive_iter_next(_1: &mut std::ops::RangeInclusive<u32>) -> Option<u32> { debug it => _1; let mut _0: std::option::Option<u32>; - scope 1 (inlined iter::range::<impl Iterator for RangeInclusive<u32>>::next) { + scope 1 (inlined iter::range::<impl Iterator for std::ops::RangeInclusive<u32>>::next) { } bb0: { - _0 = <RangeInclusive<u32> as iter::range::RangeInclusiveIteratorImpl>::spec_next(move _1) -> [return: bb1, unwind continue]; + _0 = <std::ops::RangeInclusive<u32> as iter::range::RangeInclusiveIteratorImpl>::spec_next(move _1) -> [return: bb1, unwind continue]; } bb1: { diff --git a/tests/rustdoc-json/primitives/primitive_impls.rs b/tests/rustdoc-json/primitives/primitive_impls.rs index 77d1d68f8e4..58c222ce4f0 100644 --- a/tests/rustdoc-json/primitives/primitive_impls.rs +++ b/tests/rustdoc-json/primitives/primitive_impls.rs @@ -1,4 +1,4 @@ -#![feature(no_core)] +#![feature(no_core, lang_items)] #![feature(rustc_attrs)] #![feature(rustdoc_internals)] #![no_core] @@ -6,6 +6,9 @@ //@ set impl_i32 = "$.index[*][?(@.docs=='Only core can do this')].id" +#[lang = "sized"] +trait Sized {} + /// Only core can do this impl i32 { //@ set identity = "$.index[*][?(@.docs=='Do Nothing')].id" diff --git a/tests/rustdoc-ui/custom_code_classes_in_docs-warning3.rs b/tests/rustdoc-ui/custom_code_classes_in_docs-warning3.rs index 6b1aa455d98..18ac37280c0 100644 --- a/tests/rustdoc-ui/custom_code_classes_in_docs-warning3.rs +++ b/tests/rustdoc-ui/custom_code_classes_in_docs-warning3.rs @@ -2,9 +2,12 @@ // feature. #![deny(warnings)] -#![feature(no_core)] +#![feature(no_core, lang_items)] #![no_core] +#[lang = "sized"] +trait Sized {} + /// ```{class="} /// main; /// ``` diff --git a/tests/rustdoc-ui/custom_code_classes_in_docs-warning3.stderr b/tests/rustdoc-ui/custom_code_classes_in_docs-warning3.stderr index 385b2ccacc1..cc13cc0fe53 100644 --- a/tests/rustdoc-ui/custom_code_classes_in_docs-warning3.stderr +++ b/tests/rustdoc-ui/custom_code_classes_in_docs-warning3.stderr @@ -1,5 +1,5 @@ error: unclosed quote string `"` - --> $DIR/custom_code_classes_in_docs-warning3.rs:8:1 + --> $DIR/custom_code_classes_in_docs-warning3.rs:11:1 | LL | / /// ```{class="} LL | | /// main; @@ -17,7 +17,7 @@ LL | #![deny(warnings)] = note: `#[deny(rustdoc::invalid_codeblock_attributes)]` implied by `#[deny(warnings)]` error: unclosed quote string `"` - --> $DIR/custom_code_classes_in_docs-warning3.rs:8:1 + --> $DIR/custom_code_classes_in_docs-warning3.rs:11:1 | LL | / /// ```{class="} LL | | /// main; diff --git a/tests/rustdoc-ui/doctest/relative-path-include-bytes-132203.rs b/tests/rustdoc-ui/doctest/relative-path-include-bytes-132203.rs index 5c9e2978e48..6fddaa49fac 100644 --- a/tests/rustdoc-ui/doctest/relative-path-include-bytes-132203.rs +++ b/tests/rustdoc-ui/doctest/relative-path-include-bytes-132203.rs @@ -1,4 +1,4 @@ -//@ ignore-windows +//@ ignore-windows different error message //@ revisions: edition2015 edition2024 //@[edition2015]edition:2015 //@[edition2015]check-fail diff --git a/tests/rustdoc/assoc-consts.rs b/tests/rustdoc/assoc-consts.rs index cb8e839541c..247b5b180a8 100644 --- a/tests/rustdoc/assoc-consts.rs +++ b/tests/rustdoc/assoc-consts.rs @@ -45,7 +45,7 @@ pub fn f(_: &(ToString + 'static)) {} impl Bar { //@ has assoc_consts/struct.Bar.html '//*[@id="associatedconstant.F"]' \ - // "const F: fn(_: &(dyn ToString + 'static))" + // "const F: fn(&(dyn ToString + 'static))" pub const F: fn(_: &(ToString + 'static)) = f; } diff --git a/tests/rustdoc/cfg_doc_reexport.rs b/tests/rustdoc/cfg_doc_reexport.rs index f8101e2a958..44ec3663284 100644 --- a/tests/rustdoc/cfg_doc_reexport.rs +++ b/tests/rustdoc/cfg_doc_reexport.rs @@ -1,9 +1,12 @@ #![feature(doc_cfg)] -#![feature(no_core)] +#![feature(no_core, lang_items)] #![crate_name = "foo"] #![no_core] +#[lang = "sized"] +trait Sized {} + //@ has 'foo/index.html' //@ has - '//dt/*[@class="stab portability"]' 'foobar' //@ has - '//dt/*[@class="stab portability"]' 'bar' diff --git a/tests/rustdoc/cross-crate-primitive-doc.rs b/tests/rustdoc/cross-crate-primitive-doc.rs index ca33dedcbae..0ffde5b0f2d 100644 --- a/tests/rustdoc/cross-crate-primitive-doc.rs +++ b/tests/rustdoc/cross-crate-primitive-doc.rs @@ -2,9 +2,12 @@ //@ compile-flags: --extern-html-root-url=primitive_doc=../ -Z unstable-options //@ only-linux -#![feature(no_core)] +#![feature(no_core, lang_items)] #![no_core] +#[lang = "sized"] +trait Sized {} + extern crate primitive_doc; //@ has 'cross_crate_primitive_doc/fn.foo.html' '//a[@href="../primitive_doc/primitive.usize.html"]' 'usize' diff --git a/tests/rustdoc/fn-pointer-arg-name.rs b/tests/rustdoc/fn-pointer-arg-name.rs index 3bde6e9ecfa..0ee1964511a 100644 --- a/tests/rustdoc/fn-pointer-arg-name.rs +++ b/tests/rustdoc/fn-pointer-arg-name.rs @@ -3,3 +3,11 @@ //@ has foo/fn.f.html //@ has - '//pre[@class="rust item-decl"]' 'pub fn f(callback: fn(len: usize, foo: u32))' pub fn f(callback: fn(len: usize, foo: u32)) {} + +//@ has foo/fn.g.html +//@ has - '//pre[@class="rust item-decl"]' 'pub fn g(_: fn(usize, u32))' +pub fn g(_: fn(usize, _: u32)) {} + +//@ has foo/fn.mixed.html +//@ has - '//pre[@class="rust item-decl"]' 'pub fn mixed(_: fn(_: usize, foo: u32))' +pub fn mixed(_: fn(usize, foo: u32)) {} diff --git a/tests/rustdoc/inherent-projections.rs b/tests/rustdoc/inherent-projections.rs index 4fc769f70f5..ced4db9a490 100644 --- a/tests/rustdoc/inherent-projections.rs +++ b/tests/rustdoc/inherent-projections.rs @@ -13,7 +13,7 @@ impl Owner { } // Make sure we handle bound vars correctly. -//@ has 'inherent_projections/fn.user.html' '//pre[@class="rust item-decl"]' "user(_: for<'a> fn(_: Carrier<'a>::Focus))" +//@ has 'inherent_projections/fn.user.html' '//pre[@class="rust item-decl"]' "user(_: for<'a> fn(Carrier<'a>::Focus))" pub fn user(_: for<'a> fn(Carrier<'a>::Focus)) {} pub struct Carrier<'a>(&'a ()); diff --git a/tests/rustdoc/intra-doc/no-doc-primitive.rs b/tests/rustdoc/intra-doc/no-doc-primitive.rs index 1f8622ab867..79825643b98 100644 --- a/tests/rustdoc/intra-doc/no-doc-primitive.rs +++ b/tests/rustdoc/intra-doc/no-doc-primitive.rs @@ -6,8 +6,13 @@ #![rustc_coherence_is_core] #![crate_type = "rlib"] + //@ has no_doc_primitive/index.html //! A [`char`] and its [`char::len_utf8`]. + +#[lang = "sized"] +trait Sized {} + impl char { pub fn len_utf8(self) -> usize { 42 diff --git a/tests/rustdoc/macro-higher-kinded-function.rs b/tests/rustdoc/macro-higher-kinded-function.rs index f14125d1309..738ea8fb3f1 100644 --- a/tests/rustdoc/macro-higher-kinded-function.rs +++ b/tests/rustdoc/macro-higher-kinded-function.rs @@ -11,10 +11,10 @@ macro_rules! gen { } //@ has 'foo/struct.Providers.html' -//@ has - '//*[@class="rust item-decl"]//code' "pub a: for<'tcx> fn(_: TyCtxt<'tcx>, _: u8) -> i8," -//@ has - '//*[@class="rust item-decl"]//code' "pub b: for<'tcx> fn(_: TyCtxt<'tcx>, _: u16) -> i16," -//@ has - '//*[@id="structfield.a"]/code' "a: for<'tcx> fn(_: TyCtxt<'tcx>, _: u8) -> i8" -//@ has - '//*[@id="structfield.b"]/code' "b: for<'tcx> fn(_: TyCtxt<'tcx>, _: u16) -> i16" +//@ has - '//*[@class="rust item-decl"]//code' "pub a: for<'tcx> fn(TyCtxt<'tcx>, u8) -> i8," +//@ has - '//*[@class="rust item-decl"]//code' "pub b: for<'tcx> fn(TyCtxt<'tcx>, u16) -> i16," +//@ has - '//*[@id="structfield.a"]/code' "a: for<'tcx> fn(TyCtxt<'tcx>, u8) -> i8" +//@ has - '//*[@id="structfield.b"]/code' "b: for<'tcx> fn(TyCtxt<'tcx>, u16) -> i16" gen! { (a, 'tcx, [u8], [i8]) (b, 'tcx, [u16], [i16]) diff --git a/tests/rustdoc/reexport-trait-from-hidden-111064-2.rs b/tests/rustdoc/reexport-trait-from-hidden-111064-2.rs index 2b21f9862b4..61060b3ff7c 100644 --- a/tests/rustdoc/reexport-trait-from-hidden-111064-2.rs +++ b/tests/rustdoc/reexport-trait-from-hidden-111064-2.rs @@ -1,8 +1,11 @@ // Regression test for <https://github.com/rust-lang/rust/issues/111064>. -#![feature(no_core)] +#![feature(no_core, lang_items)] #![no_core] #![crate_name = "foo"] +#[lang = "sized"] +trait Sized {} + //@ files "foo" "['sidebar-items.js', 'all.html', 'hidden', 'index.html', 'struct.Bar.html', \ // 'visible']" //@ files "foo/hidden" "['inner']" diff --git a/tests/rustdoc/safe-intrinsic.rs b/tests/rustdoc/safe-intrinsic.rs index 07af04ace60..1edc1d9f79b 100644 --- a/tests/rustdoc/safe-intrinsic.rs +++ b/tests/rustdoc/safe-intrinsic.rs @@ -1,10 +1,13 @@ #![feature(intrinsics)] -#![feature(no_core)] +#![feature(no_core, lang_items)] #![feature(rustc_attrs)] #![no_core] #![crate_name = "foo"] +#[lang = "sized"] +trait Sized {} + //@ has 'foo/fn.abort.html' //@ has - '//pre[@class="rust item-decl"]' 'pub fn abort() -> !' #[rustc_intrinsic] diff --git a/tests/rustdoc/type-layout.rs b/tests/rustdoc/type-layout.rs index 5f34c8b99e0..6de435dbcc1 100644 --- a/tests/rustdoc/type-layout.rs +++ b/tests/rustdoc/type-layout.rs @@ -86,11 +86,11 @@ pub enum WithNiche { } //@ hasraw type_layout/enum.Uninhabited.html 'Size: ' -//@ hasraw - '0 bytes (<a href="https://doc.rust-lang.org/stable/reference/glossary.html#uninhabited">uninhabited</a>)' +//@ hasraw - '0 bytes (<a href="{{channel}}/reference/glossary.html#uninhabited">uninhabited</a>)' pub enum Uninhabited {} //@ hasraw type_layout/struct.Uninhabited2.html 'Size: ' -//@ hasraw - '8 bytes (<a href="https://doc.rust-lang.org/stable/reference/glossary.html#uninhabited">uninhabited</a>)' +//@ hasraw - '8 bytes (<a href="{{channel}}/reference/glossary.html#uninhabited">uninhabited</a>)' pub struct Uninhabited2(std::convert::Infallible, u64); pub trait Project { type Assoc; } diff --git a/tests/ui-fulldeps/stable-mir/check_abi.rs b/tests/ui-fulldeps/stable-mir/check_abi.rs index 8caf3032afc..ef2d5b4854b 100644 --- a/tests/ui-fulldeps/stable-mir/check_abi.rs +++ b/tests/ui-fulldeps/stable-mir/check_abi.rs @@ -4,7 +4,6 @@ //@ ignore-stage1 //@ ignore-cross-compile //@ ignore-remote -//@ ignore-windows-gnu mingw has troubles with linking https://github.com/rust-lang/rust/pull/116837 #![feature(rustc_private)] #![feature(assert_matches)] diff --git a/tests/ui-fulldeps/stable-mir/check_allocation.rs b/tests/ui-fulldeps/stable-mir/check_allocation.rs index 072c8ba6a44..c102f86a228 100644 --- a/tests/ui-fulldeps/stable-mir/check_allocation.rs +++ b/tests/ui-fulldeps/stable-mir/check_allocation.rs @@ -5,7 +5,6 @@ //@ ignore-stage1 //@ ignore-cross-compile //@ ignore-remote -//@ ignore-windows-gnu mingw has troubles with linking https://github.com/rust-lang/rust/pull/116837 //@ edition: 2021 #![feature(rustc_private)] diff --git a/tests/ui-fulldeps/stable-mir/check_attribute.rs b/tests/ui-fulldeps/stable-mir/check_attribute.rs index 22481e275a9..11cb63f3f8a 100644 --- a/tests/ui-fulldeps/stable-mir/check_attribute.rs +++ b/tests/ui-fulldeps/stable-mir/check_attribute.rs @@ -4,7 +4,6 @@ //@ ignore-stage1 //@ ignore-cross-compile //@ ignore-remote -//@ ignore-windows-gnu mingw has troubles with linking https://github.com/rust-lang/rust/pull/116837 #![feature(rustc_private)] diff --git a/tests/ui-fulldeps/stable-mir/check_binop.rs b/tests/ui-fulldeps/stable-mir/check_binop.rs index 8c44e285108..65b3ffd27ab 100644 --- a/tests/ui-fulldeps/stable-mir/check_binop.rs +++ b/tests/ui-fulldeps/stable-mir/check_binop.rs @@ -4,7 +4,6 @@ //@ ignore-stage1 //@ ignore-cross-compile //@ ignore-remote -//@ ignore-windows-gnu mingw has troubles with linking https://github.com/rust-lang/rust/pull/116837 #![feature(rustc_private)] diff --git a/tests/ui-fulldeps/stable-mir/check_crate_defs.rs b/tests/ui-fulldeps/stable-mir/check_crate_defs.rs index ed093903381..71cca94c34f 100644 --- a/tests/ui-fulldeps/stable-mir/check_crate_defs.rs +++ b/tests/ui-fulldeps/stable-mir/check_crate_defs.rs @@ -4,7 +4,6 @@ //@ ignore-stage1 //@ ignore-cross-compile //@ ignore-remote -//@ ignore-windows-gnu mingw has troubles with linking https://github.com/rust-lang/rust/pull/116837 #![feature(rustc_private)] #![feature(assert_matches)] diff --git a/tests/ui-fulldeps/stable-mir/check_def_ty.rs b/tests/ui-fulldeps/stable-mir/check_def_ty.rs index 482dbd22d5f..37b9a83e33e 100644 --- a/tests/ui-fulldeps/stable-mir/check_def_ty.rs +++ b/tests/ui-fulldeps/stable-mir/check_def_ty.rs @@ -5,7 +5,6 @@ //@ ignore-stage1 //@ ignore-cross-compile //@ ignore-remote -//@ ignore-windows-gnu mingw has troubles with linking https://github.com/rust-lang/rust/pull/116837 //@ edition: 2021 #![feature(rustc_private)] diff --git a/tests/ui-fulldeps/stable-mir/check_defs.rs b/tests/ui-fulldeps/stable-mir/check_defs.rs index bf1f1a2ceab..cd3d76d8760 100644 --- a/tests/ui-fulldeps/stable-mir/check_defs.rs +++ b/tests/ui-fulldeps/stable-mir/check_defs.rs @@ -4,7 +4,6 @@ //@ ignore-stage1 //@ ignore-cross-compile //@ ignore-remote -//@ ignore-windows-gnu mingw has troubles with linking https://github.com/rust-lang/rust/pull/116837 //@ edition: 2021 #![feature(rustc_private)] diff --git a/tests/ui-fulldeps/stable-mir/check_foreign.rs b/tests/ui-fulldeps/stable-mir/check_foreign.rs index 4acbabbb6be..bc3956b3090 100644 --- a/tests/ui-fulldeps/stable-mir/check_foreign.rs +++ b/tests/ui-fulldeps/stable-mir/check_foreign.rs @@ -4,7 +4,6 @@ //@ ignore-stage1 //@ ignore-cross-compile //@ ignore-remote -//@ ignore-windows-gnu mingw has troubles with linking https://github.com/rust-lang/rust/pull/116837 //@ edition: 2021 #![feature(rustc_private)] diff --git a/tests/ui-fulldeps/stable-mir/check_instance.rs b/tests/ui-fulldeps/stable-mir/check_instance.rs index 464350b1045..72a138f907e 100644 --- a/tests/ui-fulldeps/stable-mir/check_instance.rs +++ b/tests/ui-fulldeps/stable-mir/check_instance.rs @@ -4,7 +4,6 @@ //@ ignore-stage1 //@ ignore-cross-compile //@ ignore-remote -//@ ignore-windows-gnu mingw has troubles with linking https://github.com/rust-lang/rust/pull/116837 //@ edition: 2021 #![feature(rustc_private)] diff --git a/tests/ui-fulldeps/stable-mir/check_intrinsics.rs b/tests/ui-fulldeps/stable-mir/check_intrinsics.rs index 6edebaf756c..2f772b97886 100644 --- a/tests/ui-fulldeps/stable-mir/check_intrinsics.rs +++ b/tests/ui-fulldeps/stable-mir/check_intrinsics.rs @@ -8,7 +8,6 @@ //@ ignore-stage1 //@ ignore-cross-compile //@ ignore-remote -//@ ignore-windows-gnu mingw has troubles with linking https://github.com/rust-lang/rust/pull/116837 #![feature(rustc_private)] #![feature(assert_matches)] diff --git a/tests/ui-fulldeps/stable-mir/check_item_kind.rs b/tests/ui-fulldeps/stable-mir/check_item_kind.rs index 23b54e6c60b..647ce534589 100644 --- a/tests/ui-fulldeps/stable-mir/check_item_kind.rs +++ b/tests/ui-fulldeps/stable-mir/check_item_kind.rs @@ -4,7 +4,6 @@ //@ ignore-stage1 //@ ignore-cross-compile //@ ignore-remote -//@ ignore-windows-gnu mingw has troubles with linking https://github.com/rust-lang/rust/pull/116837 //@ edition: 2021 #![feature(rustc_private)] diff --git a/tests/ui-fulldeps/stable-mir/check_normalization.rs b/tests/ui-fulldeps/stable-mir/check_normalization.rs index 928173b154b..de14202adb9 100644 --- a/tests/ui-fulldeps/stable-mir/check_normalization.rs +++ b/tests/ui-fulldeps/stable-mir/check_normalization.rs @@ -4,7 +4,6 @@ //@ ignore-stage1 //@ ignore-cross-compile //@ ignore-remote -//@ ignore-windows-gnu mingw has troubles with linking https://github.com/rust-lang/rust/pull/116837 //@ edition: 2021 #![feature(rustc_private)] diff --git a/tests/ui-fulldeps/stable-mir/check_trait_queries.rs b/tests/ui-fulldeps/stable-mir/check_trait_queries.rs index 304a7ce9255..23c2844d3f1 100644 --- a/tests/ui-fulldeps/stable-mir/check_trait_queries.rs +++ b/tests/ui-fulldeps/stable-mir/check_trait_queries.rs @@ -4,7 +4,6 @@ //@ ignore-stage1 //@ ignore-cross-compile //@ ignore-remote -//@ ignore-windows-gnu mingw has troubles with linking https://github.com/rust-lang/rust/pull/116837 //@ edition: 2021 #![feature(rustc_private)] diff --git a/tests/ui-fulldeps/stable-mir/check_transform.rs b/tests/ui-fulldeps/stable-mir/check_transform.rs index bcf79c456b0..d9fc924933f 100644 --- a/tests/ui-fulldeps/stable-mir/check_transform.rs +++ b/tests/ui-fulldeps/stable-mir/check_transform.rs @@ -4,7 +4,6 @@ //@ ignore-stage1 //@ ignore-cross-compile //@ ignore-remote -//@ ignore-windows-gnu mingw has troubles with linking https://github.com/rust-lang/rust/pull/116837 #![feature(rustc_private)] #![feature(assert_matches)] diff --git a/tests/ui-fulldeps/stable-mir/check_ty_fold.rs b/tests/ui-fulldeps/stable-mir/check_ty_fold.rs index e21508c9b46..9fa4929d68e 100644 --- a/tests/ui-fulldeps/stable-mir/check_ty_fold.rs +++ b/tests/ui-fulldeps/stable-mir/check_ty_fold.rs @@ -5,7 +5,6 @@ //@ ignore-stage1 //@ ignore-cross-compile //@ ignore-remote -//@ ignore-windows-gnu mingw has troubles with linking https://github.com/rust-lang/rust/pull/116837 //@ edition: 2021 #![feature(rustc_private)] diff --git a/tests/ui-fulldeps/stable-mir/compilation-result.rs b/tests/ui-fulldeps/stable-mir/compilation-result.rs index d921de73f43..b8a9e720e54 100644 --- a/tests/ui-fulldeps/stable-mir/compilation-result.rs +++ b/tests/ui-fulldeps/stable-mir/compilation-result.rs @@ -4,7 +4,6 @@ //@ ignore-stage1 //@ ignore-cross-compile //@ ignore-remote -//@ ignore-windows-gnu mingw has troubles with linking https://github.com/rust-lang/rust/pull/116837 //@ edition: 2021 #![feature(rustc_private)] diff --git a/tests/ui-fulldeps/stable-mir/crate-info.rs b/tests/ui-fulldeps/stable-mir/crate-info.rs index 53be8eb10c1..7f0e9b50335 100644 --- a/tests/ui-fulldeps/stable-mir/crate-info.rs +++ b/tests/ui-fulldeps/stable-mir/crate-info.rs @@ -4,7 +4,6 @@ //@ ignore-stage1 //@ ignore-cross-compile //@ ignore-remote -//@ ignore-windows-gnu mingw has troubles with linking https://github.com/rust-lang/rust/pull/116837 //@ edition: 2021 #![feature(rustc_private)] diff --git a/tests/ui-fulldeps/stable-mir/projections.rs b/tests/ui-fulldeps/stable-mir/projections.rs index fdb7eeed1b0..3cc71247e67 100644 --- a/tests/ui-fulldeps/stable-mir/projections.rs +++ b/tests/ui-fulldeps/stable-mir/projections.rs @@ -4,7 +4,6 @@ //@ ignore-stage1 //@ ignore-cross-compile //@ ignore-remote -//@ ignore-windows-gnu mingw has troubles with linking https://github.com/rust-lang/rust/pull/116837 //@ edition: 2021 #![feature(rustc_private)] diff --git a/tests/ui-fulldeps/stable-mir/smir_internal.rs b/tests/ui-fulldeps/stable-mir/smir_internal.rs index 6f5478c08bf..453e5372de4 100644 --- a/tests/ui-fulldeps/stable-mir/smir_internal.rs +++ b/tests/ui-fulldeps/stable-mir/smir_internal.rs @@ -5,7 +5,6 @@ //@ ignore-stage1 //@ ignore-cross-compile //@ ignore-remote -//@ ignore-windows-gnu mingw has troubles with linking https://github.com/rust-lang/rust/pull/116837 //@ edition: 2021 #![feature(rustc_private)] diff --git a/tests/ui-fulldeps/stable-mir/smir_serde.rs b/tests/ui-fulldeps/stable-mir/smir_serde.rs index 7dbf892f9e4..2c74276d550 100644 --- a/tests/ui-fulldeps/stable-mir/smir_serde.rs +++ b/tests/ui-fulldeps/stable-mir/smir_serde.rs @@ -4,7 +4,6 @@ //@ ignore-stage1 //@ ignore-cross-compile //@ ignore-remote -//@ ignore-windows-gnu mingw has troubles with linking https://github.com/rust-lang/rust/pull/116837 //@ edition: 2021 #![feature(rustc_private)] diff --git a/tests/ui-fulldeps/stable-mir/smir_visitor.rs b/tests/ui-fulldeps/stable-mir/smir_visitor.rs index 666000d3b07..0a6415d490e 100644 --- a/tests/ui-fulldeps/stable-mir/smir_visitor.rs +++ b/tests/ui-fulldeps/stable-mir/smir_visitor.rs @@ -4,7 +4,6 @@ //@ ignore-stage1 //@ ignore-cross-compile //@ ignore-remote -//@ ignore-windows-gnu mingw has troubles with linking https://github.com/rust-lang/rust/pull/116837 //@ edition: 2021 #![feature(rustc_private)] diff --git a/tests/ui/abi/abi-sysv64-arg-passing.rs b/tests/ui/abi/abi-sysv64-arg-passing.rs index 04942e984a8..c18752418a1 100644 --- a/tests/ui/abi/abi-sysv64-arg-passing.rs +++ b/tests/ui/abi/abi-sysv64-arg-passing.rs @@ -29,7 +29,8 @@ //@ ignore-aarch64 //@ ignore-windows -// note: windows is ignored as rust_test_helpers does not have the sysv64 abi on windows +// Windows is ignored because bootstrap doesn't yet know to compile rust_test_helpers with +// the sysv64 ABI on Windows. #[allow(dead_code)] #[allow(improper_ctypes)] diff --git a/tests/ui/abi/large-byval-align.rs b/tests/ui/abi/large-byval-align.rs index e39170df72b..ddd579f264e 100644 --- a/tests/ui/abi/large-byval-align.rs +++ b/tests/ui/abi/large-byval-align.rs @@ -1,6 +1,5 @@ //@ compile-flags: -Copt-level=0 //@ only-x86_64 -//@ ignore-windows //@ min-llvm-version: 19 //@ build-pass diff --git a/tests/ui/associated-consts/issue-58022.stderr b/tests/ui/associated-consts/issue-58022.stderr index 82cbc9ed3b0..37cb162b2b2 100644 --- a/tests/ui/associated-consts/issue-58022.stderr +++ b/tests/ui/associated-consts/issue-58022.stderr @@ -1,12 +1,3 @@ -error[E0790]: cannot refer to the associated constant on trait without specifying the corresponding `impl` type - --> $DIR/issue-58022.rs:4:25 - | -LL | const SIZE: usize; - | ------------------ `Foo::SIZE` defined here -LL | -LL | fn new(slice: &[u8; Foo::SIZE]) -> Self; - | ^^^^^^^^^ cannot refer to the associated constant of trait - error[E0277]: the size for values of type `[u8]` cannot be known at compilation time --> $DIR/issue-58022.rs:13:41 | @@ -21,6 +12,15 @@ LL | pub struct Bar<T: ?Sized>(T); | ^^^ = note: the return type of a function must have a statically known size +error[E0790]: cannot refer to the associated constant on trait without specifying the corresponding `impl` type + --> $DIR/issue-58022.rs:4:25 + | +LL | const SIZE: usize; + | ------------------ `Foo::SIZE` defined here +LL | +LL | fn new(slice: &[u8; Foo::SIZE]) -> Self; + | ^^^^^^^^^ cannot refer to the associated constant of trait + error[E0423]: expected function, tuple struct or tuple variant, found trait `Foo` --> $DIR/issue-58022.rs:15:9 | diff --git a/tests/ui/check-cfg/target_feature.stderr b/tests/ui/check-cfg/target_feature.stderr index bf54d17f6ec..70852423bdb 100644 --- a/tests/ui/check-cfg/target_feature.stderr +++ b/tests/ui/check-cfg/target_feature.stderr @@ -127,6 +127,7 @@ LL | cfg!(target_feature = "_UNEXPECTED_VALUE"); `isa-68881` `isa-68882` `jsconv` +`kl` `lahfsahf` `lasx` `lbt` @@ -271,6 +272,7 @@ LL | cfg!(target_feature = "_UNEXPECTED_VALUE"); `vsx` `wfxt` `wide-arithmetic` +`widekl` `x87` `xop` `xsave` diff --git a/tests/ui/const-generics/std/const-generics-range.full.stderr b/tests/ui/const-generics/std/const-generics-range.full.stderr index 5bf48ad7385..2b5c63e6643 100644 --- a/tests/ui/const-generics/std/const-generics-range.full.stderr +++ b/tests/ui/const-generics/std/const-generics-range.full.stderr @@ -4,7 +4,7 @@ error[E0741]: `std::ops::Range<usize>` must implement `ConstParamTy` to be used LL | struct _Range<const R: std::ops::Range<usize>>; | ^^^^^^^^^^^^^^^^^^^^^^ -error[E0741]: `RangeFrom<usize>` must implement `ConstParamTy` to be used as the type of a const generic parameter +error[E0741]: `std::ops::RangeFrom<usize>` must implement `ConstParamTy` to be used as the type of a const generic parameter --> $DIR/const-generics-range.rs:13:28 | LL | struct _RangeFrom<const R: std::ops::RangeFrom<usize>>; @@ -16,7 +16,7 @@ error[E0741]: `RangeFull` must implement `ConstParamTy` to be used as the type o LL | struct _RangeFull<const R: std::ops::RangeFull>; | ^^^^^^^^^^^^^^^^^^^ -error[E0741]: `RangeInclusive<usize>` must implement `ConstParamTy` to be used as the type of a const generic parameter +error[E0741]: `std::ops::RangeInclusive<usize>` must implement `ConstParamTy` to be used as the type of a const generic parameter --> $DIR/const-generics-range.rs:24:33 | LL | struct _RangeInclusive<const R: std::ops::RangeInclusive<usize>>; diff --git a/tests/ui/const-generics/std/const-generics-range.min.stderr b/tests/ui/const-generics/std/const-generics-range.min.stderr index fd23b9b248a..04e3fe74453 100644 --- a/tests/ui/const-generics/std/const-generics-range.min.stderr +++ b/tests/ui/const-generics/std/const-generics-range.min.stderr @@ -10,7 +10,7 @@ help: add `#![feature(adt_const_params)]` to the crate attributes to enable more LL + #![feature(adt_const_params)] | -error: `RangeFrom<usize>` is forbidden as the type of a const generic parameter +error: `std::ops::RangeFrom<usize>` is forbidden as the type of a const generic parameter --> $DIR/const-generics-range.rs:13:28 | LL | struct _RangeFrom<const R: std::ops::RangeFrom<usize>>; @@ -34,7 +34,7 @@ help: add `#![feature(adt_const_params)]` to the crate attributes to enable more LL + #![feature(adt_const_params)] | -error: `RangeInclusive<usize>` is forbidden as the type of a const generic parameter +error: `std::ops::RangeInclusive<usize>` is forbidden as the type of a const generic parameter --> $DIR/const-generics-range.rs:24:33 | LL | struct _RangeInclusive<const R: std::ops::RangeInclusive<usize>>; diff --git a/tests/ui/const-generics/std/const-generics-range.rs b/tests/ui/const-generics/std/const-generics-range.rs index f959f1e2949..3a238ed177e 100644 --- a/tests/ui/const-generics/std/const-generics-range.rs +++ b/tests/ui/const-generics/std/const-generics-range.rs @@ -11,7 +11,7 @@ const RANGE : _Range<{ 0 .. 1000 }> = _Range; // `RangeFrom` should be usable within const generics: struct _RangeFrom<const R: std::ops::RangeFrom<usize>>; -//[min]~^ ERROR `RangeFrom<usize>` is forbidden +//[min]~^ ERROR `std::ops::RangeFrom<usize>` is forbidden const RANGE_FROM : _RangeFrom<{ 0 .. }> = _RangeFrom; // `RangeFull` should be usable within const generics: @@ -22,7 +22,7 @@ const RANGE_FULL : _RangeFull<{ .. }> = _RangeFull; // Regression test for #70155 // `RangeInclusive` should be usable within const generics: struct _RangeInclusive<const R: std::ops::RangeInclusive<usize>>; -//[min]~^ ERROR `RangeInclusive<usize>` is forbidden +//[min]~^ ERROR `std::ops::RangeInclusive<usize>` is forbidden const RANGE_INCLUSIVE : _RangeInclusive<{ 0 ..= 999 }> = _RangeInclusive; // `RangeTo` should be usable within const generics: diff --git a/tests/ui/const-ptr/forbidden_slices.stderr b/tests/ui/const-ptr/forbidden_slices.stderr index fad078ad2b2..2e0c04dcf1e 100644 --- a/tests/ui/const-ptr/forbidden_slices.stderr +++ b/tests/ui/const-ptr/forbidden_slices.stderr @@ -190,7 +190,7 @@ LL | from_ptr_range(ptr..ptr.add(1)) error[E0080]: could not evaluate static initializer --> $SRC_DIR/core/src/ptr/const_ptr.rs:LL:COL | - = note: `ptr_offset_from_unsigned` called on pointers into different allocations + = note: `ptr_offset_from_unsigned` called on two different pointers that are not both derived from the same allocation | note: inside `std::ptr::const_ptr::<impl *const u32>::sub_ptr` --> $SRC_DIR/core/src/ptr/const_ptr.rs:LL:COL @@ -205,7 +205,7 @@ LL | pub static R9: &[u32] = unsafe { from_ptr_range(&D0..(&D0 as *const u32).ad error[E0080]: could not evaluate static initializer --> $SRC_DIR/core/src/ptr/const_ptr.rs:LL:COL | - = note: `ptr_offset_from_unsigned` called on pointers into different allocations + = note: `ptr_offset_from_unsigned` called on two different pointers that are not both derived from the same allocation | note: inside `std::ptr::const_ptr::<impl *const u32>::sub_ptr` --> $SRC_DIR/core/src/ptr/const_ptr.rs:LL:COL diff --git a/tests/ui/consts/const-slice-array-deref.rs b/tests/ui/consts/const-slice-array-deref.rs index 9d84ed4bdb0..99563ac968c 100644 --- a/tests/ui/consts/const-slice-array-deref.rs +++ b/tests/ui/consts/const-slice-array-deref.rs @@ -1,6 +1,5 @@ const ONE: [u16] = [1]; //~^ ERROR the size for values of type `[u16]` cannot be known at compilation time -//~| ERROR the size for values of type `[u16]` cannot be known at compilation time //~| ERROR mismatched types const TWO: &'static u16 = &ONE[0]; diff --git a/tests/ui/consts/const-slice-array-deref.stderr b/tests/ui/consts/const-slice-array-deref.stderr index 6e69744144e..346685380cc 100644 --- a/tests/ui/consts/const-slice-array-deref.stderr +++ b/tests/ui/consts/const-slice-array-deref.stderr @@ -12,22 +12,13 @@ error[E0308]: mismatched types LL | const ONE: [u16] = [1]; | ^^^ expected `[u16]`, found `[u16; 1]` -error[E0277]: the size for values of type `[u16]` cannot be known at compilation time - --> $DIR/const-slice-array-deref.rs:1:20 - | -LL | const ONE: [u16] = [1]; - | ^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `[u16]` - = note: constant expressions must have a statically known size - error[E0161]: cannot move a value of type `[u16]` - --> $DIR/const-slice-array-deref.rs:6:28 + --> $DIR/const-slice-array-deref.rs:5:28 | LL | const TWO: &'static u16 = &ONE[0]; | ^^^ the size of `[u16]` cannot be statically determined -error: aborting due to 4 previous errors +error: aborting due to 3 previous errors Some errors have detailed explanations: E0161, E0277, E0308. For more information about an error, try `rustc --explain E0161`. diff --git a/tests/ui/consts/const-unsized.rs b/tests/ui/consts/const-unsized.rs index 18682aa6eb6..e8af3323ceb 100644 --- a/tests/ui/consts/const-unsized.rs +++ b/tests/ui/consts/const-unsized.rs @@ -2,19 +2,19 @@ use std::fmt::Debug; const CONST_0: dyn Debug + Sync = *(&0 as &(dyn Debug + Sync)); //~^ ERROR the size for values of type -//~| ERROR the size for values of type +//~| ERROR cannot move out of a shared reference const CONST_FOO: str = *"foo"; //~^ ERROR the size for values of type -//~| ERROR the size for values of type +//~| ERROR cannot move out of a shared reference static STATIC_1: dyn Debug + Sync = *(&1 as &(dyn Debug + Sync)); //~^ ERROR the size for values of type -//~| ERROR the size for values of type +//~| ERROR cannot move out of a shared reference static STATIC_BAR: str = *"bar"; //~^ ERROR the size for values of type -//~| ERROR the size for values of type +//~| ERROR cannot move out of a shared reference fn main() { println!("{:?} {:?} {:?} {:?}", &CONST_0, &CONST_FOO, &STATIC_1, &STATIC_BAR); diff --git a/tests/ui/consts/const-unsized.stderr b/tests/ui/consts/const-unsized.stderr index 0b69cad9651..7931d7adafd 100644 --- a/tests/ui/consts/const-unsized.stderr +++ b/tests/ui/consts/const-unsized.stderr @@ -6,15 +6,6 @@ LL | const CONST_0: dyn Debug + Sync = *(&0 as &(dyn Debug + Sync)); | = help: the trait `Sized` is not implemented for `(dyn Debug + Sync + 'static)` -error[E0277]: the size for values of type `(dyn Debug + Sync + 'static)` cannot be known at compilation time - --> $DIR/const-unsized.rs:3:35 - | -LL | const CONST_0: dyn Debug + Sync = *(&0 as &(dyn Debug + Sync)); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `(dyn Debug + Sync + 'static)` - = note: constant expressions must have a statically known size - error[E0277]: the size for values of type `str` cannot be known at compilation time --> $DIR/const-unsized.rs:7:18 | @@ -23,15 +14,6 @@ LL | const CONST_FOO: str = *"foo"; | = help: the trait `Sized` is not implemented for `str` -error[E0277]: the size for values of type `str` cannot be known at compilation time - --> $DIR/const-unsized.rs:7:24 - | -LL | const CONST_FOO: str = *"foo"; - | ^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `str` - = note: constant expressions must have a statically known size - error[E0277]: the size for values of type `(dyn Debug + Sync + 'static)` cannot be known at compilation time --> $DIR/const-unsized.rs:11:18 | @@ -40,15 +22,6 @@ LL | static STATIC_1: dyn Debug + Sync = *(&1 as &(dyn Debug + Sync)); | = help: the trait `Sized` is not implemented for `(dyn Debug + Sync + 'static)` -error[E0277]: the size for values of type `(dyn Debug + Sync + 'static)` cannot be known at compilation time - --> $DIR/const-unsized.rs:11:37 - | -LL | static STATIC_1: dyn Debug + Sync = *(&1 as &(dyn Debug + Sync)); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `(dyn Debug + Sync + 'static)` - = note: constant expressions must have a statically known size - error[E0277]: the size for values of type `str` cannot be known at compilation time --> $DIR/const-unsized.rs:15:20 | @@ -57,14 +30,29 @@ LL | static STATIC_BAR: str = *"bar"; | = help: the trait `Sized` is not implemented for `str` -error[E0277]: the size for values of type `str` cannot be known at compilation time +error[E0507]: cannot move out of a shared reference + --> $DIR/const-unsized.rs:3:35 + | +LL | const CONST_0: dyn Debug + Sync = *(&0 as &(dyn Debug + Sync)); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ move occurs because value has type `dyn Debug + Sync`, which does not implement the `Copy` trait + +error[E0507]: cannot move out of a shared reference + --> $DIR/const-unsized.rs:7:24 + | +LL | const CONST_FOO: str = *"foo"; + | ^^^^^^ move occurs because value has type `str`, which does not implement the `Copy` trait + +error[E0507]: cannot move out of a shared reference + --> $DIR/const-unsized.rs:11:37 + | +LL | static STATIC_1: dyn Debug + Sync = *(&1 as &(dyn Debug + Sync)); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ move occurs because value has type `dyn Debug + Sync`, which does not implement the `Copy` trait + +error[E0507]: cannot move out of a shared reference --> $DIR/const-unsized.rs:15:26 | LL | static STATIC_BAR: str = *"bar"; - | ^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `str` - = note: constant expressions must have a statically known size + | ^^^^^^ move occurs because value has type `str`, which does not implement the `Copy` trait error[E0161]: cannot move a value of type `str` --> $DIR/const-unsized.rs:20:48 @@ -80,5 +68,5 @@ LL | println!("{:?} {:?} {:?} {:?}", &CONST_0, &CONST_FOO, &STATIC_1, &STATI error: aborting due to 10 previous errors -Some errors have detailed explanations: E0161, E0277. +Some errors have detailed explanations: E0161, E0277, E0507. For more information about an error, try `rustc --explain E0161`. diff --git a/tests/ui/consts/const_refs_to_static-ice-121413.rs b/tests/ui/consts/const_refs_to_static-ice-121413.rs index 7ef67d9a984..432ae1ad5e3 100644 --- a/tests/ui/consts/const_refs_to_static-ice-121413.rs +++ b/tests/ui/consts/const_refs_to_static-ice-121413.rs @@ -9,11 +9,9 @@ const REF_INTERIOR_MUT: &usize = { //~^ ERROR failed to resolve: use of undeclared type `AtomicUsize` //~| WARN trait objects without an explicit `dyn` are deprecated //~| ERROR the size for values of type `(dyn Sync + 'static)` cannot be known at compilation time - //~| ERROR the size for values of type `(dyn Sync + 'static)` cannot be known at compilation time //~| WARN this is accepted in the current edition (Rust 2015) but is a hard error in Rust 2021! //~| HELP if this is a dyn-compatible trait, use `dyn` //~| HELP the trait `Sized` is not implemented for `(dyn Sync + 'static)` - //~| HELP the trait `Sized` is not implemented for `(dyn Sync + 'static)` unsafe { &*(&FOO as *const _ as *const usize) } }; pub fn main() {} diff --git a/tests/ui/consts/const_refs_to_static-ice-121413.stderr b/tests/ui/consts/const_refs_to_static-ice-121413.stderr index 7beb43d84fb..8665d9b6852 100644 --- a/tests/ui/consts/const_refs_to_static-ice-121413.stderr +++ b/tests/ui/consts/const_refs_to_static-ice-121413.stderr @@ -31,16 +31,7 @@ LL | static FOO: Sync = AtomicUsize::new(0); | = help: the trait `Sized` is not implemented for `(dyn Sync + 'static)` -error[E0277]: the size for values of type `(dyn Sync + 'static)` cannot be known at compilation time - --> $DIR/const_refs_to_static-ice-121413.rs:8:24 - | -LL | static FOO: Sync = AtomicUsize::new(0); - | ^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `(dyn Sync + 'static)` - = note: constant expressions must have a statically known size - -error: aborting due to 3 previous errors; 1 warning emitted +error: aborting due to 2 previous errors; 1 warning emitted Some errors have detailed explanations: E0277, E0433. For more information about an error, try `rustc --explain E0277`. diff --git a/tests/ui/consts/offset_from_ub.rs b/tests/ui/consts/offset_from_ub.rs index 0232b03a813..88356900605 100644 --- a/tests/ui/consts/offset_from_ub.rs +++ b/tests/ui/consts/offset_from_ub.rs @@ -17,7 +17,7 @@ pub const DIFFERENT_ALLOC: usize = { let uninit2 = std::mem::MaybeUninit::<Struct>::uninit(); let field_ptr: *const Struct = &uninit2 as *const _ as *const Struct; let offset = unsafe { ptr_offset_from(field_ptr, base_ptr) }; //~ERROR evaluation of constant value failed - //~| pointers into different allocations + //~| not both derived from the same allocation offset as usize }; @@ -37,7 +37,7 @@ pub const DIFFERENT_INT: isize = { // offset_from with two different integers: l let ptr1 = 8 as *const u8; let ptr2 = 16 as *const u8; unsafe { ptr_offset_from(ptr2, ptr1) } //~ERROR evaluation of constant value failed - //~| dangling pointer + //~| not both derived from the same allocation }; const OUT_OF_BOUNDS_1: isize = { @@ -46,7 +46,7 @@ const OUT_OF_BOUNDS_1: isize = { let end_ptr = (start_ptr).wrapping_add(length); // First ptr is out of bounds unsafe { ptr_offset_from(end_ptr, start_ptr) } //~ERROR evaluation of constant value failed - //~| expected a pointer to 10 bytes of memory + //~| the memory range between them is not in-bounds of an allocation }; const OUT_OF_BOUNDS_2: isize = { @@ -55,7 +55,7 @@ const OUT_OF_BOUNDS_2: isize = { let end_ptr = (start_ptr).wrapping_add(length); // Second ptr is out of bounds unsafe { ptr_offset_from(start_ptr, end_ptr) } //~ERROR evaluation of constant value failed - //~| expected a pointer to the end of 10 bytes of memory + //~| the memory range between them is not in-bounds of an allocation }; pub const DIFFERENT_ALLOC_UNSIGNED: usize = { @@ -64,7 +64,7 @@ pub const DIFFERENT_ALLOC_UNSIGNED: usize = { let uninit2 = std::mem::MaybeUninit::<Struct>::uninit(); let field_ptr: *const Struct = &uninit2 as *const _ as *const Struct; unsafe { ptr_offset_from_unsigned(field_ptr, base_ptr) } //~ERROR evaluation of constant value failed - //~| pointers into different allocations + //~| not both derived from the same allocation }; pub const TOO_FAR_APART1: isize = { diff --git a/tests/ui/consts/offset_from_ub.stderr b/tests/ui/consts/offset_from_ub.stderr index ac4597ff011..1379365cc25 100644 --- a/tests/ui/consts/offset_from_ub.stderr +++ b/tests/ui/consts/offset_from_ub.stderr @@ -2,12 +2,12 @@ error[E0080]: evaluation of constant value failed --> $DIR/offset_from_ub.rs:19:27 | LL | let offset = unsafe { ptr_offset_from(field_ptr, base_ptr) }; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `ptr_offset_from` called on pointers into different allocations + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `ptr_offset_from` called on two different pointers that are not both derived from the same allocation error[E0080]: evaluation of constant value failed --> $SRC_DIR/core/src/ptr/const_ptr.rs:LL:COL | - = note: `ptr_offset_from` called on pointers into different allocations + = note: `ptr_offset_from` called on two different pointers that are not both derived from the same allocation | note: inside `std::ptr::const_ptr::<impl *const u8>::offset_from` --> $SRC_DIR/core/src/ptr/const_ptr.rs:LL:COL @@ -27,25 +27,25 @@ error[E0080]: evaluation of constant value failed --> $DIR/offset_from_ub.rs:39:14 | LL | unsafe { ptr_offset_from(ptr2, ptr1) } - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ out-of-bounds `offset_from` origin: expected a pointer to $BYTES bytes of memory, but got 0x8[noalloc] which is a dangling pointer (it has no provenance) + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ `ptr_offset_from` called on two different pointers that are not both derived from the same allocation error[E0080]: evaluation of constant value failed --> $DIR/offset_from_ub.rs:48:14 | LL | unsafe { ptr_offset_from(end_ptr, start_ptr) } - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ out-of-bounds `offset_from` origin: expected a pointer to $BYTES bytes of memory, but got ALLOC0 which is only $BYTES bytes from the end of the allocation + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `ptr_offset_from` called on two different pointers where the memory range between them is not in-bounds of an allocation error[E0080]: evaluation of constant value failed --> $DIR/offset_from_ub.rs:57:14 | LL | unsafe { ptr_offset_from(start_ptr, end_ptr) } - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ out-of-bounds `offset_from` origin: expected a pointer to the end of $BYTES bytes of memory, but got ALLOC1+0xa which does not have enough space to the beginning of the allocation + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `ptr_offset_from` called on two different pointers where the memory range between them is not in-bounds of an allocation error[E0080]: evaluation of constant value failed --> $DIR/offset_from_ub.rs:66:14 | LL | unsafe { ptr_offset_from_unsigned(field_ptr, base_ptr) } - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `ptr_offset_from_unsigned` called on pointers into different allocations + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `ptr_offset_from_unsigned` called on two different pointers that are not both derived from the same allocation error[E0080]: evaluation of constant value failed --> $DIR/offset_from_ub.rs:73:14 @@ -80,7 +80,7 @@ LL | unsafe { ptr_offset_from_unsigned(ptr2, ptr1) } error[E0080]: evaluation of constant value failed --> $SRC_DIR/core/src/ptr/const_ptr.rs:LL:COL | - = note: out-of-bounds `offset_from` origin: expected a pointer to $BYTES bytes of memory, but got a null pointer + = note: `ptr_offset_from` called on two different pointers that are not both derived from the same allocation | note: inside `std::ptr::const_ptr::<impl *const u8>::offset_from` --> $SRC_DIR/core/src/ptr/const_ptr.rs:LL:COL diff --git a/tests/ui/crate-loading/crateresolve1.rs b/tests/ui/crate-loading/crateresolve1.rs index 9200b6a6231..91c34c82558 100644 --- a/tests/ui/crate-loading/crateresolve1.rs +++ b/tests/ui/crate-loading/crateresolve1.rs @@ -2,11 +2,11 @@ //@ aux-build:crateresolve1-2.rs //@ aux-build:crateresolve1-3.rs -//@ normalize-stderr: "\.nll/" -> "/" +//@ normalize-stderr: "crateresolve1\..+/auxiliary/" -> "crateresolve1/auxiliary/" //@ normalize-stderr: "\\\?\\" -> "" //@ normalize-stderr: "(lib)?crateresolve1-([123])\.[a-z]+" -> "libcrateresolve1-$2.somelib" -// NOTE: This test is duplicated at `tests/ui/error-codes/E0464.rs`. +// NOTE: This test is duplicated at `tests/ui/error-codes/E0464.rs` and `E0523.rs`. extern crate crateresolve1; //~^ ERROR multiple candidates for `rlib` dependency `crateresolve1` found diff --git a/tests/ui/crate-loading/crateresolve2.rs b/tests/ui/crate-loading/crateresolve2.rs index bec692eb8d2..6446740a321 100644 --- a/tests/ui/crate-loading/crateresolve2.rs +++ b/tests/ui/crate-loading/crateresolve2.rs @@ -4,7 +4,7 @@ //@ aux-build:crateresolve2-2.rs //@ aux-build:crateresolve2-3.rs -//@ normalize-stderr: "\.nll/" -> "/" +//@ normalize-stderr: "crateresolve2\..+/auxiliary/" -> "crateresolve2/auxiliary/" //@ normalize-stderr: "\\\?\\" -> "" extern crate crateresolve2; diff --git a/tests/ui/diagnostic-width/E0271.ascii.stderr b/tests/ui/diagnostic-width/E0271.ascii.stderr index 93555b336a6..9a9c12a938f 100644 --- a/tests/ui/diagnostic-width/E0271.ascii.stderr +++ b/tests/ui/diagnostic-width/E0271.ascii.stderr @@ -15,7 +15,7 @@ note: expected this to be `Foo` LL | type Error = E; | ^ = note: required for the cast from `Box<Result<..., ()>>` to `Box<...>` - = note: the full name for the type has been written to '$TEST_BUILD_DIR/diagnostic-width/E0271.ascii/E0271.long-type-hash.txt' + = note: the full name for the type has been written to '$TEST_BUILD_DIR/$FILE.long-type-hash.txt' = note: consider using `--verbose` to print the full type name to the console error: aborting due to 1 previous error diff --git a/tests/ui/diagnostic-width/E0271.rs b/tests/ui/diagnostic-width/E0271.rs index 2faf09d46c6..06187721041 100644 --- a/tests/ui/diagnostic-width/E0271.rs +++ b/tests/ui/diagnostic-width/E0271.rs @@ -1,7 +1,7 @@ //@ revisions: ascii unicode //@[ascii] compile-flags: --diagnostic-width=40 -Zwrite-long-types-to-disk=yes //@[unicode] compile-flags: -Zunstable-options --error-format=human-unicode --diagnostic-width=40 -Zwrite-long-types-to-disk=yes -//@ normalize-stderr: "long-type-\d+" -> "long-type-hash" +//@ normalize-stderr: "'\$TEST_BUILD_DIR/.*\.long-type-\d+.txt'" -> "'$$TEST_BUILD_DIR/$$FILE.long-type-hash.txt'" trait Future { type Error; } diff --git a/tests/ui/diagnostic-width/E0271.unicode.stderr b/tests/ui/diagnostic-width/E0271.unicode.stderr index 1e9acf603b2..9c3deae6660 100644 --- a/tests/ui/diagnostic-width/E0271.unicode.stderr +++ b/tests/ui/diagnostic-width/E0271.unicode.stderr @@ -15,7 +15,7 @@ note: expected this to be `Foo` LL │ type Error = E; │ ━ ├ note: required for the cast from `Box<Result<..., ()>>` to `Box<...>` - ├ note: the full name for the type has been written to '$TEST_BUILD_DIR/diagnostic-width/E0271.unicode/E0271.long-type-hash.txt' + ├ note: the full name for the type has been written to '$TEST_BUILD_DIR/$FILE.long-type-hash.txt' ╰ note: consider using `--verbose` to print the full type name to the console error: aborting due to 1 previous error diff --git a/tests/ui/error-codes/E0462.rs b/tests/ui/error-codes/E0462.rs index 12214331445..45d35c345cb 100644 --- a/tests/ui/error-codes/E0462.rs +++ b/tests/ui/error-codes/E0462.rs @@ -1,6 +1,6 @@ //@ aux-build:found-staticlib.rs -//@ normalize-stderr: "\.nll/" -> "/" +//@ normalize-stderr: "E0462\..+/auxiliary/" -> "E0462/auxiliary/" //@ normalize-stderr: "\\\?\\" -> "" //@ normalize-stderr: "(lib)?found_staticlib\.[a-z]+" -> "libfound_staticlib.somelib" diff --git a/tests/ui/error-codes/E0464.rs b/tests/ui/error-codes/E0464.rs index aaf4d3a8f50..d1303ae91b1 100644 --- a/tests/ui/error-codes/E0464.rs +++ b/tests/ui/error-codes/E0464.rs @@ -2,7 +2,7 @@ //@ aux-build:crateresolve1-2.rs //@ aux-build:crateresolve1-3.rs -//@ normalize-stderr: "\.nll/" -> "/" +//@ normalize-stderr: "E0464\..+/auxiliary/" -> "E0464/auxiliary/" //@ normalize-stderr: "\\\?\\" -> "" //@ normalize-stderr: "(lib)?crateresolve1-([123])\.[a-z]+" -> "libcrateresolve1-$2.somelib" diff --git a/tests/ui/error-codes/E0523.rs b/tests/ui/error-codes/E0523.rs index aaf4d3a8f50..7c1869c055b 100644 --- a/tests/ui/error-codes/E0523.rs +++ b/tests/ui/error-codes/E0523.rs @@ -2,7 +2,7 @@ //@ aux-build:crateresolve1-2.rs //@ aux-build:crateresolve1-3.rs -//@ normalize-stderr: "\.nll/" -> "/" +//@ normalize-stderr: "E0523\..+/auxiliary/" -> "E0523/auxiliary/" //@ normalize-stderr: "\\\?\\" -> "" //@ normalize-stderr: "(lib)?crateresolve1-([123])\.[a-z]+" -> "libcrateresolve1-$2.somelib" diff --git a/tests/ui/error-codes/E0746.stderr b/tests/ui/error-codes/E0746.stderr index ce3e9736969..ec785561415 100644 --- a/tests/ui/error-codes/E0746.stderr +++ b/tests/ui/error-codes/E0746.stderr @@ -1,4 +1,4 @@ -error[E0746]: return type cannot have an unboxed trait object +error[E0746]: return type cannot be a trait object without pointer indirection --> $DIR/E0746.rs:8:13 | LL | fn foo() -> dyn Trait { Struct } @@ -13,7 +13,7 @@ help: alternatively, box the return type, and wrap all of the returned values in LL | fn foo() -> Box<dyn Trait> { Box::new(Struct) } | ++++ + +++++++++ + -error[E0746]: return type cannot have an unboxed trait object +error[E0746]: return type cannot be a trait object without pointer indirection --> $DIR/E0746.rs:11:13 | LL | fn bar() -> dyn Trait { diff --git a/tests/ui/extern-flag/empty-extern-arg.stderr b/tests/ui/extern-flag/empty-extern-arg.stderr index 2785b12a0ae..b9a128e02e1 100644 --- a/tests/ui/extern-flag/empty-extern-arg.stderr +++ b/tests/ui/extern-flag/empty-extern-arg.stderr @@ -8,6 +8,10 @@ error: unwinding panics are not supported without std = note: since the core library is usually precompiled with panic="unwind", rebuilding your crate with panic="abort" may not be enough to fix the problem error: requires `sized` lang_item + --> $DIR/empty-extern-arg.rs:6:11 + | +LL | fn main() {} + | ^^ error: aborting due to 4 previous errors diff --git a/tests/ui/feature-gates/feature-gate-cfg-target-thread-local.rs b/tests/ui/feature-gates/feature-gate-cfg-target-thread-local.rs index 3ab5a500dfd..131a10ea03b 100644 --- a/tests/ui/feature-gates/feature-gate-cfg-target-thread-local.rs +++ b/tests/ui/feature-gates/feature-gate-cfg-target-thread-local.rs @@ -1,4 +1,4 @@ -//@ ignore-windows +//@ ignore-windows FIXME(134939): thread_local + no_mangle doesn't work on Windows //@ aux-build:cfg-target-thread-local.rs #![feature(thread_local)] diff --git a/tests/ui/feature-gates/feature-gate-keylocker_x86.rs b/tests/ui/feature-gates/feature-gate-keylocker_x86.rs new file mode 100644 index 00000000000..cef80ad41a8 --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-keylocker_x86.rs @@ -0,0 +1,6 @@ +//@ only-x86_64 +#[target_feature(enable = "kl")] +//~^ ERROR: currently unstable +unsafe fn foo() {} + +fn main() {} diff --git a/tests/ui/feature-gates/feature-gate-keylocker_x86.stderr b/tests/ui/feature-gates/feature-gate-keylocker_x86.stderr new file mode 100644 index 00000000000..ed814d3a3ce --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-keylocker_x86.stderr @@ -0,0 +1,13 @@ +error[E0658]: the target feature `kl` is currently unstable + --> $DIR/feature-gate-keylocker_x86.rs:2:18 + | +LL | #[target_feature(enable = "kl")] + | ^^^^^^^^^^^^^ + | + = note: see issue #134813 <https://github.com/rust-lang/rust/issues/134813> for more information + = help: add `#![feature(keylocker_x86)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/feature-gates/feature-gate-new_range.rs b/tests/ui/feature-gates/feature-gate-new_range.rs new file mode 100644 index 00000000000..ecb73546d6a --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-new_range.rs @@ -0,0 +1,10 @@ +#![feature(new_range_api)] + +fn main() { + let a: core::range::RangeFrom<u8> = 1..; + //~^ mismatched types + let b: core::range::Range<u8> = 2..3; + //~^ mismatched types + let c: core::range::RangeInclusive<u8> = 4..=5; + //~^ mismatched types +} diff --git a/tests/ui/feature-gates/feature-gate-new_range.stderr b/tests/ui/feature-gates/feature-gate-new_range.stderr new file mode 100644 index 00000000000..c4241390418 --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-new_range.stderr @@ -0,0 +1,48 @@ +error[E0308]: mismatched types + --> $DIR/feature-gate-new_range.rs:4:41 + | +LL | let a: core::range::RangeFrom<u8> = 1..; + | -------------------------- ^^^ expected `RangeFrom<u8>`, found `RangeFrom<{integer}>` + | | + | expected due to this + | + = note: expected struct `std::range::RangeFrom<u8>` + found struct `std::ops::RangeFrom<{integer}>` +help: call `Into::into` on this expression to convert `std::ops::RangeFrom<{integer}>` into `std::range::RangeFrom<u8>` + | +LL | let a: core::range::RangeFrom<u8> = 1...into(); + | +++++++ + +error[E0308]: mismatched types + --> $DIR/feature-gate-new_range.rs:6:37 + | +LL | let b: core::range::Range<u8> = 2..3; + | ---------------------- ^^^^ expected `Range<u8>`, found `Range<{integer}>` + | | + | expected due to this + | + = note: expected struct `std::range::Range<u8>` + found struct `std::ops::Range<{integer}>` +help: call `Into::into` on this expression to convert `std::ops::Range<{integer}>` into `std::range::Range<u8>` + | +LL | let b: core::range::Range<u8> = 2..3.into(); + | +++++++ + +error[E0308]: mismatched types + --> $DIR/feature-gate-new_range.rs:8:46 + | +LL | let c: core::range::RangeInclusive<u8> = 4..=5; + | ------------------------------- ^^^^^ expected `RangeInclusive<u8>`, found `RangeInclusive<{integer}>` + | | + | expected due to this + | + = note: expected struct `std::range::RangeInclusive<u8>` + found struct `std::ops::RangeInclusive<{integer}>` +help: call `Into::into` on this expression to convert `std::ops::RangeInclusive<{integer}>` into `std::range::RangeInclusive<u8>` + | +LL | let c: core::range::RangeInclusive<u8> = 4..=5.into(); + | +++++++ + +error: aborting due to 3 previous errors + +For more information about this error, try `rustc --explain E0308`. diff --git a/tests/ui/impl-trait/dyn-incompatible-trait-in-return-position-dyn-trait.rs b/tests/ui/impl-trait/dyn-incompatible-trait-in-return-position-dyn-trait.rs index 046ced072ba..901d4b39cf3 100644 --- a/tests/ui/impl-trait/dyn-incompatible-trait-in-return-position-dyn-trait.rs +++ b/tests/ui/impl-trait/dyn-incompatible-trait-in-return-position-dyn-trait.rs @@ -20,7 +20,7 @@ impl DynIncompatible for B { } fn car() -> dyn DynIncompatible { //~ ERROR the trait `DynIncompatible` is not dyn compatible -//~^ ERROR return type cannot have an unboxed trait object +//~^ ERROR return type cannot be a trait object without pointer indirection if true { return A; } diff --git a/tests/ui/impl-trait/dyn-incompatible-trait-in-return-position-dyn-trait.stderr b/tests/ui/impl-trait/dyn-incompatible-trait-in-return-position-dyn-trait.stderr index 2869702d7fc..c2fd11fe23d 100644 --- a/tests/ui/impl-trait/dyn-incompatible-trait-in-return-position-dyn-trait.stderr +++ b/tests/ui/impl-trait/dyn-incompatible-trait-in-return-position-dyn-trait.stderr @@ -26,6 +26,26 @@ help: alternatively, consider constraining `foo` so it does not apply to trait o LL | fn foo() -> Self where Self: Sized; | +++++++++++++++++ +error[E0746]: return type cannot be a trait object without pointer indirection + --> $DIR/dyn-incompatible-trait-in-return-position-dyn-trait.rs:22:13 + | +LL | fn car() -> dyn DynIncompatible { + | ^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time + | +help: consider returning an `impl Trait` instead of a `dyn Trait` + | +LL | fn car() -> impl DynIncompatible { + | ~~~~ +help: alternatively, box the return type, and wrap all of the returned values in `Box::new` + | +LL ~ fn car() -> Box<dyn DynIncompatible> { +LL | +LL | if true { +LL ~ return Box::new(A); +LL | } +LL ~ Box::new(B) + | + error[E0038]: the trait `DynIncompatible` is not dyn compatible --> $DIR/dyn-incompatible-trait-in-return-position-dyn-trait.rs:30:17 | @@ -54,23 +74,6 @@ help: alternatively, consider constraining `foo` so it does not apply to trait o LL | fn foo() -> Self where Self: Sized; | +++++++++++++++++ -error[E0746]: return type cannot have an unboxed trait object - --> $DIR/dyn-incompatible-trait-in-return-position-dyn-trait.rs:22:13 - | -LL | fn car() -> dyn DynIncompatible { - | ^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: if there were a single returned type, you could use `impl Trait` instead -help: box the return type, and wrap all of the returned values in `Box::new` - | -LL ~ fn car() -> Box<dyn DynIncompatible> { -LL | -LL | if true { -LL ~ return Box::new(A); -LL | } -LL ~ Box::new(B) - | - error[E0038]: the trait `DynIncompatible` is not dyn compatible --> $DIR/dyn-incompatible-trait-in-return-position-dyn-trait.rs:32:16 | diff --git a/tests/ui/impl-trait/dyn-trait-return-should-be-impl-trait.rs b/tests/ui/impl-trait/dyn-trait-return-should-be-impl-trait.rs index af368203de0..ccf0a1ad3d4 100644 --- a/tests/ui/impl-trait/dyn-trait-return-should-be-impl-trait.rs +++ b/tests/ui/impl-trait/dyn-trait-return-should-be-impl-trait.rs @@ -6,9 +6,11 @@ impl Trait for u32 {} fn fuz() -> (usize, Trait) { (42, Struct) } //~^ ERROR E0277 +//~| ERROR E0277 //~| ERROR E0308 fn bar() -> (usize, dyn Trait) { (42, Struct) } //~^ ERROR E0277 +//~| ERROR E0277 //~| ERROR E0308 fn bap() -> Trait { Struct } //~^ ERROR E0746 diff --git a/tests/ui/impl-trait/dyn-trait-return-should-be-impl-trait.stderr b/tests/ui/impl-trait/dyn-trait-return-should-be-impl-trait.stderr index 9ed3d21c13c..11491a55738 100644 --- a/tests/ui/impl-trait/dyn-trait-return-should-be-impl-trait.stderr +++ b/tests/ui/impl-trait/dyn-trait-return-should-be-impl-trait.stderr @@ -1,49 +1,25 @@ -error[E0308]: mismatched types - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:7:35 - | -LL | fn fuz() -> (usize, Trait) { (42, Struct) } - | ^^^^^^ expected `dyn Trait`, found `Struct` - | - = note: expected trait object `(dyn Trait + 'static)` - found struct `Struct` - = help: `Struct` implements `Trait` so you could box the found value and coerce it to the trait object `Box<dyn Trait>`, you will have to change the expected type as well - error[E0277]: the size for values of type `(dyn Trait + 'static)` cannot be known at compilation time --> $DIR/dyn-trait-return-should-be-impl-trait.rs:7:13 | LL | fn fuz() -> (usize, Trait) { (42, Struct) } - | ^^^^^^^^^^^^^^ ------------ this returned value is of type `(usize, (dyn Trait + 'static))` - | | - | doesn't have a size known at compile-time + | ^^^^^^^^^^^^^^ doesn't have a size known at compile-time | = help: within `(usize, (dyn Trait + 'static))`, the trait `Sized` is not implemented for `(dyn Trait + 'static)` = note: required because it appears within the type `(usize, (dyn Trait + 'static))` = note: the return type of a function must have a statically known size -error[E0308]: mismatched types - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:10:39 - | -LL | fn bar() -> (usize, dyn Trait) { (42, Struct) } - | ^^^^^^ expected `dyn Trait`, found `Struct` - | - = note: expected trait object `(dyn Trait + 'static)` - found struct `Struct` - = help: `Struct` implements `Trait` so you could box the found value and coerce it to the trait object `Box<dyn Trait>`, you will have to change the expected type as well - error[E0277]: the size for values of type `(dyn Trait + 'static)` cannot be known at compilation time - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:10:13 + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:11:13 | LL | fn bar() -> (usize, dyn Trait) { (42, Struct) } - | ^^^^^^^^^^^^^^^^^^ ------------ this returned value is of type `(usize, (dyn Trait + 'static))` - | | - | doesn't have a size known at compile-time + | ^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time | = help: within `(usize, (dyn Trait + 'static))`, the trait `Sized` is not implemented for `(dyn Trait + 'static)` = note: required because it appears within the type `(usize, (dyn Trait + 'static))` = note: the return type of a function must have a statically known size -error[E0746]: return type cannot have an unboxed trait object - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:13:13 +error[E0746]: return type cannot be a trait object without pointer indirection + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:15:13 | LL | fn bap() -> Trait { Struct } | ^^^^^ doesn't have a size known at compile-time @@ -57,8 +33,8 @@ help: alternatively, box the return type, and wrap all of the returned values in LL | fn bap() -> Box<dyn Trait> { Box::new(Struct) } | +++++++ + +++++++++ + -error[E0746]: return type cannot have an unboxed trait object - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:15:13 +error[E0746]: return type cannot be a trait object without pointer indirection + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:17:13 | LL | fn ban() -> dyn Trait { Struct } | ^^^^^^^^^ doesn't have a size known at compile-time @@ -72,8 +48,8 @@ help: alternatively, box the return type, and wrap all of the returned values in LL | fn ban() -> Box<dyn Trait> { Box::new(Struct) } | ++++ + +++++++++ + -error[E0746]: return type cannot have an unboxed trait object - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:17:13 +error[E0746]: return type cannot be a trait object without pointer indirection + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:19:13 | LL | fn bak() -> dyn Trait { unimplemented!() } | ^^^^^^^^^ doesn't have a size known at compile-time @@ -87,14 +63,17 @@ help: alternatively, box the return type, and wrap all of the returned values in LL | fn bak() -> Box<dyn Trait> { Box::new(unimplemented!()) } | ++++ + +++++++++ + -error[E0746]: return type cannot have an unboxed trait object - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:19:13 +error[E0746]: return type cannot be a trait object without pointer indirection + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:21:13 | LL | fn bal() -> dyn Trait { | ^^^^^^^^^ doesn't have a size known at compile-time | - = help: if there were a single returned type, you could use `impl Trait` instead -help: box the return type, and wrap all of the returned values in `Box::new` +help: consider returning an `impl Trait` instead of a `dyn Trait` + | +LL | fn bal() -> impl Trait { + | ~~~~ +help: alternatively, box the return type, and wrap all of the returned values in `Box::new` | LL ~ fn bal() -> Box<dyn Trait> { LL | if true { @@ -103,14 +82,17 @@ LL | } LL ~ Box::new(42) | -error[E0746]: return type cannot have an unboxed trait object - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:25:13 +error[E0746]: return type cannot be a trait object without pointer indirection + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:27:13 | LL | fn bax() -> dyn Trait { | ^^^^^^^^^ doesn't have a size known at compile-time | - = help: if there were a single returned type, you could use `impl Trait` instead -help: box the return type, and wrap all of the returned values in `Box::new` +help: consider returning an `impl Trait` instead of a `dyn Trait` + | +LL | fn bax() -> impl Trait { + | ~~~~ +help: alternatively, box the return type, and wrap all of the returned values in `Box::new` | LL ~ fn bax() -> Box<dyn Trait> { LL | if true { @@ -119,8 +101,86 @@ LL | } else { LL ~ Box::new(42) | +error[E0746]: return type cannot be a trait object without pointer indirection + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:62:13 + | +LL | fn bat() -> dyn Trait { + | ^^^^^^^^^ doesn't have a size known at compile-time + | +help: consider returning an `impl Trait` instead of a `dyn Trait` + | +LL | fn bat() -> impl Trait { + | ~~~~ +help: alternatively, box the return type, and wrap all of the returned values in `Box::new` + | +LL ~ fn bat() -> Box<dyn Trait> { +LL | if true { +LL ~ return Box::new(0); +LL | } +LL ~ Box::new(42) + | + +error[E0746]: return type cannot be a trait object without pointer indirection + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:68:13 + | +LL | fn bay() -> dyn Trait { + | ^^^^^^^^^ doesn't have a size known at compile-time + | +help: consider returning an `impl Trait` instead of a `dyn Trait` + | +LL | fn bay() -> impl Trait { + | ~~~~ +help: alternatively, box the return type, and wrap all of the returned values in `Box::new` + | +LL ~ fn bay() -> Box<dyn Trait> { +LL | if true { +LL ~ Box::new(0) +LL | } else { +LL ~ Box::new(42) + | + +error[E0308]: mismatched types + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:7:35 + | +LL | fn fuz() -> (usize, Trait) { (42, Struct) } + | ^^^^^^ expected `dyn Trait`, found `Struct` + | + = note: expected trait object `(dyn Trait + 'static)` + found struct `Struct` + = help: `Struct` implements `Trait` so you could box the found value and coerce it to the trait object `Box<dyn Trait>`, you will have to change the expected type as well + +error[E0277]: the size for values of type `(dyn Trait + 'static)` cannot be known at compilation time + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:7:30 + | +LL | fn fuz() -> (usize, Trait) { (42, Struct) } + | ^^^^^^^^^^^^ doesn't have a size known at compile-time + | + = help: within `(usize, (dyn Trait + 'static))`, the trait `Sized` is not implemented for `(dyn Trait + 'static)` + = note: required because it appears within the type `(usize, (dyn Trait + 'static))` + = note: tuples must have a statically known size to be initialized + error[E0308]: mismatched types - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:34:16 + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:11:39 + | +LL | fn bar() -> (usize, dyn Trait) { (42, Struct) } + | ^^^^^^ expected `dyn Trait`, found `Struct` + | + = note: expected trait object `(dyn Trait + 'static)` + found struct `Struct` + = help: `Struct` implements `Trait` so you could box the found value and coerce it to the trait object `Box<dyn Trait>`, you will have to change the expected type as well + +error[E0277]: the size for values of type `(dyn Trait + 'static)` cannot be known at compilation time + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:11:34 + | +LL | fn bar() -> (usize, dyn Trait) { (42, Struct) } + | ^^^^^^^^^^^^ doesn't have a size known at compile-time + | + = help: within `(usize, (dyn Trait + 'static))`, the trait `Sized` is not implemented for `(dyn Trait + 'static)` + = note: required because it appears within the type `(usize, (dyn Trait + 'static))` + = note: tuples must have a statically known size to be initialized + +error[E0308]: mismatched types + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:36:16 | LL | fn bam() -> Box<dyn Trait> { | -------------- expected `Box<(dyn Trait + 'static)>` because of return type @@ -137,7 +197,7 @@ LL | return Box::new(Struct); | +++++++++ + error[E0308]: mismatched types - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:36:5 + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:38:5 | LL | fn bam() -> Box<dyn Trait> { | -------------- expected `Box<(dyn Trait + 'static)>` because of return type @@ -154,7 +214,7 @@ LL | Box::new(42) | +++++++++ + error[E0308]: mismatched types - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:40:16 + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:42:16 | LL | fn baq() -> Box<dyn Trait> { | -------------- expected `Box<(dyn Trait + 'static)>` because of return type @@ -171,7 +231,7 @@ LL | return Box::new(0); | +++++++++ + error[E0308]: mismatched types - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:42:5 + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:44:5 | LL | fn baq() -> Box<dyn Trait> { | -------------- expected `Box<(dyn Trait + 'static)>` because of return type @@ -188,7 +248,7 @@ LL | Box::new(42) | +++++++++ + error[E0308]: mismatched types - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:46:9 + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:48:9 | LL | fn baz() -> Box<dyn Trait> { | -------------- expected `Box<(dyn Trait + 'static)>` because of return type @@ -205,7 +265,7 @@ LL | Box::new(Struct) | +++++++++ + error[E0308]: mismatched types - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:48:9 + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:50:9 | LL | fn baz() -> Box<dyn Trait> { | -------------- expected `Box<(dyn Trait + 'static)>` because of return type @@ -222,7 +282,7 @@ LL | Box::new(42) | +++++++++ + error[E0308]: mismatched types - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:53:9 + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:55:9 | LL | fn baw() -> Box<dyn Trait> { | -------------- expected `Box<(dyn Trait + 'static)>` because of return type @@ -239,7 +299,7 @@ LL | Box::new(0) | +++++++++ + error[E0308]: mismatched types - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:55:9 + --> $DIR/dyn-trait-return-should-be-impl-trait.rs:57:9 | LL | fn baw() -> Box<dyn Trait> { | -------------- expected `Box<(dyn Trait + 'static)>` because of return type @@ -255,45 +315,7 @@ help: store this in the heap by calling `Box::new` LL | Box::new(42) | +++++++++ + -error[E0746]: return type cannot have an unboxed trait object - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:60:13 - | -LL | fn bat() -> dyn Trait { - | ^^^^^^^^^ doesn't have a size known at compile-time - | -help: consider returning an `impl Trait` instead of a `dyn Trait` - | -LL | fn bat() -> impl Trait { - | ~~~~ -help: alternatively, box the return type, and wrap all of the returned values in `Box::new` - | -LL ~ fn bat() -> Box<dyn Trait> { -LL | if true { -LL ~ return Box::new(0); -LL | } -LL ~ Box::new(42) - | - -error[E0746]: return type cannot have an unboxed trait object - --> $DIR/dyn-trait-return-should-be-impl-trait.rs:66:13 - | -LL | fn bay() -> dyn Trait { - | ^^^^^^^^^ doesn't have a size known at compile-time - | -help: consider returning an `impl Trait` instead of a `dyn Trait` - | -LL | fn bay() -> impl Trait { - | ~~~~ -help: alternatively, box the return type, and wrap all of the returned values in `Box::new` - | -LL ~ fn bay() -> Box<dyn Trait> { -LL | if true { -LL ~ Box::new(0) -LL | } else { -LL ~ Box::new(42) - | - -error: aborting due to 19 previous errors +error: aborting due to 21 previous errors Some errors have detailed explanations: E0277, E0308, E0746. For more information about an error, try `rustc --explain E0277`. diff --git a/tests/ui/impl-trait/point-to-type-err-cause-on-impl-trait-return.rs b/tests/ui/impl-trait/point-to-type-err-cause-on-impl-trait-return.rs index a8a6288eb56..719edd525de 100644 --- a/tests/ui/impl-trait/point-to-type-err-cause-on-impl-trait-return.rs +++ b/tests/ui/impl-trait/point-to-type-err-cause-on-impl-trait-return.rs @@ -63,7 +63,7 @@ fn dog() -> impl std::fmt::Display { } } -fn hat() -> dyn std::fmt::Display { //~ ERROR return type cannot have an unboxed trait object +fn hat() -> dyn std::fmt::Display { //~ ERROR return type cannot be a trait object without pointer indirection match 13 { 0 => { return 0i32; @@ -74,7 +74,7 @@ fn hat() -> dyn std::fmt::Display { //~ ERROR return type cannot have an unboxed } } -fn pug() -> dyn std::fmt::Display { //~ ERROR return type cannot have an unboxed trait object +fn pug() -> dyn std::fmt::Display { //~ ERROR return type cannot be a trait object without pointer indirection match 13 { 0 => 0i32, 1 => 1u32, @@ -82,7 +82,7 @@ fn pug() -> dyn std::fmt::Display { //~ ERROR return type cannot have an unboxed } } -fn man() -> dyn std::fmt::Display { //~ ERROR return type cannot have an unboxed trait object +fn man() -> dyn std::fmt::Display { //~ ERROR return type cannot be a trait object without pointer indirection if false { 0i32 } else { diff --git a/tests/ui/impl-trait/point-to-type-err-cause-on-impl-trait-return.stderr b/tests/ui/impl-trait/point-to-type-err-cause-on-impl-trait-return.stderr index 54849c112f5..17eaed436df 100644 --- a/tests/ui/impl-trait/point-to-type-err-cause-on-impl-trait-return.stderr +++ b/tests/ui/impl-trait/point-to-type-err-cause-on-impl-trait-return.stderr @@ -1,3 +1,62 @@ +error[E0746]: return type cannot be a trait object without pointer indirection + --> $DIR/point-to-type-err-cause-on-impl-trait-return.rs:66:13 + | +LL | fn hat() -> dyn std::fmt::Display { + | ^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time + | +help: consider returning an `impl Trait` instead of a `dyn Trait` + | +LL | fn hat() -> impl std::fmt::Display { + | ~~~~ +help: alternatively, box the return type, and wrap all of the returned values in `Box::new` + | +LL ~ fn hat() -> Box<dyn std::fmt::Display> { +LL | match 13 { +LL | 0 => { +LL ~ return Box::new(0i32); +LL | } +LL | _ => { +LL ~ Box::new(1u32) + | + +error[E0746]: return type cannot be a trait object without pointer indirection + --> $DIR/point-to-type-err-cause-on-impl-trait-return.rs:77:13 + | +LL | fn pug() -> dyn std::fmt::Display { + | ^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time + | +help: consider returning an `impl Trait` instead of a `dyn Trait` + | +LL | fn pug() -> impl std::fmt::Display { + | ~~~~ +help: alternatively, box the return type, and wrap all of the returned values in `Box::new` + | +LL ~ fn pug() -> Box<dyn std::fmt::Display> { +LL | match 13 { +LL ~ 0 => Box::new(0i32), +LL ~ 1 => Box::new(1u32), +LL ~ _ => Box::new(2u32), + | + +error[E0746]: return type cannot be a trait object without pointer indirection + --> $DIR/point-to-type-err-cause-on-impl-trait-return.rs:85:13 + | +LL | fn man() -> dyn std::fmt::Display { + | ^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time + | +help: consider returning an `impl Trait` instead of a `dyn Trait` + | +LL | fn man() -> impl std::fmt::Display { + | ~~~~ +help: alternatively, box the return type, and wrap all of the returned values in `Box::new` + | +LL ~ fn man() -> Box<dyn std::fmt::Display> { +LL | if false { +LL ~ Box::new(0i32) +LL | } else { +LL ~ Box::new(1u32) + | + error[E0308]: mismatched types --> $DIR/point-to-type-err-cause-on-impl-trait-return.rs:5:5 | @@ -165,62 +224,6 @@ help: change the type of the numeric literal from `u32` to `i32` LL | 1i32 | ~~~ -error[E0746]: return type cannot have an unboxed trait object - --> $DIR/point-to-type-err-cause-on-impl-trait-return.rs:66:13 - | -LL | fn hat() -> dyn std::fmt::Display { - | ^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | -help: consider returning an `impl Trait` instead of a `dyn Trait` - | -LL | fn hat() -> impl std::fmt::Display { - | ~~~~ -help: alternatively, box the return type, and wrap all of the returned values in `Box::new` - | -LL ~ fn hat() -> Box<dyn std::fmt::Display> { -LL | match 13 { -LL | 0 => { -LL ~ return Box::new(0i32); -LL | } -LL | _ => { -LL ~ Box::new(1u32) - | - -error[E0746]: return type cannot have an unboxed trait object - --> $DIR/point-to-type-err-cause-on-impl-trait-return.rs:77:13 - | -LL | fn pug() -> dyn std::fmt::Display { - | ^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | -help: consider returning an `impl Trait` instead of a `dyn Trait` - | -LL | fn pug() -> impl std::fmt::Display { - | ~~~~ -help: alternatively, box the return type, and wrap all of the returned values in `Box::new` - | -LL ~ fn pug() -> Box<dyn std::fmt::Display> { -LL | match 13 { -LL ~ 0 => Box::new(0i32), -LL ~ 1 => Box::new(1u32), -LL ~ _ => Box::new(2u32), - | - -error[E0746]: return type cannot have an unboxed trait object - --> $DIR/point-to-type-err-cause-on-impl-trait-return.rs:85:13 - | -LL | fn man() -> dyn std::fmt::Display { - | ^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time - | - = help: if there were a single returned type, you could use `impl Trait` instead -help: box the return type, and wrap all of the returned values in `Box::new` - | -LL ~ fn man() -> Box<dyn std::fmt::Display> { -LL | if false { -LL ~ Box::new(0i32) -LL | } else { -LL ~ Box::new(1u32) - | - error: aborting due to 12 previous errors Some errors have detailed explanations: E0308, E0746. diff --git a/tests/ui/inference/issue-71584.rs b/tests/ui/inference/issue-71584.rs index 7e4d45ec4a0..61568e5467c 100644 --- a/tests/ui/inference/issue-71584.rs +++ b/tests/ui/inference/issue-71584.rs @@ -1,4 +1,4 @@ -//@ ignore-windows different list of satisfying impls +//@ ignore-windows FIXME: We get an extra E0283 on Windows fn main() { let n: u32 = 1; let mut d: u64 = 2; diff --git a/tests/ui/issues/issue-18107.rs b/tests/ui/issues/issue-18107.rs index 4bf5b6c0f30..b1b6ff4f7ad 100644 --- a/tests/ui/issues/issue-18107.rs +++ b/tests/ui/issues/issue-18107.rs @@ -2,7 +2,7 @@ pub trait AbstractRenderer {} fn _create_render(_: &()) -> dyn AbstractRenderer -//~^ ERROR return type cannot have an unboxed trait object +//~^ ERROR return type cannot be a trait object without pointer indirection { match 0 { _ => unimplemented!() diff --git a/tests/ui/issues/issue-18107.stderr b/tests/ui/issues/issue-18107.stderr index 705f7d0df12..6956d6a34aa 100644 --- a/tests/ui/issues/issue-18107.stderr +++ b/tests/ui/issues/issue-18107.stderr @@ -1,4 +1,4 @@ -error[E0746]: return type cannot have an unboxed trait object +error[E0746]: return type cannot be a trait object without pointer indirection --> $DIR/issue-18107.rs:4:5 | LL | dyn AbstractRenderer diff --git a/tests/ui/issues/issue-5883.rs b/tests/ui/issues/issue-5883.rs index f9dd2c54d99..dd4753e0344 100644 --- a/tests/ui/issues/issue-5883.rs +++ b/tests/ui/issues/issue-5883.rs @@ -6,7 +6,7 @@ struct Struct { fn new_struct( r: dyn A + 'static //~ ERROR the size for values of type -) -> Struct { +) -> Struct { //~ ERROR the size for values of type Struct { r: r } } diff --git a/tests/ui/issues/issue-5883.stderr b/tests/ui/issues/issue-5883.stderr index d481d0ef94e..d7278ec32f5 100644 --- a/tests/ui/issues/issue-5883.stderr +++ b/tests/ui/issues/issue-5883.stderr @@ -1,4 +1,18 @@ error[E0277]: the size for values of type `(dyn A + 'static)` cannot be known at compilation time + --> $DIR/issue-5883.rs:9:6 + | +LL | ) -> Struct { + | ^^^^^^ doesn't have a size known at compile-time + | + = help: within `Struct`, the trait `Sized` is not implemented for `(dyn A + 'static)` +note: required because it appears within the type `Struct` + --> $DIR/issue-5883.rs:3:8 + | +LL | struct Struct { + | ^^^^^^ + = note: the return type of a function must have a statically known size + +error[E0277]: the size for values of type `(dyn A + 'static)` cannot be known at compilation time --> $DIR/issue-5883.rs:8:8 | LL | r: dyn A + 'static @@ -15,6 +29,6 @@ help: function arguments must have a statically known size, borrowed types alway LL | r: &dyn A + 'static | + -error: aborting due to 1 previous error +error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/issues/issue-76191.stderr b/tests/ui/issues/issue-76191.stderr index 3702bfb7769..3b89ec7cb9c 100644 --- a/tests/ui/issues/issue-76191.stderr +++ b/tests/ui/issues/issue-76191.stderr @@ -21,7 +21,7 @@ LL | RANGE => {} | `RANGE` is interpreted as a constant, not a new binding | = note: expected type `i32` - found struct `RangeInclusive<i32>` + found struct `std::ops::RangeInclusive<i32>` help: you may want to move the range into the match block | LL | 0..=255 => {} @@ -43,7 +43,7 @@ LL | RANGE2 => {} | `RANGE2` is interpreted as a constant, not a new binding | = note: expected type `i32` - found struct `RangeInclusive<i32>` + found struct `std::ops::RangeInclusive<i32>` = note: constants only support matching by type, if you meant to match against a range of values, consider using a range pattern like `min ..= max` in the match block error: aborting due to 3 previous errors diff --git a/tests/ui/json/json-multiple.rs b/tests/ui/json/json-multiple.rs index 296a60d2453..8ad57939d5d 100644 --- a/tests/ui/json/json-multiple.rs +++ b/tests/ui/json/json-multiple.rs @@ -1,5 +1,6 @@ //@ build-pass //@ ignore-pass (different metadata emitted in different modes) //@ compile-flags: --json=diagnostic-short --json artifacts --error-format=json +//@ normalize-stderr: "json-multiple\..+/libjson_multiple.rlib" -> "json-multiple/libjson_multiple.rlib" #![crate_type = "lib"] diff --git a/tests/ui/json/json-options.rs b/tests/ui/json/json-options.rs index 33df25e27b6..a6654bfcac6 100644 --- a/tests/ui/json/json-options.rs +++ b/tests/ui/json/json-options.rs @@ -1,5 +1,6 @@ //@ build-pass //@ ignore-pass (different metadata emitted in different modes) //@ compile-flags: --json=diagnostic-short,artifacts --error-format=json +//@ normalize-stderr: "json-options\..+/libjson_options.rlib" -> "json-options/libjson_options.rlib" #![crate_type = "lib"] diff --git a/tests/ui/lang-items/lang-item-missing.stderr b/tests/ui/lang-items/lang-item-missing.stderr index 08e679a7c55..63bca95adf7 100644 --- a/tests/ui/lang-items/lang-item-missing.stderr +++ b/tests/ui/lang-items/lang-item-missing.stderr @@ -1,4 +1,8 @@ error: requires `sized` lang_item + --> $DIR/lang-item-missing.rs:11:60 + | +LL | extern "C" fn main(_argc: i32, _argv: *const *const u8) -> i32 { + | ^^^ error: aborting due to 1 previous error diff --git a/tests/ui/lazy-type-alias/def-site-param-defaults-wf.rs b/tests/ui/lazy-type-alias/def-site-param-defaults-wf.rs new file mode 100644 index 00000000000..90bb0a294f8 --- /dev/null +++ b/tests/ui/lazy-type-alias/def-site-param-defaults-wf.rs @@ -0,0 +1,9 @@ +//! Ensure that we check generic parameter defaults for well-formedness at the definition site. +#![feature(lazy_type_alias)] +#![allow(incomplete_features)] + +type Alias<T = Vec<str>, const N: usize = {0 - 1}> = T; +//~^ ERROR evaluation of constant value failed +//~| ERROR the size for values of type `str` cannot be known at compilation time + +fn main() {} diff --git a/tests/ui/lazy-type-alias/def-site-param-defaults-wf.stderr b/tests/ui/lazy-type-alias/def-site-param-defaults-wf.stderr new file mode 100644 index 00000000000..da0021ccaf4 --- /dev/null +++ b/tests/ui/lazy-type-alias/def-site-param-defaults-wf.stderr @@ -0,0 +1,20 @@ +error[E0080]: evaluation of constant value failed + --> $DIR/def-site-param-defaults-wf.rs:5:44 + | +LL | type Alias<T = Vec<str>, const N: usize = {0 - 1}> = T; + | ^^^^^ attempt to compute `0_usize - 1_usize`, which would overflow + +error[E0277]: the size for values of type `str` cannot be known at compilation time + --> $DIR/def-site-param-defaults-wf.rs:5:16 + | +LL | type Alias<T = Vec<str>, const N: usize = {0 - 1}> = T; + | ^^^^^^^^ doesn't have a size known at compile-time + | + = help: the trait `Sized` is not implemented for `str` +note: required by an implicit `Sized` bound in `Vec` + --> $SRC_DIR/alloc/src/vec/mod.rs:LL:COL + +error: aborting due to 2 previous errors + +Some errors have detailed explanations: E0080, E0277. +For more information about an error, try `rustc --explain E0080`. diff --git a/tests/ui/lazy-type-alias/def-site-predicates-wf.rs b/tests/ui/lazy-type-alias/def-site-predicates-wf.rs new file mode 100644 index 00000000000..5d9235347cb --- /dev/null +++ b/tests/ui/lazy-type-alias/def-site-predicates-wf.rs @@ -0,0 +1,13 @@ +//! Ensure that we check the predicates at the definition site for well-formedness. +#![feature(lazy_type_alias)] +#![allow(incomplete_features)] + +type Alias0 = () +where + Vec<str>:; //~ ERROR the size for values of type `str` cannot be known at compilation time + +type Alias1 = () +where + Vec<str>: Sized; //~ ERROR the size for values of type `str` cannot be known at compilation time + +fn main() {} diff --git a/tests/ui/lazy-type-alias/def-site-predicates-wf.stderr b/tests/ui/lazy-type-alias/def-site-predicates-wf.stderr new file mode 100644 index 00000000000..b44e702c35c --- /dev/null +++ b/tests/ui/lazy-type-alias/def-site-predicates-wf.stderr @@ -0,0 +1,23 @@ +error[E0277]: the size for values of type `str` cannot be known at compilation time + --> $DIR/def-site-predicates-wf.rs:7:5 + | +LL | Vec<str>:; + | ^^^^^^^^ doesn't have a size known at compile-time + | + = help: the trait `Sized` is not implemented for `str` +note: required by an implicit `Sized` bound in `Vec` + --> $SRC_DIR/alloc/src/vec/mod.rs:LL:COL + +error[E0277]: the size for values of type `str` cannot be known at compilation time + --> $DIR/def-site-predicates-wf.rs:11:15 + | +LL | Vec<str>: Sized; + | ^^^^^ doesn't have a size known at compile-time + | + = help: the trait `Sized` is not implemented for `str` +note: required by an implicit `Sized` bound in `Vec` + --> $SRC_DIR/alloc/src/vec/mod.rs:LL:COL + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/lifetimes/tail-expr-lock-poisoning.rs b/tests/ui/lifetimes/tail-expr-lock-poisoning.rs index d7c7b2e2414..1c838a9e5e1 100644 --- a/tests/ui/lifetimes/tail-expr-lock-poisoning.rs +++ b/tests/ui/lifetimes/tail-expr-lock-poisoning.rs @@ -1,5 +1,4 @@ //@ revisions: edition2021 edition2024 -//@ ignore-wasm no panic support //@ needs-subprocess //@ [edition2024] edition: 2024 //@ run-pass diff --git a/tests/ui/linkage-attr/linkage-attr-does-not-panic-llvm-issue-33992.rs b/tests/ui/linkage-attr/linkage-attr-does-not-panic-llvm-issue-33992.rs index a169997927e..df73eddd8d5 100644 --- a/tests/ui/linkage-attr/linkage-attr-does-not-panic-llvm-issue-33992.rs +++ b/tests/ui/linkage-attr/linkage-attr-does-not-panic-llvm-issue-33992.rs @@ -1,5 +1,4 @@ //@ run-pass -//@ ignore-windows //@ ignore-apple //@ ignore-wasm32 common linkage not implemented right now @@ -11,9 +10,11 @@ pub static TEST2: bool = true; #[linkage = "internal"] pub static TEST3: bool = true; +#[cfg(not(target_env = "msvc"))] #[linkage = "linkonce"] pub static TEST4: bool = true; +#[cfg(not(target_env = "msvc"))] #[linkage = "linkonce_odr"] pub static TEST5: bool = true; diff --git a/tests/ui/linkage-attr/propagate-generic-issue-18804/main.rs b/tests/ui/linkage-attr/propagate-generic-issue-18804/main.rs index 56a9358cce3..8c194ec50df 100644 --- a/tests/ui/linkage-attr/propagate-generic-issue-18804/main.rs +++ b/tests/ui/linkage-attr/propagate-generic-issue-18804/main.rs @@ -3,7 +3,6 @@ // functions. Failure results in a linker error. //@ ignore-emscripten no weak symbol support -//@ ignore-windows no extern_weak linkage //@ ignore-apple no extern_weak linkage //@ aux-build:lib.rs diff --git a/tests/ui/logging-only-prints-once.rs b/tests/ui/logging-only-prints-once.rs index 5377d5eeae2..bb8c29694b5 100644 --- a/tests/ui/logging-only-prints-once.rs +++ b/tests/ui/logging-only-prints-once.rs @@ -1,5 +1,4 @@ //@ run-pass -//@ ignore-windows //@ needs-threads use std::cell::Cell; diff --git a/tests/ui/lto/weak-works.rs b/tests/ui/lto/weak-works.rs index 00e10b97d60..1ff47ca602d 100644 --- a/tests/ui/lto/weak-works.rs +++ b/tests/ui/lto/weak-works.rs @@ -1,7 +1,8 @@ //@ run-pass //@ compile-flags: -C codegen-units=8 -Z thinlto -//@ ignore-windows +//@ ignore-i686-pc-windows-gnu +//@ ignore-x86_64-pc-windows-gnu #![feature(linkage)] diff --git a/tests/ui/mismatched_types/closure-arg-type-mismatch-issue-45727.current.fixed b/tests/ui/mismatched_types/closure-arg-type-mismatch-issue-45727.current.fixed index 25943d11fc4..ba46a447802 100644 --- a/tests/ui/mismatched_types/closure-arg-type-mismatch-issue-45727.current.fixed +++ b/tests/ui/mismatched_types/closure-arg-type-mismatch-issue-45727.current.fixed @@ -5,9 +5,9 @@ fn main() { let _ = (-10..=10).find(|x: &i32| x.signum() == 0); //[current]~^ ERROR type mismatch in closure arguments - //[next]~^^ ERROR expected a `FnMut(&<RangeInclusive<{integer}> as Iterator>::Item)` closure, found + //[next]~^^ ERROR expected a `FnMut(&<std::ops::RangeInclusive<{integer}> as Iterator>::Item)` closure, found let _ = (-10..=10).find(|x: &i32| x.signum() == 0); //[current]~^ ERROR type mismatch in closure arguments //[next]~^^ ERROR expected `RangeInclusive<{integer}>` to be an iterator that yields `&&i32`, but it yields `{integer}` - //[next]~| ERROR expected a `FnMut(&<RangeInclusive<{integer}> as Iterator>::Item)` closure, found + //[next]~| ERROR expected a `FnMut(&<std::ops::RangeInclusive<{integer}> as Iterator>::Item)` closure, found } diff --git a/tests/ui/mismatched_types/closure-arg-type-mismatch-issue-45727.next.stderr b/tests/ui/mismatched_types/closure-arg-type-mismatch-issue-45727.next.stderr index 696214c0a3c..b7161310619 100644 --- a/tests/ui/mismatched_types/closure-arg-type-mismatch-issue-45727.next.stderr +++ b/tests/ui/mismatched_types/closure-arg-type-mismatch-issue-45727.next.stderr @@ -1,14 +1,14 @@ -error[E0277]: expected a `FnMut(&<RangeInclusive<{integer}> as Iterator>::Item)` closure, found `{closure@$DIR/closure-arg-type-mismatch-issue-45727.rs:6:29: 6:37}` +error[E0277]: expected a `FnMut(&<std::ops::RangeInclusive<{integer}> as Iterator>::Item)` closure, found `{closure@$DIR/closure-arg-type-mismatch-issue-45727.rs:6:29: 6:37}` --> $DIR/closure-arg-type-mismatch-issue-45727.rs:6:29 | LL | let _ = (-10..=10).find(|x: i32| x.signum() == 0); - | ---- ^^^^^^^^^^^^^^^^^^^^^^^^ expected an `FnMut(&<RangeInclusive<{integer}> as Iterator>::Item)` closure, found `{closure@$DIR/closure-arg-type-mismatch-issue-45727.rs:6:29: 6:37}` + | ---- ^^^^^^^^^^^^^^^^^^^^^^^^ expected an `FnMut(&<std::ops::RangeInclusive<{integer}> as Iterator>::Item)` closure, found `{closure@$DIR/closure-arg-type-mismatch-issue-45727.rs:6:29: 6:37}` | | | required by a bound introduced by this call | - = help: the trait `for<'a> FnMut(&'a <RangeInclusive<{integer}> as Iterator>::Item)` is not implemented for closure `{closure@$DIR/closure-arg-type-mismatch-issue-45727.rs:6:29: 6:37}` + = help: the trait `for<'a> FnMut(&'a <std::ops::RangeInclusive<{integer}> as Iterator>::Item)` is not implemented for closure `{closure@$DIR/closure-arg-type-mismatch-issue-45727.rs:6:29: 6:37}` = note: expected a closure with arguments `(i32,)` - found a closure with arguments `(&<RangeInclusive<{integer}> as Iterator>::Item,)` + found a closure with arguments `(&<std::ops::RangeInclusive<{integer}> as Iterator>::Item,)` note: required by a bound in `find` --> $SRC_DIR/core/src/iter/traits/iterator.rs:LL:COL @@ -18,17 +18,17 @@ error[E0271]: expected `RangeInclusive<{integer}>` to be an iterator that yields LL | let _ = (-10..=10).find(|x: &&&i32| x.signum() == 0); | ^^^^ expected `&&i32`, found integer -error[E0277]: expected a `FnMut(&<RangeInclusive<{integer}> as Iterator>::Item)` closure, found `{closure@$DIR/closure-arg-type-mismatch-issue-45727.rs:9:29: 9:40}` +error[E0277]: expected a `FnMut(&<std::ops::RangeInclusive<{integer}> as Iterator>::Item)` closure, found `{closure@$DIR/closure-arg-type-mismatch-issue-45727.rs:9:29: 9:40}` --> $DIR/closure-arg-type-mismatch-issue-45727.rs:9:29 | LL | let _ = (-10..=10).find(|x: &&&i32| x.signum() == 0); - | ---- ^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected an `FnMut(&<RangeInclusive<{integer}> as Iterator>::Item)` closure, found `{closure@$DIR/closure-arg-type-mismatch-issue-45727.rs:9:29: 9:40}` + | ---- ^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected an `FnMut(&<std::ops::RangeInclusive<{integer}> as Iterator>::Item)` closure, found `{closure@$DIR/closure-arg-type-mismatch-issue-45727.rs:9:29: 9:40}` | | | required by a bound introduced by this call | - = help: the trait `for<'a> FnMut(&'a <RangeInclusive<{integer}> as Iterator>::Item)` is not implemented for closure `{closure@$DIR/closure-arg-type-mismatch-issue-45727.rs:9:29: 9:40}` + = help: the trait `for<'a> FnMut(&'a <std::ops::RangeInclusive<{integer}> as Iterator>::Item)` is not implemented for closure `{closure@$DIR/closure-arg-type-mismatch-issue-45727.rs:9:29: 9:40}` = note: expected a closure with arguments `(&&&i32,)` - found a closure with arguments `(&<RangeInclusive<{integer}> as Iterator>::Item,)` + found a closure with arguments `(&<std::ops::RangeInclusive<{integer}> as Iterator>::Item,)` note: required by a bound in `find` --> $SRC_DIR/core/src/iter/traits/iterator.rs:LL:COL diff --git a/tests/ui/mismatched_types/closure-arg-type-mismatch-issue-45727.rs b/tests/ui/mismatched_types/closure-arg-type-mismatch-issue-45727.rs index 9e44489cbf1..0fd56707763 100644 --- a/tests/ui/mismatched_types/closure-arg-type-mismatch-issue-45727.rs +++ b/tests/ui/mismatched_types/closure-arg-type-mismatch-issue-45727.rs @@ -5,9 +5,9 @@ fn main() { let _ = (-10..=10).find(|x: i32| x.signum() == 0); //[current]~^ ERROR type mismatch in closure arguments - //[next]~^^ ERROR expected a `FnMut(&<RangeInclusive<{integer}> as Iterator>::Item)` closure, found + //[next]~^^ ERROR expected a `FnMut(&<std::ops::RangeInclusive<{integer}> as Iterator>::Item)` closure, found let _ = (-10..=10).find(|x: &&&i32| x.signum() == 0); //[current]~^ ERROR type mismatch in closure arguments //[next]~^^ ERROR expected `RangeInclusive<{integer}>` to be an iterator that yields `&&i32`, but it yields `{integer}` - //[next]~| ERROR expected a `FnMut(&<RangeInclusive<{integer}> as Iterator>::Item)` closure, found + //[next]~| ERROR expected a `FnMut(&<std::ops::RangeInclusive<{integer}> as Iterator>::Item)` closure, found } diff --git a/tests/ui/never_type/issue-52443.stderr b/tests/ui/never_type/issue-52443.stderr index 1c5a0d65142..bb60c33595c 100644 --- a/tests/ui/never_type/issue-52443.stderr +++ b/tests/ui/never_type/issue-52443.stderr @@ -31,7 +31,7 @@ help: give the `break` a value of the expected type LL | [(); loop { break 42 }]; | ++ -error[E0015]: cannot use `for` loop on `RangeFrom<usize>` in constants +error[E0015]: cannot use `for` loop on `std::ops::RangeFrom<usize>` in constants --> $DIR/issue-52443.rs:9:21 | LL | [(); { for _ in 0usize.. {}; 0}]; @@ -39,7 +39,7 @@ LL | [(); { for _ in 0usize.. {}; 0}]; | = note: calls in constants are limited to constant functions, tuple structs and tuple variants -error[E0015]: cannot use `for` loop on `RangeFrom<usize>` in constants +error[E0015]: cannot use `for` loop on `std::ops::RangeFrom<usize>` in constants --> $DIR/issue-52443.rs:9:21 | LL | [(); { for _ in 0usize.. {}; 0}]; diff --git a/tests/ui/new-range/disabled.rs b/tests/ui/new-range/disabled.rs new file mode 100644 index 00000000000..1a5fe3f9743 --- /dev/null +++ b/tests/ui/new-range/disabled.rs @@ -0,0 +1,27 @@ +//@ check-pass + +#![feature(new_range_api)] + +fn main() { + // Unchanged + let a: core::range::RangeFull = ..; + let b: core::range::RangeTo<u8> = ..2; + let c: core::range::RangeToInclusive<u8> = ..=3; + + let _: core::ops::RangeFull = a; + let _: core::ops::RangeTo<u8> = b; + let _: core::ops::RangeToInclusive<u8> = c; + + // Changed + let a: core::range::legacy::RangeFrom<u8> = 1..; + let b: core::range::legacy::Range<u8> = 2..3; + let c: core::range::legacy::RangeInclusive<u8> = 4..=5; + + let a: core::ops::RangeFrom<u8> = a; + let b: core::ops::Range<u8> = b; + let c: core::ops::RangeInclusive<u8> = c; + + let _: core::ops::RangeFrom<u8> = a.into_iter(); + let _: core::ops::Range<u8> = b.into_iter(); + let _: core::ops::RangeInclusive<u8> = c.into_iter(); +} diff --git a/tests/ui/new-range/enabled.rs b/tests/ui/new-range/enabled.rs new file mode 100644 index 00000000000..a5fb76ad52b --- /dev/null +++ b/tests/ui/new-range/enabled.rs @@ -0,0 +1,24 @@ +//@ check-pass + +#![feature(new_range_api)] +#![feature(new_range)] + +fn main() { + // Unchanged + let a: core::range::RangeFull = ..; + let b: core::range::RangeTo<u8> = ..2; + let c: core::range::RangeToInclusive<u8> = ..=3; + + let _: core::ops::RangeFull = a; + let _: core::ops::RangeTo<u8> = b; + let _: core::ops::RangeToInclusive<u8> = c; + + // Changed + let a: core::range::RangeFrom<u8> = 1..; + let b: core::range::Range<u8> = 2..3; + let c: core::range::RangeInclusive<u8> = 4..=5; + + let _: core::range::IterRangeFrom<u8> = a.into_iter(); + let _: core::range::IterRange<u8> = b.into_iter(); + let _: core::range::IterRangeInclusive<u8> = c.into_iter(); +} diff --git a/tests/ui/nll/get_default.legacy.stderr b/tests/ui/nll/get_default.legacy.stderr new file mode 100644 index 00000000000..699250312dc --- /dev/null +++ b/tests/ui/nll/get_default.legacy.stderr @@ -0,0 +1,18 @@ +error[E0502]: cannot borrow `*map` as mutable because it is also borrowed as immutable + --> $DIR/get_default.rs:35:17 + | +LL | fn err(map: &mut Map) -> &String { + | - let's call the lifetime of this reference `'1` +LL | loop { +LL | match map.get() { + | --- immutable borrow occurs here +LL | Some(v) => { +LL | map.set(String::new()); // We always expect an error here. + | ^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here +LL | +LL | return v; + | - returning this value requires that `*map` is borrowed for `'1` + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0502`. diff --git a/tests/ui/nll/get_default.stderr b/tests/ui/nll/get_default.nll.stderr index af79771e7e1..9b5976ca717 100644 --- a/tests/ui/nll/get_default.stderr +++ b/tests/ui/nll/get_default.nll.stderr @@ -1,5 +1,5 @@ error[E0502]: cannot borrow `*map` as mutable because it is also borrowed as immutable - --> $DIR/get_default.rs:21:17 + --> $DIR/get_default.rs:24:17 | LL | fn ok(map: &mut Map) -> &String { | - let's call the lifetime of this reference `'1` @@ -14,7 +14,7 @@ LL | map.set(String::new()); // Ideally, this would not error. | ^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here error[E0502]: cannot borrow `*map` as mutable because it is also borrowed as immutable - --> $DIR/get_default.rs:32:17 + --> $DIR/get_default.rs:35:17 | LL | fn err(map: &mut Map) -> &String { | - let's call the lifetime of this reference `'1` @@ -22,14 +22,14 @@ LL | loop { LL | match map.get() { | --- immutable borrow occurs here LL | Some(v) => { -LL | map.set(String::new()); // Both AST and MIR error here +LL | map.set(String::new()); // We always expect an error here. | ^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here LL | LL | return v; | - returning this value requires that `*map` is borrowed for `'1` error[E0502]: cannot borrow `*map` as mutable because it is also borrowed as immutable - --> $DIR/get_default.rs:37:17 + --> $DIR/get_default.rs:40:17 | LL | fn err(map: &mut Map) -> &String { | - let's call the lifetime of this reference `'1` @@ -40,7 +40,7 @@ LL | match map.get() { LL | return v; | - returning this value requires that `*map` is borrowed for `'1` ... -LL | map.set(String::new()); // Ideally, just AST would error here +LL | map.set(String::new()); // Ideally, this would not error. | ^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here error: aborting due to 3 previous errors diff --git a/tests/ui/nll/get_default.polonius.stderr b/tests/ui/nll/get_default.polonius.stderr new file mode 100644 index 00000000000..699250312dc --- /dev/null +++ b/tests/ui/nll/get_default.polonius.stderr @@ -0,0 +1,18 @@ +error[E0502]: cannot borrow `*map` as mutable because it is also borrowed as immutable + --> $DIR/get_default.rs:35:17 + | +LL | fn err(map: &mut Map) -> &String { + | - let's call the lifetime of this reference `'1` +LL | loop { +LL | match map.get() { + | --- immutable borrow occurs here +LL | Some(v) => { +LL | map.set(String::new()); // We always expect an error here. + | ^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here +LL | +LL | return v; + | - returning this value requires that `*map` is borrowed for `'1` + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0502`. diff --git a/tests/ui/nll/get_default.rs b/tests/ui/nll/get_default.rs index ffac8a33da1..c3c09e9c2c5 100644 --- a/tests/ui/nll/get_default.rs +++ b/tests/ui/nll/get_default.rs @@ -1,7 +1,10 @@ // Basic test for free regions in the NLL code. This test ought to -// report an error due to a reborrowing constraint. Right now, we get -// a variety of errors from the older, AST-based machinery (notably -// borrowck), and then we get the NLL error at the end. +// report an error due to a reborrowing constraint. + +//@ ignore-compare-mode-polonius (explicit revisions) +//@ revisions: nll polonius legacy +//@ [polonius] compile-flags: -Z polonius=next +//@ [legacy] compile-flags: -Z polonius=legacy struct Map { } @@ -19,7 +22,7 @@ fn ok(map: &mut Map) -> &String { } None => { map.set(String::new()); // Ideally, this would not error. - //~^ ERROR borrowed as immutable + //[nll]~^ ERROR borrowed as immutable } } } @@ -29,13 +32,13 @@ fn err(map: &mut Map) -> &String { loop { match map.get() { Some(v) => { - map.set(String::new()); // Both AST and MIR error here + map.set(String::new()); // We always expect an error here. //~^ ERROR borrowed as immutable return v; } None => { - map.set(String::new()); // Ideally, just AST would error here - //~^ ERROR borrowed as immutable + map.set(String::new()); // Ideally, this would not error. + //[nll]~^ ERROR borrowed as immutable } } } diff --git a/tests/ui/nll/issue-46589.stderr b/tests/ui/nll/issue-46589.nll.stderr index abf62aaa510..dc80c1d08de 100644 --- a/tests/ui/nll/issue-46589.stderr +++ b/tests/ui/nll/issue-46589.nll.stderr @@ -1,5 +1,5 @@ error[E0499]: cannot borrow `**other` as mutable more than once at a time - --> $DIR/issue-46589.rs:23:21 + --> $DIR/issue-46589.rs:24:21 | LL | *other = match (*other).get_self() { | -------- first mutable borrow occurs here diff --git a/tests/ui/nll/issue-46589.rs b/tests/ui/nll/issue-46589.rs index 417d9cab657..10aff0d7b4e 100644 --- a/tests/ui/nll/issue-46589.rs +++ b/tests/ui/nll/issue-46589.rs @@ -1,8 +1,9 @@ -// This tests passes in Polonius mode, so is skipped in the automated compare-mode. -// We will manually check it passes in Polonius tests, as we can't have a test here -// which conditionally passes depending on a test revision/compile-flags. - -//@ ignore-compare-mode-polonius +//@ ignore-compare-mode-polonius (explicit revisions) +//@ revisions: nll polonius_next polonius +//@ [polonius_next] check-pass +//@ [polonius_next] compile-flags: -Zpolonius=next +//@ [polonius] check-pass +//@ [polonius] compile-flags: -Zpolonius struct Foo; @@ -21,7 +22,7 @@ impl Foo { *other = match (*other).get_self() { Some(s) => s, None => (*other).new_self() - //~^ ERROR cannot borrow `**other` as mutable more than once at a time [E0499] + //[nll]~^ ERROR cannot borrow `**other` as mutable more than once at a time [E0499] }; let c = other; diff --git a/tests/ui/nll/polonius/assignment-kills-loans.rs b/tests/ui/nll/polonius/assignment-kills-loans.rs index 182262e5c4b..56ea9c2f1f9 100644 --- a/tests/ui/nll/polonius/assignment-kills-loans.rs +++ b/tests/ui/nll/polonius/assignment-kills-loans.rs @@ -4,8 +4,11 @@ // facts only on simple assignments, but not projections, incorrectly causing errors to be emitted // for code accepted by NLL. They are all variations from example code in the NLL RFC. +//@ ignore-compare-mode-polonius (explicit revisions) +//@ revisions: polonius_next polonius //@ check-pass -//@ compile-flags: -Z polonius +//@ [polonius_next] compile-flags: -Z polonius=next +//@ [polonius] compile-flags: -Z polonius struct List<T> { value: T, diff --git a/tests/ui/nll/polonius/assignment-to-differing-field.stderr b/tests/ui/nll/polonius/assignment-to-differing-field.legacy.stderr index c46d010e4f5..cf5594dbd07 100644 --- a/tests/ui/nll/polonius/assignment-to-differing-field.stderr +++ b/tests/ui/nll/polonius/assignment-to-differing-field.legacy.stderr @@ -1,5 +1,5 @@ error[E0499]: cannot borrow `list.0.value` as mutable more than once at a time - --> $DIR/assignment-to-differing-field.rs:20:21 + --> $DIR/assignment-to-differing-field.rs:23:21 | LL | fn assignment_to_field_projection<'a, T>( | -- lifetime `'a` defined here @@ -11,7 +11,7 @@ LL | return result; | ------ returning this value requires that `list.0.value` is borrowed for `'a` error[E0499]: cannot borrow `list.0.next` as mutable more than once at a time - --> $DIR/assignment-to-differing-field.rs:23:26 + --> $DIR/assignment-to-differing-field.rs:26:26 | LL | fn assignment_to_field_projection<'a, T>( | -- lifetime `'a` defined here @@ -23,7 +23,7 @@ LL | list.1 = n; | ---------- assignment requires that `list.0.next` is borrowed for `'a` error[E0499]: cannot borrow `list.0.0.0.0.0.value` as mutable more than once at a time - --> $DIR/assignment-to-differing-field.rs:37:21 + --> $DIR/assignment-to-differing-field.rs:40:21 | LL | fn assignment_through_projection_chain<'a, T>( | -- lifetime `'a` defined here @@ -35,7 +35,7 @@ LL | return result; | ------ returning this value requires that `list.0.0.0.0.0.value` is borrowed for `'a` error[E0499]: cannot borrow `list.0.0.0.0.0.next` as mutable more than once at a time - --> $DIR/assignment-to-differing-field.rs:40:26 + --> $DIR/assignment-to-differing-field.rs:43:26 | LL | fn assignment_through_projection_chain<'a, T>( | -- lifetime `'a` defined here diff --git a/tests/ui/nll/polonius/assignment-to-differing-field.polonius.stderr b/tests/ui/nll/polonius/assignment-to-differing-field.polonius.stderr new file mode 100644 index 00000000000..cf5594dbd07 --- /dev/null +++ b/tests/ui/nll/polonius/assignment-to-differing-field.polonius.stderr @@ -0,0 +1,51 @@ +error[E0499]: cannot borrow `list.0.value` as mutable more than once at a time + --> $DIR/assignment-to-differing-field.rs:23:21 + | +LL | fn assignment_to_field_projection<'a, T>( + | -- lifetime `'a` defined here +... +LL | result.push(&mut (list.0).value); + | ^^^^^^^^^^^^^^^^^^^ `list.0.value` was mutably borrowed here in the previous iteration of the loop +... +LL | return result; + | ------ returning this value requires that `list.0.value` is borrowed for `'a` + +error[E0499]: cannot borrow `list.0.next` as mutable more than once at a time + --> $DIR/assignment-to-differing-field.rs:26:26 + | +LL | fn assignment_to_field_projection<'a, T>( + | -- lifetime `'a` defined here +... +LL | if let Some(n) = (list.0).next.as_mut() { + | ^^^^^^^^^^^^^ `list.0.next` was mutably borrowed here in the previous iteration of the loop +LL | +LL | list.1 = n; + | ---------- assignment requires that `list.0.next` is borrowed for `'a` + +error[E0499]: cannot borrow `list.0.0.0.0.0.value` as mutable more than once at a time + --> $DIR/assignment-to-differing-field.rs:40:21 + | +LL | fn assignment_through_projection_chain<'a, T>( + | -- lifetime `'a` defined here +... +LL | result.push(&mut ((((list.0).0).0).0).0.value); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `list.0.0.0.0.0.value` was mutably borrowed here in the previous iteration of the loop +... +LL | return result; + | ------ returning this value requires that `list.0.0.0.0.0.value` is borrowed for `'a` + +error[E0499]: cannot borrow `list.0.0.0.0.0.next` as mutable more than once at a time + --> $DIR/assignment-to-differing-field.rs:43:26 + | +LL | fn assignment_through_projection_chain<'a, T>( + | -- lifetime `'a` defined here +... +LL | if let Some(n) = ((((list.0).0).0).0).0.next.as_mut() { + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ `list.0.0.0.0.0.next` was mutably borrowed here in the previous iteration of the loop +LL | +LL | *((((list.0).0).0).0).1 = n; + | --------------------------- assignment requires that `list.0.0.0.0.0.next` is borrowed for `'a` + +error: aborting due to 4 previous errors + +For more information about this error, try `rustc --explain E0499`. diff --git a/tests/ui/nll/polonius/assignment-to-differing-field.rs b/tests/ui/nll/polonius/assignment-to-differing-field.rs index fb6c9569525..9701cd2bb5e 100644 --- a/tests/ui/nll/polonius/assignment-to-differing-field.rs +++ b/tests/ui/nll/polonius/assignment-to-differing-field.rs @@ -4,7 +4,10 @@ // that we do not kill too many borrows. Assignments to the `.1` // field projections should leave the borrows on `.0` intact. -//@ compile-flags: -Z polonius +//@ ignore-compare-mode-polonius (explicit revisions) +//@ revisions: polonius legacy +//@ [polonius] compile-flags: -Z polonius=next +//@ [legacy] compile-flags: -Z polonius=legacy struct List<T> { value: T, diff --git a/tests/ui/nll/polonius/call-kills-loans.rs b/tests/ui/nll/polonius/call-kills-loans.rs index c02293c9a78..0657c42f48c 100644 --- a/tests/ui/nll/polonius/call-kills-loans.rs +++ b/tests/ui/nll/polonius/call-kills-loans.rs @@ -4,8 +4,11 @@ // by NLL but was incorrectly rejected by Polonius because of these // missing `killed` facts. +//@ ignore-compare-mode-polonius (explicit revisions) +//@ revisions: polonius_next polonius //@ check-pass -//@ compile-flags: -Z polonius +//@ [polonius_next] compile-flags: -Z polonius=next +//@ [polonius] compile-flags: -Z polonius struct Thing; diff --git a/tests/ui/nll/polonius/issue-46589.rs b/tests/ui/nll/polonius/issue-46589.rs deleted file mode 100644 index af791f7e24d..00000000000 --- a/tests/ui/nll/polonius/issue-46589.rs +++ /dev/null @@ -1,31 +0,0 @@ -// This test is a copy of `ui/nll/issue-46589.rs` which fails in NLL but succeeds in Polonius. -// As we can't have a test here which conditionally passes depending on a test -// revision/compile-flags. We ensure here that it passes in Polonius mode. - -//@ check-pass -//@ compile-flags: -Z polonius - -struct Foo; - -impl Foo { - fn get_self(&mut self) -> Option<&mut Self> { - Some(self) - } - - fn new_self(&mut self) -> &mut Self { - self - } - - fn trigger_bug(&mut self) { - let other = &mut (&mut *self); - - *other = match (*other).get_self() { - Some(s) => s, - None => (*other).new_self() - }; - - let c = other; - } -} - -fn main() {} diff --git a/tests/ui/nll/polonius/location-insensitive-scopes-liveness.rs b/tests/ui/nll/polonius/location-insensitive-scopes-liveness.rs index cb56c8f6deb..677b7aa1df8 100644 --- a/tests/ui/nll/polonius/location-insensitive-scopes-liveness.rs +++ b/tests/ui/nll/polonius/location-insensitive-scopes-liveness.rs @@ -5,9 +5,11 @@ // than `liveness::trace`, on some specific CFGs shapes: a variable was dead during tracing but its // regions were marked live later, and live loans were not recomputed at this point. +//@ ignore-compare-mode-polonius (explicit revisions) +//@ revisions: polonius_next polonius //@ check-pass -//@ revisions: nll polonius -//@ [polonius] compile-flags: -Zpolonius=next +//@ [polonius_next] compile-flags: -Z polonius=next +//@ [polonius] compile-flags: -Z polonius // minimized from wavefc-cli-3.0.0 fn repro1() { diff --git a/tests/ui/nll/polonius/polonius-smoke-test.stderr b/tests/ui/nll/polonius/polonius-smoke-test.legacy.stderr index a8a8267290d..1268f6167f8 100644 --- a/tests/ui/nll/polonius/polonius-smoke-test.stderr +++ b/tests/ui/nll/polonius/polonius-smoke-test.legacy.stderr @@ -1,11 +1,11 @@ error[E0515]: cannot return reference to local variable `x` - --> $DIR/polonius-smoke-test.rs:6:5 + --> $DIR/polonius-smoke-test.rs:10:5 | LL | &x | ^^ returns a reference to data owned by the current function error[E0503]: cannot use `x` because it was mutably borrowed - --> $DIR/polonius-smoke-test.rs:12:13 + --> $DIR/polonius-smoke-test.rs:16:13 | LL | let y = &mut x; | ------ `x` is borrowed here @@ -15,7 +15,7 @@ LL | let w = y; | - borrow later used here error[E0505]: cannot move out of `x` because it is borrowed - --> $DIR/polonius-smoke-test.rs:18:13 + --> $DIR/polonius-smoke-test.rs:22:13 | LL | pub fn use_while_mut_fr(x: &mut i32) -> &mut i32 { | - - let's call the lifetime of this reference `'1` @@ -35,7 +35,7 @@ LL + let y = &mut x.clone(); | error[E0505]: cannot move out of `s` because it is borrowed - --> $DIR/polonius-smoke-test.rs:42:5 + --> $DIR/polonius-smoke-test.rs:46:5 | LL | let s = &mut 1; | - binding `s` declared here diff --git a/tests/ui/nll/polonius/polonius-smoke-test.polonius.stderr b/tests/ui/nll/polonius/polonius-smoke-test.polonius.stderr new file mode 100644 index 00000000000..1268f6167f8 --- /dev/null +++ b/tests/ui/nll/polonius/polonius-smoke-test.polonius.stderr @@ -0,0 +1,59 @@ +error[E0515]: cannot return reference to local variable `x` + --> $DIR/polonius-smoke-test.rs:10:5 + | +LL | &x + | ^^ returns a reference to data owned by the current function + +error[E0503]: cannot use `x` because it was mutably borrowed + --> $DIR/polonius-smoke-test.rs:16:13 + | +LL | let y = &mut x; + | ------ `x` is borrowed here +LL | let z = x; + | ^ use of borrowed `x` +LL | let w = y; + | - borrow later used here + +error[E0505]: cannot move out of `x` because it is borrowed + --> $DIR/polonius-smoke-test.rs:22:13 + | +LL | pub fn use_while_mut_fr(x: &mut i32) -> &mut i32 { + | - - let's call the lifetime of this reference `'1` + | | + | binding `x` declared here +LL | let y = &mut *x; + | ------- borrow of `*x` occurs here +LL | let z = x; + | ^ move out of `x` occurs here +LL | y + | - returning this value requires that `*x` is borrowed for `'1` + | +help: consider cloning the value if the performance cost is acceptable + | +LL - let y = &mut *x; +LL + let y = &mut x.clone(); + | + +error[E0505]: cannot move out of `s` because it is borrowed + --> $DIR/polonius-smoke-test.rs:46:5 + | +LL | let s = &mut 1; + | - binding `s` declared here +LL | let r = &mut *s; + | ------- borrow of `*s` occurs here +LL | let tmp = foo(&r); +LL | s; + | ^ move out of `s` occurs here +LL | tmp; + | --- borrow later used here + | +help: consider cloning the value if the performance cost is acceptable + | +LL - let r = &mut *s; +LL + let r = &mut s.clone(); + | + +error: aborting due to 4 previous errors + +Some errors have detailed explanations: E0503, E0505, E0515. +For more information about an error, try `rustc --explain E0503`. diff --git a/tests/ui/nll/polonius/polonius-smoke-test.rs b/tests/ui/nll/polonius/polonius-smoke-test.rs index ea5cdb263f5..7fbb3f9b47c 100644 --- a/tests/ui/nll/polonius/polonius-smoke-test.rs +++ b/tests/ui/nll/polonius/polonius-smoke-test.rs @@ -1,5 +1,9 @@ -// Check that Polonius borrow check works for simple cases. -//@ compile-flags: -Z polonius +// Check that Polonius works for simple cases. + +//@ ignore-compare-mode-polonius (explicit revisions) +//@ revisions: polonius legacy +//@ [polonius] compile-flags: -Z polonius=next +//@ [legacy] compile-flags: -Z polonius=legacy pub fn return_ref_to_local() -> &'static i32 { let x = 0; diff --git a/tests/ui/nll/polonius/storagedead-kills-loans.rs b/tests/ui/nll/polonius/storagedead-kills-loans.rs index 89cf919bb48..75a37e6ece5 100644 --- a/tests/ui/nll/polonius/storagedead-kills-loans.rs +++ b/tests/ui/nll/polonius/storagedead-kills-loans.rs @@ -3,8 +3,11 @@ // is correctly accepted by NLL but was incorrectly rejected by // Polonius because of these missing `killed` facts. +//@ ignore-compare-mode-polonius (explicit revisions) +//@ revisions: polonius_next polonius //@ check-pass -//@ compile-flags: -Z polonius +//@ [polonius_next] compile-flags: -Z polonius=next +//@ [polonius] compile-flags: -Z polonius use std::{io, mem}; use std::io::Read; diff --git a/tests/ui/nll/polonius/subset-relations.stderr b/tests/ui/nll/polonius/subset-relations.legacy.stderr index 9deca6449a8..10d42ca58d9 100644 --- a/tests/ui/nll/polonius/subset-relations.stderr +++ b/tests/ui/nll/polonius/subset-relations.legacy.stderr @@ -1,5 +1,5 @@ error: lifetime may not live long enough - --> $DIR/subset-relations.rs:10:5 + --> $DIR/subset-relations.rs:13:5 | LL | fn missing_subset<'a, 'b>(x: &'a u32, y: &'b u32) -> &'a u32 { | -- -- lifetime `'b` defined here diff --git a/tests/ui/nll/polonius/subset-relations.polonius.stderr b/tests/ui/nll/polonius/subset-relations.polonius.stderr new file mode 100644 index 00000000000..10d42ca58d9 --- /dev/null +++ b/tests/ui/nll/polonius/subset-relations.polonius.stderr @@ -0,0 +1,14 @@ +error: lifetime may not live long enough + --> $DIR/subset-relations.rs:13:5 + | +LL | fn missing_subset<'a, 'b>(x: &'a u32, y: &'b u32) -> &'a u32 { + | -- -- lifetime `'b` defined here + | | + | lifetime `'a` defined here +LL | y + | ^ function was supposed to return data with lifetime `'a` but it is returning data with lifetime `'b` + | + = help: consider adding the following bound: `'b: 'a` + +error: aborting due to 1 previous error + diff --git a/tests/ui/nll/polonius/subset-relations.rs b/tests/ui/nll/polonius/subset-relations.rs index 3c1af1983cf..d47e4e05533 100644 --- a/tests/ui/nll/polonius/subset-relations.rs +++ b/tests/ui/nll/polonius/subset-relations.rs @@ -3,7 +3,10 @@ // two free regions outlive each other, without any evidence that this // relation holds. -//@ compile-flags: -Z polonius +//@ ignore-compare-mode-polonius (explicit revisions) +//@ revisions: polonius legacy +//@ [polonius] compile-flags: -Z polonius=next +//@ [legacy] compile-flags: -Z polonius=legacy // returning `y` requires that `'b: 'a`, but it's not known to be true fn missing_subset<'a, 'b>(x: &'a u32, y: &'b u32) -> &'a u32 { @@ -22,7 +25,7 @@ fn implied_bounds_subset<'a, 'b>(x: &'a &'b mut u32) -> &'a u32 { // `'b: 'a` is declared, and `'a: 'c` is known via implied bounds: // `'b: 'c` is therefore known to hold transitively -fn transitively_valid_subset<'a, 'b: 'a, 'c>(x: &'c &'a u32, y: &'b u32) -> &'c u32 { +fn transitively_valid_subset<'a, 'b: 'a, 'c>(x: &'c &'a u32, y: &'b u32) -> &'c u32 { y } diff --git a/tests/ui/panics/issue-47429-short-backtraces.rs b/tests/ui/panics/issue-47429-short-backtraces.rs index 4a73ebe8712..378ade67bfd 100644 --- a/tests/ui/panics/issue-47429-short-backtraces.rs +++ b/tests/ui/panics/issue-47429-short-backtraces.rs @@ -17,8 +17,6 @@ //@ ignore-msvc see #62897 and `backtrace-debuginfo.rs` test //@ ignore-android FIXME #17520 //@ ignore-openbsd no support for libbacktrace without filename -//@ ignore-wasm no panic support -//@ ignore-emscripten no panic support //@ ignore-fuchsia Backtraces not symbolized //@ needs-subprocess diff --git a/tests/ui/panics/issue-47429-short-backtraces.run.stderr b/tests/ui/panics/issue-47429-short-backtraces.run.stderr index c6e2d13fb5d..32dc6592271 100644 --- a/tests/ui/panics/issue-47429-short-backtraces.run.stderr +++ b/tests/ui/panics/issue-47429-short-backtraces.run.stderr @@ -1,5 +1,5 @@ -thread 'main' panicked at $DIR/issue-47429-short-backtraces.rs:26:5: +thread 'main' panicked at $DIR/issue-47429-short-backtraces.rs:24:5: explicit panic stack backtrace: 0: std::panicking::begin_panic diff --git a/tests/ui/panics/runtime-switch.rs b/tests/ui/panics/runtime-switch.rs index 9f0be8c7ddf..7d5b4169340 100644 --- a/tests/ui/panics/runtime-switch.rs +++ b/tests/ui/panics/runtime-switch.rs @@ -18,7 +18,6 @@ //@ ignore-android FIXME #17520 //@ ignore-openbsd no support for libbacktrace without filename //@ ignore-wasm no backtrace support -//@ ignore-emscripten no panic support //@ ignore-fuchsia Backtrace not symbolized //@ needs-subprocess diff --git a/tests/ui/panics/runtime-switch.run.stderr b/tests/ui/panics/runtime-switch.run.stderr index 458a0ee534a..70ed127af86 100644 --- a/tests/ui/panics/runtime-switch.run.stderr +++ b/tests/ui/panics/runtime-switch.run.stderr @@ -1,5 +1,5 @@ -thread 'main' panicked at $DIR/runtime-switch.rs:29:5: +thread 'main' panicked at $DIR/runtime-switch.rs:28:5: explicit panic stack backtrace: 0: std::panicking::begin_panic diff --git a/tests/ui/panics/short-ice-remove-middle-frames-2.rs b/tests/ui/panics/short-ice-remove-middle-frames-2.rs index 48f60b14170..660530f0ead 100644 --- a/tests/ui/panics/short-ice-remove-middle-frames-2.rs +++ b/tests/ui/panics/short-ice-remove-middle-frames-2.rs @@ -5,7 +5,6 @@ //@ needs-unwind //@ ignore-android FIXME #17520 //@ ignore-openbsd no support for libbacktrace without filename -//@ ignore-emscripten no panic //@ ignore-sgx Backtraces not symbolized //@ ignore-fuchsia Backtraces not symbolized //@ ignore-msvc the `__rust_{begin,end}_short_backtrace` symbols aren't reliable. diff --git a/tests/ui/panics/short-ice-remove-middle-frames-2.run.stderr b/tests/ui/panics/short-ice-remove-middle-frames-2.run.stderr index 1fddcca6951..664d51e185d 100644 --- a/tests/ui/panics/short-ice-remove-middle-frames-2.run.stderr +++ b/tests/ui/panics/short-ice-remove-middle-frames-2.run.stderr @@ -1,5 +1,5 @@ -thread 'main' panicked at $DIR/short-ice-remove-middle-frames-2.rs:63:5: +thread 'main' panicked at $DIR/short-ice-remove-middle-frames-2.rs:62:5: debug!!! stack backtrace: 0: std::panicking::begin_panic diff --git a/tests/ui/panics/short-ice-remove-middle-frames.rs b/tests/ui/panics/short-ice-remove-middle-frames.rs index 216c5127799..41fb6e9950e 100644 --- a/tests/ui/panics/short-ice-remove-middle-frames.rs +++ b/tests/ui/panics/short-ice-remove-middle-frames.rs @@ -5,7 +5,6 @@ //@ needs-unwind //@ ignore-android FIXME #17520 //@ ignore-openbsd no support for libbacktrace without filename -//@ ignore-emscripten no panic //@ ignore-sgx Backtraces not symbolized //@ ignore-fuchsia Backtraces not symbolized //@ ignore-msvc the `__rust_{begin,end}_short_backtrace` symbols aren't reliable. diff --git a/tests/ui/panics/short-ice-remove-middle-frames.run.stderr b/tests/ui/panics/short-ice-remove-middle-frames.run.stderr index 630b09d8d1e..e966462331f 100644 --- a/tests/ui/panics/short-ice-remove-middle-frames.run.stderr +++ b/tests/ui/panics/short-ice-remove-middle-frames.run.stderr @@ -1,5 +1,5 @@ -thread 'main' panicked at $DIR/short-ice-remove-middle-frames.rs:59:5: +thread 'main' panicked at $DIR/short-ice-remove-middle-frames.rs:58:5: debug!!! stack backtrace: 0: std::panicking::begin_panic diff --git a/tests/ui/parser/mod_file_not_exist.rs b/tests/ui/parser/mod_file_not_exist.rs index e7727944147..49ce44982ab 100644 --- a/tests/ui/parser/mod_file_not_exist.rs +++ b/tests/ui/parser/mod_file_not_exist.rs @@ -1,5 +1,3 @@ -//@ ignore-windows - mod not_a_real_file; //~ ERROR file not found for module `not_a_real_file` //~^ HELP to create the module `not_a_real_file`, create file diff --git a/tests/ui/parser/mod_file_not_exist.stderr b/tests/ui/parser/mod_file_not_exist.stderr index 40041b11c8b..d9e4e8f31f5 100644 --- a/tests/ui/parser/mod_file_not_exist.stderr +++ b/tests/ui/parser/mod_file_not_exist.stderr @@ -1,5 +1,5 @@ error[E0583]: file not found for module `not_a_real_file` - --> $DIR/mod_file_not_exist.rs:3:1 + --> $DIR/mod_file_not_exist.rs:1:1 | LL | mod not_a_real_file; | ^^^^^^^^^^^^^^^^^^^^ @@ -8,7 +8,7 @@ LL | mod not_a_real_file; = note: if there is a `mod not_a_real_file` elsewhere in the crate already, import it with `use crate::...` instead error[E0433]: failed to resolve: use of unresolved module or unlinked crate `mod_file_aux` - --> $DIR/mod_file_not_exist.rs:7:16 + --> $DIR/mod_file_not_exist.rs:5:16 | LL | assert_eq!(mod_file_aux::bar(), 10); | ^^^^^^^^^^^^ use of unresolved module or unlinked crate `mod_file_aux` diff --git a/tests/ui/privacy/privacy2.rs b/tests/ui/privacy/privacy2.rs index ab6d805544e..c82cd442559 100644 --- a/tests/ui/privacy/privacy2.rs +++ b/tests/ui/privacy/privacy2.rs @@ -14,16 +14,20 @@ mod bar { } pub fn foo() {} +//~^ ERROR requires `sized` lang_item fn test1() { + //~^ ERROR requires `sized` lang_item use bar::foo; //~^ ERROR unresolved import `bar::foo` [E0432] //~| no `foo` in `bar` } fn test2() { + //~^ ERROR requires `sized` lang_item use bar::glob::foo; //~^ ERROR `foo` is private } fn main() {} +//~^ ERROR requires `sized` lang_item diff --git a/tests/ui/privacy/privacy2.stderr b/tests/ui/privacy/privacy2.stderr index 46bb9823dbf..39bab67a660 100644 --- a/tests/ui/privacy/privacy2.stderr +++ b/tests/ui/privacy/privacy2.stderr @@ -1,11 +1,11 @@ error[E0432]: unresolved import `bar::foo` - --> $DIR/privacy2.rs:19:9 + --> $DIR/privacy2.rs:21:9 | LL | use bar::foo; | ^^^^^^^^ no `foo` in `bar` error[E0603]: function import `foo` is private - --> $DIR/privacy2.rs:25:20 + --> $DIR/privacy2.rs:28:20 | LL | use bar::glob::foo; | ^^^ private function import @@ -22,8 +22,40 @@ LL | pub fn foo() {} | ^^^^^^^^^^^^ you could import this directly error: requires `sized` lang_item + --> $DIR/privacy2.rs:16:14 + | +LL | pub fn foo() {} + | ^^ + +error: requires `sized` lang_item + --> $DIR/privacy2.rs:19:12 + | +LL | fn test1() { + | ____________^ +LL | | +LL | | use bar::foo; +... | +LL | | } + | |_^ + +error: requires `sized` lang_item + --> $DIR/privacy2.rs:26:12 + | +LL | fn test2() { + | ____________^ +LL | | +LL | | use bar::glob::foo; +LL | | +LL | | } + | |_^ + +error: requires `sized` lang_item + --> $DIR/privacy2.rs:32:11 + | +LL | fn main() {} + | ^^ -error: aborting due to 3 previous errors +error: aborting due to 6 previous errors Some errors have detailed explanations: E0432, E0603. For more information about an error, try `rustc --explain E0432`. diff --git a/tests/ui/privacy/privacy3.rs b/tests/ui/privacy/privacy3.rs index 6298a6bc8cf..2bb3c1b3c61 100644 --- a/tests/ui/privacy/privacy3.rs +++ b/tests/ui/privacy/privacy3.rs @@ -11,12 +11,15 @@ mod bar { mod glob { fn gpriv() {} + //~^ ERROR requires `sized` lang_item } } pub fn foo() {} +//~^ ERROR requires `sized` lang_item fn test1() { + //~^ ERROR requires `sized` lang_item use bar::gpriv; //~^ ERROR unresolved import `bar::gpriv` [E0432] //~| no `gpriv` in `bar` @@ -27,3 +30,4 @@ fn test1() { } fn main() {} +//~^ ERROR requires `sized` lang_item diff --git a/tests/ui/privacy/privacy3.stderr b/tests/ui/privacy/privacy3.stderr index df66c84751b..06a287d35ea 100644 --- a/tests/ui/privacy/privacy3.stderr +++ b/tests/ui/privacy/privacy3.stderr @@ -1,11 +1,39 @@ error[E0432]: unresolved import `bar::gpriv` - --> $DIR/privacy3.rs:20:9 + --> $DIR/privacy3.rs:23:9 | LL | use bar::gpriv; | ^^^^^^^^^^ no `gpriv` in `bar` error: requires `sized` lang_item + --> $DIR/privacy3.rs:18:14 + | +LL | pub fn foo() {} + | ^^ + +error: requires `sized` lang_item + --> $DIR/privacy3.rs:21:12 + | +LL | fn test1() { + | ____________^ +LL | | +LL | | use bar::gpriv; +... | +LL | | gpriv(); +LL | | } + | |_^ + +error: requires `sized` lang_item + --> $DIR/privacy3.rs:32:11 + | +LL | fn main() {} + | ^^ + +error: requires `sized` lang_item + --> $DIR/privacy3.rs:13:20 + | +LL | fn gpriv() {} + | ^^ -error: aborting due to 2 previous errors +error: aborting due to 5 previous errors For more information about this error, try `rustc --explain E0432`. diff --git a/tests/ui/proc-macro/issue-59191-replace-root-with-fn.stderr b/tests/ui/proc-macro/issue-59191-replace-root-with-fn.stderr index 08e679a7c55..2d0c92ff297 100644 --- a/tests/ui/proc-macro/issue-59191-replace-root-with-fn.stderr +++ b/tests/ui/proc-macro/issue-59191-replace-root-with-fn.stderr @@ -1,4 +1,10 @@ error: requires `sized` lang_item + --> $DIR/issue-59191-replace-root-with-fn.rs:9:1 + | +LL | #![issue_59191::no_main] + | ^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: this error originates in the attribute macro `issue_59191::no_main` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/range/issue-54505-no-literals.stderr b/tests/ui/range/issue-54505-no-literals.stderr index 5894bb6ba55..c6d4384bcd3 100644 --- a/tests/ui/range/issue-54505-no-literals.stderr +++ b/tests/ui/range/issue-54505-no-literals.stderr @@ -47,7 +47,7 @@ LL | take_range(std::ops::RangeFrom { start: 1 }); | arguments to this function are incorrect | = note: expected reference `&_` - found struct `RangeFrom<{integer}>` + found struct `std::ops::RangeFrom<{integer}>` note: function defined here --> $DIR/issue-54505-no-literals.rs:12:4 | @@ -67,7 +67,7 @@ LL | take_range(::std::ops::RangeFrom { start: 1 }); | arguments to this function are incorrect | = note: expected reference `&_` - found struct `RangeFrom<{integer}>` + found struct `std::ops::RangeFrom<{integer}>` note: function defined here --> $DIR/issue-54505-no-literals.rs:12:4 | @@ -127,7 +127,7 @@ LL | take_range(std::ops::RangeInclusive::new(0, 1)); | arguments to this function are incorrect | = note: expected reference `&_` - found struct `RangeInclusive<{integer}>` + found struct `std::ops::RangeInclusive<{integer}>` note: function defined here --> $DIR/issue-54505-no-literals.rs:12:4 | @@ -147,7 +147,7 @@ LL | take_range(::std::ops::RangeInclusive::new(0, 1)); | arguments to this function are incorrect | = note: expected reference `&_` - found struct `RangeInclusive<{integer}>` + found struct `std::ops::RangeInclusive<{integer}>` note: function defined here --> $DIR/issue-54505-no-literals.rs:12:4 | diff --git a/tests/ui/range/issue-54505.stderr b/tests/ui/range/issue-54505.stderr index 291e097e865..8b669b2910f 100644 --- a/tests/ui/range/issue-54505.stderr +++ b/tests/ui/range/issue-54505.stderr @@ -27,7 +27,7 @@ LL | take_range(1..); | arguments to this function are incorrect | = note: expected reference `&_` - found struct `RangeFrom<{integer}>` + found struct `std::ops::RangeFrom<{integer}>` note: function defined here --> $DIR/issue-54505.rs:10:4 | @@ -72,7 +72,7 @@ LL | take_range(0..=1); | arguments to this function are incorrect | = note: expected reference `&_` - found struct `RangeInclusive<{integer}>` + found struct `std::ops::RangeInclusive<{integer}>` note: function defined here --> $DIR/issue-54505.rs:10:4 | diff --git a/tests/ui/range/range-1.stderr b/tests/ui/range/range-1.stderr index f77601bc43c..37669dd3f47 100644 --- a/tests/ui/range/range-1.stderr +++ b/tests/ui/range/range-1.stderr @@ -30,7 +30,7 @@ LL | let range = *arr..; | ^^^^ doesn't have a size known at compile-time | = help: the trait `Sized` is not implemented for `[{integer}]` -note: required by an implicit `Sized` bound in `RangeFrom` +note: required by an implicit `Sized` bound in `std::ops::RangeFrom` --> $SRC_DIR/core/src/ops/range.rs:LL:COL error: aborting due to 3 previous errors diff --git a/tests/ui/simd/array-trait.rs b/tests/ui/simd/array-trait.rs index 67583bf8208..32cbf01428c 100644 --- a/tests/ui/simd/array-trait.rs +++ b/tests/ui/simd/array-trait.rs @@ -24,10 +24,12 @@ pub struct T<S: Simd>([S::Lane; S::SIZE]); //~| ERROR SIMD vector element type should be a primitive scalar //~| ERROR unconstrained generic constant -extern "rust-intrinsic" { - fn simd_insert<T, E>(x: T, idx: u32, y: E) -> T; - fn simd_extract<T, E>(x: T, idx: u32) -> E; -} +#[rustc_intrinsic] +unsafe fn simd_insert<T, E>(x: T, idx: u32, y: E) -> T; + +#[rustc_intrinsic] +unsafe fn simd_extract<T, E>(x: T, idx: u32) -> E; + pub fn main() { let mut t = T::<i32x4>([0; 4]); diff --git a/tests/ui/simd/array-type.rs b/tests/ui/simd/array-type.rs index 8ca53b1a453..d1de7004416 100644 --- a/tests/ui/simd/array-type.rs +++ b/tests/ui/simd/array-type.rs @@ -12,10 +12,12 @@ struct S([i32; 4]); #[derive(Copy, Clone)] struct T<const N: usize>([i32; N]); -extern "rust-intrinsic" { - fn simd_insert<T, E>(x: T, idx: u32, y: E) -> T; - fn simd_extract<T, E>(x: T, idx: u32) -> E; -} +#[rustc_intrinsic] +unsafe fn simd_insert<T, E>(x: T, idx: u32, y: E) -> T; + +#[rustc_intrinsic] +unsafe fn simd_extract<T, E>(x: T, idx: u32) -> E; + pub fn main() { let mut s = S([0; 4]); diff --git a/tests/ui/simd/generics.rs b/tests/ui/simd/generics.rs index f96a7cd75e9..453ed86c14a 100644 --- a/tests/ui/simd/generics.rs +++ b/tests/ui/simd/generics.rs @@ -21,9 +21,8 @@ struct B<T>([T; 4]); struct C<T, const N: usize>([T; N]); -extern "rust-intrinsic" { - fn simd_add<T>(x: T, y: T) -> T; -} +#[rustc_intrinsic] +unsafe fn simd_add<T>(x: T, y: T) -> T; fn add<T: ops::Add<Output=T>>(lhs: T, rhs: T) -> T { lhs + rhs diff --git a/tests/ui/simd/intrinsic/float-math-pass.rs b/tests/ui/simd/intrinsic/float-math-pass.rs index 24b9941133e..74cb51a0606 100644 --- a/tests/ui/simd/intrinsic/float-math-pass.rs +++ b/tests/ui/simd/intrinsic/float-math-pass.rs @@ -15,27 +15,59 @@ #[derive(Copy, Clone, PartialEq, Debug)] struct f32x4(pub [f32; 4]); -extern "rust-intrinsic" { - fn simd_fsqrt<T>(x: T) -> T; - fn simd_fabs<T>(x: T) -> T; - fn simd_fsin<T>(x: T) -> T; - fn simd_fcos<T>(x: T) -> T; - fn simd_fexp<T>(x: T) -> T; - fn simd_fexp2<T>(x: T) -> T; - fn simd_fma<T>(x: T, y: T, z: T) -> T; - fn simd_relaxed_fma<T>(x: T, y: T, z: T) -> T; - fn simd_flog<T>(x: T) -> T; - fn simd_flog10<T>(x: T) -> T; - fn simd_flog2<T>(x: T) -> T; - fn simd_fpow<T>(x: T, y: T) -> T; - fn simd_fpowi<T>(x: T, y: i32) -> T; - - // rounding functions - fn simd_ceil<T>(x: T) -> T; - fn simd_floor<T>(x: T) -> T; - fn simd_round<T>(x: T) -> T; - fn simd_trunc<T>(x: T) -> T; -} +#[rustc_intrinsic] +unsafe fn simd_fsqrt<T>(x: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_fabs<T>(x: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_fsin<T>(x: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_fcos<T>(x: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_fexp<T>(x: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_fexp2<T>(x: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_fma<T>(x: T, y: T, z: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_relaxed_fma<T>(x: T, y: T, z: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_flog<T>(x: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_flog10<T>(x: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_flog2<T>(x: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_fpow<T>(x: T, y: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_fpowi<T>(x: T, y: i32) -> T; + + +// rounding functions +#[rustc_intrinsic] +unsafe fn simd_ceil<T>(x: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_floor<T>(x: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_round<T>(x: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_trunc<T>(x: T) -> T; + macro_rules! assert_approx_eq_f32 { ($a:expr, $b:expr) => ({ diff --git a/tests/ui/simd/intrinsic/generic-arithmetic-2.rs b/tests/ui/simd/intrinsic/generic-arithmetic-2.rs index 663bcdf1981..0fcff8584c8 100644 --- a/tests/ui/simd/intrinsic/generic-arithmetic-2.rs +++ b/tests/ui/simd/intrinsic/generic-arithmetic-2.rs @@ -14,25 +14,54 @@ pub struct u32x4(pub [u32; 4]); #[derive(Copy, Clone)] pub struct f32x4(pub [f32; 4]); -extern "rust-intrinsic" { - fn simd_add<T>(x: T, y: T) -> T; - fn simd_sub<T>(x: T, y: T) -> T; - fn simd_mul<T>(x: T, y: T) -> T; - fn simd_div<T>(x: T, y: T) -> T; - fn simd_rem<T>(x: T, y: T) -> T; - fn simd_shl<T>(x: T, y: T) -> T; - fn simd_shr<T>(x: T, y: T) -> T; - fn simd_and<T>(x: T, y: T) -> T; - fn simd_or<T>(x: T, y: T) -> T; - fn simd_xor<T>(x: T, y: T) -> T; - - fn simd_neg<T>(x: T) -> T; - fn simd_bswap<T>(x: T) -> T; - fn simd_bitreverse<T>(x: T) -> T; - fn simd_ctlz<T>(x: T) -> T; - fn simd_ctpop<T>(x: T) -> T; - fn simd_cttz<T>(x: T) -> T; -} +#[rustc_intrinsic] +unsafe fn simd_add<T>(x: T, y: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_sub<T>(x: T, y: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_mul<T>(x: T, y: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_div<T>(x: T, y: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_rem<T>(x: T, y: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_shl<T>(x: T, y: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_shr<T>(x: T, y: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_and<T>(x: T, y: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_or<T>(x: T, y: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_xor<T>(x: T, y: T) -> T; + + +#[rustc_intrinsic] +unsafe fn simd_neg<T>(x: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_bswap<T>(x: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_bitreverse<T>(x: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_ctlz<T>(x: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_ctpop<T>(x: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_cttz<T>(x: T) -> T; fn main() { let x = i32x4([0, 0, 0, 0]); diff --git a/tests/ui/simd/intrinsic/generic-arithmetic-2.stderr b/tests/ui/simd/intrinsic/generic-arithmetic-2.stderr index 6f5f86d7d37..e67de2fe903 100644 --- a/tests/ui/simd/intrinsic/generic-arithmetic-2.stderr +++ b/tests/ui/simd/intrinsic/generic-arithmetic-2.stderr @@ -1,143 +1,143 @@ error[E0511]: invalid monomorphization of `simd_add` intrinsic: expected SIMD input type, found non-SIMD `i32` - --> $DIR/generic-arithmetic-2.rs:81:9 + --> $DIR/generic-arithmetic-2.rs:110:9 | LL | simd_add(0, 0); | ^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_sub` intrinsic: expected SIMD input type, found non-SIMD `i32` - --> $DIR/generic-arithmetic-2.rs:83:9 + --> $DIR/generic-arithmetic-2.rs:112:9 | LL | simd_sub(0, 0); | ^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_mul` intrinsic: expected SIMD input type, found non-SIMD `i32` - --> $DIR/generic-arithmetic-2.rs:85:9 + --> $DIR/generic-arithmetic-2.rs:114:9 | LL | simd_mul(0, 0); | ^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_div` intrinsic: expected SIMD input type, found non-SIMD `i32` - --> $DIR/generic-arithmetic-2.rs:87:9 + --> $DIR/generic-arithmetic-2.rs:116:9 | LL | simd_div(0, 0); | ^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_shl` intrinsic: expected SIMD input type, found non-SIMD `i32` - --> $DIR/generic-arithmetic-2.rs:89:9 + --> $DIR/generic-arithmetic-2.rs:118:9 | LL | simd_shl(0, 0); | ^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_shr` intrinsic: expected SIMD input type, found non-SIMD `i32` - --> $DIR/generic-arithmetic-2.rs:91:9 + --> $DIR/generic-arithmetic-2.rs:120:9 | LL | simd_shr(0, 0); | ^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_and` intrinsic: expected SIMD input type, found non-SIMD `i32` - --> $DIR/generic-arithmetic-2.rs:93:9 + --> $DIR/generic-arithmetic-2.rs:122:9 | LL | simd_and(0, 0); | ^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_or` intrinsic: expected SIMD input type, found non-SIMD `i32` - --> $DIR/generic-arithmetic-2.rs:95:9 + --> $DIR/generic-arithmetic-2.rs:124:9 | LL | simd_or(0, 0); | ^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_xor` intrinsic: expected SIMD input type, found non-SIMD `i32` - --> $DIR/generic-arithmetic-2.rs:97:9 + --> $DIR/generic-arithmetic-2.rs:126:9 | LL | simd_xor(0, 0); | ^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_neg` intrinsic: expected SIMD input type, found non-SIMD `i32` - --> $DIR/generic-arithmetic-2.rs:100:9 + --> $DIR/generic-arithmetic-2.rs:129:9 | LL | simd_neg(0); | ^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_bswap` intrinsic: expected SIMD input type, found non-SIMD `i32` - --> $DIR/generic-arithmetic-2.rs:102:9 + --> $DIR/generic-arithmetic-2.rs:131:9 | LL | simd_bswap(0); | ^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_bitreverse` intrinsic: expected SIMD input type, found non-SIMD `i32` - --> $DIR/generic-arithmetic-2.rs:104:9 + --> $DIR/generic-arithmetic-2.rs:133:9 | LL | simd_bitreverse(0); | ^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_ctlz` intrinsic: expected SIMD input type, found non-SIMD `i32` - --> $DIR/generic-arithmetic-2.rs:106:9 + --> $DIR/generic-arithmetic-2.rs:135:9 | LL | simd_ctlz(0); | ^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_cttz` intrinsic: expected SIMD input type, found non-SIMD `i32` - --> $DIR/generic-arithmetic-2.rs:108:9 + --> $DIR/generic-arithmetic-2.rs:137:9 | LL | simd_cttz(0); | ^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_shl` intrinsic: unsupported operation on `f32x4` with element `f32` - --> $DIR/generic-arithmetic-2.rs:111:9 + --> $DIR/generic-arithmetic-2.rs:140:9 | LL | simd_shl(z, z); | ^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_shr` intrinsic: unsupported operation on `f32x4` with element `f32` - --> $DIR/generic-arithmetic-2.rs:113:9 + --> $DIR/generic-arithmetic-2.rs:142:9 | LL | simd_shr(z, z); | ^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_and` intrinsic: unsupported operation on `f32x4` with element `f32` - --> $DIR/generic-arithmetic-2.rs:115:9 + --> $DIR/generic-arithmetic-2.rs:144:9 | LL | simd_and(z, z); | ^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_or` intrinsic: unsupported operation on `f32x4` with element `f32` - --> $DIR/generic-arithmetic-2.rs:117:9 + --> $DIR/generic-arithmetic-2.rs:146:9 | LL | simd_or(z, z); | ^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_xor` intrinsic: unsupported operation on `f32x4` with element `f32` - --> $DIR/generic-arithmetic-2.rs:119:9 + --> $DIR/generic-arithmetic-2.rs:148:9 | LL | simd_xor(z, z); | ^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_bswap` intrinsic: unsupported operation on `f32x4` with element `f32` - --> $DIR/generic-arithmetic-2.rs:121:9 + --> $DIR/generic-arithmetic-2.rs:150:9 | LL | simd_bswap(z); | ^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_bitreverse` intrinsic: unsupported operation on `f32x4` with element `f32` - --> $DIR/generic-arithmetic-2.rs:123:9 + --> $DIR/generic-arithmetic-2.rs:152:9 | LL | simd_bitreverse(z); | ^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_ctlz` intrinsic: unsupported operation on `f32x4` with element `f32` - --> $DIR/generic-arithmetic-2.rs:125:9 + --> $DIR/generic-arithmetic-2.rs:154:9 | LL | simd_ctlz(z); | ^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_ctpop` intrinsic: unsupported operation on `f32x4` with element `f32` - --> $DIR/generic-arithmetic-2.rs:127:9 + --> $DIR/generic-arithmetic-2.rs:156:9 | LL | simd_ctpop(z); | ^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_cttz` intrinsic: unsupported operation on `f32x4` with element `f32` - --> $DIR/generic-arithmetic-2.rs:129:9 + --> $DIR/generic-arithmetic-2.rs:158:9 | LL | simd_cttz(z); | ^^^^^^^^^^^^ diff --git a/tests/ui/simd/intrinsic/generic-arithmetic-pass.rs b/tests/ui/simd/intrinsic/generic-arithmetic-pass.rs index e4eb2a9da27..4a18c0164e4 100644 --- a/tests/ui/simd/intrinsic/generic-arithmetic-pass.rs +++ b/tests/ui/simd/intrinsic/generic-arithmetic-pass.rs @@ -23,25 +23,54 @@ macro_rules! all_eq { }}; } -extern "rust-intrinsic" { - fn simd_add<T>(x: T, y: T) -> T; - fn simd_sub<T>(x: T, y: T) -> T; - fn simd_mul<T>(x: T, y: T) -> T; - fn simd_div<T>(x: T, y: T) -> T; - fn simd_rem<T>(x: T, y: T) -> T; - fn simd_shl<T>(x: T, y: T) -> T; - fn simd_shr<T>(x: T, y: T) -> T; - fn simd_and<T>(x: T, y: T) -> T; - fn simd_or<T>(x: T, y: T) -> T; - fn simd_xor<T>(x: T, y: T) -> T; - - fn simd_neg<T>(x: T) -> T; - fn simd_bswap<T>(x: T) -> T; - fn simd_bitreverse<T>(x: T) -> T; - fn simd_ctlz<T>(x: T) -> T; - fn simd_ctpop<T>(x: T) -> T; - fn simd_cttz<T>(x: T) -> T; -} +#[rustc_intrinsic] +unsafe fn simd_add<T>(x: T, y: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_sub<T>(x: T, y: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_mul<T>(x: T, y: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_div<T>(x: T, y: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_rem<T>(x: T, y: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_shl<T>(x: T, y: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_shr<T>(x: T, y: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_and<T>(x: T, y: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_or<T>(x: T, y: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_xor<T>(x: T, y: T) -> T; + + +#[rustc_intrinsic] +unsafe fn simd_neg<T>(x: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_bswap<T>(x: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_bitreverse<T>(x: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_ctlz<T>(x: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_ctpop<T>(x: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_cttz<T>(x: T) -> T; fn main() { let x1 = i32x4([1, 2, 3, 4]); diff --git a/tests/ui/simd/intrinsic/generic-arithmetic-saturating-2.rs b/tests/ui/simd/intrinsic/generic-arithmetic-saturating-2.rs index ec6ac78df1a..85464402d6a 100644 --- a/tests/ui/simd/intrinsic/generic-arithmetic-saturating-2.rs +++ b/tests/ui/simd/intrinsic/generic-arithmetic-saturating-2.rs @@ -14,10 +14,12 @@ pub struct x4<T>(pub [T; 4]); #[derive(Copy, Clone)] pub struct f32x4(pub [f32; 4]); -extern "rust-intrinsic" { - fn simd_saturating_add<T>(x: T, y: T) -> T; - fn simd_saturating_sub<T>(x: T, y: T) -> T; -} +#[rustc_intrinsic] +unsafe fn simd_saturating_add<T>(x: T, y: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_saturating_sub<T>(x: T, y: T) -> T; + fn main() { let x = i32x4([0, 0, 0, 0]); diff --git a/tests/ui/simd/intrinsic/generic-arithmetic-saturating-2.stderr b/tests/ui/simd/intrinsic/generic-arithmetic-saturating-2.stderr index f349cb56560..cf275db7e43 100644 --- a/tests/ui/simd/intrinsic/generic-arithmetic-saturating-2.stderr +++ b/tests/ui/simd/intrinsic/generic-arithmetic-saturating-2.stderr @@ -1,11 +1,11 @@ error[E0511]: invalid monomorphization of `simd_saturating_add` intrinsic: expected element type `f32` of vector type `f32x4` to be a signed or unsigned integer type - --> $DIR/generic-arithmetic-saturating-2.rs:33:9 + --> $DIR/generic-arithmetic-saturating-2.rs:35:9 | LL | simd_saturating_add(z, z); | ^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_saturating_sub` intrinsic: expected element type `f32` of vector type `f32x4` to be a signed or unsigned integer type - --> $DIR/generic-arithmetic-saturating-2.rs:35:9 + --> $DIR/generic-arithmetic-saturating-2.rs:37:9 | LL | simd_saturating_sub(z, z); | ^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/simd/intrinsic/generic-arithmetic-saturating-pass.rs b/tests/ui/simd/intrinsic/generic-arithmetic-saturating-pass.rs index 57bda5c2d62..5fe65257d15 100644 --- a/tests/ui/simd/intrinsic/generic-arithmetic-saturating-pass.rs +++ b/tests/ui/simd/intrinsic/generic-arithmetic-saturating-pass.rs @@ -12,10 +12,12 @@ struct u32x4(pub [u32; 4]); #[derive(Copy, Clone)] struct I32<const N: usize>([i32; N]); -extern "rust-intrinsic" { - fn simd_saturating_add<T>(x: T, y: T) -> T; - fn simd_saturating_sub<T>(x: T, y: T) -> T; -} +#[rustc_intrinsic] +unsafe fn simd_saturating_add<T>(x: T, y: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_saturating_sub<T>(x: T, y: T) -> T; + fn main() { // unsigned diff --git a/tests/ui/simd/intrinsic/generic-as.rs b/tests/ui/simd/intrinsic/generic-as.rs index e97bf12c144..124ca56bc88 100644 --- a/tests/ui/simd/intrinsic/generic-as.rs +++ b/tests/ui/simd/intrinsic/generic-as.rs @@ -2,9 +2,9 @@ #![feature(repr_simd, intrinsics)] -extern "rust-intrinsic" { - fn simd_as<T, U>(x: T) -> U; -} + +#[rustc_intrinsic] +unsafe fn simd_as<T, U>(x: T) -> U; #[derive(Copy, Clone)] #[repr(simd)] diff --git a/tests/ui/simd/intrinsic/generic-bitmask-pass.rs b/tests/ui/simd/intrinsic/generic-bitmask-pass.rs index db10020bd46..08526991fbe 100644 --- a/tests/ui/simd/intrinsic/generic-bitmask-pass.rs +++ b/tests/ui/simd/intrinsic/generic-bitmask-pass.rs @@ -21,9 +21,8 @@ struct u8x4(pub [u8; 4]); #[derive(Copy, Clone, PartialEq, Debug)] struct Tx4<T>(pub [T; 4]); -extern "rust-intrinsic" { - fn simd_bitmask<T, U>(x: T) -> U; -} +#[rustc_intrinsic] +unsafe fn simd_bitmask<T, U>(x: T) -> U; fn main() { let z = u32x4([0, 0, 0, 0]); diff --git a/tests/ui/simd/intrinsic/generic-bitmask.rs b/tests/ui/simd/intrinsic/generic-bitmask.rs index 29b9279c370..49589d22bbf 100644 --- a/tests/ui/simd/intrinsic/generic-bitmask.rs +++ b/tests/ui/simd/intrinsic/generic-bitmask.rs @@ -30,9 +30,8 @@ struct u8x32([u8; 32]); #[derive(Copy, Clone)] struct u8x64([u8; 64]); -extern "rust-intrinsic" { - fn simd_bitmask<T, U>(x: T) -> U; -} +#[rustc_intrinsic] +unsafe fn simd_bitmask<T, U>(x: T) -> U; fn main() { let m2 = u32x2([0; 2]); diff --git a/tests/ui/simd/intrinsic/generic-bitmask.stderr b/tests/ui/simd/intrinsic/generic-bitmask.stderr index 0de3f8eead8..c217bb2d8f1 100644 --- a/tests/ui/simd/intrinsic/generic-bitmask.stderr +++ b/tests/ui/simd/intrinsic/generic-bitmask.stderr @@ -1,29 +1,29 @@ error[E0511]: invalid monomorphization of `simd_bitmask` intrinsic: cannot return `u16`, expected `u8` or `[u8; 1]` - --> $DIR/generic-bitmask.rs:53:22 + --> $DIR/generic-bitmask.rs:52:22 | LL | let _: u16 = simd_bitmask(m2); | ^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_bitmask` intrinsic: cannot return `u16`, expected `u8` or `[u8; 1]` - --> $DIR/generic-bitmask.rs:56:22 + --> $DIR/generic-bitmask.rs:55:22 | LL | let _: u16 = simd_bitmask(m8); | ^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_bitmask` intrinsic: cannot return `u32`, expected `u16` or `[u8; 2]` - --> $DIR/generic-bitmask.rs:59:22 + --> $DIR/generic-bitmask.rs:58:22 | LL | let _: u32 = simd_bitmask(m16); | ^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_bitmask` intrinsic: cannot return `u64`, expected `u32` or `[u8; 4]` - --> $DIR/generic-bitmask.rs:62:22 + --> $DIR/generic-bitmask.rs:61:22 | LL | let _: u64 = simd_bitmask(m32); | ^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_bitmask` intrinsic: cannot return `u128`, expected `u64` or `[u8; 8]` - --> $DIR/generic-bitmask.rs:65:23 + --> $DIR/generic-bitmask.rs:64:23 | LL | let _: u128 = simd_bitmask(m64); | ^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/simd/intrinsic/generic-bswap-byte.rs b/tests/ui/simd/intrinsic/generic-bswap-byte.rs index f1702538165..4521573636c 100644 --- a/tests/ui/simd/intrinsic/generic-bswap-byte.rs +++ b/tests/ui/simd/intrinsic/generic-bswap-byte.rs @@ -10,9 +10,8 @@ struct i8x4([i8; 4]); #[derive(Copy, Clone)] struct u8x4([u8; 4]); -extern "rust-intrinsic" { - fn simd_bswap<T>(x: T) -> T; -} +#[rustc_intrinsic] +unsafe fn simd_bswap<T>(x: T) -> T; fn main() { unsafe { diff --git a/tests/ui/simd/intrinsic/generic-cast-pass.rs b/tests/ui/simd/intrinsic/generic-cast-pass.rs index e0319a6461a..2155d845864 100644 --- a/tests/ui/simd/intrinsic/generic-cast-pass.rs +++ b/tests/ui/simd/intrinsic/generic-cast-pass.rs @@ -3,9 +3,9 @@ #![feature(repr_simd, intrinsics)] -extern "rust-intrinsic" { - fn simd_cast<T, U>(x: T) -> U; -} + +#[rustc_intrinsic] +unsafe fn simd_cast<T, U>(x: T) -> U; use std::cmp::{max, min}; diff --git a/tests/ui/simd/intrinsic/generic-cast-pointer-width.rs b/tests/ui/simd/intrinsic/generic-cast-pointer-width.rs index 1c09a9fbf3b..9f28898654f 100644 --- a/tests/ui/simd/intrinsic/generic-cast-pointer-width.rs +++ b/tests/ui/simd/intrinsic/generic-cast-pointer-width.rs @@ -1,9 +1,8 @@ //@ run-pass #![feature(repr_simd, intrinsics)] -extern "rust-intrinsic" { - fn simd_cast<T, U>(x: T) -> U; -} +#[rustc_intrinsic] +unsafe fn simd_cast<T, U>(x: T) -> U; #[derive(Copy, Clone)] #[repr(simd)] diff --git a/tests/ui/simd/intrinsic/generic-cast.rs b/tests/ui/simd/intrinsic/generic-cast.rs index 33978a2f739..7f398804eb4 100644 --- a/tests/ui/simd/intrinsic/generic-cast.rs +++ b/tests/ui/simd/intrinsic/generic-cast.rs @@ -21,9 +21,8 @@ struct f32x4([f32; 4]); struct f32x8([f32; 8]); -extern "rust-intrinsic" { - fn simd_cast<T, U>(x: T) -> U; -} +#[rustc_intrinsic] +unsafe fn simd_cast<T, U>(x: T) -> U; fn main() { let x = i32x4([0, 0, 0, 0]); diff --git a/tests/ui/simd/intrinsic/generic-cast.stderr b/tests/ui/simd/intrinsic/generic-cast.stderr index 2f9d44037af..1b6ac03f8c9 100644 --- a/tests/ui/simd/intrinsic/generic-cast.stderr +++ b/tests/ui/simd/intrinsic/generic-cast.stderr @@ -1,23 +1,23 @@ error[E0511]: invalid monomorphization of `simd_cast` intrinsic: expected SIMD input type, found non-SIMD `i32` - --> $DIR/generic-cast.rs:32:9 + --> $DIR/generic-cast.rs:31:9 | LL | simd_cast::<i32, i32>(0); | ^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_cast` intrinsic: expected SIMD input type, found non-SIMD `i32` - --> $DIR/generic-cast.rs:34:9 + --> $DIR/generic-cast.rs:33:9 | LL | simd_cast::<i32, i32x4>(0); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_cast` intrinsic: expected SIMD return type, found non-SIMD `i32` - --> $DIR/generic-cast.rs:36:9 + --> $DIR/generic-cast.rs:35:9 | LL | simd_cast::<i32x4, i32>(x); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_cast` intrinsic: expected return type with length 4 (same as input type `i32x4`), found `i32x8` with length 8 - --> $DIR/generic-cast.rs:38:9 + --> $DIR/generic-cast.rs:37:9 | LL | simd_cast::<_, i32x8>(x); | ^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/simd/intrinsic/generic-comparison-pass.rs b/tests/ui/simd/intrinsic/generic-comparison-pass.rs index a4d84a4c534..68f98372e1d 100644 --- a/tests/ui/simd/intrinsic/generic-comparison-pass.rs +++ b/tests/ui/simd/intrinsic/generic-comparison-pass.rs @@ -14,14 +14,24 @@ struct u32x4(pub [u32; 4]); #[derive(Copy, Clone)] struct f32x4(pub [f32; 4]); -extern "rust-intrinsic" { - fn simd_eq<T, U>(x: T, y: T) -> U; - fn simd_ne<T, U>(x: T, y: T) -> U; - fn simd_lt<T, U>(x: T, y: T) -> U; - fn simd_le<T, U>(x: T, y: T) -> U; - fn simd_gt<T, U>(x: T, y: T) -> U; - fn simd_ge<T, U>(x: T, y: T) -> U; -} + +#[rustc_intrinsic] +unsafe fn simd_eq<T, U>(x: T, y: T) -> U; + +#[rustc_intrinsic] +unsafe fn simd_ne<T, U>(x: T, y: T) -> U; + +#[rustc_intrinsic] +unsafe fn simd_lt<T, U>(x: T, y: T) -> U; + +#[rustc_intrinsic] +unsafe fn simd_le<T, U>(x: T, y: T) -> U; + +#[rustc_intrinsic] +unsafe fn simd_gt<T, U>(x: T, y: T) -> U; + +#[rustc_intrinsic] +unsafe fn simd_ge<T, U>(x: T, y: T) -> U; macro_rules! cmp { ($method: ident($lhs: expr, $rhs: expr)) => {{ diff --git a/tests/ui/simd/intrinsic/generic-comparison.rs b/tests/ui/simd/intrinsic/generic-comparison.rs index f7f0655f3d2..e5adb49f6a3 100644 --- a/tests/ui/simd/intrinsic/generic-comparison.rs +++ b/tests/ui/simd/intrinsic/generic-comparison.rs @@ -11,14 +11,24 @@ struct i32x4([i32; 4]); #[allow(non_camel_case_types)] struct i16x8([i16; 8]); -extern "rust-intrinsic" { - fn simd_eq<T, U>(x: T, y: T) -> U; - fn simd_ne<T, U>(x: T, y: T) -> U; - fn simd_lt<T, U>(x: T, y: T) -> U; - fn simd_le<T, U>(x: T, y: T) -> U; - fn simd_gt<T, U>(x: T, y: T) -> U; - fn simd_ge<T, U>(x: T, y: T) -> U; -} + +#[rustc_intrinsic] +unsafe fn simd_eq<T, U>(x: T, y: T) -> U; + +#[rustc_intrinsic] +unsafe fn simd_ne<T, U>(x: T, y: T) -> U; + +#[rustc_intrinsic] +unsafe fn simd_lt<T, U>(x: T, y: T) -> U; + +#[rustc_intrinsic] +unsafe fn simd_le<T, U>(x: T, y: T) -> U; + +#[rustc_intrinsic] +unsafe fn simd_gt<T, U>(x: T, y: T) -> U; + +#[rustc_intrinsic] +unsafe fn simd_ge<T, U>(x: T, y: T) -> U; fn main() { let x = i32x4([0, 0, 0, 0]); diff --git a/tests/ui/simd/intrinsic/generic-comparison.stderr b/tests/ui/simd/intrinsic/generic-comparison.stderr index ac4d4918827..cc66d2ce40a 100644 --- a/tests/ui/simd/intrinsic/generic-comparison.stderr +++ b/tests/ui/simd/intrinsic/generic-comparison.stderr @@ -1,107 +1,107 @@ error[E0511]: invalid monomorphization of `simd_eq` intrinsic: expected SIMD input type, found non-SIMD `i32` - --> $DIR/generic-comparison.rs:27:9 + --> $DIR/generic-comparison.rs:37:9 | LL | simd_eq::<i32, i32>(0, 0); | ^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_ne` intrinsic: expected SIMD input type, found non-SIMD `i32` - --> $DIR/generic-comparison.rs:29:9 + --> $DIR/generic-comparison.rs:39:9 | LL | simd_ne::<i32, i32>(0, 0); | ^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_lt` intrinsic: expected SIMD input type, found non-SIMD `i32` - --> $DIR/generic-comparison.rs:31:9 + --> $DIR/generic-comparison.rs:41:9 | LL | simd_lt::<i32, i32>(0, 0); | ^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_le` intrinsic: expected SIMD input type, found non-SIMD `i32` - --> $DIR/generic-comparison.rs:33:9 + --> $DIR/generic-comparison.rs:43:9 | LL | simd_le::<i32, i32>(0, 0); | ^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_gt` intrinsic: expected SIMD input type, found non-SIMD `i32` - --> $DIR/generic-comparison.rs:35:9 + --> $DIR/generic-comparison.rs:45:9 | LL | simd_gt::<i32, i32>(0, 0); | ^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_ge` intrinsic: expected SIMD input type, found non-SIMD `i32` - --> $DIR/generic-comparison.rs:37:9 + --> $DIR/generic-comparison.rs:47:9 | LL | simd_ge::<i32, i32>(0, 0); | ^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_eq` intrinsic: expected SIMD return type, found non-SIMD `i32` - --> $DIR/generic-comparison.rs:40:9 + --> $DIR/generic-comparison.rs:50:9 | LL | simd_eq::<_, i32>(x, x); | ^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_ne` intrinsic: expected SIMD return type, found non-SIMD `i32` - --> $DIR/generic-comparison.rs:42:9 + --> $DIR/generic-comparison.rs:52:9 | LL | simd_ne::<_, i32>(x, x); | ^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_lt` intrinsic: expected SIMD return type, found non-SIMD `i32` - --> $DIR/generic-comparison.rs:44:9 + --> $DIR/generic-comparison.rs:54:9 | LL | simd_lt::<_, i32>(x, x); | ^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_le` intrinsic: expected SIMD return type, found non-SIMD `i32` - --> $DIR/generic-comparison.rs:46:9 + --> $DIR/generic-comparison.rs:56:9 | LL | simd_le::<_, i32>(x, x); | ^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_gt` intrinsic: expected SIMD return type, found non-SIMD `i32` - --> $DIR/generic-comparison.rs:48:9 + --> $DIR/generic-comparison.rs:58:9 | LL | simd_gt::<_, i32>(x, x); | ^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_ge` intrinsic: expected SIMD return type, found non-SIMD `i32` - --> $DIR/generic-comparison.rs:50:9 + --> $DIR/generic-comparison.rs:60:9 | LL | simd_ge::<_, i32>(x, x); | ^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_eq` intrinsic: expected return type with length 4 (same as input type `i32x4`), found `i16x8` with length 8 - --> $DIR/generic-comparison.rs:53:9 + --> $DIR/generic-comparison.rs:63:9 | LL | simd_eq::<_, i16x8>(x, x); | ^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_ne` intrinsic: expected return type with length 4 (same as input type `i32x4`), found `i16x8` with length 8 - --> $DIR/generic-comparison.rs:55:9 + --> $DIR/generic-comparison.rs:65:9 | LL | simd_ne::<_, i16x8>(x, x); | ^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_lt` intrinsic: expected return type with length 4 (same as input type `i32x4`), found `i16x8` with length 8 - --> $DIR/generic-comparison.rs:57:9 + --> $DIR/generic-comparison.rs:67:9 | LL | simd_lt::<_, i16x8>(x, x); | ^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_le` intrinsic: expected return type with length 4 (same as input type `i32x4`), found `i16x8` with length 8 - --> $DIR/generic-comparison.rs:59:9 + --> $DIR/generic-comparison.rs:69:9 | LL | simd_le::<_, i16x8>(x, x); | ^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_gt` intrinsic: expected return type with length 4 (same as input type `i32x4`), found `i16x8` with length 8 - --> $DIR/generic-comparison.rs:61:9 + --> $DIR/generic-comparison.rs:71:9 | LL | simd_gt::<_, i16x8>(x, x); | ^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_ge` intrinsic: expected return type with length 4 (same as input type `i32x4`), found `i16x8` with length 8 - --> $DIR/generic-comparison.rs:63:9 + --> $DIR/generic-comparison.rs:73:9 | LL | simd_ge::<_, i16x8>(x, x); | ^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/simd/intrinsic/generic-elements-pass.rs b/tests/ui/simd/intrinsic/generic-elements-pass.rs index 7b1bda4fbcd..8cb600bc9e4 100644 --- a/tests/ui/simd/intrinsic/generic-elements-pass.rs +++ b/tests/ui/simd/intrinsic/generic-elements-pass.rs @@ -16,12 +16,15 @@ struct i32x4([i32; 4]); #[allow(non_camel_case_types)] struct i32x8([i32; 8]); -extern "rust-intrinsic" { - fn simd_insert<T, E>(x: T, idx: u32, y: E) -> T; - fn simd_extract<T, E>(x: T, idx: u32) -> E; +#[rustc_intrinsic] +unsafe fn simd_insert<T, E>(x: T, idx: u32, y: E) -> T; - fn simd_shuffle<T, I, U>(x: T, y: T, idx: I) -> U; -} +#[rustc_intrinsic] +unsafe fn simd_extract<T, E>(x: T, idx: u32) -> E; + + +#[rustc_intrinsic] +unsafe fn simd_shuffle<T, I, U>(x: T, y: T, idx: I) -> U; #[repr(simd)] struct SimdShuffleIdx<const LEN: usize>([u32; LEN]); diff --git a/tests/ui/simd/intrinsic/generic-elements.rs b/tests/ui/simd/intrinsic/generic-elements.rs index 5d784a25eab..4be6645f029 100644 --- a/tests/ui/simd/intrinsic/generic-elements.rs +++ b/tests/ui/simd/intrinsic/generic-elements.rs @@ -29,13 +29,20 @@ struct f32x4([f32; 4]); #[allow(non_camel_case_types)] struct f32x8([f32; 8]); -extern "rust-intrinsic" { - fn simd_insert<T, E>(x: T, idx: u32, y: E) -> T; - fn simd_extract<T, E>(x: T, idx: u32) -> E; - fn simd_shuffle<T, I, U>(x: T, y: T, idx: I) -> U; - fn simd_shuffle_generic<T, U, const IDX: &'static [u32]>(x: T, y: T) -> U; -} +#[rustc_intrinsic] +unsafe fn simd_insert<T, E>(x: T, idx: u32, y: E) -> T; + +#[rustc_intrinsic] +unsafe fn simd_extract<T, E>(x: T, idx: u32) -> E; + + +#[rustc_intrinsic] +unsafe fn simd_shuffle<T, I, U>(x: T, y: T, idx: I) -> U; + +#[rustc_intrinsic] +unsafe fn simd_shuffle_generic<T, U, const IDX: &'static [u32]>(x: T, y: T) -> U; + #[repr(simd)] struct SimdShuffleIdx<const LEN: usize>([u32; LEN]); diff --git a/tests/ui/simd/intrinsic/generic-elements.stderr b/tests/ui/simd/intrinsic/generic-elements.stderr index fd726d75326..8104c3ba5a2 100644 --- a/tests/ui/simd/intrinsic/generic-elements.stderr +++ b/tests/ui/simd/intrinsic/generic-elements.stderr @@ -1,125 +1,125 @@ error[E0511]: invalid monomorphization of `simd_insert` intrinsic: expected SIMD input type, found non-SIMD `i32` - --> $DIR/generic-elements.rs:47:9 + --> $DIR/generic-elements.rs:54:9 | LL | simd_insert(0, 0, 0); | ^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_insert` intrinsic: expected inserted type `i32` (element of input `i32x4`), found `f64` - --> $DIR/generic-elements.rs:49:9 + --> $DIR/generic-elements.rs:56:9 | LL | simd_insert(x, 0, 1.0); | ^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_extract` intrinsic: expected return type `i32` (element of input `i32x4`), found `f32` - --> $DIR/generic-elements.rs:51:9 + --> $DIR/generic-elements.rs:58:9 | LL | simd_extract::<_, f32>(x, 0); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_shuffle` intrinsic: expected SIMD input type, found non-SIMD `i32` - --> $DIR/generic-elements.rs:55:9 + --> $DIR/generic-elements.rs:62:9 | LL | simd_shuffle::<i32, _, i32>(0, 0, IDX2); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_shuffle` intrinsic: expected SIMD input type, found non-SIMD `i32` - --> $DIR/generic-elements.rs:58:9 + --> $DIR/generic-elements.rs:65:9 | LL | simd_shuffle::<i32, _, i32>(0, 0, IDX4); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_shuffle` intrinsic: expected SIMD input type, found non-SIMD `i32` - --> $DIR/generic-elements.rs:61:9 + --> $DIR/generic-elements.rs:68:9 | LL | simd_shuffle::<i32, _, i32>(0, 0, IDX8); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_shuffle` intrinsic: expected return element type `i32` (element of input `i32x4`), found `f32x2` with element type `f32` - --> $DIR/generic-elements.rs:64:9 + --> $DIR/generic-elements.rs:71:9 | LL | simd_shuffle::<_, _, f32x2>(x, x, IDX2); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_shuffle` intrinsic: expected return element type `i32` (element of input `i32x4`), found `f32x4` with element type `f32` - --> $DIR/generic-elements.rs:66:9 + --> $DIR/generic-elements.rs:73:9 | LL | simd_shuffle::<_, _, f32x4>(x, x, IDX4); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_shuffle` intrinsic: expected return element type `i32` (element of input `i32x4`), found `f32x8` with element type `f32` - --> $DIR/generic-elements.rs:68:9 + --> $DIR/generic-elements.rs:75:9 | LL | simd_shuffle::<_, _, f32x8>(x, x, IDX8); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_shuffle` intrinsic: expected return type of length 2, found `i32x8` with length 8 - --> $DIR/generic-elements.rs:71:9 + --> $DIR/generic-elements.rs:78:9 | LL | simd_shuffle::<_, _, i32x8>(x, x, IDX2); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_shuffle` intrinsic: expected return type of length 4, found `i32x8` with length 8 - --> $DIR/generic-elements.rs:73:9 + --> $DIR/generic-elements.rs:80:9 | LL | simd_shuffle::<_, _, i32x8>(x, x, IDX4); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_shuffle` intrinsic: expected return type of length 8, found `i32x2` with length 2 - --> $DIR/generic-elements.rs:75:9 + --> $DIR/generic-elements.rs:82:9 | LL | simd_shuffle::<_, _, i32x2>(x, x, IDX8); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_shuffle_generic` intrinsic: expected SIMD input type, found non-SIMD `i32` - --> $DIR/generic-elements.rs:79:9 + --> $DIR/generic-elements.rs:86:9 | LL | simd_shuffle_generic::<i32, i32, I2>(0, 0); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_shuffle_generic` intrinsic: expected SIMD input type, found non-SIMD `i32` - --> $DIR/generic-elements.rs:82:9 + --> $DIR/generic-elements.rs:89:9 | LL | simd_shuffle_generic::<i32, i32, I4>(0, 0); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_shuffle_generic` intrinsic: expected SIMD input type, found non-SIMD `i32` - --> $DIR/generic-elements.rs:85:9 + --> $DIR/generic-elements.rs:92:9 | LL | simd_shuffle_generic::<i32, i32, I8>(0, 0); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_shuffle_generic` intrinsic: expected return element type `i32` (element of input `i32x4`), found `f32x2` with element type `f32` - --> $DIR/generic-elements.rs:88:9 + --> $DIR/generic-elements.rs:95:9 | LL | simd_shuffle_generic::<_, f32x2, I2>(x, x); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_shuffle_generic` intrinsic: expected return element type `i32` (element of input `i32x4`), found `f32x4` with element type `f32` - --> $DIR/generic-elements.rs:90:9 + --> $DIR/generic-elements.rs:97:9 | LL | simd_shuffle_generic::<_, f32x4, I4>(x, x); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_shuffle_generic` intrinsic: expected return element type `i32` (element of input `i32x4`), found `f32x8` with element type `f32` - --> $DIR/generic-elements.rs:92:9 + --> $DIR/generic-elements.rs:99:9 | LL | simd_shuffle_generic::<_, f32x8, I8>(x, x); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_shuffle_generic` intrinsic: expected return type of length 2, found `i32x8` with length 8 - --> $DIR/generic-elements.rs:95:9 + --> $DIR/generic-elements.rs:102:9 | LL | simd_shuffle_generic::<_, i32x8, I2>(x, x); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_shuffle_generic` intrinsic: expected return type of length 4, found `i32x8` with length 8 - --> $DIR/generic-elements.rs:97:9 + --> $DIR/generic-elements.rs:104:9 | LL | simd_shuffle_generic::<_, i32x8, I4>(x, x); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_shuffle_generic` intrinsic: expected return type of length 8, found `i32x2` with length 2 - --> $DIR/generic-elements.rs:99:9 + --> $DIR/generic-elements.rs:106:9 | LL | simd_shuffle_generic::<_, i32x2, I8>(x, x); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/simd/intrinsic/generic-gather-pass.rs b/tests/ui/simd/intrinsic/generic-gather-pass.rs index 3315d1cdaa2..0b2cf47e989 100644 --- a/tests/ui/simd/intrinsic/generic-gather-pass.rs +++ b/tests/ui/simd/intrinsic/generic-gather-pass.rs @@ -10,10 +10,11 @@ #[derive(Copy, Clone, PartialEq, Debug)] struct x4<T>(pub [T; 4]); -extern "rust-intrinsic" { - fn simd_gather<T, U, V>(x: T, y: U, z: V) -> T; - fn simd_scatter<T, U, V>(x: T, y: U, z: V) -> (); -} +#[rustc_intrinsic] +unsafe fn simd_gather<T, U, V>(x: T, y: U, z: V) -> T; + +#[rustc_intrinsic] +unsafe fn simd_scatter<T, U, V>(x: T, y: U, z: V) -> (); fn main() { let mut x = [0_f32, 1., 2., 3., 4., 5., 6., 7.]; diff --git a/tests/ui/simd/intrinsic/generic-reduction-pass.rs b/tests/ui/simd/intrinsic/generic-reduction-pass.rs index 699fb396259..8408d0f203b 100644 --- a/tests/ui/simd/intrinsic/generic-reduction-pass.rs +++ b/tests/ui/simd/intrinsic/generic-reduction-pass.rs @@ -24,19 +24,38 @@ struct f32x4(pub [f32; 4]); #[derive(Copy, Clone)] struct b8x4(pub [i8; 4]); -extern "rust-intrinsic" { - fn simd_reduce_add_unordered<T, U>(x: T) -> U; - fn simd_reduce_mul_unordered<T, U>(x: T) -> U; - fn simd_reduce_add_ordered<T, U>(x: T, acc: U) -> U; - fn simd_reduce_mul_ordered<T, U>(x: T, acc: U) -> U; - fn simd_reduce_min<T, U>(x: T) -> U; - fn simd_reduce_max<T, U>(x: T) -> U; - fn simd_reduce_and<T, U>(x: T) -> U; - fn simd_reduce_or<T, U>(x: T) -> U; - fn simd_reduce_xor<T, U>(x: T) -> U; - fn simd_reduce_all<T>(x: T) -> bool; - fn simd_reduce_any<T>(x: T) -> bool; -} +#[rustc_intrinsic] +unsafe fn simd_reduce_add_unordered<T, U>(x: T) -> U; + +#[rustc_intrinsic] +unsafe fn simd_reduce_mul_unordered<T, U>(x: T) -> U; + +#[rustc_intrinsic] +unsafe fn simd_reduce_add_ordered<T, U>(x: T, acc: U) -> U; + +#[rustc_intrinsic] +unsafe fn simd_reduce_mul_ordered<T, U>(x: T, acc: U) -> U; + +#[rustc_intrinsic] +unsafe fn simd_reduce_min<T, U>(x: T) -> U; + +#[rustc_intrinsic] +unsafe fn simd_reduce_max<T, U>(x: T) -> U; + +#[rustc_intrinsic] +unsafe fn simd_reduce_and<T, U>(x: T) -> U; + +#[rustc_intrinsic] +unsafe fn simd_reduce_or<T, U>(x: T) -> U; + +#[rustc_intrinsic] +unsafe fn simd_reduce_xor<T, U>(x: T) -> U; + +#[rustc_intrinsic] +unsafe fn simd_reduce_all<T>(x: T) -> bool; + +#[rustc_intrinsic] +unsafe fn simd_reduce_any<T>(x: T) -> bool; fn main() { unsafe { diff --git a/tests/ui/simd/intrinsic/generic-reduction.rs b/tests/ui/simd/intrinsic/generic-reduction.rs index 1986deafb6a..ead13250643 100644 --- a/tests/ui/simd/intrinsic/generic-reduction.rs +++ b/tests/ui/simd/intrinsic/generic-reduction.rs @@ -15,16 +15,26 @@ pub struct f32x4(pub [f32; 4]); #[derive(Copy, Clone)] pub struct u32x4(pub [u32; 4]); +#[rustc_intrinsic] +unsafe fn simd_reduce_add_ordered<T, U>(x: T, y: U) -> U; -extern "rust-intrinsic" { - fn simd_reduce_add_ordered<T, U>(x: T, y: U) -> U; - fn simd_reduce_mul_ordered<T, U>(x: T, y: U) -> U; - fn simd_reduce_and<T, U>(x: T) -> U; - fn simd_reduce_or<T, U>(x: T) -> U; - fn simd_reduce_xor<T, U>(x: T) -> U; - fn simd_reduce_all<T>(x: T) -> bool; - fn simd_reduce_any<T>(x: T) -> bool; -} +#[rustc_intrinsic] +unsafe fn simd_reduce_mul_ordered<T, U>(x: T, y: U) -> U; + +#[rustc_intrinsic] +unsafe fn simd_reduce_and<T, U>(x: T) -> U; + +#[rustc_intrinsic] +unsafe fn simd_reduce_or<T, U>(x: T) -> U; + +#[rustc_intrinsic] +unsafe fn simd_reduce_xor<T, U>(x: T) -> U; + +#[rustc_intrinsic] +unsafe fn simd_reduce_all<T>(x: T) -> bool; + +#[rustc_intrinsic] +unsafe fn simd_reduce_any<T>(x: T) -> bool; fn main() { let x = u32x4([0, 0, 0, 0]); diff --git a/tests/ui/simd/intrinsic/generic-reduction.stderr b/tests/ui/simd/intrinsic/generic-reduction.stderr index 1028faf69a7..302b9ae1d77 100644 --- a/tests/ui/simd/intrinsic/generic-reduction.stderr +++ b/tests/ui/simd/intrinsic/generic-reduction.stderr @@ -1,59 +1,59 @@ error[E0511]: invalid monomorphization of `simd_reduce_add_ordered` intrinsic: expected return type `f32` (element of input `f32x4`), found `i32` - --> $DIR/generic-reduction.rs:34:9 + --> $DIR/generic-reduction.rs:44:9 | LL | simd_reduce_add_ordered(z, 0); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_reduce_mul_ordered` intrinsic: expected return type `f32` (element of input `f32x4`), found `i32` - --> $DIR/generic-reduction.rs:36:9 + --> $DIR/generic-reduction.rs:46:9 | LL | simd_reduce_mul_ordered(z, 1); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_reduce_and` intrinsic: expected return type `u32` (element of input `u32x4`), found `f32` - --> $DIR/generic-reduction.rs:39:22 + --> $DIR/generic-reduction.rs:49:22 | LL | let _: f32 = simd_reduce_and(x); | ^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_reduce_or` intrinsic: expected return type `u32` (element of input `u32x4`), found `f32` - --> $DIR/generic-reduction.rs:41:22 + --> $DIR/generic-reduction.rs:51:22 | LL | let _: f32 = simd_reduce_or(x); | ^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_reduce_xor` intrinsic: expected return type `u32` (element of input `u32x4`), found `f32` - --> $DIR/generic-reduction.rs:43:22 + --> $DIR/generic-reduction.rs:53:22 | LL | let _: f32 = simd_reduce_xor(x); | ^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_reduce_and` intrinsic: unsupported simd_reduce_and from `f32x4` with element `f32` to `f32` - --> $DIR/generic-reduction.rs:46:22 + --> $DIR/generic-reduction.rs:56:22 | LL | let _: f32 = simd_reduce_and(z); | ^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_reduce_or` intrinsic: unsupported simd_reduce_or from `f32x4` with element `f32` to `f32` - --> $DIR/generic-reduction.rs:48:22 + --> $DIR/generic-reduction.rs:58:22 | LL | let _: f32 = simd_reduce_or(z); | ^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_reduce_xor` intrinsic: unsupported simd_reduce_xor from `f32x4` with element `f32` to `f32` - --> $DIR/generic-reduction.rs:50:22 + --> $DIR/generic-reduction.rs:60:22 | LL | let _: f32 = simd_reduce_xor(z); | ^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_reduce_all` intrinsic: unsupported simd_reduce_all from `f32x4` with element `f32` to `bool` - --> $DIR/generic-reduction.rs:53:23 + --> $DIR/generic-reduction.rs:63:23 | LL | let _: bool = simd_reduce_all(z); | ^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_reduce_any` intrinsic: unsupported simd_reduce_any from `f32x4` with element `f32` to `bool` - --> $DIR/generic-reduction.rs:55:23 + --> $DIR/generic-reduction.rs:65:23 | LL | let _: bool = simd_reduce_any(z); | ^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/simd/intrinsic/generic-select-pass.rs b/tests/ui/simd/intrinsic/generic-select-pass.rs index 5690bad5048..6b1b6cb79db 100644 --- a/tests/ui/simd/intrinsic/generic-select-pass.rs +++ b/tests/ui/simd/intrinsic/generic-select-pass.rs @@ -29,10 +29,12 @@ struct f32x4(pub [f32; 4]); #[derive(Copy, Clone, PartialEq, Debug)] struct b8x4(pub [i8; 4]); -extern "rust-intrinsic" { - fn simd_select<T, U>(x: T, a: U, b: U) -> U; - fn simd_select_bitmask<T, U>(x: T, a: U, b: U) -> U; -} +#[rustc_intrinsic] +unsafe fn simd_select<T, U>(x: T, a: U, b: U) -> U; + +#[rustc_intrinsic] +unsafe fn simd_select_bitmask<T, U>(x: T, a: U, b: U) -> U; + fn main() { let m0 = b8x4([!0, !0, !0, !0]); diff --git a/tests/ui/simd/intrinsic/generic-select.rs b/tests/ui/simd/intrinsic/generic-select.rs index 52e02649590..340fe3f3592 100644 --- a/tests/ui/simd/intrinsic/generic-select.rs +++ b/tests/ui/simd/intrinsic/generic-select.rs @@ -22,10 +22,13 @@ struct b8x4(pub [i8; 4]); #[derive(Copy, Clone, PartialEq)] struct b8x8(pub [i8; 8]); -extern "rust-intrinsic" { - fn simd_select<T, U>(x: T, a: U, b: U) -> U; - fn simd_select_bitmask<T, U>(x: T, a: U, b: U) -> U; -} + +#[rustc_intrinsic] +unsafe fn simd_select<T, U>(x: T, a: U, b: U) -> U; + +#[rustc_intrinsic] +unsafe fn simd_select_bitmask<T, U>(x: T, a: U, b: U) -> U; + fn main() { let m4 = b8x4([0, 0, 0, 0]); diff --git a/tests/ui/simd/intrinsic/generic-select.stderr b/tests/ui/simd/intrinsic/generic-select.stderr index d576f1bc774..a97fc91f951 100644 --- a/tests/ui/simd/intrinsic/generic-select.stderr +++ b/tests/ui/simd/intrinsic/generic-select.stderr @@ -1,47 +1,47 @@ error[E0511]: invalid monomorphization of `simd_select` intrinsic: mismatched lengths: mask length `8` != other vector length `4` - --> $DIR/generic-select.rs:39:9 + --> $DIR/generic-select.rs:42:9 | LL | simd_select(m8, x, x); | ^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_select` intrinsic: mask element type is `u32`, expected `i_` - --> $DIR/generic-select.rs:42:9 + --> $DIR/generic-select.rs:45:9 | LL | simd_select(x, x, x); | ^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_select` intrinsic: mask element type is `f32`, expected `i_` - --> $DIR/generic-select.rs:45:9 + --> $DIR/generic-select.rs:48:9 | LL | simd_select(z, z, z); | ^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_select` intrinsic: expected SIMD argument type, found non-SIMD `u32` - --> $DIR/generic-select.rs:48:9 + --> $DIR/generic-select.rs:51:9 | LL | simd_select(m4, 0u32, 1u32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_select_bitmask` intrinsic: invalid bitmask `u16`, expected `u8` or `[u8; 1]` - --> $DIR/generic-select.rs:51:9 + --> $DIR/generic-select.rs:54:9 | LL | simd_select_bitmask(0u16, x, x); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_select_bitmask` intrinsic: expected SIMD argument type, found non-SIMD `u32` - --> $DIR/generic-select.rs:54:9 + --> $DIR/generic-select.rs:57:9 | LL | simd_select_bitmask(0u8, 1u32, 2u32); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_select_bitmask` intrinsic: invalid bitmask `f32`, expected `u8` or `[u8; 1]` - --> $DIR/generic-select.rs:57:9 + --> $DIR/generic-select.rs:60:9 | LL | simd_select_bitmask(0.0f32, x, x); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0511]: invalid monomorphization of `simd_select_bitmask` intrinsic: invalid bitmask `&str`, expected `u8` or `[u8; 1]` - --> $DIR/generic-select.rs:60:9 + --> $DIR/generic-select.rs:63:9 | LL | simd_select_bitmask("x", x, x); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/simd/intrinsic/generic-shuffle.rs b/tests/ui/simd/intrinsic/generic-shuffle.rs index 2752718d99d..1223b8ebe19 100644 --- a/tests/ui/simd/intrinsic/generic-shuffle.rs +++ b/tests/ui/simd/intrinsic/generic-shuffle.rs @@ -9,9 +9,9 @@ #[derive(Copy, Clone)] pub struct Simd<T, const N: usize>([T; N]); -extern "rust-intrinsic" { - fn simd_shuffle<T, I, U>(a: T, b: T, i: I) -> U; -} +#[rustc_intrinsic] +unsafe fn simd_shuffle<T, I, U>(a: T, b: T, i: I) -> U; + fn main() { const I: Simd<u32, 2> = Simd([0; 2]); diff --git a/tests/ui/simd/intrinsic/inlining-issue67557-ice.rs b/tests/ui/simd/intrinsic/inlining-issue67557-ice.rs index d9239ef5801..b324ac40749 100644 --- a/tests/ui/simd/intrinsic/inlining-issue67557-ice.rs +++ b/tests/ui/simd/intrinsic/inlining-issue67557-ice.rs @@ -5,9 +5,8 @@ //@ compile-flags: -Zmir-opt-level=4 #![feature(intrinsics, repr_simd)] -extern "rust-intrinsic" { - fn simd_shuffle<T, I, U>(x: T, y: T, idx: I) -> U; -} +#[rustc_intrinsic] +unsafe fn simd_shuffle<T, I, U>(x: T, y: T, idx: I) -> U; #[repr(simd)] #[derive(Debug, PartialEq)] diff --git a/tests/ui/simd/intrinsic/inlining-issue67557.rs b/tests/ui/simd/intrinsic/inlining-issue67557.rs index 23dd5075f96..319bb15c015 100644 --- a/tests/ui/simd/intrinsic/inlining-issue67557.rs +++ b/tests/ui/simd/intrinsic/inlining-issue67557.rs @@ -5,9 +5,8 @@ //@ compile-flags: -Zmir-opt-level=4 #![feature(intrinsics, repr_simd)] -extern "rust-intrinsic" { - fn simd_shuffle<T, I, U>(x: T, y: T, idx: I) -> U; -} +#[rustc_intrinsic] +unsafe fn simd_shuffle<T, I, U>(x: T, y: T, idx: I) -> U; #[repr(simd)] #[derive(Debug, PartialEq)] diff --git a/tests/ui/simd/intrinsic/issue-85855.rs b/tests/ui/simd/intrinsic/issue-85855.rs index dc04699f7f8..daeea793d1b 100644 --- a/tests/ui/simd/intrinsic/issue-85855.rs +++ b/tests/ui/simd/intrinsic/issue-85855.rs @@ -5,15 +5,18 @@ #![feature(intrinsics)] #![crate_type="lib"] -extern "rust-intrinsic" { - fn simd_saturating_add<'a, T: 'a>(x: T, y: T); - //~^ ERROR: intrinsic has wrong number of lifetime parameters - fn simd_add<'a, T>(x: T, y: T) -> T; +#[rustc_intrinsic] +unsafe fn simd_saturating_add<'a, T: 'a>(x: T, y: T); +//~^ ERROR: intrinsic has wrong number of lifetime parameters - fn simd_sub<T, U>(x: T, y: U); - //~^ ERROR: intrinsic has wrong number of type parameters +#[rustc_intrinsic] +unsafe fn simd_add<'a, T>(x: T, y: T) -> T; - fn simd_mul<T, const N: usize>(x: T, y: T); - //~^ ERROR: intrinsic has wrong number of const parameters -} +#[rustc_intrinsic] +unsafe fn simd_sub<T, U>(x: T, y: U); +//~^ ERROR: intrinsic has wrong number of type parameters + +#[rustc_intrinsic] +unsafe fn simd_mul<T, const N: usize>(x: T, y: T); +//~^ ERROR: intrinsic has wrong number of const parameters diff --git a/tests/ui/simd/intrinsic/issue-85855.stderr b/tests/ui/simd/intrinsic/issue-85855.stderr index fb2f1fbc5b1..b91a606ba68 100644 --- a/tests/ui/simd/intrinsic/issue-85855.stderr +++ b/tests/ui/simd/intrinsic/issue-85855.stderr @@ -1,20 +1,20 @@ error[E0094]: intrinsic has wrong number of lifetime parameters: found 1, expected 0 - --> $DIR/issue-85855.rs:9:27 + --> $DIR/issue-85855.rs:10:30 | -LL | fn simd_saturating_add<'a, T: 'a>(x: T, y: T); - | ^^^^^^^^^^^ expected 0 lifetime parameters +LL | unsafe fn simd_saturating_add<'a, T: 'a>(x: T, y: T); + | ^^^^^^^^^^^ expected 0 lifetime parameters error[E0094]: intrinsic has wrong number of type parameters: found 2, expected 1 - --> $DIR/issue-85855.rs:14:16 + --> $DIR/issue-85855.rs:17:19 | -LL | fn simd_sub<T, U>(x: T, y: U); - | ^^^^^^ expected 1 type parameter +LL | unsafe fn simd_sub<T, U>(x: T, y: U); + | ^^^^^^ expected 1 type parameter error[E0094]: intrinsic has wrong number of const parameters: found 1, expected 0 - --> $DIR/issue-85855.rs:17:16 + --> $DIR/issue-85855.rs:21:19 | -LL | fn simd_mul<T, const N: usize>(x: T, y: T); - | ^^^^^^^^^^^^^^^^^^^ expected 0 const parameters +LL | unsafe fn simd_mul<T, const N: usize>(x: T, y: T); + | ^^^^^^^^^^^^^^^^^^^ expected 0 const parameters error: aborting due to 3 previous errors diff --git a/tests/ui/simd/intrinsic/ptr-cast.rs b/tests/ui/simd/intrinsic/ptr-cast.rs index 0490734b48a..559b8ba1b5c 100644 --- a/tests/ui/simd/intrinsic/ptr-cast.rs +++ b/tests/ui/simd/intrinsic/ptr-cast.rs @@ -2,11 +2,15 @@ #![feature(repr_simd, intrinsics)] -extern "rust-intrinsic" { - fn simd_cast_ptr<T, U>(x: T) -> U; - fn simd_expose_provenance<T, U>(x: T) -> U; - fn simd_with_exposed_provenance<T, U>(x: T) -> U; -} + +#[rustc_intrinsic] +unsafe fn simd_cast_ptr<T, U>(x: T) -> U; + +#[rustc_intrinsic] +unsafe fn simd_expose_provenance<T, U>(x: T) -> U; + +#[rustc_intrinsic] +unsafe fn simd_with_exposed_provenance<T, U>(x: T) -> U; #[derive(Copy, Clone)] #[repr(simd)] diff --git a/tests/ui/simd/issue-105439.rs b/tests/ui/simd/issue-105439.rs index 3cb43fc8b1a..108bb282df2 100644 --- a/tests/ui/simd/issue-105439.rs +++ b/tests/ui/simd/issue-105439.rs @@ -9,9 +9,8 @@ #[repr(simd)] struct i32x4([i32; 4]); -extern "rust-intrinsic" { - pub(crate) fn simd_add<T>(x: T, y: T) -> T; -} +#[rustc_intrinsic] +pub(crate) unsafe fn simd_add<T>(x: T, y: T) -> T; #[inline(always)] fn to_array(a: i32x4) -> [i32; 4] { diff --git a/tests/ui/simd/issue-39720.rs b/tests/ui/simd/issue-39720.rs index 2b51c0224c6..8d7666faaf9 100644 --- a/tests/ui/simd/issue-39720.rs +++ b/tests/ui/simd/issue-39720.rs @@ -11,9 +11,8 @@ pub struct Char3(pub [i8; 3]); #[derive(Copy, Clone, Debug)] pub struct Short3(pub [i16; 3]); -extern "rust-intrinsic" { - fn simd_cast<T, U>(x: T) -> U; -} +#[rustc_intrinsic] +unsafe fn simd_cast<T, U>(x: T) -> U; fn main() { let cast: Short3 = unsafe { simd_cast(Char3([10, -3, -9])) }; diff --git a/tests/ui/simd/issue-85915-simd-ptrs.rs b/tests/ui/simd/issue-85915-simd-ptrs.rs index edf60e0205c..2e7baf48ee3 100644 --- a/tests/ui/simd/issue-85915-simd-ptrs.rs +++ b/tests/ui/simd/issue-85915-simd-ptrs.rs @@ -22,10 +22,12 @@ struct f32x4([f32; 4]); #[derive(Copy, Clone, PartialEq, Debug)] struct i32x4([i32; 4]); -extern "rust-intrinsic" { - fn simd_gather<T, U, V>(x: T, y: U, z: V) -> T; - fn simd_scatter<T, U, V>(x: T, y: U, z: V) -> (); -} + +#[rustc_intrinsic] +unsafe fn simd_gather<T, U, V>(x: T, y: U, z: V) -> T; + +#[rustc_intrinsic] +unsafe fn simd_scatter<T, U, V>(x: T, y: U, z: V) -> (); fn main() { let mut x = [0_f32, 1., 2., 3., 4., 5., 6., 7.]; diff --git a/tests/ui/simd/issue-89193.rs b/tests/ui/simd/issue-89193.rs index 9530124a7cc..4b4fb9d9169 100644 --- a/tests/ui/simd/issue-89193.rs +++ b/tests/ui/simd/issue-89193.rs @@ -10,9 +10,8 @@ #[derive(Copy, Clone, PartialEq, Debug)] struct x4<T>(pub [T; 4]); -extern "rust-intrinsic" { - fn simd_gather<T, U, V>(x: T, y: U, z: V) -> T; -} +#[rustc_intrinsic] +unsafe fn simd_gather<T, U, V>(x: T, y: U, z: V) -> T; fn main() { let x: [usize; 4] = [10, 11, 12, 13]; diff --git a/tests/ui/simd/masked-load-store-build-fail.rs b/tests/ui/simd/masked-load-store-build-fail.rs index fbd657763c9..b8742184eb0 100644 --- a/tests/ui/simd/masked-load-store-build-fail.rs +++ b/tests/ui/simd/masked-load-store-build-fail.rs @@ -1,10 +1,12 @@ //@ build-fail #![feature(repr_simd, intrinsics)] -extern "rust-intrinsic" { - fn simd_masked_load<M, P, T>(mask: M, pointer: P, values: T) -> T; - fn simd_masked_store<M, P, T>(mask: M, pointer: P, values: T) -> (); -} + +#[rustc_intrinsic] +unsafe fn simd_masked_load<M, P, T>(mask: M, pointer: P, values: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_masked_store<M, P, T>(mask: M, pointer: P, values: T) -> (); #[derive(Copy, Clone)] #[repr(simd)] diff --git a/tests/ui/simd/masked-load-store-build-fail.stderr b/tests/ui/simd/masked-load-store-build-fail.stderr index 59af83fe0e8..8a8d8eb99e2 100644 --- a/tests/ui/simd/masked-load-store-build-fail.stderr +++ b/tests/ui/simd/masked-load-store-build-fail.stderr @@ -1,5 +1,5 @@ error[E0511]: invalid monomorphization of `simd_masked_load` intrinsic: expected third argument with length 8 (same as input type `Simd<i8, 8>`), found `Simd<u8, 4>` with length 4 - --> $DIR/masked-load-store-build-fail.rs:18:9 + --> $DIR/masked-load-store-build-fail.rs:20:9 | LL | / simd_masked_load( LL | | Simd::<i8, 8>([-1, 0, -1, -1, 0, 0, 0, 0]), @@ -9,7 +9,7 @@ LL | | ); | |_________^ error[E0511]: invalid monomorphization of `simd_masked_load` intrinsic: expected element type `u8` of second argument `*const i8` to be a pointer to the element type `u8` of the first argument `Simd<u8, 4>`, found `u8` != `*_ u8` - --> $DIR/masked-load-store-build-fail.rs:25:9 + --> $DIR/masked-load-store-build-fail.rs:27:9 | LL | / simd_masked_load( LL | | Simd::<i8, 4>([-1, 0, -1, -1]), @@ -19,7 +19,7 @@ LL | | ); | |_________^ error[E0511]: invalid monomorphization of `simd_masked_load` intrinsic: expected element type `u32` of second argument `*const u8` to be a pointer to the element type `u32` of the first argument `Simd<u32, 4>`, found `u32` != `*_ u32` - --> $DIR/masked-load-store-build-fail.rs:32:9 + --> $DIR/masked-load-store-build-fail.rs:34:9 | LL | / simd_masked_load( LL | | Simd::<i8, 4>([-1, 0, -1, -1]), @@ -29,7 +29,7 @@ LL | | ); | |_________^ error[E0511]: invalid monomorphization of `simd_masked_load` intrinsic: expected element type `u8` of third argument `Simd<u8, 4>` to be a signed integer type - --> $DIR/masked-load-store-build-fail.rs:39:9 + --> $DIR/masked-load-store-build-fail.rs:41:9 | LL | / simd_masked_load( LL | | Simd::<u8, 4>([1, 0, 1, 1]), @@ -39,7 +39,7 @@ LL | | ); | |_________^ error[E0511]: invalid monomorphization of `simd_masked_store` intrinsic: expected element type `u32` of second argument `*const u8` to be a pointer to the element type `u32` of the first argument `Simd<u32, 4>`, found `u32` != `*mut u32` - --> $DIR/masked-load-store-build-fail.rs:46:9 + --> $DIR/masked-load-store-build-fail.rs:48:9 | LL | / simd_masked_store( LL | | Simd([-1i8; 4]), @@ -49,7 +49,7 @@ LL | | ); | |_________^ error[E0511]: invalid monomorphization of `simd_masked_store` intrinsic: expected element type `u8` of second argument `*const u8` to be a pointer to the element type `u8` of the first argument `Simd<u8, 4>`, found `u8` != `*mut u8` - --> $DIR/masked-load-store-build-fail.rs:53:9 + --> $DIR/masked-load-store-build-fail.rs:55:9 | LL | / simd_masked_store( LL | | Simd([-1i8; 4]), @@ -59,7 +59,7 @@ LL | | ); | |_________^ error[E0511]: invalid monomorphization of `simd_masked_store` intrinsic: expected third argument with length 4 (same as input type `Simd<i8, 4>`), found `Simd<u8, 2>` with length 2 - --> $DIR/masked-load-store-build-fail.rs:60:9 + --> $DIR/masked-load-store-build-fail.rs:62:9 | LL | / simd_masked_store( LL | | Simd([-1i8; 4]), @@ -69,7 +69,7 @@ LL | | ); | |_________^ error[E0511]: invalid monomorphization of `simd_masked_store` intrinsic: expected element type `u8` of third argument `Simd<u32, 4>` to be a signed integer type - --> $DIR/masked-load-store-build-fail.rs:67:9 + --> $DIR/masked-load-store-build-fail.rs:69:9 | LL | / simd_masked_store( LL | | Simd([1u32; 4]), diff --git a/tests/ui/simd/masked-load-store-check-fail.rs b/tests/ui/simd/masked-load-store-check-fail.rs index 39c82c41385..0f36bf6443f 100644 --- a/tests/ui/simd/masked-load-store-check-fail.rs +++ b/tests/ui/simd/masked-load-store-check-fail.rs @@ -1,10 +1,11 @@ //@ check-fail #![feature(repr_simd, intrinsics)] -extern "rust-intrinsic" { - fn simd_masked_load<M, P, T>(mask: M, pointer: P, values: T) -> T; - fn simd_masked_store<M, P, T>(mask: M, pointer: P, values: T) -> (); -} +#[rustc_intrinsic] +unsafe fn simd_masked_load<M, P, T>(mask: M, pointer: P, values: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_masked_store<M, P, T>(mask: M, pointer: P, values: T) -> (); #[derive(Copy, Clone)] #[repr(simd)] diff --git a/tests/ui/simd/masked-load-store-check-fail.stderr b/tests/ui/simd/masked-load-store-check-fail.stderr index 5d205d607c9..fa65798fc94 100644 --- a/tests/ui/simd/masked-load-store-check-fail.stderr +++ b/tests/ui/simd/masked-load-store-check-fail.stderr @@ -1,5 +1,5 @@ error[E0308]: mismatched types - --> $DIR/masked-load-store-check-fail.rs:21:13 + --> $DIR/masked-load-store-check-fail.rs:22:13 | LL | let _x: Simd<u8, 2> = simd_masked_load( | ---------------- arguments to this function are incorrect @@ -10,7 +10,7 @@ LL | Simd::<u8, 4>([9; 4]) = note: expected struct `Simd<_, 2>` found struct `Simd<_, 4>` help: the return type of this call is `Simd<u8, 4>` due to the type of the argument passed - --> $DIR/masked-load-store-check-fail.rs:18:31 + --> $DIR/masked-load-store-check-fail.rs:19:31 | LL | let _x: Simd<u8, 2> = simd_masked_load( | _______________________________^ @@ -21,13 +21,13 @@ LL | | Simd::<u8, 4>([9; 4]) LL | | ); | |_________^ note: function defined here - --> $DIR/masked-load-store-check-fail.rs:5:8 + --> $DIR/masked-load-store-check-fail.rs:5:11 | -LL | fn simd_masked_load<M, P, T>(mask: M, pointer: P, values: T) -> T; - | ^^^^^^^^^^^^^^^^ +LL | unsafe fn simd_masked_load<M, P, T>(mask: M, pointer: P, values: T) -> T; + | ^^^^^^^^^^^^^^^^ --------- error[E0308]: mismatched types - --> $DIR/masked-load-store-check-fail.rs:28:13 + --> $DIR/masked-load-store-check-fail.rs:29:13 | LL | let _x: Simd<u32, 4> = simd_masked_load( | ---------------- arguments to this function are incorrect @@ -38,7 +38,7 @@ LL | default = note: expected struct `Simd<u32, _>` found struct `Simd<u8, _>` help: the return type of this call is `Simd<u8, 4>` due to the type of the argument passed - --> $DIR/masked-load-store-check-fail.rs:25:32 + --> $DIR/masked-load-store-check-fail.rs:26:32 | LL | let _x: Simd<u32, 4> = simd_masked_load( | ________________________________^ @@ -49,10 +49,10 @@ LL | | default LL | | ); | |_________^ note: function defined here - --> $DIR/masked-load-store-check-fail.rs:5:8 + --> $DIR/masked-load-store-check-fail.rs:5:11 | -LL | fn simd_masked_load<M, P, T>(mask: M, pointer: P, values: T) -> T; - | ^^^^^^^^^^^^^^^^ +LL | unsafe fn simd_masked_load<M, P, T>(mask: M, pointer: P, values: T) -> T; + | ^^^^^^^^^^^^^^^^ --------- error: aborting due to 2 previous errors diff --git a/tests/ui/simd/masked-load-store.rs b/tests/ui/simd/masked-load-store.rs index 902143f9261..4b4195f51f1 100644 --- a/tests/ui/simd/masked-load-store.rs +++ b/tests/ui/simd/masked-load-store.rs @@ -1,10 +1,11 @@ //@ run-pass #![feature(repr_simd, intrinsics)] -extern "rust-intrinsic" { - fn simd_masked_load<M, P, T>(mask: M, pointer: P, values: T) -> T; - fn simd_masked_store<M, P, T>(mask: M, pointer: P, values: T) -> (); -} +#[rustc_intrinsic] +unsafe fn simd_masked_load<M, P, T>(mask: M, pointer: P, values: T) -> T; + +#[rustc_intrinsic] +unsafe fn simd_masked_store<M, P, T>(mask: M, pointer: P, values: T) -> (); #[derive(Copy, Clone)] #[repr(simd)] diff --git a/tests/ui/simd/monomorphize-shuffle-index.generic.stderr b/tests/ui/simd/monomorphize-shuffle-index.generic.stderr index 2d1fa1f8da2..b0a8da59fac 100644 --- a/tests/ui/simd/monomorphize-shuffle-index.generic.stderr +++ b/tests/ui/simd/monomorphize-shuffle-index.generic.stderr @@ -1,5 +1,5 @@ error: overly complex generic constant - --> $DIR/monomorphize-shuffle-index.rs:29:45 + --> $DIR/monomorphize-shuffle-index.rs:32:45 | LL | return simd_shuffle_generic::<_, _, { &Self::I.0 }>(a, b); | ^^----------^^ diff --git a/tests/ui/simd/monomorphize-shuffle-index.rs b/tests/ui/simd/monomorphize-shuffle-index.rs index 140cf6fbe96..01926408a2c 100644 --- a/tests/ui/simd/monomorphize-shuffle-index.rs +++ b/tests/ui/simd/monomorphize-shuffle-index.rs @@ -4,12 +4,15 @@ #![feature(repr_simd, intrinsics, adt_const_params, unsized_const_params, generic_const_exprs)] #![allow(incomplete_features)] -extern "rust-intrinsic" { - #[cfg(old)] - fn simd_shuffle<T, I, U>(a: T, b: T, i: I) -> U; - #[cfg(any(generic, generic_with_fn))] - fn simd_shuffle_generic<T, U, const I: &'static [u32]>(a: T, b: T) -> U; -} + +#[rustc_intrinsic] +#[cfg(old)] +unsafe fn simd_shuffle<T, I, U>(a: T, b: T, i: I) -> U; + +#[rustc_intrinsic] +#[cfg(any(generic, generic_with_fn))] +unsafe fn simd_shuffle_generic<T, U, const I: &'static [u32]>(a: T, b: T) -> U; + #[derive(Copy, Clone)] #[repr(simd)] diff --git a/tests/ui/simd/repr_packed.rs b/tests/ui/simd/repr_packed.rs index 1ba15bda98d..a666892226e 100644 --- a/tests/ui/simd/repr_packed.rs +++ b/tests/ui/simd/repr_packed.rs @@ -22,9 +22,8 @@ fn check_ty<T>() { check_size_align::<T, 15>(); } -extern "rust-intrinsic" { - fn simd_add<T>(a: T, b: T) -> T; -} +#[rustc_intrinsic] +unsafe fn simd_add<T>(a: T, b: T) -> T; fn main() { check_ty::<u8>(); diff --git a/tests/ui/simd/shuffle.rs b/tests/ui/simd/shuffle.rs index 96c0ed2118f..2cae5a1e7de 100644 --- a/tests/ui/simd/shuffle.rs +++ b/tests/ui/simd/shuffle.rs @@ -8,9 +8,8 @@ use std::marker::ConstParamTy; -extern "rust-intrinsic" { - fn simd_shuffle<T, I, U>(a: T, b: T, i: I) -> U; -} +#[rustc_intrinsic] +unsafe fn simd_shuffle<T, I, U>(a: T, b: T, i: I) -> U; #[derive(Copy, Clone, ConstParamTy, PartialEq, Eq)] #[repr(simd)] diff --git a/tests/ui/simd/simd-bitmask-notpow2.rs b/tests/ui/simd/simd-bitmask-notpow2.rs index 3499bf33ed5..d7572ef4a2a 100644 --- a/tests/ui/simd/simd-bitmask-notpow2.rs +++ b/tests/ui/simd/simd-bitmask-notpow2.rs @@ -4,10 +4,12 @@ //@ ignore-endian-big #![feature(repr_simd, intrinsics)] -extern "rust-intrinsic" { - fn simd_bitmask<T, U>(v: T) -> U; - fn simd_select_bitmask<T, U>(m: T, a: U, b: U) -> U; -} +#[rustc_intrinsic] +unsafe fn simd_bitmask<T, U>(v: T) -> U; + +#[rustc_intrinsic] +unsafe fn simd_select_bitmask<T, U>(m: T, a: U, b: U) -> U; + fn main() { // Non-power-of-2 multi-byte mask. diff --git a/tests/ui/simd/simd-bitmask.rs b/tests/ui/simd/simd-bitmask.rs index 82f73fca951..4275ab0f40c 100644 --- a/tests/ui/simd/simd-bitmask.rs +++ b/tests/ui/simd/simd-bitmask.rs @@ -1,10 +1,12 @@ //@run-pass #![feature(repr_simd, intrinsics)] -extern "rust-intrinsic" { - fn simd_bitmask<T, U>(v: T) -> U; - fn simd_select_bitmask<T, U>(m: T, a: U, b: U) -> U; -} +#[rustc_intrinsic] +unsafe fn simd_bitmask<T, U>(v: T) -> U; + +#[rustc_intrinsic] +unsafe fn simd_select_bitmask<T, U>(m: T, a: U, b: U) -> U; + #[derive(Copy, Clone)] #[repr(simd)] diff --git a/tests/ui/static/issue-24446.rs b/tests/ui/static/issue-24446.rs index 6cf8846506d..830e373c189 100644 --- a/tests/ui/static/issue-24446.rs +++ b/tests/ui/static/issue-24446.rs @@ -2,7 +2,6 @@ fn main() { static foo: dyn Fn() -> u32 = || -> u32 { //~^ ERROR the size for values of type //~| ERROR cannot be shared between threads safely - //~| ERROR the size for values of type //~| ERROR mismatched types 0 }; diff --git a/tests/ui/static/issue-24446.stderr b/tests/ui/static/issue-24446.stderr index 8cb034000be..033caf07d8e 100644 --- a/tests/ui/static/issue-24446.stderr +++ b/tests/ui/static/issue-24446.stderr @@ -15,33 +15,19 @@ LL | static foo: dyn Fn() -> u32 = || -> u32 { | = help: the trait `Sized` is not implemented for `(dyn Fn() -> u32 + 'static)` -error[E0277]: the size for values of type `(dyn Fn() -> u32 + 'static)` cannot be known at compilation time - --> $DIR/issue-24446.rs:2:35 - | -LL | static foo: dyn Fn() -> u32 = || -> u32 { - | ___________________________________^ -... | -LL | | 0 -LL | | }; - | |_____^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `(dyn Fn() -> u32 + 'static)` - = note: constant expressions must have a statically known size - error[E0308]: mismatched types --> $DIR/issue-24446.rs:2:35 | LL | static foo: dyn Fn() -> u32 = || -> u32 { | ___________________________________^ ... | -LL | | 0 LL | | }; | |_____^ expected `dyn Fn`, found closure | = note: expected trait object `(dyn Fn() -> u32 + 'static)` found closure `{closure@$DIR/issue-24446.rs:2:35: 2:44}` -error: aborting due to 4 previous errors +error: aborting due to 3 previous errors Some errors have detailed explanations: E0277, E0308. For more information about an error, try `rustc --explain E0277`. diff --git a/tests/ui/statics/unsized_type2.stderr b/tests/ui/statics/unsized_type2.stderr index b18a99fab72..ffbbe218c87 100644 --- a/tests/ui/statics/unsized_type2.stderr +++ b/tests/ui/statics/unsized_type2.stderr @@ -11,6 +11,12 @@ note: required because it appears within the type `Foo` LL | pub struct Foo { | ^^^ +error[E0308]: mismatched types + --> $DIR/unsized_type2.rs:14:45 + | +LL | pub static WITH_ERROR: Foo = Foo { version: 0 }; + | ^ expected `str`, found integer + error[E0277]: the size for values of type `str` cannot be known at compilation time --> $DIR/unsized_type2.rs:14:30 | @@ -23,13 +29,7 @@ note: required because it appears within the type `Foo` | LL | pub struct Foo { | ^^^ - = note: constant expressions must have a statically known size - -error[E0308]: mismatched types - --> $DIR/unsized_type2.rs:14:45 - | -LL | pub static WITH_ERROR: Foo = Foo { version: 0 }; - | ^ expected `str`, found integer + = note: structs must have a statically known size to be initialized error: aborting due to 3 previous errors diff --git a/tests/ui/suggestions/dyn-incompatible-trait-references-self.stderr b/tests/ui/suggestions/dyn-incompatible-trait-references-self.stderr index ae009d26029..4576017abaf 100644 --- a/tests/ui/suggestions/dyn-incompatible-trait-references-self.stderr +++ b/tests/ui/suggestions/dyn-incompatible-trait-references-self.stderr @@ -34,6 +34,18 @@ LL | trait Other: Sized {} | this trait is not dyn compatible... error[E0277]: the size for values of type `Self` cannot be known at compilation time + --> $DIR/dyn-incompatible-trait-references-self.rs:4:22 + | +LL | fn bat(&self) -> Self {} + | ^^^^ doesn't have a size known at compile-time + | + = note: the return type of a function must have a statically known size +help: consider further restricting `Self` + | +LL | fn bat(&self) -> Self where Self: Sized {} + | +++++++++++++++++ + +error[E0277]: the size for values of type `Self` cannot be known at compilation time --> $DIR/dyn-incompatible-trait-references-self.rs:2:22 | LL | fn baz(&self, _: Self) {} @@ -61,18 +73,6 @@ LL | fn bat(&self) -> Self {} = note: expected type parameter `Self` found unit type `()` -error[E0277]: the size for values of type `Self` cannot be known at compilation time - --> $DIR/dyn-incompatible-trait-references-self.rs:4:22 - | -LL | fn bat(&self) -> Self {} - | ^^^^ doesn't have a size known at compile-time - | - = note: the return type of a function must have a statically known size -help: consider further restricting `Self` - | -LL | fn bat(&self) -> Self where Self: Sized {} - | +++++++++++++++++ - error: aborting due to 5 previous errors Some errors have detailed explanations: E0038, E0277, E0308. diff --git a/tests/ui/suggestions/missing-lifetime-specifier.rs b/tests/ui/suggestions/missing-lifetime-specifier.rs index dd437fc0c0b..a957477897d 100644 --- a/tests/ui/suggestions/missing-lifetime-specifier.rs +++ b/tests/ui/suggestions/missing-lifetime-specifier.rs @@ -1,6 +1,5 @@ // The specific errors produced depend the thread-local implementation. // Run only on platforms with "fast" TLS. -//@ ignore-windows FIXME(#84933) //@ ignore-wasm globals are used instead of thread locals //@ ignore-emscripten globals are used instead of thread locals //@ ignore-android does not use #[thread_local] diff --git a/tests/ui/suggestions/missing-lifetime-specifier.stderr b/tests/ui/suggestions/missing-lifetime-specifier.stderr index e0b6bb872b5..1fdbf3b0c79 100644 --- a/tests/ui/suggestions/missing-lifetime-specifier.stderr +++ b/tests/ui/suggestions/missing-lifetime-specifier.stderr @@ -1,5 +1,5 @@ error[E0106]: missing lifetime specifiers - --> $DIR/missing-lifetime-specifier.rs:28:44 + --> $DIR/missing-lifetime-specifier.rs:27:44 | LL | static a: RefCell<HashMap<i32, Vec<Vec<Foo>>>> = RefCell::new(HashMap::new()); | ^^^ expected 2 lifetime parameters @@ -11,7 +11,7 @@ LL | static a: RefCell<HashMap<i32, Vec<Vec<Foo<'static, 'static>>>>> = RefC | ++++++++++++++++++ error[E0106]: missing lifetime specifiers - --> $DIR/missing-lifetime-specifier.rs:32:44 + --> $DIR/missing-lifetime-specifier.rs:31:44 | LL | static b: RefCell<HashMap<i32, Vec<Vec<&Bar>>>> = RefCell::new(HashMap::new()); | ^^^^ expected 2 lifetime parameters @@ -25,7 +25,7 @@ LL | static b: RefCell<HashMap<i32, Vec<Vec<&'static Bar<'static, 'static>>> | +++++++ ++++++++++++++++++ error[E0106]: missing lifetime specifiers - --> $DIR/missing-lifetime-specifier.rs:36:47 + --> $DIR/missing-lifetime-specifier.rs:35:47 | LL | static c: RefCell<HashMap<i32, Vec<Vec<Qux<i32>>>>> = RefCell::new(HashMap::new()); | ^ expected 2 lifetime parameters @@ -37,7 +37,7 @@ LL | static c: RefCell<HashMap<i32, Vec<Vec<Qux<'static, 'static, i32>>>>> = | +++++++++++++++++ error[E0106]: missing lifetime specifiers - --> $DIR/missing-lifetime-specifier.rs:40:44 + --> $DIR/missing-lifetime-specifier.rs:39:44 | LL | static d: RefCell<HashMap<i32, Vec<Vec<&Tar<i32>>>>> = RefCell::new(HashMap::new()); | ^ ^ expected 2 lifetime parameters @@ -51,7 +51,7 @@ LL | static d: RefCell<HashMap<i32, Vec<Vec<&'static Tar<'static, 'static, i | +++++++ +++++++++++++++++ error[E0106]: missing lifetime specifier - --> $DIR/missing-lifetime-specifier.rs:49:44 + --> $DIR/missing-lifetime-specifier.rs:48:44 | LL | static f: RefCell<HashMap<i32, Vec<Vec<&Tar<'static, i32>>>>> = RefCell::new(HashMap::new()); | ^ expected named lifetime parameter @@ -63,7 +63,7 @@ LL | static f: RefCell<HashMap<i32, Vec<Vec<&'static Tar<'static, i32>>>>> = | +++++++ error[E0107]: union takes 2 lifetime arguments but 1 lifetime argument was supplied - --> $DIR/missing-lifetime-specifier.rs:45:44 + --> $DIR/missing-lifetime-specifier.rs:44:44 | LL | static e: RefCell<HashMap<i32, Vec<Vec<Qux<'static, i32>>>>> = RefCell::new(HashMap::new()); | ^^^ ------- supplied 1 lifetime argument @@ -71,7 +71,7 @@ LL | static e: RefCell<HashMap<i32, Vec<Vec<Qux<'static, i32>>>>> = RefCell: | expected 2 lifetime arguments | note: union defined here, with 2 lifetime parameters: `'t`, `'k` - --> $DIR/missing-lifetime-specifier.rs:21:11 + --> $DIR/missing-lifetime-specifier.rs:20:11 | LL | pub union Qux<'t, 'k, I> { | ^^^ -- -- @@ -81,7 +81,7 @@ LL | static e: RefCell<HashMap<i32, Vec<Vec<Qux<'static, 'static, i32>>>>> = | +++++++++ error[E0107]: trait takes 2 lifetime arguments but 1 lifetime argument was supplied - --> $DIR/missing-lifetime-specifier.rs:49:45 + --> $DIR/missing-lifetime-specifier.rs:48:45 | LL | static f: RefCell<HashMap<i32, Vec<Vec<&Tar<'static, i32>>>>> = RefCell::new(HashMap::new()); | ^^^ ------- supplied 1 lifetime argument @@ -89,7 +89,7 @@ LL | static f: RefCell<HashMap<i32, Vec<Vec<&Tar<'static, i32>>>>> = RefCell | expected 2 lifetime arguments | note: trait defined here, with 2 lifetime parameters: `'t`, `'k` - --> $DIR/missing-lifetime-specifier.rs:25:7 + --> $DIR/missing-lifetime-specifier.rs:24:7 | LL | trait Tar<'t, 'k, I> {} | ^^^ -- -- diff --git a/tests/ui/suggestions/unnecessary_dot_for_floating_point_literal.stderr b/tests/ui/suggestions/unnecessary_dot_for_floating_point_literal.stderr index 8b48ee9f124..c0162ec2cab 100644 --- a/tests/ui/suggestions/unnecessary_dot_for_floating_point_literal.stderr +++ b/tests/ui/suggestions/unnecessary_dot_for_floating_point_literal.stderr @@ -22,7 +22,7 @@ LL | let _: f64 = 1..; | expected due to this | = note: expected type `f64` - found struct `RangeFrom<{integer}>` + found struct `std::ops::RangeFrom<{integer}>` help: remove the unnecessary `.` operator for a floating point literal | LL | let _: f64 = 1.; diff --git a/tests/ui/target-feature/forbidden-hardfloat-target-feature-attribute.rs b/tests/ui/target-feature/forbidden-hardfloat-target-feature-attribute.rs index dab01179c0b..215e64979f7 100644 --- a/tests/ui/target-feature/forbidden-hardfloat-target-feature-attribute.rs +++ b/tests/ui/target-feature/forbidden-hardfloat-target-feature-attribute.rs @@ -1,3 +1,4 @@ +//! Ensure ABI-incompatible features cannot be enabled via `#[target_feature]`. //@ compile-flags: --target=riscv32e-unknown-none-elf --crate-type=lib //@ needs-llvm-components: riscv #![feature(no_core, lang_items, riscv_target_feature)] diff --git a/tests/ui/target-feature/forbidden-hardfloat-target-feature-attribute.stderr b/tests/ui/target-feature/forbidden-hardfloat-target-feature-attribute.stderr index 9df56d86729..bfe767e5ffb 100644 --- a/tests/ui/target-feature/forbidden-hardfloat-target-feature-attribute.stderr +++ b/tests/ui/target-feature/forbidden-hardfloat-target-feature-attribute.stderr @@ -1,5 +1,5 @@ error: target feature `d` cannot be enabled with `#[target_feature]`: this feature is incompatible with the target ABI - --> $DIR/forbidden-hardfloat-target-feature-attribute.rs:9:18 + --> $DIR/forbidden-hardfloat-target-feature-attribute.rs:10:18 | LL | #[target_feature(enable = "d")] | ^^^^^^^^^^^^ diff --git a/tests/ui/target-feature/forbidden-hardfloat-target-feature-cfg.rs b/tests/ui/target-feature/forbidden-hardfloat-target-feature-cfg.rs deleted file mode 100644 index 8755791c1c0..00000000000 --- a/tests/ui/target-feature/forbidden-hardfloat-target-feature-cfg.rs +++ /dev/null @@ -1,14 +0,0 @@ -//@ compile-flags: --target=x86_64-unknown-linux-gnu --crate-type=lib -//@ needs-llvm-components: x86 -//@ check-pass -#![feature(no_core, lang_items)] -#![no_core] -#![allow(unexpected_cfgs)] - -#[lang = "sized"] -pub trait Sized {} - -// The compile_error macro does not exist, so if the `cfg` evaluates to `true` this -// complains about the missing macro rather than showing the error... but that's good enough. -#[cfg(not(target_feature = "x87"))] -compile_error!("the x87 feature *should* be exposed in `cfg`"); diff --git a/tests/ui/target-feature/forbidden-hardfloat-target-feature-flag-disable-implied.rs b/tests/ui/target-feature/forbidden-hardfloat-target-feature-flag-disable-implied.rs index 3d09217327a..81f138b175f 100644 --- a/tests/ui/target-feature/forbidden-hardfloat-target-feature-flag-disable-implied.rs +++ b/tests/ui/target-feature/forbidden-hardfloat-target-feature-flag-disable-implied.rs @@ -1,8 +1,11 @@ +//! Ensure that if disabling a target feature implies disabling an ABI-required target feature, +//! we complain. //@ compile-flags: --target=x86_64-unknown-linux-gnu --crate-type=lib //@ needs-llvm-components: x86 //@ compile-flags: -Ctarget-feature=-sse // For now this is just a warning. //@ build-pass +//@error-pattern: must be enabled to ensure that the ABI #![feature(no_core, lang_items)] #![no_core] diff --git a/tests/ui/target-feature/forbidden-hardfloat-target-feature-flag-disable-neon.rs b/tests/ui/target-feature/forbidden-hardfloat-target-feature-flag-disable-neon.rs index 95c366bb3f5..7242bcc85bf 100644 --- a/tests/ui/target-feature/forbidden-hardfloat-target-feature-flag-disable-neon.rs +++ b/tests/ui/target-feature/forbidden-hardfloat-target-feature-flag-disable-neon.rs @@ -3,6 +3,7 @@ //@ compile-flags: -Ctarget-feature=-neon // For now this is just a warning. //@ build-pass +//@error-pattern: must be enabled to ensure that the ABI #![feature(no_core, lang_items)] #![no_core] diff --git a/tests/ui/target-feature/forbidden-hardfloat-target-feature-flag-disable.rs b/tests/ui/target-feature/forbidden-hardfloat-target-feature-flag-disable.rs index fd8023664da..7eebcf05dc0 100644 --- a/tests/ui/target-feature/forbidden-hardfloat-target-feature-flag-disable.rs +++ b/tests/ui/target-feature/forbidden-hardfloat-target-feature-flag-disable.rs @@ -1,8 +1,10 @@ +//! Ensure ABI-required features cannot be disabled via `-Ctarget-feature`. //@ compile-flags: --target=x86_64-unknown-linux-gnu --crate-type=lib //@ needs-llvm-components: x86 //@ compile-flags: -Ctarget-feature=-x87 // For now this is just a warning. //@ build-pass +//@error-pattern: must be enabled to ensure that the ABI #![feature(no_core, lang_items)] #![no_core] diff --git a/tests/ui/target-feature/forbidden-hardfloat-target-feature-flag.rs b/tests/ui/target-feature/forbidden-hardfloat-target-feature-flag.rs new file mode 100644 index 00000000000..f277a309cd6 --- /dev/null +++ b/tests/ui/target-feature/forbidden-hardfloat-target-feature-flag.rs @@ -0,0 +1,12 @@ +//! Ensure ABI-incompatible features cannot be enabled via `-Ctarget-feature`. +//@ compile-flags: --target=x86_64-unknown-linux-gnu --crate-type=lib +//@ needs-llvm-components: x86 +//@ compile-flags: -Ctarget-feature=+soft-float +// For now this is just a warning. +//@ build-pass +//@error-pattern: must be disabled to ensure that the ABI +#![feature(no_core, lang_items, riscv_target_feature)] +#![no_core] + +#[lang = "sized"] +pub trait Sized {} diff --git a/tests/ui/target-feature/forbidden-hardfloat-target-feature-flag.stderr b/tests/ui/target-feature/forbidden-hardfloat-target-feature-flag.stderr new file mode 100644 index 00000000000..e49672f33b9 --- /dev/null +++ b/tests/ui/target-feature/forbidden-hardfloat-target-feature-flag.stderr @@ -0,0 +1,11 @@ +warning: target feature `soft-float` must be disabled to ensure that the ABI of the current target can be implemented correctly + | + = note: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #116344 <https://github.com/rust-lang/rust/issues/116344> + +warning: unstable feature specified for `-Ctarget-feature`: `soft-float` + | + = note: this feature is not stably supported; its behavior can change in the future + +warning: 2 warnings emitted + diff --git a/tests/ui/target-feature/forbidden-target-feature-attribute.rs b/tests/ui/target-feature/forbidden-target-feature-attribute.rs index 2ba5f2215c7..6bb6f8aaffb 100644 --- a/tests/ui/target-feature/forbidden-target-feature-attribute.rs +++ b/tests/ui/target-feature/forbidden-target-feature-attribute.rs @@ -1,11 +1,12 @@ -//@ compile-flags: --target=x86_64-unknown-linux-gnu --crate-type=lib -//@ needs-llvm-components: x86 +//! Ensure "forbidden" target features cannot be enabled via `#[target_feature]`. +//@ compile-flags: --target=riscv32e-unknown-none-elf --crate-type=lib +//@ needs-llvm-components: riscv #![feature(no_core, lang_items)] #![no_core] #[lang = "sized"] pub trait Sized {} -#[target_feature(enable = "soft-float")] +#[target_feature(enable = "forced-atomics")] //~^ERROR: cannot be enabled with pub unsafe fn my_fun() {} diff --git a/tests/ui/target-feature/forbidden-target-feature-attribute.stderr b/tests/ui/target-feature/forbidden-target-feature-attribute.stderr index f3d54cc19d3..f8ea0c0e793 100644 --- a/tests/ui/target-feature/forbidden-target-feature-attribute.stderr +++ b/tests/ui/target-feature/forbidden-target-feature-attribute.stderr @@ -1,8 +1,8 @@ -error: target feature `soft-float` cannot be enabled with `#[target_feature]`: unsound because it changes float ABI - --> $DIR/forbidden-target-feature-attribute.rs:9:18 +error: target feature `forced-atomics` cannot be enabled with `#[target_feature]`: unsound because it changes the ABI of atomic operations + --> $DIR/forbidden-target-feature-attribute.rs:10:18 | -LL | #[target_feature(enable = "soft-float")] - | ^^^^^^^^^^^^^^^^^^^^^ +LL | #[target_feature(enable = "forced-atomics")] + | ^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 1 previous error diff --git a/tests/ui/target-feature/forbidden-target-feature-cfg.rs b/tests/ui/target-feature/forbidden-target-feature-cfg.rs index 1f001e9f8ff..e848ffde018 100644 --- a/tests/ui/target-feature/forbidden-target-feature-cfg.rs +++ b/tests/ui/target-feature/forbidden-target-feature-cfg.rs @@ -1,5 +1,6 @@ -//@ compile-flags: --target=x86_64-unknown-none --crate-type=lib -//@ needs-llvm-components: x86 +//! Ensure "forbidden" target features are not exposed via `cfg`. +//@ compile-flags: --target=riscv32e-unknown-none-elf --crate-type=lib +//@ needs-llvm-components: riscv //@ check-pass #![feature(no_core, lang_items)] #![no_core] @@ -10,5 +11,5 @@ pub trait Sized {} // The compile_error macro does not exist, so if the `cfg` evaluates to `true` this // complains about the missing macro rather than showing the error... but that's good enough. -#[cfg(target_feature = "soft-float")] -compile_error!("the soft-float feature should not be exposed in `cfg`"); +#[cfg(target_feature = "forced-atomics")] +compile_error!("the forced-atomics feature should not be exposed in `cfg`"); diff --git a/tests/ui/target-feature/forbidden-target-feature-flag-disable.rs b/tests/ui/target-feature/forbidden-target-feature-flag-disable.rs index b09c53bd46a..cf85c521228 100644 --- a/tests/ui/target-feature/forbidden-target-feature-flag-disable.rs +++ b/tests/ui/target-feature/forbidden-target-feature-flag-disable.rs @@ -1,8 +1,10 @@ -//@ compile-flags: --target=x86_64-unknown-linux-gnu --crate-type=lib -//@ needs-llvm-components: x86 -//@ compile-flags: -Ctarget-feature=-soft-float +//! Ensure "forbidden" target features cannot be disabled via `-Ctarget-feature`. +//@ compile-flags: --target=riscv32e-unknown-none-elf --crate-type=lib +//@ needs-llvm-components: riscv +//@ compile-flags: -Ctarget-feature=-forced-atomics // For now this is just a warning. //@ build-pass +//@error-pattern: unsound because it changes the ABI #![feature(no_core, lang_items)] #![no_core] diff --git a/tests/ui/target-feature/forbidden-target-feature-flag-disable.stderr b/tests/ui/target-feature/forbidden-target-feature-flag-disable.stderr index 797cd4be5c2..171ed0de6aa 100644 --- a/tests/ui/target-feature/forbidden-target-feature-flag-disable.stderr +++ b/tests/ui/target-feature/forbidden-target-feature-flag-disable.stderr @@ -1,4 +1,4 @@ -warning: target feature `soft-float` cannot be disabled with `-Ctarget-feature`: unsound because it changes float ABI +warning: target feature `forced-atomics` cannot be disabled with `-Ctarget-feature`: unsound because it changes the ABI of atomic operations | = note: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: for more information, see issue #116344 <https://github.com/rust-lang/rust/issues/116344> diff --git a/tests/ui/target-feature/forbidden-target-feature-flag.rs b/tests/ui/target-feature/forbidden-target-feature-flag.rs index 0f688fde7f4..245841eb039 100644 --- a/tests/ui/target-feature/forbidden-target-feature-flag.rs +++ b/tests/ui/target-feature/forbidden-target-feature-flag.rs @@ -1,8 +1,10 @@ -//@ compile-flags: --target=x86_64-unknown-linux-gnu --crate-type=lib -//@ needs-llvm-components: x86 -//@ compile-flags: -Ctarget-feature=+soft-float +//! Ensure "forbidden" target features cannot be enabled via `-Ctarget-feature`. +//@ compile-flags: --target=riscv32e-unknown-none-elf --crate-type=lib +//@ needs-llvm-components: riscv +//@ compile-flags: -Ctarget-feature=+forced-atomics // For now this is just a warning. //@ build-pass +//@error-pattern: unsound because it changes the ABI #![feature(no_core, lang_items)] #![no_core] diff --git a/tests/ui/target-feature/forbidden-target-feature-flag.stderr b/tests/ui/target-feature/forbidden-target-feature-flag.stderr index 075666fbf66..f8490f066d1 100644 --- a/tests/ui/target-feature/forbidden-target-feature-flag.stderr +++ b/tests/ui/target-feature/forbidden-target-feature-flag.stderr @@ -1,4 +1,4 @@ -warning: target feature `soft-float` cannot be enabled with `-Ctarget-feature`: unsound because it changes float ABI +warning: target feature `forced-atomics` cannot be enabled with `-Ctarget-feature`: unsound because it changes the ABI of atomic operations | = note: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: for more information, see issue #116344 <https://github.com/rust-lang/rust/issues/116344> diff --git a/tests/ui/target_modifiers/auxiliary/default_reg_struct_return.rs b/tests/ui/target_modifiers/auxiliary/default_reg_struct_return.rs new file mode 100644 index 00000000000..355e7c56e94 --- /dev/null +++ b/tests/ui/target_modifiers/auxiliary/default_reg_struct_return.rs @@ -0,0 +1,20 @@ +//@ compile-flags: --target i686-unknown-linux-gnu -Cpanic=abort +// Auxiliary build problems with aarch64-apple: +// Shared library linking cc seems to convert "-m32" flag into -arch armv4t +// Auxiliary build problems with i686-mingw: linker `cc` not found +//@ only-x86 +//@ ignore-windows +//@ ignore-apple +//@ needs-llvm-components: x86 +#![crate_type = "rlib"] +#![no_core] +#![feature(no_core, lang_items, repr_simd)] + +#[lang = "sized"] +trait Sized {} +#[lang = "copy"] +trait Copy {} + +pub fn somefun() {} + +pub struct S; diff --git a/tests/ui/target_modifiers/auxiliary/wrong_regparm.rs b/tests/ui/target_modifiers/auxiliary/wrong_regparm.rs new file mode 100644 index 00000000000..2e16f1ee747 --- /dev/null +++ b/tests/ui/target_modifiers/auxiliary/wrong_regparm.rs @@ -0,0 +1,20 @@ +//@ compile-flags: --target i686-unknown-linux-gnu -Zregparm=2 -Cpanic=abort +// Auxiliary build problems with aarch64-apple: +// Shared library linking cc seems to convert "-m32" flag into -arch armv4t +// Auxiliary build problems with i686-mingw: linker `cc` not found +//@ only-x86 +//@ ignore-windows +//@ ignore-apple +//@ needs-llvm-components: x86 +#![crate_type = "rlib"] +#![no_core] +#![feature(no_core, lang_items, repr_simd)] + +#[lang = "sized"] +trait Sized {} +#[lang = "copy"] +trait Copy {} + +pub fn somefun() {} + +pub struct S; diff --git a/tests/ui/target_modifiers/auxiliary/wrong_regparm_and_ret.rs b/tests/ui/target_modifiers/auxiliary/wrong_regparm_and_ret.rs new file mode 100644 index 00000000000..39c6be9d589 --- /dev/null +++ b/tests/ui/target_modifiers/auxiliary/wrong_regparm_and_ret.rs @@ -0,0 +1,20 @@ +//@ compile-flags: --target i686-unknown-linux-gnu -Zregparm=2 -Zreg-struct-return=true -Cpanic=abort +// Auxiliary build problems with aarch64-apple: +// Shared library linking cc seems to convert "-m32" flag into -arch armv4t +// Auxiliary build problems with i686-mingw: linker `cc` not found +//@ only-x86 +//@ ignore-windows +//@ ignore-apple +//@ needs-llvm-components: x86 +#![crate_type = "rlib"] +#![no_core] +#![feature(no_core, lang_items, repr_simd)] + +#[lang = "sized"] +trait Sized {} +#[lang = "copy"] +trait Copy {} + +pub fn somefun() {} + +pub struct S; diff --git a/tests/ui/target_modifiers/defaults_check.error.stderr b/tests/ui/target_modifiers/defaults_check.error.stderr new file mode 100644 index 00000000000..c545dd71069 --- /dev/null +++ b/tests/ui/target_modifiers/defaults_check.error.stderr @@ -0,0 +1,13 @@ +error: mixing `-Zreg-struct-return` will cause an ABI mismatch in crate `defaults_check` + --> $DIR/defaults_check.rs:20:1 + | +LL | #![crate_type = "rlib"] + | ^ + | + = help: the `-Zreg-struct-return` flag modifies the ABI so Rust crates compiled with different values of this flag cannot be used together safely + = note: `-Zreg-struct-return=true` in this crate is incompatible with `-Zreg-struct-return=` in dependency `default_reg_struct_return` + = help: set `-Zreg-struct-return=` in this crate or `-Zreg-struct-return=true` in `default_reg_struct_return` + = help: if you are sure this will not cause problems, you may use `-Cunsafe-allow-abi-mismatch=reg-struct-return` to silence this error + +error: aborting due to 1 previous error + diff --git a/tests/ui/target_modifiers/defaults_check.rs b/tests/ui/target_modifiers/defaults_check.rs new file mode 100644 index 00000000000..b8f4848d3a4 --- /dev/null +++ b/tests/ui/target_modifiers/defaults_check.rs @@ -0,0 +1,27 @@ +// Tests that default unspecified target modifier value in dependency crate is ok linked +// with the same value, explicitly specified +//@ aux-crate:default_reg_struct_return=default_reg_struct_return.rs +//@ compile-flags: --target i686-unknown-linux-gnu -Cpanic=abort +//@ revisions:error ok ok_explicit +//@[ok] compile-flags: +//@[ok_explicit] compile-flags: -Zreg-struct-return=false +//@[error] compile-flags: -Zreg-struct-return=true + +// Auxiliary build problems with aarch64-apple: +// Shared library linking cc seems to convert "-m32" flag into -arch armv4t +// Auxiliary build problems with i686-mingw: linker `cc` not found +//@ only-x86 +//@ ignore-windows +//@ ignore-apple +//@ needs-llvm-components: x86 +//@[ok] build-pass +//@[ok_explicit] build-pass + +#![crate_type = "rlib"] +//[error]~^ ERROR mixing `-Zreg-struct-return` will cause an ABI mismatch in crate `defaults_check` +#![no_core] +#![feature(no_core, lang_items, repr_simd)] + +fn foo() { + default_reg_struct_return::somefun(); +} diff --git a/tests/ui/target_modifiers/incompatible_regparm.allow_no_value.stderr b/tests/ui/target_modifiers/incompatible_regparm.allow_no_value.stderr new file mode 100644 index 00000000000..8597332825b --- /dev/null +++ b/tests/ui/target_modifiers/incompatible_regparm.allow_no_value.stderr @@ -0,0 +1,2 @@ +error: codegen option `unsafe-allow-abi-mismatch` requires a comma-separated list of strings (C unsafe-allow-abi-mismatch=<value>) + diff --git a/tests/ui/target_modifiers/incompatible_regparm.error_generated.stderr b/tests/ui/target_modifiers/incompatible_regparm.error_generated.stderr new file mode 100644 index 00000000000..692fc7a4e3f --- /dev/null +++ b/tests/ui/target_modifiers/incompatible_regparm.error_generated.stderr @@ -0,0 +1,13 @@ +error: mixing `-Zregparm` will cause an ABI mismatch in crate `incompatible_regparm` + --> $DIR/incompatible_regparm.rs:16:1 + | +LL | #![crate_type = "rlib"] + | ^ + | + = help: the `-Zregparm` flag modifies the ABI so Rust crates compiled with different values of this flag cannot be used together safely + = note: `-Zregparm=1` in this crate is incompatible with `-Zregparm=2` in dependency `wrong_regparm` + = help: set `-Zregparm=2` in this crate or `-Zregparm=1` in `wrong_regparm` + = help: if you are sure this will not cause problems, you may use `-Cunsafe-allow-abi-mismatch=regparm` to silence this error + +error: aborting due to 1 previous error + diff --git a/tests/ui/target_modifiers/incompatible_regparm.rs b/tests/ui/target_modifiers/incompatible_regparm.rs new file mode 100644 index 00000000000..e866c5aa891 --- /dev/null +++ b/tests/ui/target_modifiers/incompatible_regparm.rs @@ -0,0 +1,23 @@ +//@ aux-crate:wrong_regparm=wrong_regparm.rs +//@ compile-flags: --target i686-unknown-linux-gnu -Zregparm=1 -Cpanic=abort +// Auxiliary build problems with aarch64-apple: +// Shared library linking cc seems to convert "-m32" flag into -arch armv4t +// Auxiliary build problems with i686-mingw: linker `cc` not found +//@ only-x86 +//@ ignore-windows +//@ ignore-apple +//@ needs-llvm-components: x86 +//@ revisions:error_generated allow_regparm_mismatch allow_no_value + +//@[allow_regparm_mismatch] compile-flags: -Cunsafe-allow-abi-mismatch=regparm +//@[allow_regparm_mismatch] build-pass +//@[allow_no_value] compile-flags: -Cunsafe-allow-abi-mismatch + +#![crate_type = "rlib"] +//[error_generated]~^ ERROR mixing `-Zregparm` will cause an ABI mismatch in crate `incompatible_regparm` +#![no_core] +#![feature(no_core, lang_items, repr_simd)] + +fn foo() { + wrong_regparm::somefun(); +} diff --git a/tests/ui/target_modifiers/two_flags.rs b/tests/ui/target_modifiers/two_flags.rs new file mode 100644 index 00000000000..ca17117a267 --- /dev/null +++ b/tests/ui/target_modifiers/two_flags.rs @@ -0,0 +1,23 @@ +//@ aux-crate:wrong_regparm_and_ret=wrong_regparm_and_ret.rs +//@ compile-flags: --target i686-unknown-linux-gnu -Cpanic=abort +// Auxiliary build problems with aarch64-apple: +// Shared library linking cc seems to convert "-m32" flag into -arch armv4t +// Auxiliary build problems with i686-mingw: linker `cc` not found +//@ only-x86 +//@ ignore-windows +//@ ignore-apple +//@ needs-llvm-components: x86 +//@ revisions:two_allowed unknown_allowed + +//@[two_allowed] compile-flags: -Cunsafe-allow-abi-mismatch=regparm,reg-struct-return +//@[two_allowed] build-pass +//@[unknown_allowed] compile-flags: -Cunsafe-allow-abi-mismatch=unknown_flag -Zregparm=2 -Zreg-struct-return=true + +#![crate_type = "rlib"] +//[unknown_allowed]~^ ERROR unknown target modifier `unknown_flag`, requested by `-Cunsafe-allow-abi-mismatch=unknown_flag` +#![no_core] +#![feature(no_core, lang_items, repr_simd)] + +fn foo() { + wrong_regparm_and_ret::somefun(); +} diff --git a/tests/ui/target_modifiers/two_flags.unknown_allowed.stderr b/tests/ui/target_modifiers/two_flags.unknown_allowed.stderr new file mode 100644 index 00000000000..c8040c6e389 --- /dev/null +++ b/tests/ui/target_modifiers/two_flags.unknown_allowed.stderr @@ -0,0 +1,8 @@ +error: unknown target modifier `unknown_flag`, requested by `-Cunsafe-allow-abi-mismatch=unknown_flag` + --> $DIR/two_flags.rs:16:1 + | +LL | #![crate_type = "rlib"] + | ^ + +error: aborting due to 1 previous error + diff --git a/tests/ui/test-attrs/test-panic-abort-disabled.rs b/tests/ui/test-attrs/test-panic-abort-disabled.rs index 05dd9395c2b..e83be65f925 100644 --- a/tests/ui/test-attrs/test-panic-abort-disabled.rs +++ b/tests/ui/test-attrs/test-panic-abort-disabled.rs @@ -4,8 +4,6 @@ //@ run-flags: --test-threads=1 //@ needs-unwind -//@ ignore-wasm no panic support -//@ ignore-emscripten no panic support //@ needs-subprocess #![cfg(test)] diff --git a/tests/ui/test-attrs/test-panic-abort-nocapture.rs b/tests/ui/test-attrs/test-panic-abort-nocapture.rs index f7e15dbdbc3..6a1025ea087 100644 --- a/tests/ui/test-attrs/test-panic-abort-nocapture.rs +++ b/tests/ui/test-attrs/test-panic-abort-nocapture.rs @@ -7,8 +7,6 @@ //@ normalize-stdout: "finished in \d+\.\d+s" -> "finished in $$TIME" //@ ignore-android #120567 -//@ ignore-wasm no panic support -//@ ignore-emscripten no panic support //@ needs-subprocess #![cfg(test)] diff --git a/tests/ui/test-attrs/test-panic-abort-nocapture.run.stderr b/tests/ui/test-attrs/test-panic-abort-nocapture.run.stderr index 25681171170..b9f267838b1 100644 --- a/tests/ui/test-attrs/test-panic-abort-nocapture.run.stderr +++ b/tests/ui/test-attrs/test-panic-abort-nocapture.run.stderr @@ -1,11 +1,11 @@ -thread 'main' panicked at $DIR/test-panic-abort-nocapture.rs:34:5: +thread 'main' panicked at $DIR/test-panic-abort-nocapture.rs:32:5: assertion `left == right` failed left: 2 right: 4 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace -thread 'main' panicked at $DIR/test-panic-abort-nocapture.rs:28:5: +thread 'main' panicked at $DIR/test-panic-abort-nocapture.rs:26:5: assertion `left == right` failed left: 2 right: 4 diff --git a/tests/ui/test-attrs/test-panic-abort.rs b/tests/ui/test-attrs/test-panic-abort.rs index 951cf54346b..6c9b641fb6f 100644 --- a/tests/ui/test-attrs/test-panic-abort.rs +++ b/tests/ui/test-attrs/test-panic-abort.rs @@ -7,8 +7,6 @@ //@ normalize-stdout: "finished in \d+\.\d+s" -> "finished in $$TIME" //@ ignore-android #120567 -//@ ignore-wasm no panic support -//@ ignore-emscripten no panic support //@ needs-subprocess #![cfg(test)] diff --git a/tests/ui/test-attrs/test-panic-abort.run.stdout b/tests/ui/test-attrs/test-panic-abort.run.stdout index 844808e8637..0faa7f0dfce 100644 --- a/tests/ui/test-attrs/test-panic-abort.run.stdout +++ b/tests/ui/test-attrs/test-panic-abort.run.stdout @@ -18,7 +18,7 @@ testing123 ---- it_fails stderr ---- testing321 -thread 'main' panicked at $DIR/test-panic-abort.rs:39:5: +thread 'main' panicked at $DIR/test-panic-abort.rs:37:5: assertion `left == right` failed left: 2 right: 5 diff --git a/tests/ui/threads-sendsync/spawning-with-debug.rs b/tests/ui/threads-sendsync/spawning-with-debug.rs index 90a81c1e53b..3b7107e2dbf 100644 --- a/tests/ui/threads-sendsync/spawning-with-debug.rs +++ b/tests/ui/threads-sendsync/spawning-with-debug.rs @@ -1,7 +1,6 @@ //@ run-pass #![allow(unused_must_use)] #![allow(unused_mut)] -//@ ignore-windows //@ exec-env:RUST_LOG=debug //@ needs-threads diff --git a/tests/ui/threads-sendsync/thread-local-extern-static.rs b/tests/ui/threads-sendsync/thread-local-extern-static.rs index ca66f8ad1d3..ce2a221ec2e 100644 --- a/tests/ui/threads-sendsync/thread-local-extern-static.rs +++ b/tests/ui/threads-sendsync/thread-local-extern-static.rs @@ -1,5 +1,5 @@ //@ run-pass -//@ ignore-windows +//@ ignore-windows FIXME(134939): thread_local + no_mangle doesn't work on Windows //@ aux-build:thread-local-extern-static.rs #![feature(cfg_target_thread_local, thread_local)] diff --git a/tests/ui/trait-bounds/ice-unsized-tuple-const-issue-121443.rs b/tests/ui/trait-bounds/ice-unsized-tuple-const-issue-121443.rs index c3a2ab82adc..5277de29464 100644 --- a/tests/ui/trait-bounds/ice-unsized-tuple-const-issue-121443.rs +++ b/tests/ui/trait-bounds/ice-unsized-tuple-const-issue-121443.rs @@ -8,7 +8,6 @@ type Fn = dyn FnOnce() -> u8; const TEST: Fn = some_fn; //~^ ERROR cannot find value `some_fn` in this scope //~| ERROR the size for values of type `(dyn FnOnce() -> u8 + 'static)` cannot be known at compilation time -//~| ERROR the size for values of type `(dyn FnOnce() -> u8 + 'static)` cannot be known at compilation time const TEST2: (Fn, u8) = (TEST, 0); //~^ ERROR the size for values of type `(dyn FnOnce() -> u8 + 'static)` cannot be known at compilation time //~| ERROR the size for values of type `(dyn FnOnce() -> u8 + 'static)` cannot be known at compilation time diff --git a/tests/ui/trait-bounds/ice-unsized-tuple-const-issue-121443.stderr b/tests/ui/trait-bounds/ice-unsized-tuple-const-issue-121443.stderr index 0e92979ccd5..76e015a7238 100644 --- a/tests/ui/trait-bounds/ice-unsized-tuple-const-issue-121443.stderr +++ b/tests/ui/trait-bounds/ice-unsized-tuple-const-issue-121443.stderr @@ -13,16 +13,7 @@ LL | const TEST: Fn = some_fn; = help: the trait `Sized` is not implemented for `(dyn FnOnce() -> u8 + 'static)` error[E0277]: the size for values of type `(dyn FnOnce() -> u8 + 'static)` cannot be known at compilation time - --> $DIR/ice-unsized-tuple-const-issue-121443.rs:8:18 - | -LL | const TEST: Fn = some_fn; - | ^^^^^^^ doesn't have a size known at compile-time - | - = help: the trait `Sized` is not implemented for `(dyn FnOnce() -> u8 + 'static)` - = note: constant expressions must have a statically known size - -error[E0277]: the size for values of type `(dyn FnOnce() -> u8 + 'static)` cannot be known at compilation time - --> $DIR/ice-unsized-tuple-const-issue-121443.rs:12:14 + --> $DIR/ice-unsized-tuple-const-issue-121443.rs:11:14 | LL | const TEST2: (Fn, u8) = (TEST, 0); | ^^^^^^^^ doesn't have a size known at compile-time @@ -31,7 +22,7 @@ LL | const TEST2: (Fn, u8) = (TEST, 0); = note: only the last element of a tuple may have a dynamically sized type error[E0277]: the size for values of type `(dyn FnOnce() -> u8 + 'static)` cannot be known at compilation time - --> $DIR/ice-unsized-tuple-const-issue-121443.rs:12:25 + --> $DIR/ice-unsized-tuple-const-issue-121443.rs:11:25 | LL | const TEST2: (Fn, u8) = (TEST, 0); | ^^^^^^^^^ doesn't have a size known at compile-time @@ -39,7 +30,7 @@ LL | const TEST2: (Fn, u8) = (TEST, 0); = help: the trait `Sized` is not implemented for `(dyn FnOnce() -> u8 + 'static)` = note: only the last element of a tuple may have a dynamically sized type -error: aborting due to 5 previous errors +error: aborting due to 4 previous errors Some errors have detailed explanations: E0277, E0425. For more information about an error, try `rustc --explain E0277`. diff --git a/tests/ui/traits/const-traits/span-bug-issue-121418.stderr b/tests/ui/traits/const-traits/span-bug-issue-121418.stderr index f41c19b4573..92cfecd0540 100644 --- a/tests/ui/traits/const-traits/span-bug-issue-121418.stderr +++ b/tests/ui/traits/const-traits/span-bug-issue-121418.stderr @@ -8,17 +8,6 @@ LL | impl const dyn T { | = note: only trait implementations may be annotated with `const` -error[E0308]: mismatched types - --> $DIR/span-bug-issue-121418.rs:8:27 - | -LL | pub const fn new() -> std::sync::Mutex<dyn T> {} - | --- ^^^^^^^^^^^^^^^^^^^^^^^ expected `Mutex<dyn T>`, found `()` - | | - | implicitly returns `()` as its body has no tail or `return` expression - | - = note: expected struct `Mutex<(dyn T + 'static)>` - found unit type `()` - error[E0277]: the size for values of type `(dyn T + 'static)` cannot be known at compilation time --> $DIR/span-bug-issue-121418.rs:8:27 | @@ -30,6 +19,17 @@ note: required because it appears within the type `Mutex<(dyn T + 'static)>` --> $SRC_DIR/std/src/sync/poison/mutex.rs:LL:COL = note: the return type of a function must have a statically known size +error[E0308]: mismatched types + --> $DIR/span-bug-issue-121418.rs:8:27 + | +LL | pub const fn new() -> std::sync::Mutex<dyn T> {} + | --- ^^^^^^^^^^^^^^^^^^^^^^^ expected `Mutex<dyn T>`, found `()` + | | + | implicitly returns `()` as its body has no tail or `return` expression + | + = note: expected struct `Mutex<(dyn T + 'static)>` + found unit type `()` + error: aborting due to 3 previous errors Some errors have detailed explanations: E0277, E0308. diff --git a/tests/ui/traits/issue-77982.rs b/tests/ui/traits/issue-77982.rs index dce25e62e46..b2a488e18e8 100644 --- a/tests/ui/traits/issue-77982.rs +++ b/tests/ui/traits/issue-77982.rs @@ -1,5 +1,6 @@ -//@ ignore-windows different list of satisfying impls -//@ ignore-arm different list of satisfying impls +//@ ignore-windows FIXME: We get an extra E0283 on Windows +//@ ignore-arm extra satisfying impls + use std::collections::HashMap; fn what() { diff --git a/tests/ui/traits/issue-77982.stderr b/tests/ui/traits/issue-77982.stderr index 2b26a1b7ab1..4907a6dd17a 100644 --- a/tests/ui/traits/issue-77982.stderr +++ b/tests/ui/traits/issue-77982.stderr @@ -1,5 +1,5 @@ error[E0283]: type annotations needed - --> $DIR/issue-77982.rs:10:10 + --> $DIR/issue-77982.rs:11:10 | LL | opts.get(opt.as_ref()); | ^^^ ------------ type must be known at this point @@ -18,7 +18,7 @@ LL | opts.get::<Q>(opt.as_ref()); | +++++ error[E0283]: type annotations needed - --> $DIR/issue-77982.rs:10:10 + --> $DIR/issue-77982.rs:11:10 | LL | opts.get(opt.as_ref()); | ^^^ ------ type must be known at this point @@ -36,7 +36,7 @@ LL | opts.get::<Q>(opt.as_ref()); | +++++ error[E0283]: type annotations needed - --> $DIR/issue-77982.rs:15:59 + --> $DIR/issue-77982.rs:16:59 | LL | let ips: Vec<_> = (0..100_000).map(|_| u32::from(0u32.into())).collect(); | --- ^^^^ @@ -56,13 +56,13 @@ LL | let ips: Vec<_> = (0..100_000).map(|_| u32::from(<u32 as Into<T>>::into | +++++++++++++++++++++++ ~ error[E0283]: type annotations needed for `Box<_>` - --> $DIR/issue-77982.rs:38:9 + --> $DIR/issue-77982.rs:39:9 | LL | let _ = ().foo(); | ^ --- type must be known at this point | note: multiple `impl`s satisfying `(): Foo<'_, _>` found - --> $DIR/issue-77982.rs:31:1 + --> $DIR/issue-77982.rs:32:1 | LL | impl Foo<'static, u32> for () {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -74,13 +74,13 @@ LL | let _: Box<T> = ().foo(); | ++++++++ error[E0283]: type annotations needed for `Box<_>` - --> $DIR/issue-77982.rs:42:9 + --> $DIR/issue-77982.rs:43:9 | LL | let _ = (&()).bar(); | ^ --- type must be known at this point | note: multiple `impl`s satisfying `&(): Bar<'_, _>` found - --> $DIR/issue-77982.rs:34:1 + --> $DIR/issue-77982.rs:35:1 | LL | impl<'a> Bar<'static, u32> for &'a () {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/traits/negative-bounds/opaque-type-unsatisfied-bound.rs b/tests/ui/traits/negative-bounds/opaque-type-unsatisfied-bound.rs index cbd591eec96..ea6df938704 100644 --- a/tests/ui/traits/negative-bounds/opaque-type-unsatisfied-bound.rs +++ b/tests/ui/traits/negative-bounds/opaque-type-unsatisfied-bound.rs @@ -13,8 +13,9 @@ fn main() { } fn weird0() -> impl Sized + !Sized {} -//~^ ERROR the trait bound `(): !Sized` is not satisfied +//~^ ERROR type mismatch resolving fn weird1() -> impl !Sized + Sized {} -//~^ ERROR the trait bound `(): !Sized` is not satisfied +//~^ ERROR type mismatch resolving fn weird2() -> impl !Sized {} -//~^ ERROR the trait bound `(): !Sized` is not satisfied +//~^ ERROR type mismatch resolving +//~| ERROR the size for values of type diff --git a/tests/ui/traits/negative-bounds/opaque-type-unsatisfied-bound.stderr b/tests/ui/traits/negative-bounds/opaque-type-unsatisfied-bound.stderr index 3dad6d534fd..41d9e74f807 100644 --- a/tests/ui/traits/negative-bounds/opaque-type-unsatisfied-bound.stderr +++ b/tests/ui/traits/negative-bounds/opaque-type-unsatisfied-bound.stderr @@ -1,20 +1,29 @@ -error[E0277]: the trait bound `(): !Sized` is not satisfied +error[E0277]: the size for values of type `impl !Sized` cannot be known at compilation time + --> $DIR/opaque-type-unsatisfied-bound.rs:19:16 + | +LL | fn weird2() -> impl !Sized {} + | ^^^^^^^^^^^ doesn't have a size known at compile-time + | + = help: the trait `Sized` is not implemented for `impl !Sized` + = note: the return type of a function must have a statically known size + +error[E0271]: type mismatch resolving `impl !Sized + Sized == ()` --> $DIR/opaque-type-unsatisfied-bound.rs:15:16 | LL | fn weird0() -> impl Sized + !Sized {} - | ^^^^^^^^^^^^^^^^^^^ the trait bound `(): !Sized` is not satisfied + | ^^^^^^^^^^^^^^^^^^^ types differ -error[E0277]: the trait bound `(): !Sized` is not satisfied +error[E0271]: type mismatch resolving `impl !Sized + Sized == ()` --> $DIR/opaque-type-unsatisfied-bound.rs:17:16 | LL | fn weird1() -> impl !Sized + Sized {} - | ^^^^^^^^^^^^^^^^^^^ the trait bound `(): !Sized` is not satisfied + | ^^^^^^^^^^^^^^^^^^^ types differ -error[E0277]: the trait bound `(): !Sized` is not satisfied +error[E0271]: type mismatch resolving `impl !Sized == ()` --> $DIR/opaque-type-unsatisfied-bound.rs:19:16 | LL | fn weird2() -> impl !Sized {} - | ^^^^^^^^^^^ the trait bound `(): !Sized` is not satisfied + | ^^^^^^^^^^^ types differ error[E0277]: the trait bound `impl !Trait: Trait` is not satisfied --> $DIR/opaque-type-unsatisfied-bound.rs:12:13 @@ -30,6 +39,7 @@ note: required by a bound in `consume` LL | fn consume(_: impl Trait) {} | ^^^^^ required by this bound in `consume` -error: aborting due to 4 previous errors +error: aborting due to 5 previous errors -For more information about this error, try `rustc --explain E0277`. +Some errors have detailed explanations: E0271, E0277. +For more information about an error, try `rustc --explain E0271`. diff --git a/tests/ui/traits/negative-bounds/opaque-type-unsatisfied-fn-bound.rs b/tests/ui/traits/negative-bounds/opaque-type-unsatisfied-fn-bound.rs index 39422914afc..ce42bce0ad4 100644 --- a/tests/ui/traits/negative-bounds/opaque-type-unsatisfied-fn-bound.rs +++ b/tests/ui/traits/negative-bounds/opaque-type-unsatisfied-fn-bound.rs @@ -3,6 +3,6 @@ #![feature(negative_bounds, unboxed_closures)] fn produce() -> impl !Fn<(u32,)> {} -//~^ ERROR the trait bound `(): !Fn(u32)` is not satisfied +//~^ ERROR type mismatch resolving fn main() {} diff --git a/tests/ui/traits/negative-bounds/opaque-type-unsatisfied-fn-bound.stderr b/tests/ui/traits/negative-bounds/opaque-type-unsatisfied-fn-bound.stderr index 760e5aa62f2..e1b84e0df7a 100644 --- a/tests/ui/traits/negative-bounds/opaque-type-unsatisfied-fn-bound.stderr +++ b/tests/ui/traits/negative-bounds/opaque-type-unsatisfied-fn-bound.stderr @@ -1,9 +1,9 @@ -error[E0277]: the trait bound `(): !Fn(u32)` is not satisfied +error[E0271]: type mismatch resolving `impl !Fn<(u32,)> == ()` --> $DIR/opaque-type-unsatisfied-fn-bound.rs:5:17 | LL | fn produce() -> impl !Fn<(u32,)> {} - | ^^^^^^^^^^^^^^^^ the trait bound `(): !Fn(u32)` is not satisfied + | ^^^^^^^^^^^^^^^^ types differ error: aborting due to 1 previous error -For more information about this error, try `rustc --explain E0277`. +For more information about this error, try `rustc --explain E0271`. diff --git a/tests/ui/typeck/issue-105946.rs b/tests/ui/typeck/issue-105946.rs index f53f31138f8..0ee70f9346c 100644 --- a/tests/ui/typeck/issue-105946.rs +++ b/tests/ui/typeck/issue-105946.rs @@ -1,4 +1,5 @@ fn digit() -> str { + //~^ ERROR the size for values of type return {}; //~^ ERROR: mismatched types [E0308] } diff --git a/tests/ui/typeck/issue-105946.stderr b/tests/ui/typeck/issue-105946.stderr index 33d4e0b141a..30fe2000a46 100644 --- a/tests/ui/typeck/issue-105946.stderr +++ b/tests/ui/typeck/issue-105946.stderr @@ -1,5 +1,5 @@ error[E0425]: cannot find value `_y` in this scope - --> $DIR/issue-105946.rs:6:10 + --> $DIR/issue-105946.rs:7:10 | LL | let [_y..] = [Box::new(1), Box::new(2)]; | ^^ not found in this scope @@ -10,7 +10,7 @@ LL | let [_y @ ..] = [Box::new(1), Box::new(2)]; | + error[E0658]: `X..` patterns in slices are experimental - --> $DIR/issue-105946.rs:6:10 + --> $DIR/issue-105946.rs:7:10 | LL | let [_y..] = [Box::new(1), Box::new(2)]; | ^^^^ @@ -19,19 +19,28 @@ LL | let [_y..] = [Box::new(1), Box::new(2)]; = help: add `#![feature(half_open_range_patterns_in_slices)]` to the crate attributes to enable = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date +error[E0277]: the size for values of type `str` cannot be known at compilation time + --> $DIR/issue-105946.rs:1:15 + | +LL | fn digit() -> str { + | ^^^ doesn't have a size known at compile-time + | + = help: the trait `Sized` is not implemented for `str` + = note: the return type of a function must have a statically known size + error[E0308]: mismatched types - --> $DIR/issue-105946.rs:2:12 + --> $DIR/issue-105946.rs:3:12 | LL | return {}; | ^^ expected `str`, found `()` error[E0527]: pattern requires 1 element but array has 2 - --> $DIR/issue-105946.rs:6:9 + --> $DIR/issue-105946.rs:7:9 | LL | let [_y..] = [Box::new(1), Box::new(2)]; | ^^^^^^ expected 2 elements -error: aborting due to 4 previous errors +error: aborting due to 5 previous errors -Some errors have detailed explanations: E0308, E0425, E0527, E0658. -For more information about an error, try `rustc --explain E0308`. +Some errors have detailed explanations: E0277, E0308, E0425, E0527, E0658. +For more information about an error, try `rustc --explain E0277`. diff --git a/tests/ui/typeck/issue-43189.rs b/tests/ui/typeck/issue-43189.rs index 9c8cc70e63a..ee0fe15eeba 100644 --- a/tests/ui/typeck/issue-43189.rs +++ b/tests/ui/typeck/issue-43189.rs @@ -1,7 +1,6 @@ // Issue 46112: An extern crate pub re-exporting libcore was causing // paths rooted from `std` to be misrendered in the diagnostic output. -//@ ignore-windows //@ aux-build:xcrate-issue-43189-a.rs //@ aux-build:xcrate-issue-43189-b.rs diff --git a/tests/ui/typeck/issue-43189.stderr b/tests/ui/typeck/issue-43189.stderr index 8432cbeca2a..3cc1ba9ddfe 100644 --- a/tests/ui/typeck/issue-43189.stderr +++ b/tests/ui/typeck/issue-43189.stderr @@ -1,5 +1,5 @@ error[E0599]: no method named `a` found for unit type `()` in the current scope - --> $DIR/issue-43189.rs:10:8 + --> $DIR/issue-43189.rs:9:8 | LL | ().a(); | ^ method not found in `()` diff --git a/tests/ui/typeck/issue-46112.rs b/tests/ui/typeck/issue-46112.rs index 4671ddd06c8..cc8029771d6 100644 --- a/tests/ui/typeck/issue-46112.rs +++ b/tests/ui/typeck/issue-46112.rs @@ -1,7 +1,6 @@ // Issue 46112: An extern crate pub re-exporting libcore was causing // paths rooted from `std` to be misrendered in the diagnostic output. -//@ ignore-windows //@ aux-build:xcrate-issue-46112-rexport-core.rs extern crate xcrate_issue_46112_rexport_core; diff --git a/tests/ui/typeck/issue-46112.stderr b/tests/ui/typeck/issue-46112.stderr index 16beaea75db..9d439d10f1e 100644 --- a/tests/ui/typeck/issue-46112.stderr +++ b/tests/ui/typeck/issue-46112.stderr @@ -1,5 +1,5 @@ error[E0308]: mismatched types - --> $DIR/issue-46112.rs:9:21 + --> $DIR/issue-46112.rs:8:21 | LL | fn main() { test(Ok(())); } | -- ^^ expected `Option<()>`, found `()` @@ -9,7 +9,7 @@ LL | fn main() { test(Ok(())); } = note: expected enum `Option<()>` found unit type `()` help: the type constructed contains `()` due to the type of the argument passed - --> $DIR/issue-46112.rs:9:18 + --> $DIR/issue-46112.rs:8:18 | LL | fn main() { test(Ok(())); } | ^^^--^ diff --git a/tests/ui/unsized/box-instead-of-dyn-fn.rs b/tests/ui/unsized/box-instead-of-dyn-fn.rs index 321c2ebf5a1..720176081d6 100644 --- a/tests/ui/unsized/box-instead-of-dyn-fn.rs +++ b/tests/ui/unsized/box-instead-of-dyn-fn.rs @@ -3,7 +3,7 @@ use std::fmt::Debug; // Test to suggest boxing the return type, and the closure branch of the `if` fn print_on_or_the_other<'a>(a: i32, b: &'a String) -> dyn Fn() + 'a { - //~^ ERROR return type cannot have an unboxed trait object + //~^ ERROR return type cannot be a trait object without pointer indirection if a % 2 == 0 { move || println!("{a}") } else { diff --git a/tests/ui/unsized/box-instead-of-dyn-fn.stderr b/tests/ui/unsized/box-instead-of-dyn-fn.stderr index 1f1845569ef..1836d5dfffe 100644 --- a/tests/ui/unsized/box-instead-of-dyn-fn.stderr +++ b/tests/ui/unsized/box-instead-of-dyn-fn.stderr @@ -1,4 +1,4 @@ -error[E0746]: return type cannot have an unboxed trait object +error[E0746]: return type cannot be a trait object without pointer indirection --> $DIR/box-instead-of-dyn-fn.rs:5:56 | LL | fn print_on_or_the_other<'a>(a: i32, b: &'a String) -> dyn Fn() + 'a { diff --git a/tests/ui/unsized/issue-91801.rs b/tests/ui/unsized/issue-91801.rs index 096b1a93574..d906a08a55a 100644 --- a/tests/ui/unsized/issue-91801.rs +++ b/tests/ui/unsized/issue-91801.rs @@ -6,7 +6,7 @@ pub static ALL_VALIDATORS: &[(&'static str, &'static Validator)] = &[("validate that credits and debits balance", &validate_something)]; fn or<'a>(first: &'static Validator<'a>, second: &'static Validator<'a>) -> Validator<'a> { - //~^ ERROR return type cannot have an unboxed trait object + //~^ ERROR return type cannot be a trait object without pointer indirection return Box::new(move |something: &'_ Something| -> Result<(), ()> { first(something).or_else(|_| second(something)) }); diff --git a/tests/ui/unsized/issue-91801.stderr b/tests/ui/unsized/issue-91801.stderr index e13cabbb81d..28e10f9caa4 100644 --- a/tests/ui/unsized/issue-91801.stderr +++ b/tests/ui/unsized/issue-91801.stderr @@ -1,4 +1,4 @@ -error[E0746]: return type cannot have an unboxed trait object +error[E0746]: return type cannot be a trait object without pointer indirection --> $DIR/issue-91801.rs:8:77 | LL | fn or<'a>(first: &'static Validator<'a>, second: &'static Validator<'a>) -> Validator<'a> { diff --git a/tests/ui/unsized/issue-91803.rs b/tests/ui/unsized/issue-91803.rs index c74897cc4bc..8d35c7582b8 100644 --- a/tests/ui/unsized/issue-91803.rs +++ b/tests/ui/unsized/issue-91803.rs @@ -1,7 +1,7 @@ trait Foo<'a> {} fn or<'a>(first: &'static dyn Foo<'a>) -> dyn Foo<'a> { - //~^ ERROR return type cannot have an unboxed trait object + //~^ ERROR return type cannot be a trait object without pointer indirection return Box::new(panic!()); } diff --git a/tests/ui/unsized/issue-91803.stderr b/tests/ui/unsized/issue-91803.stderr index 3b89066499d..e0fde4b1c1b 100644 --- a/tests/ui/unsized/issue-91803.stderr +++ b/tests/ui/unsized/issue-91803.stderr @@ -1,4 +1,4 @@ -error[E0746]: return type cannot have an unboxed trait object +error[E0746]: return type cannot be a trait object without pointer indirection --> $DIR/issue-91803.rs:3:43 | LL | fn or<'a>(first: &'static dyn Foo<'a>) -> dyn Foo<'a> { diff --git a/tests/ui/where-clauses/ignore-err-clauses.rs b/tests/ui/where-clauses/ignore-err-clauses.rs index c76f0e1a8b2..428ebf4b408 100644 --- a/tests/ui/where-clauses/ignore-err-clauses.rs +++ b/tests/ui/where-clauses/ignore-err-clauses.rs @@ -1,6 +1,7 @@ use std::ops::Add; fn dbl<T>(x: T) -> <T as Add>::Output +//~^ ERROR type annotations needed where T: Copy + Add, UUU: Copy, diff --git a/tests/ui/where-clauses/ignore-err-clauses.stderr b/tests/ui/where-clauses/ignore-err-clauses.stderr index 4cf553da4c5..fbf1b99334f 100644 --- a/tests/ui/where-clauses/ignore-err-clauses.stderr +++ b/tests/ui/where-clauses/ignore-err-clauses.stderr @@ -1,9 +1,16 @@ error[E0412]: cannot find type `UUU` in this scope - --> $DIR/ignore-err-clauses.rs:6:5 + --> $DIR/ignore-err-clauses.rs:7:5 | LL | UUU: Copy, | ^^^ not found in this scope -error: aborting due to 1 previous error +error[E0282]: type annotations needed + --> $DIR/ignore-err-clauses.rs:3:14 + | +LL | fn dbl<T>(x: T) -> <T as Add>::Output + | ^ cannot infer type for type parameter `T` + +error: aborting due to 2 previous errors -For more information about this error, try `rustc --explain E0412`. +Some errors have detailed explanations: E0282, E0412. +For more information about an error, try `rustc --explain E0282`. |
