diff --git a/Cargo.lock b/Cargo.lock index 6d823c5b5a596..271a2f7962cac 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3214,7 +3214,7 @@ dependencies = [ [[package]] name = "run_make_support" -version = "0.2.0" +version = "0.0.0" dependencies = [ "bstr", "build_helper", diff --git a/compiler/rustc_attr_parsing/messages.ftl b/compiler/rustc_attr_parsing/messages.ftl index 8a709ea5d20cc..bec3a1e8a599b 100644 --- a/compiler/rustc_attr_parsing/messages.ftl +++ b/compiler/rustc_attr_parsing/messages.ftl @@ -146,12 +146,12 @@ attr_parsing_unused_duplicate = unused attribute .suggestion = remove this attribute .note = attribute also specified here - .warn = {-passes_previously_accepted} + .warn = {-attr_parsing_previously_accepted} attr_parsing_unused_multiple = multiple `{$name}` attributes .suggestion = remove this attribute .note = attribute also specified here --attr_parsing_perviously_accepted = +-attr_parsing_previously_accepted = this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! diff --git a/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs b/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs index cb3956d46a01c..fdec09edaa150 100644 --- a/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs +++ b/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs @@ -15,7 +15,7 @@ pub(crate) struct OptimizeParser; impl SingleAttributeParser for OptimizeParser { const PATH: &[Symbol] = &[sym::optimize]; - const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepLast; + const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepOutermost; const ON_DUPLICATE: OnDuplicate = OnDuplicate::WarnButFutureError; const TEMPLATE: AttributeTemplate = template!(List: "size|speed|none"); @@ -56,7 +56,7 @@ pub(crate) struct ExportNameParser; impl SingleAttributeParser for ExportNameParser { const PATH: &[rustc_span::Symbol] = &[sym::export_name]; - const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepFirst; + const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepInnermost; const ON_DUPLICATE: OnDuplicate = OnDuplicate::WarnButFutureError; const TEMPLATE: AttributeTemplate = template!(NameValueStr: "name"); diff --git a/compiler/rustc_attr_parsing/src/attributes/deprecation.rs b/compiler/rustc_attr_parsing/src/attributes/deprecation.rs index 702ad66f57805..08cf1ab5d190f 100644 --- a/compiler/rustc_attr_parsing/src/attributes/deprecation.rs +++ b/compiler/rustc_attr_parsing/src/attributes/deprecation.rs @@ -36,7 +36,7 @@ fn get( impl SingleAttributeParser for DeprecationParser { const PATH: &[Symbol] = &[sym::deprecated]; - const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepFirst; + const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepInnermost; const ON_DUPLICATE: OnDuplicate = OnDuplicate::Error; const TEMPLATE: AttributeTemplate = template!( Word, diff --git a/compiler/rustc_attr_parsing/src/attributes/dummy.rs b/compiler/rustc_attr_parsing/src/attributes/dummy.rs index 8a9b94fb1ffae..e5e1c3bb6b6a9 100644 --- a/compiler/rustc_attr_parsing/src/attributes/dummy.rs +++ b/compiler/rustc_attr_parsing/src/attributes/dummy.rs @@ -9,7 +9,7 @@ use crate::parser::ArgParser; pub(crate) struct DummyParser; impl SingleAttributeParser for DummyParser { const PATH: &[Symbol] = &[sym::rustc_dummy]; - const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepFirst; + const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepInnermost; const ON_DUPLICATE: OnDuplicate = OnDuplicate::Ignore; const TEMPLATE: AttributeTemplate = template!(Word); // Anything, really diff --git a/compiler/rustc_attr_parsing/src/attributes/inline.rs b/compiler/rustc_attr_parsing/src/attributes/inline.rs index 11844f4cd950f..fe812175218d1 100644 --- a/compiler/rustc_attr_parsing/src/attributes/inline.rs +++ b/compiler/rustc_attr_parsing/src/attributes/inline.rs @@ -16,7 +16,7 @@ pub(crate) struct InlineParser; impl SingleAttributeParser for InlineParser { const PATH: &'static [Symbol] = &[sym::inline]; - const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepLast; + const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepOutermost; const ON_DUPLICATE: OnDuplicate = OnDuplicate::WarnButFutureError; const TEMPLATE: AttributeTemplate = template!(Word, List: "always|never"); @@ -57,7 +57,7 @@ pub(crate) struct RustcForceInlineParser; impl SingleAttributeParser for RustcForceInlineParser { const PATH: &'static [Symbol] = &[sym::rustc_force_inline]; - const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepLast; + const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepOutermost; const ON_DUPLICATE: OnDuplicate = OnDuplicate::WarnButFutureError; const TEMPLATE: AttributeTemplate = template!(Word, List: "reason", NameValueStr: "reason"); diff --git a/compiler/rustc_attr_parsing/src/attributes/link_attrs.rs b/compiler/rustc_attr_parsing/src/attributes/link_attrs.rs index 1a66eec870f25..23a8e96482de8 100644 --- a/compiler/rustc_attr_parsing/src/attributes/link_attrs.rs +++ b/compiler/rustc_attr_parsing/src/attributes/link_attrs.rs @@ -14,7 +14,7 @@ pub(crate) struct LinkNameParser; impl SingleAttributeParser for LinkNameParser { const PATH: &[Symbol] = &[sym::link_name]; - const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepFirst; + const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepInnermost; const ON_DUPLICATE: OnDuplicate = OnDuplicate::WarnButFutureError; const TEMPLATE: AttributeTemplate = template!(NameValueStr: "name"); @@ -36,7 +36,7 @@ pub(crate) struct LinkSectionParser; impl SingleAttributeParser for LinkSectionParser { const PATH: &[Symbol] = &[sym::link_section]; - const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepFirst; + const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepInnermost; const ON_DUPLICATE: OnDuplicate = OnDuplicate::WarnButFutureError; const TEMPLATE: AttributeTemplate = template!(NameValueStr: "name"); diff --git a/compiler/rustc_attr_parsing/src/attributes/mod.rs b/compiler/rustc_attr_parsing/src/attributes/mod.rs index 0225b14133624..68c716d1a99d1 100644 --- a/compiler/rustc_attr_parsing/src/attributes/mod.rs +++ b/compiler/rustc_attr_parsing/src/attributes/mod.rs @@ -140,7 +140,7 @@ impl, S: Stage> AttributeParser for Single if let Some(pa) = T::convert(cx, args) { match T::ATTRIBUTE_ORDER { // keep the first and report immediately. ignore this attribute - AttributeOrder::KeepFirst => { + AttributeOrder::KeepInnermost => { if let Some((_, unused)) = group.1 { T::ON_DUPLICATE.exec::(cx, cx.attr_span, unused); return; @@ -148,7 +148,7 @@ impl, S: Stage> AttributeParser for Single } // keep the new one and warn about the previous, // then replace - AttributeOrder::KeepLast => { + AttributeOrder::KeepOutermost => { if let Some((_, used)) = group.1 { T::ON_DUPLICATE.exec::(cx, used, cx.attr_span); } @@ -165,9 +165,6 @@ impl, S: Stage> AttributeParser for Single } } -// FIXME(jdonszelmann): logic is implemented but the attribute parsers needing -// them will be merged in another PR -#[allow(unused)] pub(crate) enum OnDuplicate { /// Give a default warning Warn, @@ -213,39 +210,29 @@ impl OnDuplicate { } } } -// -// FIXME(jdonszelmann): logic is implemented but the attribute parsers needing -// them will be merged in another PR -#[allow(unused)] + pub(crate) enum AttributeOrder { - /// Duplicates after the first attribute will be an error. I.e. only keep the lowest attribute. + /// Duplicates after the innermost instance of the attribute will be an error/warning. + /// Only keep the lowest attribute. /// - /// Attributes are processed from bottom to top, so this raises an error on all the attributes + /// Attributes are processed from bottom to top, so this raises a warning/error on all the attributes /// further above the lowest one: /// ``` /// #[stable(since="1.0")] //~ WARNING duplicated attribute /// #[stable(since="2.0")] /// ``` - /// - /// This should be used where duplicates would be ignored, but carry extra - /// meaning that could cause confusion. For example, `#[stable(since="1.0")] - /// #[stable(since="2.0")]`, which version should be used for `stable`? - KeepFirst, + KeepInnermost, - /// Duplicates preceding the last instance of the attribute will be a - /// warning, with a note that this will be an error in the future. + /// Duplicates before the outermost instance of the attribute will be an error/warning. + /// Only keep the highest attribute. /// - /// Attributes are processed from bottom to top, so this raises a warning on all the attributes - /// below the higher one: + /// Attributes are processed from bottom to top, so this raises a warning/error on all the attributes + /// below the highest one: /// ``` /// #[path="foo.rs"] /// #[path="bar.rs"] //~ WARNING duplicated attribute /// ``` - /// - /// This is the same as `FutureWarnFollowing`, except the last attribute is - /// the one that is "used". Ideally these can eventually migrate to - /// `ErrorPreceding`. - KeepLast, + KeepOutermost, } /// An even simpler version of [`SingleAttributeParser`]: @@ -271,7 +258,7 @@ impl, S: Stage> Default for WithoutArgs { impl, S: Stage> SingleAttributeParser for WithoutArgs { const PATH: &[Symbol] = T::PATH; - const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepLast; + const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepOutermost; const ON_DUPLICATE: OnDuplicate = T::ON_DUPLICATE; const TEMPLATE: AttributeTemplate = template!(Word); diff --git a/compiler/rustc_attr_parsing/src/attributes/must_use.rs b/compiler/rustc_attr_parsing/src/attributes/must_use.rs index b5eb85f68b4f8..e0a3e6755099b 100644 --- a/compiler/rustc_attr_parsing/src/attributes/must_use.rs +++ b/compiler/rustc_attr_parsing/src/attributes/must_use.rs @@ -12,7 +12,7 @@ pub(crate) struct MustUseParser; impl SingleAttributeParser for MustUseParser { const PATH: &[Symbol] = &[sym::must_use]; - const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepLast; + const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepOutermost; const ON_DUPLICATE: OnDuplicate = OnDuplicate::WarnButFutureError; const TEMPLATE: AttributeTemplate = template!(Word, NameValueStr: "reason"); diff --git a/compiler/rustc_attr_parsing/src/attributes/path.rs b/compiler/rustc_attr_parsing/src/attributes/path.rs index 0dfbc9a9aa875..febb1b45a18f0 100644 --- a/compiler/rustc_attr_parsing/src/attributes/path.rs +++ b/compiler/rustc_attr_parsing/src/attributes/path.rs @@ -10,7 +10,7 @@ pub(crate) struct PathParser; impl SingleAttributeParser for PathParser { const PATH: &[Symbol] = &[sym::path]; - const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepLast; + const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepOutermost; const ON_DUPLICATE: OnDuplicate = OnDuplicate::WarnButFutureError; const TEMPLATE: AttributeTemplate = template!(NameValueStr: "file"); diff --git a/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs b/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs index e6b6a6fe3c9e5..ec821cb11ce9f 100644 --- a/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs +++ b/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs @@ -11,7 +11,7 @@ pub(crate) struct RustcLayoutScalarValidRangeStart; impl SingleAttributeParser for RustcLayoutScalarValidRangeStart { const PATH: &'static [Symbol] = &[sym::rustc_layout_scalar_valid_range_start]; - const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepFirst; + const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepInnermost; const ON_DUPLICATE: OnDuplicate = OnDuplicate::Error; const TEMPLATE: AttributeTemplate = template!(List: "start"); @@ -25,7 +25,7 @@ pub(crate) struct RustcLayoutScalarValidRangeEnd; impl SingleAttributeParser for RustcLayoutScalarValidRangeEnd { const PATH: &'static [Symbol] = &[sym::rustc_layout_scalar_valid_range_end]; - const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepFirst; + const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepInnermost; const ON_DUPLICATE: OnDuplicate = OnDuplicate::Error; const TEMPLATE: AttributeTemplate = template!(List: "end"); @@ -62,7 +62,7 @@ pub(crate) struct RustcObjectLifetimeDefaultParser; impl SingleAttributeParser for RustcObjectLifetimeDefaultParser { const PATH: &[rustc_span::Symbol] = &[sym::rustc_object_lifetime_default]; - const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepFirst; + const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepInnermost; const ON_DUPLICATE: OnDuplicate = OnDuplicate::Error; const TEMPLATE: AttributeTemplate = template!(Word); diff --git a/compiler/rustc_attr_parsing/src/attributes/test_attrs.rs b/compiler/rustc_attr_parsing/src/attributes/test_attrs.rs index cea3ee52ff43d..ee81f64860f80 100644 --- a/compiler/rustc_attr_parsing/src/attributes/test_attrs.rs +++ b/compiler/rustc_attr_parsing/src/attributes/test_attrs.rs @@ -11,7 +11,7 @@ pub(crate) struct IgnoreParser; impl SingleAttributeParser for IgnoreParser { const PATH: &[Symbol] = &[sym::ignore]; - const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepLast; + const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepOutermost; const ON_DUPLICATE: OnDuplicate = OnDuplicate::Warn; const TEMPLATE: AttributeTemplate = template!(Word, NameValueStr: "reason"); diff --git a/compiler/rustc_attr_parsing/src/attributes/traits.rs b/compiler/rustc_attr_parsing/src/attributes/traits.rs index 83a98c53c7f74..c29dbf4d1e9e2 100644 --- a/compiler/rustc_attr_parsing/src/attributes/traits.rs +++ b/compiler/rustc_attr_parsing/src/attributes/traits.rs @@ -12,7 +12,7 @@ pub(crate) struct SkipDuringMethodDispatchParser; impl SingleAttributeParser for SkipDuringMethodDispatchParser { const PATH: &[Symbol] = &[sym::rustc_skip_during_method_dispatch]; - const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepFirst; + const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepInnermost; const ON_DUPLICATE: OnDuplicate = OnDuplicate::Error; const TEMPLATE: AttributeTemplate = template!(List: "array, boxed_slice"); diff --git a/compiler/rustc_attr_parsing/src/attributes/transparency.rs b/compiler/rustc_attr_parsing/src/attributes/transparency.rs index ce5ceb9139a5c..c9fdc57cc06eb 100644 --- a/compiler/rustc_attr_parsing/src/attributes/transparency.rs +++ b/compiler/rustc_attr_parsing/src/attributes/transparency.rs @@ -14,7 +14,7 @@ pub(crate) struct TransparencyParser; #[allow(rustc::diagnostic_outside_of_impl)] impl SingleAttributeParser for TransparencyParser { const PATH: &[Symbol] = &[sym::rustc_macro_transparency]; - const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepFirst; + const ATTRIBUTE_ORDER: AttributeOrder = AttributeOrder::KeepInnermost; const ON_DUPLICATE: OnDuplicate = OnDuplicate::Custom(|cx, used, unused| { cx.dcx().span_err(vec![used, unused], "multiple macro transparency attributes"); }); diff --git a/compiler/rustc_borrowck/src/consumers.rs b/compiler/rustc_borrowck/src/consumers.rs index 1f087b092346e..1c4ff5a677902 100644 --- a/compiler/rustc_borrowck/src/consumers.rs +++ b/compiler/rustc_borrowck/src/consumers.rs @@ -1,7 +1,9 @@ //! This file provides API for compiler consumers. +use rustc_data_structures::fx::FxHashMap; use rustc_hir::def_id::LocalDefId; use rustc_index::IndexVec; +use rustc_middle::bug; use rustc_middle::mir::{Body, Promoted}; use rustc_middle::ty::TyCtxt; @@ -17,7 +19,39 @@ pub use super::polonius::legacy::{ pub use super::region_infer::RegionInferenceContext; use crate::{BorrowCheckRootCtxt, do_mir_borrowck}; -/// Options determining the output behavior of [`get_body_with_borrowck_facts`]. +/// Struct used during mir borrowck to collect bodies with facts for a typeck root and all +/// its nested bodies. +pub(crate) struct BorrowckConsumer<'tcx> { + options: ConsumerOptions, + bodies: FxHashMap>, +} + +impl<'tcx> BorrowckConsumer<'tcx> { + pub(crate) fn new(options: ConsumerOptions) -> Self { + Self { options, bodies: Default::default() } + } + + pub(crate) fn insert_body(&mut self, def_id: LocalDefId, body: BodyWithBorrowckFacts<'tcx>) { + if self.bodies.insert(def_id, body).is_some() { + bug!("unexpected previous body for {def_id:?}"); + } + } + + /// Should the Polonius input facts be computed? + pub(crate) fn polonius_input(&self) -> bool { + matches!( + self.options, + ConsumerOptions::PoloniusInputFacts | ConsumerOptions::PoloniusOutputFacts + ) + } + + /// Should we run Polonius and collect the output facts? + pub(crate) fn polonius_output(&self) -> bool { + matches!(self.options, ConsumerOptions::PoloniusOutputFacts) + } +} + +/// Options determining the output behavior of [`get_bodies_with_borrowck_facts`]. /// /// If executing under `-Z polonius` the choice here has no effect, and everything as if /// [`PoloniusOutputFacts`](ConsumerOptions::PoloniusOutputFacts) had been selected @@ -43,17 +77,6 @@ pub enum ConsumerOptions { PoloniusOutputFacts, } -impl ConsumerOptions { - /// Should the Polonius input facts be computed? - pub(crate) fn polonius_input(&self) -> bool { - matches!(self, Self::PoloniusInputFacts | Self::PoloniusOutputFacts) - } - /// Should we run Polonius and collect the output facts? - pub(crate) fn polonius_output(&self) -> bool { - matches!(self, Self::PoloniusOutputFacts) - } -} - /// A `Body` with information computed by the borrow checker. This struct is /// intended to be consumed by compiler consumers. /// @@ -82,25 +105,35 @@ pub struct BodyWithBorrowckFacts<'tcx> { pub output_facts: Option>, } -/// This function computes borrowck facts for the given body. The [`ConsumerOptions`] -/// determine which facts are returned. This function makes a copy of the body because -/// it needs to regenerate the region identifiers. It should never be invoked during a -/// typical compilation session due to the unnecessary overhead of returning -/// [`BodyWithBorrowckFacts`]. +/// This function computes borrowck facts for the given def id and all its nested bodies. +/// It must be called with a typeck root which will then borrowck all nested bodies as well. +/// The [`ConsumerOptions`] determine which facts are returned. This function makes a copy +/// of the bodies because it needs to regenerate the region identifiers. It should never be +/// invoked during a typical compilation session due to the unnecessary overhead of +/// returning [`BodyWithBorrowckFacts`]. /// /// Note: -/// * This function will panic if the required body was already stolen. This +/// * This function will panic if the required bodies were already stolen. This /// can, for example, happen when requesting a body of a `const` function /// because they are evaluated during typechecking. The panic can be avoided /// by overriding the `mir_borrowck` query. You can find a complete example -/// that shows how to do this at `tests/run-make/obtain-borrowck/`. +/// that shows how to do this at `tests/ui-fulldeps/obtain-borrowck.rs`. /// /// * Polonius is highly unstable, so expect regular changes in its signature or other details. -pub fn get_body_with_borrowck_facts( +pub fn get_bodies_with_borrowck_facts( tcx: TyCtxt<'_>, - def_id: LocalDefId, + root_def_id: LocalDefId, options: ConsumerOptions, -) -> BodyWithBorrowckFacts<'_> { - let mut root_cx = BorrowCheckRootCtxt::new(tcx, def_id); - *do_mir_borrowck(&mut root_cx, def_id, Some(options)).1.unwrap() +) -> FxHashMap> { + let mut root_cx = + BorrowCheckRootCtxt::new(tcx, root_def_id, Some(BorrowckConsumer::new(options))); + + // See comment in `rustc_borrowck::mir_borrowck` + let nested_bodies = tcx.nested_bodies_within(root_def_id); + for def_id in nested_bodies { + root_cx.get_or_insert_nested(def_id); + } + + do_mir_borrowck(&mut root_cx, root_def_id); + root_cx.consumer.unwrap().bodies } diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs index 82b300dcb17d9..321b18c9b78b2 100644 --- a/compiler/rustc_borrowck/src/lib.rs +++ b/compiler/rustc_borrowck/src/lib.rs @@ -51,7 +51,7 @@ use smallvec::SmallVec; use tracing::{debug, instrument}; use crate::borrow_set::{BorrowData, BorrowSet}; -use crate::consumers::{BodyWithBorrowckFacts, ConsumerOptions}; +use crate::consumers::BodyWithBorrowckFacts; use crate::dataflow::{BorrowIndex, Borrowck, BorrowckDomain, Borrows}; use crate::diagnostics::{ AccessKind, BorrowckDiagnosticsBuffer, IllegalMoveOriginKind, MoveError, RegionName, @@ -124,7 +124,7 @@ fn mir_borrowck( let opaque_types = ConcreteOpaqueTypes(Default::default()); Ok(tcx.arena.alloc(opaque_types)) } else { - let mut root_cx = BorrowCheckRootCtxt::new(tcx, def); + let mut root_cx = BorrowCheckRootCtxt::new(tcx, def, None); // We need to manually borrowck all nested bodies from the HIR as // we do not generate MIR for dead code. Not doing so causes us to // never check closures in dead code. @@ -134,7 +134,7 @@ fn mir_borrowck( } let PropagatedBorrowCheckResults { closure_requirements, used_mut_upvars } = - do_mir_borrowck(&mut root_cx, def, None).0; + do_mir_borrowck(&mut root_cx, def); debug_assert!(closure_requirements.is_none()); debug_assert!(used_mut_upvars.is_empty()); root_cx.finalize() @@ -289,17 +289,12 @@ impl<'tcx> ClosureOutlivesSubjectTy<'tcx> { /// Perform the actual borrow checking. /// -/// Use `consumer_options: None` for the default behavior of returning -/// [`PropagatedBorrowCheckResults`] only. Otherwise, return [`BodyWithBorrowckFacts`] -/// according to the given [`ConsumerOptions`]. -/// /// For nested bodies this should only be called through `root_cx.get_or_insert_nested`. #[instrument(skip(root_cx), level = "debug")] fn do_mir_borrowck<'tcx>( root_cx: &mut BorrowCheckRootCtxt<'tcx>, def: LocalDefId, - consumer_options: Option, -) -> (PropagatedBorrowCheckResults<'tcx>, Option>>) { +) -> PropagatedBorrowCheckResults<'tcx> { let tcx = root_cx.tcx; let infcx = BorrowckInferCtxt::new(tcx, def); let (input_body, promoted) = tcx.mir_promoted(def); @@ -343,7 +338,6 @@ fn do_mir_borrowck<'tcx>( &location_table, &move_data, &borrow_set, - consumer_options, ); // Dump MIR results into a file, if that is enabled. This lets us @@ -483,23 +477,24 @@ fn do_mir_borrowck<'tcx>( used_mut_upvars: mbcx.used_mut_upvars, }; - let body_with_facts = if consumer_options.is_some() { - Some(Box::new(BodyWithBorrowckFacts { - body: body_owned, - promoted, - borrow_set, - region_inference_context: regioncx, - location_table: polonius_input.as_ref().map(|_| location_table), - input_facts: polonius_input, - output_facts: polonius_output, - })) - } else { - None - }; + if let Some(consumer) = &mut root_cx.consumer { + consumer.insert_body( + def, + BodyWithBorrowckFacts { + body: body_owned, + promoted, + borrow_set, + region_inference_context: regioncx, + location_table: polonius_input.as_ref().map(|_| location_table), + input_facts: polonius_input, + output_facts: polonius_output, + }, + ); + } debug!("do_mir_borrowck: result = {:#?}", result); - (result, body_with_facts) + result } fn get_flow_results<'a, 'tcx>( diff --git a/compiler/rustc_borrowck/src/nll.rs b/compiler/rustc_borrowck/src/nll.rs index af4505072960c..41f67e78930f0 100644 --- a/compiler/rustc_borrowck/src/nll.rs +++ b/compiler/rustc_borrowck/src/nll.rs @@ -18,7 +18,6 @@ use rustc_span::sym; use tracing::{debug, instrument}; use crate::borrow_set::BorrowSet; -use crate::consumers::ConsumerOptions; use crate::diagnostics::RegionErrors; use crate::handle_placeholders::compute_sccs_applying_placeholder_outlives_constraints; use crate::polonius::PoloniusDiagnosticsContext; @@ -83,12 +82,11 @@ pub(crate) fn compute_regions<'tcx>( location_table: &PoloniusLocationTable, move_data: &MoveData<'tcx>, borrow_set: &BorrowSet<'tcx>, - consumer_options: Option, ) -> NllOutput<'tcx> { let is_polonius_legacy_enabled = infcx.tcx.sess.opts.unstable_opts.polonius.is_legacy_enabled(); - let polonius_input = consumer_options.map(|c| c.polonius_input()).unwrap_or_default() + let polonius_input = root_cx.consumer.as_ref().map_or(false, |c| c.polonius_input()) || is_polonius_legacy_enabled; - let polonius_output = consumer_options.map(|c| c.polonius_output()).unwrap_or_default() + let polonius_output = root_cx.consumer.as_ref().map_or(false, |c| c.polonius_output()) || is_polonius_legacy_enabled; let mut polonius_facts = (polonius_input || PoloniusFacts::enabled(infcx.tcx)).then_some(PoloniusFacts::default()); diff --git a/compiler/rustc_borrowck/src/root_cx.rs b/compiler/rustc_borrowck/src/root_cx.rs index 66b526fa02a50..9b1d12aede513 100644 --- a/compiler/rustc_borrowck/src/root_cx.rs +++ b/compiler/rustc_borrowck/src/root_cx.rs @@ -6,6 +6,7 @@ use rustc_middle::ty::{OpaqueHiddenType, Ty, TyCtxt, TypeVisitableExt}; use rustc_span::ErrorGuaranteed; use smallvec::SmallVec; +use crate::consumers::BorrowckConsumer; use crate::{ClosureRegionRequirements, ConcreteOpaqueTypes, PropagatedBorrowCheckResults}; /// The shared context used by both the root as well as all its nested @@ -16,16 +17,24 @@ pub(super) struct BorrowCheckRootCtxt<'tcx> { concrete_opaque_types: ConcreteOpaqueTypes<'tcx>, nested_bodies: FxHashMap>, tainted_by_errors: Option, + /// This should be `None` during normal compilation. See [`crate::consumers`] for more + /// information on how this is used. + pub(crate) consumer: Option>, } impl<'tcx> BorrowCheckRootCtxt<'tcx> { - pub(super) fn new(tcx: TyCtxt<'tcx>, root_def_id: LocalDefId) -> BorrowCheckRootCtxt<'tcx> { + pub(super) fn new( + tcx: TyCtxt<'tcx>, + root_def_id: LocalDefId, + consumer: Option>, + ) -> BorrowCheckRootCtxt<'tcx> { BorrowCheckRootCtxt { tcx, root_def_id, concrete_opaque_types: Default::default(), nested_bodies: Default::default(), tainted_by_errors: None, + consumer, } } @@ -71,7 +80,7 @@ impl<'tcx> BorrowCheckRootCtxt<'tcx> { self.root_def_id.to_def_id() ); if !self.nested_bodies.contains_key(&def_id) { - let result = super::do_mir_borrowck(self, def_id, None).0; + let result = super::do_mir_borrowck(self, def_id); if let Some(prev) = self.nested_bodies.insert(def_id, result) { bug!("unexpected previous nested body: {prev:?}"); } diff --git a/compiler/rustc_errors/src/emitter.rs b/compiler/rustc_errors/src/emitter.rs index 2f398cea926cd..510f37f37e2ac 100644 --- a/compiler/rustc_errors/src/emitter.rs +++ b/compiler/rustc_errors/src/emitter.rs @@ -3526,7 +3526,7 @@ pub fn is_case_difference(sm: &SourceMap, suggested: &str, sp: Span) -> bool { // All the chars that differ in capitalization are confusable (above): let confusable = iter::zip(found.chars(), suggested.chars()) .filter(|(f, s)| f != s) - .all(|(f, s)| (ascii_confusables.contains(&f) || ascii_confusables.contains(&s))); + .all(|(f, s)| ascii_confusables.contains(&f) || ascii_confusables.contains(&s)); confusable && found.to_lowercase() == suggested.to_lowercase() // FIXME: We sometimes suggest the same thing we already have, which is a // bug, but be defensive against that here. diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index e41bc8f852e58..fc9d795cb2315 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -59,8 +59,7 @@ declare_lint! { } declare_lint! { - /// The `overflowing_literals` lint detects literal out of range for its - /// type. + /// The `overflowing_literals` lint detects literals out of range for their type. /// /// ### Example /// @@ -72,9 +71,9 @@ declare_lint! { /// /// ### Explanation /// - /// It is usually a mistake to use a literal that overflows the type where - /// it is used. Either use a literal that is within range, or change the - /// type to be within the range of the literal. + /// It is usually a mistake to use a literal that overflows its type + /// Change either the literal or its type such that the literal is + /// within the range of its type. OVERFLOWING_LITERALS, Deny, "literal out of range for its type" diff --git a/compiler/rustc_lint/src/unused.rs b/compiler/rustc_lint/src/unused.rs index d3942a1c81632..a9eb1739f7f10 100644 --- a/compiler/rustc_lint/src/unused.rs +++ b/compiler/rustc_lint/src/unused.rs @@ -1,7 +1,7 @@ use std::iter; use rustc_ast::util::{classify, parser}; -use rustc_ast::{self as ast, ExprKind, HasAttrs as _, StmtKind}; +use rustc_ast::{self as ast, ExprKind, FnRetTy, HasAttrs as _, StmtKind}; use rustc_attr_data_structures::{AttributeKind, find_attr}; use rustc_data_structures::fx::FxHashMap; use rustc_errors::{MultiSpan, pluralize}; @@ -599,6 +599,7 @@ enum UnusedDelimsCtx { AnonConst, MatchArmExpr, IndexExpr, + ClosureBody, } impl From for &'static str { @@ -620,6 +621,7 @@ impl From for &'static str { UnusedDelimsCtx::ArrayLenExpr | UnusedDelimsCtx::AnonConst => "const expression", UnusedDelimsCtx::MatchArmExpr => "match arm expression", UnusedDelimsCtx::IndexExpr => "index expression", + UnusedDelimsCtx::ClosureBody => "closure body", } } } @@ -919,6 +921,11 @@ trait UnusedDelimLint { let (args_to_check, ctx) = match *call_or_other { Call(_, ref args) => (&args[..], UnusedDelimsCtx::FunctionArg), MethodCall(ref call) => (&call.args[..], UnusedDelimsCtx::MethodArg), + Closure(ref closure) + if matches!(closure.fn_decl.output, FnRetTy::Default(_)) => + { + (&[closure.body.clone()][..], UnusedDelimsCtx::ClosureBody) + } // actual catch-all arm _ => { return; @@ -1508,6 +1515,7 @@ impl UnusedDelimLint for UnusedBraces { && (ctx != UnusedDelimsCtx::AnonConst || (matches!(expr.kind, ast::ExprKind::Lit(_)) && !expr.span.from_expansion())) + && ctx != UnusedDelimsCtx::ClosureBody && !cx.sess().source_map().is_multiline(value.span) && value.attrs.is_empty() && !value.span.from_expansion() diff --git a/compiler/rustc_parse/src/parser/item.rs b/compiler/rustc_parse/src/parser/item.rs index 9ed7124a11c38..d6cc98d505cdc 100644 --- a/compiler/rustc_parse/src/parser/item.rs +++ b/compiler/rustc_parse/src/parser/item.rs @@ -2206,7 +2206,7 @@ impl<'a> Parser<'a> { if self.look_ahead(1, |t| *t == token::Bang) && self.look_ahead(2, |t| t.is_ident()) { return IsMacroRulesItem::Yes { has_bang: true }; - } else if self.look_ahead(1, |t| (t.is_ident())) { + } else if self.look_ahead(1, |t| t.is_ident()) { // macro_rules foo self.dcx().emit_err(errors::MacroRulesMissingBang { span: macro_rules_span, diff --git a/compiler/rustc_resolve/src/build_reduced_graph.rs b/compiler/rustc_resolve/src/build_reduced_graph.rs index f775cac149e9e..ef122deba4e7b 100644 --- a/compiler/rustc_resolve/src/build_reduced_graph.rs +++ b/compiler/rustc_resolve/src/build_reduced_graph.rs @@ -162,28 +162,30 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { } } - pub(crate) fn get_macro(&mut self, res: Res) -> Option<&MacroData> { + pub(crate) fn get_macro(&self, res: Res) -> Option<&'ra MacroData> { match res { Res::Def(DefKind::Macro(..), def_id) => Some(self.get_macro_by_def_id(def_id)), - Res::NonMacroAttr(_) => Some(&self.non_macro_attr), + Res::NonMacroAttr(_) => Some(self.non_macro_attr), _ => None, } } - pub(crate) fn get_macro_by_def_id(&mut self, def_id: DefId) -> &MacroData { - if self.macro_map.contains_key(&def_id) { - return &self.macro_map[&def_id]; - } - - let loaded_macro = self.cstore().load_macro_untracked(def_id, self.tcx); - let macro_data = match loaded_macro { - LoadedMacro::MacroDef { def, ident, attrs, span, edition } => { - self.compile_macro(&def, ident, &attrs, span, ast::DUMMY_NODE_ID, edition) - } - LoadedMacro::ProcMacro(ext) => MacroData::new(Arc::new(ext)), - }; + pub(crate) fn get_macro_by_def_id(&self, def_id: DefId) -> &'ra MacroData { + // Local macros are always compiled. + match def_id.as_local() { + Some(local_def_id) => self.local_macro_map[&local_def_id], + None => *self.extern_macro_map.borrow_mut().entry(def_id).or_insert_with(|| { + let loaded_macro = self.cstore().load_macro_untracked(def_id, self.tcx); + let macro_data = match loaded_macro { + LoadedMacro::MacroDef { def, ident, attrs, span, edition } => { + self.compile_macro(&def, ident, &attrs, span, ast::DUMMY_NODE_ID, edition) + } + LoadedMacro::ProcMacro(ext) => MacroData::new(Arc::new(ext)), + }; - self.macro_map.entry(def_id).or_insert(macro_data) + self.arenas.alloc_macro(macro_data) + }), + } } pub(crate) fn build_reduced_graph( @@ -1203,7 +1205,7 @@ impl<'a, 'ra, 'tcx> BuildReducedGraphVisitor<'a, 'ra, 'tcx> { fn insert_unused_macro(&mut self, ident: Ident, def_id: LocalDefId, node_id: NodeId) { if !ident.as_str().starts_with('_') { self.r.unused_macros.insert(def_id, (node_id, ident)); - let nrules = self.r.macro_map[&def_id.to_def_id()].nrules; + let nrules = self.r.local_macro_map[&def_id].nrules; self.r.unused_macro_rules.insert(node_id, DenseBitSet::new_filled(nrules)); } } @@ -1222,7 +1224,7 @@ impl<'a, 'ra, 'tcx> BuildReducedGraphVisitor<'a, 'ra, 'tcx> { Some((macro_kind, ident, span)) => { let res = Res::Def(DefKind::Macro(macro_kind), def_id.to_def_id()); let macro_data = MacroData::new(self.r.dummy_ext(macro_kind)); - self.r.macro_map.insert(def_id.to_def_id(), macro_data); + self.r.new_local_macro(def_id, macro_data); self.r.proc_macro_stubs.insert(def_id); (res, ident, span, false) } diff --git a/compiler/rustc_resolve/src/def_collector.rs b/compiler/rustc_resolve/src/def_collector.rs index 1e345b11c1466..e2caf632dd2d5 100644 --- a/compiler/rustc_resolve/src/def_collector.rs +++ b/compiler/rustc_resolve/src/def_collector.rs @@ -165,7 +165,7 @@ impl<'a, 'ra, 'tcx> visit::Visitor<'a> for DefCollector<'a, 'ra, 'tcx> { self.create_def(i.id, i.kind.ident().map(|ident| ident.name), def_kind, i.span); if let Some(macro_data) = opt_macro_data { - self.resolver.macro_map.insert(def_id.to_def_id(), macro_data); + self.resolver.new_local_macro(def_id, macro_data); } self.with_parent(def_id, |this| { diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs index c99bc747fd21d..c4ff5770e766e 100644 --- a/compiler/rustc_resolve/src/diagnostics.rs +++ b/compiler/rustc_resolve/src/diagnostics.rs @@ -1669,9 +1669,14 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { let mut all_attrs: UnordMap> = UnordMap::default(); // We're collecting these in a hashmap, and handle ordering the output further down. #[allow(rustc::potential_query_instability)] - for (def_id, data) in &self.macro_map { + for (def_id, data) in self + .local_macro_map + .iter() + .map(|(local_id, data)| (local_id.to_def_id(), data)) + .chain(self.extern_macro_map.borrow().iter().map(|(id, d)| (*id, d))) + { for helper_attr in &data.ext.helper_attrs { - let item_name = self.tcx.item_name(*def_id); + let item_name = self.tcx.item_name(def_id); all_attrs.entry(*helper_attr).or_default().push(item_name); if helper_attr == &ident.name { derives.push(item_name); diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs index e015eb7a63695..8114021510e2f 100644 --- a/compiler/rustc_resolve/src/late/diagnostics.rs +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -328,8 +328,7 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { let module_did = mod_prefix.as_ref().and_then(Res::mod_def_id); let mod_prefix = - mod_prefix.map_or_else(String::new, |res| (format!("{} ", res.descr()))); - + mod_prefix.map_or_else(String::new, |res| format!("{} ", res.descr())); (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)), module_did, None) }; diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index f8ca20c568f13..6e4c5ef1909d3 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -1128,10 +1128,12 @@ pub struct Resolver<'ra, 'tcx> { builtin_macros: FxHashMap, registered_tools: &'tcx RegisteredTools, macro_use_prelude: FxIndexMap>, - macro_map: FxHashMap, + local_macro_map: FxHashMap, + /// Lazily populated cache of macros loaded from external crates. + extern_macro_map: RefCell>, dummy_ext_bang: Arc, dummy_ext_derive: Arc, - non_macro_attr: MacroData, + non_macro_attr: &'ra MacroData, local_macro_def_scopes: FxHashMap>, ast_transform_scopes: FxHashMap>, unused_macros: FxIndexMap, @@ -1241,6 +1243,7 @@ pub struct ResolverArenas<'ra> { imports: TypedArena>, name_resolutions: TypedArena>>, ast_paths: TypedArena, + macros: TypedArena, dropless: DroplessArena, } @@ -1287,7 +1290,7 @@ impl<'ra> ResolverArenas<'ra> { self.name_resolutions.alloc(Default::default()) } fn alloc_macro_rules_scope(&'ra self, scope: MacroRulesScope<'ra>) -> MacroRulesScopeRef<'ra> { - Interned::new_unchecked(self.dropless.alloc(Cell::new(scope))) + self.dropless.alloc(Cell::new(scope)) } fn alloc_macro_rules_binding( &'ra self, @@ -1298,6 +1301,9 @@ impl<'ra> ResolverArenas<'ra> { fn alloc_ast_paths(&'ra self, paths: &[ast::Path]) -> &'ra [ast::Path] { self.ast_paths.alloc_from_iter(paths.iter().cloned()) } + fn alloc_macro(&'ra self, macro_data: MacroData) -> &'ra MacroData { + self.macros.alloc(macro_data) + } fn alloc_pattern_spans(&'ra self, spans: impl Iterator) -> &'ra [Span] { self.dropless.alloc_from_iter(spans) } @@ -1540,10 +1546,12 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { builtin_macros: Default::default(), registered_tools, macro_use_prelude: Default::default(), - macro_map: FxHashMap::default(), + local_macro_map: Default::default(), + extern_macro_map: Default::default(), dummy_ext_bang: Arc::new(SyntaxExtension::dummy_bang(edition)), dummy_ext_derive: Arc::new(SyntaxExtension::dummy_derive(edition)), - non_macro_attr: MacroData::new(Arc::new(SyntaxExtension::non_macro_attr(edition))), + non_macro_attr: arenas + .alloc_macro(MacroData::new(Arc::new(SyntaxExtension::non_macro_attr(edition)))), invocation_parent_scopes: Default::default(), output_macro_rules_scopes: Default::default(), macro_rules_scopes: Default::default(), @@ -1616,6 +1624,12 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { ) } + fn new_local_macro(&mut self, def_id: LocalDefId, macro_data: MacroData) -> &'ra MacroData { + let mac = self.arenas.alloc_macro(macro_data); + self.local_macro_map.insert(def_id, mac); + mac + } + fn next_node_id(&mut self) -> NodeId { let start = self.next_node_id; let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds"); @@ -1734,7 +1748,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { f(self, MacroNS); } - fn is_builtin_macro(&mut self, res: Res) -> bool { + fn is_builtin_macro(&self, res: Res) -> bool { self.get_macro(res).is_some_and(|macro_data| macro_data.ext.builtin_name.is_some()) } diff --git a/compiler/rustc_resolve/src/macros.rs b/compiler/rustc_resolve/src/macros.rs index acbefe53422f7..89bbe8dad98a9 100644 --- a/compiler/rustc_resolve/src/macros.rs +++ b/compiler/rustc_resolve/src/macros.rs @@ -9,7 +9,6 @@ use rustc_ast::expand::StrippedCfgItem; use rustc_ast::{self as ast, Crate, NodeId, attr}; use rustc_ast_pretty::pprust; use rustc_attr_data_structures::StabilityLevel; -use rustc_data_structures::intern::Interned; use rustc_errors::{Applicability, DiagCtxtHandle, StashKey}; use rustc_expand::base::{ Annotatable, DeriveResolution, Indeterminate, ResolverExpand, SyntaxExtension, @@ -80,7 +79,7 @@ pub(crate) enum MacroRulesScope<'ra> { /// This helps to avoid uncontrollable growth of `macro_rules!` scope chains, /// which usually grow linearly with the number of macro invocations /// in a module (including derives) and hurt performance. -pub(crate) type MacroRulesScopeRef<'ra> = Interned<'ra, Cell>>; +pub(crate) type MacroRulesScopeRef<'ra> = &'ra Cell>; /// Macro namespace is separated into two sub-namespaces, one for bang macros and /// one for attribute-like macros (attributes, derives). @@ -354,8 +353,8 @@ impl<'ra, 'tcx> ResolverExpand for Resolver<'ra, 'tcx> { if unused_arms.is_empty() { continue; } - let def_id = self.local_def_id(node_id).to_def_id(); - let m = &self.macro_map[&def_id]; + let def_id = self.local_def_id(node_id); + let m = &self.local_macro_map[&def_id]; let SyntaxExtensionKind::LegacyBang(ref ext) = m.ext.kind else { continue; }; @@ -1132,7 +1131,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { } } - pub(crate) fn check_reserved_macro_name(&mut self, ident: Ident, res: Res) { + pub(crate) fn check_reserved_macro_name(&self, ident: Ident, res: Res) { // Reserve some names that are not quite covered by the general check // performed on `Resolver::builtin_attrs`. if ident.name == sym::cfg || ident.name == sym::cfg_attr { @@ -1148,7 +1147,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { /// /// Possibly replace its expander to a pre-defined one for built-in macros. pub(crate) fn compile_macro( - &mut self, + &self, macro_def: &ast::MacroDef, ident: Ident, attrs: &[rustc_hir::Attribute], diff --git a/library/core/src/marker.rs b/library/core/src/marker.rs index 1c0629f259db2..6531d3ec766a9 100644 --- a/library/core/src/marker.rs +++ b/library/core/src/marker.rs @@ -210,6 +210,11 @@ pub trait PointeeSized { /// - `Trait` is dyn-compatible[^1]. /// - The type is sized. /// - The type outlives `'a`. +/// - Trait objects `dyn TraitA + AutoA... + 'a` implement `Unsize` +/// if all of these conditions are met: +/// - `TraitB` is a supertrait of `TraitA`. +/// - `AutoB...` is a subset of `AutoA...`. +/// - `'a` outlives `'b`. /// - Structs `Foo<..., T1, ..., Tn, ...>` implement `Unsize>` /// where any number of (type and const) parameters may be changed if all of these conditions /// are met: diff --git a/library/core/src/unicode/unicode_data.rs b/library/core/src/unicode/unicode_data.rs index 25b9c6e0e0e94..b57234bbee9a2 100644 --- a/library/core/src/unicode/unicode_data.rs +++ b/library/core/src/unicode/unicode_data.rs @@ -82,7 +82,7 @@ unsafe fn skip_search( let needle = needle as u32; let last_idx = - match short_offset_runs.binary_search_by_key(&(needle << 11), |header| (header.0 << 11)) { + match short_offset_runs.binary_search_by_key(&(needle << 11), |header| header.0 << 11) { Ok(idx) => idx + 1, Err(idx) => idx, }; diff --git a/library/std/src/sys/fs/unix.rs b/library/std/src/sys/fs/unix.rs index dc278274f00f4..b310db2dac485 100644 --- a/library/std/src/sys/fs/unix.rs +++ b/library/std/src/sys/fs/unix.rs @@ -1491,7 +1491,6 @@ impl File { target_os = "redox", target_os = "espidf", target_os = "horizon", - target_os = "vxworks", target_os = "nuttx", )))] let to_timespec = |time: Option| match time { diff --git a/library/std/src/sys/pal/unix/thread.rs b/library/std/src/sys/pal/unix/thread.rs index 53f0d1eeda5bf..e4f5520d8a33e 100644 --- a/library/std/src/sys/pal/unix/thread.rs +++ b/library/std/src/sys/pal/unix/thread.rs @@ -222,7 +222,7 @@ impl Thread { #[cfg(target_os = "vxworks")] pub fn set_name(name: &CStr) { - let mut name = truncate_cstr::<{ libc::VX_TASK_RENAME_LENGTH - 1 }>(name); + let mut name = truncate_cstr::<{ (libc::VX_TASK_RENAME_LENGTH - 1) as usize }>(name); let res = unsafe { libc::taskNameSet(libc::taskIdSelf(), name.as_mut_ptr()) }; debug_assert_eq!(res, libc::OK); } diff --git a/src/doc/rustc/src/platform-support/wasm32-wasip1.md b/src/doc/rustc/src/platform-support/wasm32-wasip1.md index 1e7447698bc99..a8a9e5505810b 100644 --- a/src/doc/rustc/src/platform-support/wasm32-wasip1.md +++ b/src/doc/rustc/src/platform-support/wasm32-wasip1.md @@ -42,6 +42,7 @@ said since when this document was last updated those interested in maintaining this target are: [@alexcrichton](https://github.com/alexcrichton) +[@loganek](https://github.com/loganek) ## Requirements diff --git a/src/tools/clippy/clippy_lints/src/unused_async.rs b/src/tools/clippy/clippy_lints/src/unused_async.rs index 8ceaa3dc58ec0..e67afc7f5a8b5 100644 --- a/src/tools/clippy/clippy_lints/src/unused_async.rs +++ b/src/tools/clippy/clippy_lints/src/unused_async.rs @@ -169,7 +169,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedAsync { let iter = self .unused_async_fns .iter() - .filter(|UnusedAsyncFn { def_id, .. }| (!self.async_fns_as_value.contains(def_id))); + .filter(|UnusedAsyncFn { def_id, .. }| !self.async_fns_as_value.contains(def_id)); for fun in iter { span_lint_hir_and_then( diff --git a/src/tools/clippy/clippy_utils/src/ty/mod.rs b/src/tools/clippy/clippy_utils/src/ty/mod.rs index bffbcf073ab0f..fe208c032f4c0 100644 --- a/src/tools/clippy/clippy_utils/src/ty/mod.rs +++ b/src/tools/clippy/clippy_utils/src/ty/mod.rs @@ -889,7 +889,7 @@ impl AdtVariantInfo { .enumerate() .map(|(i, f)| (i, approx_ty_size(cx, f.ty(cx.tcx, subst)))) .collect::>(); - fields_size.sort_by(|(_, a_size), (_, b_size)| (a_size.cmp(b_size))); + fields_size.sort_by(|(_, a_size), (_, b_size)| a_size.cmp(b_size)); Self { ind: i, @@ -898,7 +898,7 @@ impl AdtVariantInfo { } }) .collect::>(); - variants_size.sort_by(|a, b| (b.size.cmp(&a.size))); + variants_size.sort_by(|a, b| b.size.cmp(&a.size)); variants_size } } diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index 3e879e0e4bbeb..933a32392bddf 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -1777,6 +1777,12 @@ impl<'test> TestCx<'test> { // Allow tests to use internal features. rustc.args(&["-A", "internal_features"]); + // Allow tests to have unused parens and braces. + // Add #![deny(unused_parens, unused_braces)] to the test file if you want to + // test that these lints are working. + rustc.args(&["-A", "unused_parens"]); + rustc.args(&["-A", "unused_braces"]); + if self.props.force_host { self.maybe_add_external_args(&mut rustc, &self.config.host_rustcflags); if !is_rustdoc { diff --git a/src/tools/run-make-support/CHANGELOG.md b/src/tools/run-make-support/CHANGELOG.md deleted file mode 100644 index c1b7b618a9217..0000000000000 --- a/src/tools/run-make-support/CHANGELOG.md +++ /dev/null @@ -1,83 +0,0 @@ -# Changelog - -All notable changes to the `run_make_support` library should be documented in this file. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the support -library should adhere to [Semantic Versioning](https://semver.org/spec/v2.0.0.html) even if it's -not intended for public consumption (it's moreso to help internally, to help test writers track -changes to the support library). - -This support library will probably never reach 1.0. Please bump the minor version in `Cargo.toml` if -you make any breaking changes or other significant changes, or bump the patch version for bug fixes. - -## [0.2.0] - 2024-06-11 - -### Added - -- Added `fs_wrapper` module which provides panic-on-fail helpers for their respective `std::fs` - counterparts, the motivation is to: - - Reduce littering `.unwrap()` or `.expect()` everywhere for fs operations - - Help the test writer avoid forgetting to check fs results (even though enforced by - `-Dunused_must_use`) - - Provide better panic messages by default -- Added `path()` helper which creates a `Path` relative to `cwd()` (but is less noisy). - -### Changed - -- Marked many functions with `#[must_use]`, and rmake.rs are now compiled with `-Dunused_must_use`. - -## [0.1.0] - 2024-06-09 - -### Changed - -- Use *drop bombs* to enforce that commands are executed; a command invocation will panic if it is - constructed but never executed. Execution methods `Command::{run, run_fail}` will defuse the drop - bomb. -- Added `Command` helpers that forward to `std::process::Command` counterparts. - -### Removed - -- The `env_var` method which was incorrectly named and is `env_clear` underneath and is a footgun - from `impl_common_helpers`. For example, removing `TMPDIR` on Unix and `TMP`/`TEMP` breaks - `std::env::temp_dir` and wrecks anything using that, such as rustc's codgen. -- Removed `Deref`/`DerefMut` for `run_make_support::Command` -> `std::process::Command` because it - causes a method chain like `htmldocck().arg().run()` to fail, because `arg()` resolves to - `std::process::Command` which also returns a `&mut std::process::Command`, causing the `run()` to - be not found. - -## [0.0.0] - 2024-06-09 - -Consider this version to contain all changes made to the support library before we started to track -changes in this changelog. - -### Added - -- Custom command wrappers around `std::process::Command` (`run_make_support::Command`) and custom - wrapper around `std::process::Output` (`CompletedProcess`) to make it more convenient to work with - commands and their output, and help avoid forgetting to check for exit status. - - `Command`: `set_stdin`, `run`, `run_fail`. - - `CompletedProcess`: `std{err,out}_utf8`, `status`, `assert_std{err,out}_{equals, contains, - not_contains}`, `assert_exit_code`. -- `impl_common_helpers` macro to avoid repeating adding common convenience methods, including: - - Environment manipulation methods: `env`, `env_remove` - - Command argument providers: `arg`, `args` - - Common invocation inspection (of the command invocation up until `inspect` is called): - `inspect` - - Execution methods: `run` (for commands expected to succeed execution, exit status `0`) and - `run_fail` (for commands expected to fail execution, exit status non-zero). -- Command wrappers around: `rustc`, `clang`, `cc`, `rustc`, `rustdoc`, `llvm-readobj`. -- Thin helpers to construct `python` and `htmldocck` commands. -- `run` and `run_fail` (like `Command::{run, run_fail}`) for running binaries, which sets suitable - env vars (like `LD_LIB_PATH` or equivalent, `TARGET_RPATH_ENV`, `PATH` on Windows). -- Pseudo command `diff` which has similar functionality as the cli util but not the same API. -- Convenience panic-on-fail helpers `env_var`, `env_var_os`, `cwd` for their `std::env` conterparts. -- Convenience panic-on-fail helpers for reading respective env vars: `target`, `source_root`. -- Platform check helpers: `is_windows`, `is_msvc`, `cygpath_windows`, `uname`. -- fs helpers: `copy_dir_all`. -- `recursive_diff` helper. -- Generic `assert_not_contains` helper. -- Scoped run-with-teardown helper `run_in_tmpdir` which is designed to run commands in a temporary - directory that is cleared when closure returns. -- Helpers for constructing the name of binaries and libraries: `rust_lib_name`, `static_lib_name`, - `bin_name`, `dynamic_lib_name`. -- Re-export libraries: `gimli`, `object`, `regex`, `wasmparsmer`. diff --git a/src/tools/run-make-support/Cargo.toml b/src/tools/run-make-support/Cargo.toml index 3226f467ba4f9..a4e7534137d5e 100644 --- a/src/tools/run-make-support/Cargo.toml +++ b/src/tools/run-make-support/Cargo.toml @@ -1,18 +1,27 @@ [package] name = "run_make_support" -version = "0.2.0" -edition = "2021" +version = "0.0.0" +edition = "2024" [dependencies] + +# These dependencies are either used to implement part of support library +# functionality, or re-exported to test recipe programs via the support library, +# or both. + +# tidy-alphabetical-start bstr = "1.12" +gimli = "0.32" +libc = "0.2" object = "0.37" +regex = "1.11" +serde_json = "1.0" similar = "2.7" wasmparser = { version = "0.219", default-features = false, features = ["std"] } -regex = "1.11" -gimli = "0.32" +# tidy-alphabetical-end + +# Shared with bootstrap and compiletest build_helper = { path = "../../build_helper" } -serde_json = "1.0" -libc = "0.2" [lib] crate-type = ["lib", "dylib"] diff --git a/src/tools/run-make-support/src/artifact_names.rs b/src/tools/run-make-support/src/artifact_names.rs index b0d588d3550ac..a889b30e145d6 100644 --- a/src/tools/run-make-support/src/artifact_names.rs +++ b/src/tools/run-make-support/src/artifact_names.rs @@ -2,7 +2,7 @@ //! libraries which are target-dependent. use crate::target; -use crate::targets::is_msvc; +use crate::targets::is_windows_msvc; /// Construct the static library name based on the target. #[track_caller] @@ -10,7 +10,7 @@ use crate::targets::is_msvc; pub fn static_lib_name(name: &str) -> String { assert!(!name.contains(char::is_whitespace), "static library name cannot contain whitespace"); - if is_msvc() { format!("{name}.lib") } else { format!("lib{name}.a") } + if is_windows_msvc() { format!("{name}.lib") } else { format!("lib{name}.a") } } /// Construct the dynamic library name based on the target. @@ -45,7 +45,7 @@ pub fn dynamic_lib_extension() -> &'static str { #[track_caller] #[must_use] pub fn msvc_import_dynamic_lib_name(name: &str) -> String { - assert!(is_msvc(), "this function is exclusive to MSVC"); + assert!(is_windows_msvc(), "this function is exclusive to MSVC"); assert!(!name.contains(char::is_whitespace), "import library name cannot contain whitespace"); format!("{name}.dll.lib") diff --git a/src/tools/run-make-support/src/external_deps/c_build.rs b/src/tools/run-make-support/src/external_deps/c_build.rs index 9dd30713f958b..ecbf5ba8fe0d0 100644 --- a/src/tools/run-make-support/src/external_deps/c_build.rs +++ b/src/tools/run-make-support/src/external_deps/c_build.rs @@ -4,7 +4,7 @@ use crate::artifact_names::{dynamic_lib_name, static_lib_name}; use crate::external_deps::c_cxx_compiler::{cc, cxx}; use crate::external_deps::llvm::llvm_ar; use crate::path_helpers::path; -use crate::targets::{is_darwin, is_msvc, is_windows}; +use crate::targets::{is_darwin, is_windows, is_windows_msvc}; // FIXME(Oneirical): These native build functions should take a Path-based generic. @@ -24,12 +24,12 @@ pub fn build_native_static_lib_optimized(lib_name: &str) -> PathBuf { #[track_caller] fn build_native_static_lib_internal(lib_name: &str, optimzed: bool) -> PathBuf { - let obj_file = if is_msvc() { format!("{lib_name}") } else { format!("{lib_name}.o") }; + let obj_file = if is_windows_msvc() { format!("{lib_name}") } else { format!("{lib_name}.o") }; let src = format!("{lib_name}.c"); let lib_path = static_lib_name(lib_name); let mut cc = cc(); - if !is_msvc() { + if !is_windows_msvc() { cc.arg("-v"); } if optimzed { @@ -37,7 +37,7 @@ fn build_native_static_lib_internal(lib_name: &str, optimzed: bool) -> PathBuf { } cc.arg("-c").out_exe(&obj_file).input(src).optimize().run(); - let obj_file = if is_msvc() { + let obj_file = if is_windows_msvc() { PathBuf::from(format!("{lib_name}.obj")) } else { PathBuf::from(format!("{lib_name}.o")) @@ -50,16 +50,17 @@ fn build_native_static_lib_internal(lib_name: &str, optimzed: bool) -> PathBuf { /// [`std::env::consts::DLL_PREFIX`] and [`std::env::consts::DLL_EXTENSION`]. #[track_caller] pub fn build_native_dynamic_lib(lib_name: &str) -> PathBuf { - let obj_file = if is_msvc() { format!("{lib_name}") } else { format!("{lib_name}.o") }; + let obj_file = if is_windows_msvc() { format!("{lib_name}") } else { format!("{lib_name}.o") }; let src = format!("{lib_name}.c"); let lib_path = dynamic_lib_name(lib_name); - if is_msvc() { + if is_windows_msvc() { cc().arg("-c").out_exe(&obj_file).input(src).run(); } else { cc().arg("-v").arg("-c").out_exe(&obj_file).input(src).run(); }; - let obj_file = if is_msvc() { format!("{lib_name}.obj") } else { format!("{lib_name}.o") }; - if is_msvc() { + let obj_file = + if is_windows_msvc() { format!("{lib_name}.obj") } else { format!("{lib_name}.o") }; + if is_windows_msvc() { let out_arg = format!("-out:{lib_path}"); cc().input(&obj_file).args(&["-link", "-dll", &out_arg]).run(); } else if is_darwin() { @@ -79,15 +80,15 @@ pub fn build_native_dynamic_lib(lib_name: &str) -> PathBuf { /// Built from a C++ file. #[track_caller] pub fn build_native_static_lib_cxx(lib_name: &str) -> PathBuf { - let obj_file = if is_msvc() { format!("{lib_name}") } else { format!("{lib_name}.o") }; + let obj_file = if is_windows_msvc() { format!("{lib_name}") } else { format!("{lib_name}.o") }; let src = format!("{lib_name}.cpp"); let lib_path = static_lib_name(lib_name); - if is_msvc() { + if is_windows_msvc() { cxx().arg("-EHs").arg("-c").out_exe(&obj_file).input(src).run(); } else { cxx().arg("-c").out_exe(&obj_file).input(src).run(); }; - let obj_file = if is_msvc() { + let obj_file = if is_windows_msvc() { PathBuf::from(format!("{lib_name}.obj")) } else { PathBuf::from(format!("{lib_name}.o")) diff --git a/src/tools/run-make-support/src/external_deps/c_cxx_compiler/cc.rs b/src/tools/run-make-support/src/external_deps/c_cxx_compiler/cc.rs index 0e6d6ea6075d2..31469e669e18e 100644 --- a/src/tools/run-make-support/src/external_deps/c_cxx_compiler/cc.rs +++ b/src/tools/run-make-support/src/external_deps/c_cxx_compiler/cc.rs @@ -1,7 +1,7 @@ use std::path::Path; use crate::command::Command; -use crate::{env_var, is_msvc}; +use crate::{env_var, is_windows_msvc}; /// Construct a new platform-specific C compiler invocation. /// @@ -82,7 +82,7 @@ impl Cc { pub fn out_exe(&mut self, name: &str) -> &mut Self { let mut path = std::path::PathBuf::from(name); - if is_msvc() { + if is_windows_msvc() { path.set_extension("exe"); let fe_path = path.clone(); path.set_extension(""); @@ -108,7 +108,7 @@ impl Cc { /// Optimize the output. /// Equivalent to `-O3` for GNU-compatible linkers or `-O2` for MSVC linkers. pub fn optimize(&mut self) -> &mut Self { - if is_msvc() { + if is_windows_msvc() { self.cmd.arg("-O2"); } else { self.cmd.arg("-O3"); diff --git a/src/tools/run-make-support/src/external_deps/c_cxx_compiler/extras.rs b/src/tools/run-make-support/src/external_deps/c_cxx_compiler/extras.rs index c031763387362..ac7392641c0d7 100644 --- a/src/tools/run-make-support/src/external_deps/c_cxx_compiler/extras.rs +++ b/src/tools/run-make-support/src/external_deps/c_cxx_compiler/extras.rs @@ -1,9 +1,9 @@ -use crate::{is_msvc, is_win7, is_windows, uname}; +use crate::{is_win7, is_windows, is_windows_msvc, uname}; /// `EXTRACFLAGS` pub fn extra_c_flags() -> Vec<&'static str> { if is_windows() { - if is_msvc() { + if is_windows_msvc() { let mut libs = vec!["ws2_32.lib", "userenv.lib", "bcrypt.lib", "ntdll.lib", "synchronization.lib"]; if is_win7() { @@ -29,7 +29,7 @@ pub fn extra_c_flags() -> Vec<&'static str> { /// `EXTRACXXFLAGS` pub fn extra_cxx_flags() -> Vec<&'static str> { if is_windows() { - if is_msvc() { vec![] } else { vec!["-lstdc++"] } + if is_windows_msvc() { vec![] } else { vec!["-lstdc++"] } } else { match &uname()[..] { "Darwin" => vec!["-lc++"], diff --git a/src/tools/run-make-support/src/external_deps/rustc.rs b/src/tools/run-make-support/src/external_deps/rustc.rs index 72a1e062a38da..1ea549ca7ea13 100644 --- a/src/tools/run-make-support/src/external_deps/rustc.rs +++ b/src/tools/run-make-support/src/external_deps/rustc.rs @@ -6,7 +6,7 @@ use crate::command::Command; use crate::env::env_var; use crate::path_helpers::cwd; use crate::util::set_host_compiler_dylib_path; -use crate::{is_aix, is_darwin, is_msvc, is_windows, target, uname}; +use crate::{is_aix, is_darwin, is_windows, is_windows_msvc, target, uname}; /// Construct a new `rustc` invocation. This will automatically set the library /// search path as `-L cwd()`. Use [`bare_rustc`] to avoid this. @@ -377,7 +377,7 @@ impl Rustc { // So we end up with the following hack: we link use static:-bundle to only // link the parts of libstdc++ that we actually use, which doesn't include // the dependency on the pthreads DLL. - if !is_msvc() { + if !is_windows_msvc() { self.cmd.arg("-lstatic:-bundle=stdc++"); }; } else if is_darwin() { diff --git a/src/tools/run-make-support/src/lib.rs b/src/tools/run-make-support/src/lib.rs index 67d8c351a59fb..29cd6c4ad1591 100644 --- a/src/tools/run-make-support/src/lib.rs +++ b/src/tools/run-make-support/src/lib.rs @@ -3,9 +3,6 @@ //! notably is built via cargo: this means that if your test wants some non-trivial utility, such //! as `object` or `wasmparser`, they can be re-exported and be made available through this library. -// We want to control use declaration ordering and spacing (and preserve use group comments), so -// skip rustfmt on this file. -#![cfg_attr(rustfmt, rustfmt::skip)] #![warn(unreachable_pub)] mod command; @@ -22,8 +19,8 @@ pub mod path_helpers; pub mod run; pub mod scoped_run; pub mod string; -pub mod targets; pub mod symbols; +pub mod targets; // Internally we call our fs-related support module as `fs`, but re-export its content as `rfs` // to tests to avoid colliding with commonly used `use std::fs;`. @@ -36,77 +33,56 @@ pub mod rfs { } // Re-exports of third-party library crates. -// tidy-alphabetical-start -pub use bstr; -pub use gimli; -pub use libc; -pub use object; -pub use regex; -pub use serde_json; -pub use similar; -pub use wasmparser; -// tidy-alphabetical-end +pub use {bstr, gimli, libc, object, regex, serde_json, similar, wasmparser}; -// Re-exports of external dependencies. -pub use external_deps::{ - cargo, c_build, c_cxx_compiler, clang, htmldocck, llvm, python, rustc, rustdoc +// Helpers for building names of output artifacts that are potentially target-specific. +pub use crate::artifact_names::{ + bin_name, dynamic_lib_extension, dynamic_lib_name, msvc_import_dynamic_lib_name, rust_lib_name, + static_lib_name, }; - -// These rely on external dependencies. -pub use c_cxx_compiler::{Cc, Gcc, cc, cxx, extra_c_flags, extra_cxx_flags, gcc}; -pub use c_build::{ +pub use crate::assertion_helpers::{ + assert_contains, assert_contains_regex, assert_count_is, assert_dirs_are_equal, assert_equals, + assert_not_contains, assert_not_contains_regex, +}; +// `diff` is implemented in terms of the [similar] library. +// +// [similar]: https://github.com/mitsuhiko/similar +pub use crate::diff::{Diff, diff}; +// Panic-on-fail [`std::env::var`] and [`std::env::var_os`] wrappers. +pub use crate::env::{env_var, env_var_os, set_current_dir}; +pub use crate::external_deps::c_build::{ build_native_dynamic_lib, build_native_static_lib, build_native_static_lib_cxx, build_native_static_lib_optimized, }; -pub use cargo::cargo; -pub use clang::{clang, Clang}; -pub use htmldocck::htmldocck; -pub use llvm::{ - llvm_ar, llvm_bcanalyzer, llvm_dis, llvm_dwarfdump, llvm_filecheck, llvm_nm, llvm_objcopy, - llvm_objdump, llvm_profdata, llvm_readobj, LlvmAr, LlvmBcanalyzer, LlvmDis, LlvmDwarfdump, - LlvmFilecheck, LlvmNm, LlvmObjcopy, LlvmObjdump, LlvmProfdata, LlvmReadobj, -}; -pub use python::python_command; -pub use rustc::{bare_rustc, rustc, rustc_path, Rustc}; -pub use rustdoc::{bare_rustdoc, rustdoc, Rustdoc}; - -/// [`diff`][mod@diff] is implemented in terms of the [similar] library. -/// -/// [similar]: https://github.com/mitsuhiko/similar -pub use diff::{diff, Diff}; - -/// Panic-on-fail [`std::env::var`] and [`std::env::var_os`] wrappers. -pub use env::{env_var, env_var_os, set_current_dir}; - -/// Convenience helpers for running binaries and other commands. -pub use run::{cmd, run, run_fail, run_with_args}; - -/// Helpers for checking target information. -pub use targets::{ - apple_os, is_aix, is_darwin, is_msvc, is_windows, is_windows_gnu, is_windows_msvc, is_win7, llvm_components_contain, - target, uname, +// Re-exports of external dependencies. +pub use crate::external_deps::c_cxx_compiler::{ + Cc, Gcc, cc, cxx, extra_c_flags, extra_cxx_flags, gcc, }; - -/// Helpers for building names of output artifacts that are potentially target-specific. -pub use artifact_names::{ - bin_name, dynamic_lib_extension, dynamic_lib_name, msvc_import_dynamic_lib_name, rust_lib_name, - static_lib_name, +pub use crate::external_deps::cargo::cargo; +pub use crate::external_deps::clang::{Clang, clang}; +pub use crate::external_deps::htmldocck::htmldocck; +pub use crate::external_deps::llvm::{ + self, LlvmAr, LlvmBcanalyzer, LlvmDis, LlvmDwarfdump, LlvmFilecheck, LlvmNm, LlvmObjcopy, + LlvmObjdump, LlvmProfdata, LlvmReadobj, llvm_ar, llvm_bcanalyzer, llvm_dis, llvm_dwarfdump, + llvm_filecheck, llvm_nm, llvm_objcopy, llvm_objdump, llvm_profdata, llvm_readobj, }; - -/// Path-related helpers. -pub use path_helpers::{ +pub use crate::external_deps::python::python_command; +pub use crate::external_deps::rustc::{self, Rustc, bare_rustc, rustc, rustc_path}; +pub use crate::external_deps::rustdoc::{Rustdoc, bare_rustdoc, rustdoc}; +// Path-related helpers. +pub use crate::path_helpers::{ build_root, cwd, filename_contains, filename_not_in_denylist, has_extension, has_prefix, has_suffix, not_contains, path, shallow_find_directories, shallow_find_files, source_root, }; - -/// Helpers for scoped test execution where certain properties are attempted to be maintained. -pub use scoped_run::{run_in_tmpdir, test_while_readonly}; - -pub use assertion_helpers::{ - assert_contains, assert_contains_regex, assert_count_is, assert_dirs_are_equal, assert_equals, - assert_not_contains, assert_not_contains_regex, -}; - -pub use string::{ +// Convenience helpers for running binaries and other commands. +pub use crate::run::{cmd, run, run_fail, run_with_args}; +// Helpers for scoped test execution where certain properties are attempted to be maintained. +pub use crate::scoped_run::{run_in_tmpdir, test_while_readonly}; +pub use crate::string::{ count_regex_matches_in_files_with_extension, invalid_utf8_contains, invalid_utf8_not_contains, }; +// Helpers for checking target information. +pub use crate::targets::{ + apple_os, is_aix, is_darwin, is_win7, is_windows, is_windows_gnu, is_windows_msvc, + llvm_components_contain, target, uname, +}; diff --git a/src/tools/run-make-support/src/linker.rs b/src/tools/run-make-support/src/linker.rs index 89093cf011393..b2893ad88fe21 100644 --- a/src/tools/run-make-support/src/linker.rs +++ b/src/tools/run-make-support/src/linker.rs @@ -1,6 +1,6 @@ use regex::Regex; -use crate::{Rustc, is_msvc}; +use crate::{Rustc, is_windows_msvc}; /// Asserts that `rustc` uses LLD for linking when executed. pub fn assert_rustc_uses_lld(rustc: &mut Rustc) { @@ -22,7 +22,7 @@ pub fn assert_rustc_doesnt_use_lld(rustc: &mut Rustc) { fn get_stderr_with_linker_messages(rustc: &mut Rustc) -> String { // lld-link is used if msvc, otherwise a gnu-compatible lld is used. - let linker_version_flag = if is_msvc() { "--version" } else { "-Wl,-v" }; + let linker_version_flag = if is_windows_msvc() { "--version" } else { "-Wl,-v" }; let output = rustc.arg("-Wlinker-messages").link_arg(linker_version_flag).run(); output.stderr_utf8() diff --git a/src/tools/run-make-support/src/targets.rs b/src/tools/run-make-support/src/targets.rs index 1ab2e2ab2be40..b20e12561fbfa 100644 --- a/src/tools/run-make-support/src/targets.rs +++ b/src/tools/run-make-support/src/targets.rs @@ -16,10 +16,10 @@ pub fn is_windows() -> bool { target().contains("windows") } -/// Check if target uses msvc. +/// Check if target is windows-msvc. #[must_use] -pub fn is_msvc() -> bool { - target().contains("msvc") +pub fn is_windows_msvc() -> bool { + target().ends_with("windows-msvc") } /// Check if target is windows-gnu. @@ -28,12 +28,6 @@ pub fn is_windows_gnu() -> bool { target().ends_with("windows-gnu") } -/// Check if target is windows-msvc. -#[must_use] -pub fn is_windows_msvc() -> bool { - target().ends_with("windows-msvc") -} - /// Check if target is win7. #[must_use] pub fn is_win7() -> bool { diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/cli/scip.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/cli/scip.rs index d258c5d8191fb..37f83f6dee678 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/cli/scip.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/cli/scip.rs @@ -25,7 +25,7 @@ impl flags::Scip { eprintln!("Generating SCIP start..."); let now = Instant::now(); - let no_progress = &|s| (eprintln!("rust-analyzer: Loading {s}")); + let no_progress = &|s| eprintln!("rust-analyzer: Loading {s}"); let root = vfs::AbsPathBuf::assert_utf8(std::env::current_dir()?.join(&self.path)).normalize(); diff --git a/src/tools/test-float-parse/src/lib.rs b/src/tools/test-float-parse/src/lib.rs index 0bd4878f9a626..1321a3c335499 100644 --- a/src/tools/test-float-parse/src/lib.rs +++ b/src/tools/test-float-parse/src/lib.rs @@ -340,7 +340,7 @@ fn launch_tests(tests: &mut [TestInfo], cfg: &Config) -> Duration { for test in tests.iter_mut() { test.progress = Some(ui::Progress::new(test, &mut all_progress_bars)); ui::set_panic_hook(&all_progress_bars); - ((test.launch)(test, cfg)); + (test.launch)(test, cfg); } start.elapsed() diff --git a/src/tools/unicode-table-generator/src/range_search.rs b/src/tools/unicode-table-generator/src/range_search.rs index 02f9cf16d4d37..4d1dd9b423b59 100644 --- a/src/tools/unicode-table-generator/src/range_search.rs +++ b/src/tools/unicode-table-generator/src/range_search.rs @@ -80,7 +80,7 @@ unsafe fn skip_search( let needle = needle as u32; let last_idx = - match short_offset_runs.binary_search_by_key(&(needle << 11), |header| (header.0 << 11)) { + match short_offset_runs.binary_search_by_key(&(needle << 11), |header| header.0 << 11) { Ok(idx) => idx + 1, Err(idx) => idx, }; diff --git a/tests/run-make/archive-duplicate-names/rmake.rs b/tests/run-make/archive-duplicate-names/rmake.rs index 62a3556619984..0c352b3ae1b57 100644 --- a/tests/run-make/archive-duplicate-names/rmake.rs +++ b/tests/run-make/archive-duplicate-names/rmake.rs @@ -6,7 +6,7 @@ //@ ignore-cross-compile // Reason: the compiled binary is executed -use run_make_support::{cc, is_msvc, llvm_ar, rfs, run, rustc}; +use run_make_support::{cc, is_windows_msvc, llvm_ar, rfs, run, rustc}; fn main() { rfs::create_dir("a"); @@ -15,7 +15,7 @@ fn main() { compile_obj_force_foo("b", "bar"); let mut ar = llvm_ar(); ar.obj_to_ar().arg("libfoo.a"); - if is_msvc() { + if is_windows_msvc() { ar.arg("a/foo.obj").arg("b/foo.obj").run(); } else { ar.arg("a/foo.o").arg("b/foo.o").run(); @@ -27,9 +27,9 @@ fn main() { #[track_caller] pub fn compile_obj_force_foo(dir: &str, lib_name: &str) { - let obj_file = if is_msvc() { format!("{dir}/foo") } else { format!("{dir}/foo.o") }; + let obj_file = if is_windows_msvc() { format!("{dir}/foo") } else { format!("{dir}/foo.o") }; let src = format!("{lib_name}.c"); - if is_msvc() { + if is_windows_msvc() { cc().arg("-c").out_exe(&obj_file).input(src).run(); } else { cc().arg("-v").arg("-c").out_exe(&obj_file).input(src).run(); diff --git a/tests/run-make/c-link-to-rust-dylib/rmake.rs b/tests/run-make/c-link-to-rust-dylib/rmake.rs index 3a48af8a3665a..ece0c81d2da6e 100644 --- a/tests/run-make/c-link-to-rust-dylib/rmake.rs +++ b/tests/run-make/c-link-to-rust-dylib/rmake.rs @@ -3,12 +3,14 @@ //@ ignore-cross-compile -use run_make_support::{cc, cwd, dynamic_lib_extension, is_msvc, rfs, run, run_fail, rustc}; +use run_make_support::{ + cc, cwd, dynamic_lib_extension, is_windows_msvc, rfs, run, run_fail, rustc, +}; fn main() { rustc().input("foo.rs").run(); - if is_msvc() { + if is_windows_msvc() { let lib = "foo.dll.lib"; cc().input("bar.c").arg(lib).out_exe("bar").run(); diff --git a/tests/run-make/c-unwind-abi-catch-lib-panic/rmake.rs b/tests/run-make/c-unwind-abi-catch-lib-panic/rmake.rs index 62e1748b6fb92..ba5fe589acb03 100644 --- a/tests/run-make/c-unwind-abi-catch-lib-panic/rmake.rs +++ b/tests/run-make/c-unwind-abi-catch-lib-panic/rmake.rs @@ -8,11 +8,11 @@ //@ needs-unwind // Reason: this test exercises unwinding a panic -use run_make_support::{cc, is_msvc, llvm_ar, run, rustc, static_lib_name}; +use run_make_support::{cc, is_windows_msvc, llvm_ar, run, rustc, static_lib_name}; fn main() { // Compile `add.c` into an object file. - if is_msvc() { + if is_windows_msvc() { cc().arg("-c").out_exe("add").input("add.c").run(); } else { cc().arg("-v").arg("-c").out_exe("add.o").input("add.c").run(); @@ -24,7 +24,7 @@ fn main() { rustc().emit("obj").input("panic.rs").run(); // Now, create an archive using these two objects. - if is_msvc() { + if is_windows_msvc() { llvm_ar().obj_to_ar().args(&[&static_lib_name("add"), "add.obj", "panic.o"]).run(); } else { llvm_ar().obj_to_ar().args(&[&static_lib_name("add"), "add.o", "panic.o"]).run(); diff --git a/tests/run-make/cdylib-dylib-linkage/rmake.rs b/tests/run-make/cdylib-dylib-linkage/rmake.rs index a8fd8e2d16848..3c145d9f99cf3 100644 --- a/tests/run-make/cdylib-dylib-linkage/rmake.rs +++ b/tests/run-make/cdylib-dylib-linkage/rmake.rs @@ -9,7 +9,7 @@ use run_make_support::{ bin_name, cc, dynamic_lib_extension, dynamic_lib_name, filename_contains, has_extension, - has_prefix, has_suffix, is_msvc, msvc_import_dynamic_lib_name, path, run, rustc, + has_prefix, has_suffix, is_windows_msvc, msvc_import_dynamic_lib_name, path, run, rustc, shallow_find_files, target, }; @@ -19,7 +19,7 @@ fn main() { let sysroot = rustc().print("sysroot").run().stdout_utf8(); let sysroot = sysroot.trim(); let target_sysroot = path(sysroot).join("lib/rustlib").join(target()).join("lib"); - if is_msvc() { + if is_windows_msvc() { let mut libs = shallow_find_files(&target_sysroot, |path| { has_prefix(path, "libstd-") && has_suffix(path, ".dll.lib") }); diff --git a/tests/run-make/cdylib/rmake.rs b/tests/run-make/cdylib/rmake.rs index 21b83d1b1a91f..21fd8b486c489 100644 --- a/tests/run-make/cdylib/rmake.rs +++ b/tests/run-make/cdylib/rmake.rs @@ -10,13 +10,13 @@ //@ ignore-cross-compile -use run_make_support::{cc, cwd, dynamic_lib_name, is_msvc, rfs, run, rustc}; +use run_make_support::{cc, cwd, dynamic_lib_name, is_windows_msvc, rfs, run, rustc}; fn main() { rustc().input("bar.rs").run(); rustc().input("foo.rs").run(); - if is_msvc() { + if is_windows_msvc() { cc().input("foo.c").arg("foo.dll.lib").out_exe("foo").run(); } else { cc().input("foo.c").arg("-lfoo").library_search_path(cwd()).output("foo").run(); diff --git a/tests/run-make/compiler-rt-works-on-mingw/rmake.rs b/tests/run-make/compiler-rt-works-on-mingw/rmake.rs index f1b41f96312de..b15e56db1bb75 100644 --- a/tests/run-make/compiler-rt-works-on-mingw/rmake.rs +++ b/tests/run-make/compiler-rt-works-on-mingw/rmake.rs @@ -5,7 +5,7 @@ //@ only-windows-gnu -use run_make_support::{cxx, is_msvc, llvm_ar, run, rustc, static_lib_name}; +use run_make_support::{cxx, llvm_ar, run, rustc, static_lib_name}; fn main() { cxx().input("foo.cpp").arg("-c").out_exe("foo.o").run(); diff --git a/tests/run-make/link-args-order/rmake.rs b/tests/run-make/link-args-order/rmake.rs index 7a67c12f74c8d..e3c730bfec55e 100644 --- a/tests/run-make/link-args-order/rmake.rs +++ b/tests/run-make/link-args-order/rmake.rs @@ -6,10 +6,10 @@ // checks that linker arguments remain intact and in the order they were originally passed in. // See https://github.com/rust-lang/rust/pull/70665 -use run_make_support::{is_msvc, rustc}; +use run_make_support::{is_windows_msvc, rustc}; fn main() { - let linker = if is_msvc() { "msvc" } else { "ld" }; + let linker = if is_windows_msvc() { "msvc" } else { "ld" }; rustc() .input("empty.rs") diff --git a/tests/run-make/link-dedup/rmake.rs b/tests/run-make/link-dedup/rmake.rs index 874e6e0083bdf..84fdf87e9c70e 100644 --- a/tests/run-make/link-dedup/rmake.rs +++ b/tests/run-make/link-dedup/rmake.rs @@ -9,7 +9,7 @@ use std::fmt::Write; -use run_make_support::{is_msvc, rustc, target}; +use run_make_support::{is_windows_msvc, rustc, target}; fn main() { rustc().input("depa.rs").run(); @@ -32,7 +32,7 @@ fn main() { fn needle_from_libs(libs: &[&str]) -> String { let mut needle = String::new(); for lib in libs { - if is_msvc() { + if is_windows_msvc() { needle.write_fmt(format_args!(r#""{lib}.lib" "#)).unwrap(); } else if target().contains("wasm") { needle.write_fmt(format_args!(r#""-l" "{lib}" "#)).unwrap(); diff --git a/tests/run-make/native-link-modifier-bundle/rmake.rs b/tests/run-make/native-link-modifier-bundle/rmake.rs index 058b66b15f12f..64ee7733498ec 100644 --- a/tests/run-make/native-link-modifier-bundle/rmake.rs +++ b/tests/run-make/native-link-modifier-bundle/rmake.rs @@ -20,7 +20,7 @@ // Reason: cross-compilation fails to export native symbols use run_make_support::{ - build_native_static_lib, dynamic_lib_name, is_msvc, llvm_nm, rust_lib_name, rustc, + build_native_static_lib, dynamic_lib_name, is_windows_msvc, llvm_nm, rust_lib_name, rustc, static_lib_name, }; @@ -60,7 +60,7 @@ fn main() { .assert_stdout_contains_regex("U _*native_func"); // This part of the test does not function on Windows MSVC - no symbols are printed. - if !is_msvc() { + if !is_windows_msvc() { // Build a cdylib, `native-staticlib` will not appear on the linker line because it was // bundled previously. The cdylib will contain the `native_func` symbol in the end. rustc() diff --git a/tests/run-make/native-link-modifier-whole-archive/rmake.rs b/tests/run-make/native-link-modifier-whole-archive/rmake.rs index b8b814043e5cd..90b0203e278c9 100644 --- a/tests/run-make/native-link-modifier-whole-archive/rmake.rs +++ b/tests/run-make/native-link-modifier-whole-archive/rmake.rs @@ -10,11 +10,11 @@ // Reason: compiling C++ code does not work well when cross-compiling // plus, the compiled binary is executed -use run_make_support::{cxx, is_msvc, llvm_ar, run, run_with_args, rustc, static_lib_name}; +use run_make_support::{cxx, is_windows_msvc, llvm_ar, run, run_with_args, rustc, static_lib_name}; fn main() { let mut cxx = cxx(); - if is_msvc() { + if is_windows_msvc() { cxx.arg("-EHs"); } cxx.input("c_static_lib_with_constructor.cpp") @@ -24,7 +24,7 @@ fn main() { let mut llvm_ar = llvm_ar(); llvm_ar.obj_to_ar(); - if is_msvc() { + if is_windows_msvc() { llvm_ar .output_input( static_lib_name("c_static_lib_with_constructor"), diff --git a/tests/run-make/pointer-auth-link-with-c/rmake.rs b/tests/run-make/pointer-auth-link-with-c/rmake.rs index 7b6dff10eaec0..a4d7454e5755a 100644 --- a/tests/run-make/pointer-auth-link-with-c/rmake.rs +++ b/tests/run-make/pointer-auth-link-with-c/rmake.rs @@ -9,7 +9,7 @@ //@ ignore-cross-compile // Reason: the compiled binary is executed -use run_make_support::{build_native_static_lib, cc, is_msvc, llvm_ar, run, rustc}; +use run_make_support::{build_native_static_lib, cc, is_windows_msvc, llvm_ar, run, rustc}; fn main() { build_native_static_lib("test"); @@ -21,7 +21,7 @@ fn main() { .input("test.c") .arg("-mbranch-protection=bti+pac-ret+leaf") .run(); - let obj_file = if is_msvc() { "test.obj" } else { "test" }; + let obj_file = if is_windows_msvc() { "test.obj" } else { "test" }; llvm_ar().obj_to_ar().output_input("libtest.a", &obj_file).run(); rustc().arg("-Zbranch-protection=bti,pac-ret,leaf").input("test.rs").run(); run("test"); @@ -33,7 +33,7 @@ fn main() { // .input("test.c") // .arg("-mbranch-protection=bti+pac-ret+pc+leaf") // .run(); - // let obj_file = if is_msvc() { "test.obj" } else { "test" }; + // let obj_file = if is_windows_msvc() { "test.obj" } else { "test" }; // llvm_ar().obj_to_ar().output_input("libtest.a", &obj_file).run(); // rustc().arg("-Zbranch-protection=bti,pac-ret,pc,leaf").input("test.rs").run(); // run("test"); diff --git a/tests/run-make/print-native-static-libs/rmake.rs b/tests/run-make/print-native-static-libs/rmake.rs index a51ac934c722e..4502c874cae60 100644 --- a/tests/run-make/print-native-static-libs/rmake.rs +++ b/tests/run-make/print-native-static-libs/rmake.rs @@ -12,7 +12,7 @@ //@ ignore-cross-compile //@ ignore-wasm -use run_make_support::{is_msvc, rustc}; +use run_make_support::{is_windows_msvc, rustc}; fn main() { // build supporting crate @@ -41,9 +41,9 @@ fn main() { ($lib:literal in $args:ident) => {{ let lib = format!( "{}{}{}", - if !is_msvc() { "-l" } else { "" }, + if !is_windows_msvc() { "-l" } else { "" }, $lib, - if !is_msvc() { "" } else { ".lib" }, + if !is_windows_msvc() { "" } else { ".lib" }, ); let found = $args.contains(&&*lib); assert!(found, "unable to find lib `{}` in those linker args: {:?}", lib, $args); diff --git a/tests/run-make/raw-dylib-alt-calling-convention/rmake.rs b/tests/run-make/raw-dylib-alt-calling-convention/rmake.rs index 1a1622f275421..0843c6beae823 100644 --- a/tests/run-make/raw-dylib-alt-calling-convention/rmake.rs +++ b/tests/run-make/raw-dylib-alt-calling-convention/rmake.rs @@ -9,7 +9,9 @@ //@ only-x86 //@ only-windows -use run_make_support::{build_native_dynamic_lib, diff, is_msvc, run, run_with_args, rustc}; +use run_make_support::{ + build_native_dynamic_lib, diff, is_windows_msvc, run, run_with_args, rustc, +}; fn main() { rustc() @@ -21,7 +23,7 @@ fn main() { build_native_dynamic_lib("extern"); let out = run("driver").stdout_utf8(); diff().expected_file("output.txt").actual_text("actual", out).normalize(r#"\r"#, "").run(); - if is_msvc() { + if is_windows_msvc() { let out_msvc = run_with_args("driver", &["true"]).stdout_utf8(); diff() .expected_file("output.msvc.txt") diff --git a/tests/run-make/raw-dylib-import-name-type/rmake.rs b/tests/run-make/raw-dylib-import-name-type/rmake.rs index 13a2c99150e5b..71f255ab39f06 100644 --- a/tests/run-make/raw-dylib-import-name-type/rmake.rs +++ b/tests/run-make/raw-dylib-import-name-type/rmake.rs @@ -11,14 +11,14 @@ //@ only-windows // Reason: this test specifically exercises a 32bit Windows calling convention. -use run_make_support::{cc, diff, is_msvc, run, rustc}; +use run_make_support::{cc, diff, is_windows_msvc, run, rustc}; // NOTE: build_native_dynamic lib is not used, as the special `def` files // must be passed to the CC compiler. fn main() { rustc().crate_type("bin").input("driver.rs").run(); - if is_msvc() { + if is_windows_msvc() { cc().arg("-c").out_exe("extern").input("extern.c").run(); cc().input("extern.obj") .arg("extern.msvc.def") diff --git a/tests/run-make/raw-dylib-inline-cross-dylib/rmake.rs b/tests/run-make/raw-dylib-inline-cross-dylib/rmake.rs index 6e3b31a0cdbdc..a167e8198a7c8 100644 --- a/tests/run-make/raw-dylib-inline-cross-dylib/rmake.rs +++ b/tests/run-make/raw-dylib-inline-cross-dylib/rmake.rs @@ -7,7 +7,7 @@ //@ only-windows -use run_make_support::{cc, diff, is_msvc, llvm_objdump, run, rustc}; +use run_make_support::{cc, diff, is_windows_msvc, llvm_objdump, run, rustc}; fn main() { rustc() @@ -31,7 +31,7 @@ fn main() { .assert_stdout_not_contains("inline_library_function") // Make sure we do find an import to the functions we expect to be imported. .assert_stdout_contains("library_function"); - if is_msvc() { + if is_windows_msvc() { cc().arg("-c").out_exe("extern_1").input("extern_1.c").run(); cc().arg("-c").out_exe("extern_2").input("extern_2.c").run(); cc().input("extern_1.obj") diff --git a/tests/run-make/raw-dylib-link-ordinal/rmake.rs b/tests/run-make/raw-dylib-link-ordinal/rmake.rs index b52181ae3f9d6..43274b9765bb1 100644 --- a/tests/run-make/raw-dylib-link-ordinal/rmake.rs +++ b/tests/run-make/raw-dylib-link-ordinal/rmake.rs @@ -11,7 +11,7 @@ //@ only-windows -use run_make_support::{cc, diff, is_msvc, run, rustc}; +use run_make_support::{cc, diff, is_windows_msvc, run, rustc}; // NOTE: build_native_dynamic lib is not used, as the special `def` files // must be passed to the CC compiler. @@ -19,7 +19,7 @@ use run_make_support::{cc, diff, is_msvc, run, rustc}; fn main() { rustc().crate_type("lib").crate_name("raw_dylib_test").input("lib.rs").run(); rustc().crate_type("bin").input("driver.rs").run(); - if is_msvc() { + if is_windows_msvc() { cc().arg("-c").out_exe("exporter").input("exporter.c").run(); cc().input("exporter.obj") .arg("exporter.def") diff --git a/tests/run-make/raw-dylib-stdcall-ordinal/rmake.rs b/tests/run-make/raw-dylib-stdcall-ordinal/rmake.rs index 320ea1520d85f..f898cc0f8c8d4 100644 --- a/tests/run-make/raw-dylib-stdcall-ordinal/rmake.rs +++ b/tests/run-make/raw-dylib-stdcall-ordinal/rmake.rs @@ -10,7 +10,7 @@ //@ only-windows // Reason: this test specifically exercises a 32bit Windows calling convention. -use run_make_support::{cc, diff, is_msvc, run, rustc}; +use run_make_support::{cc, diff, is_windows_msvc, run, rustc}; // NOTE: build_native_dynamic lib is not used, as the special `def` files // must be passed to the CC compiler. @@ -18,7 +18,7 @@ use run_make_support::{cc, diff, is_msvc, run, rustc}; fn main() { rustc().crate_type("lib").crate_name("raw_dylib_test").input("lib.rs").run(); rustc().crate_type("bin").input("driver.rs").run(); - if is_msvc() { + if is_windows_msvc() { cc().arg("-c").out_exe("exporter").input("exporter.c").run(); cc().input("exporter.obj") .arg("exporter-msvc.def") diff --git a/tests/run-make/rlib-format-packed-bundled-libs/rmake.rs b/tests/run-make/rlib-format-packed-bundled-libs/rmake.rs index ff0438a6b72be..f0929a3ee85eb 100644 --- a/tests/run-make/rlib-format-packed-bundled-libs/rmake.rs +++ b/tests/run-make/rlib-format-packed-bundled-libs/rmake.rs @@ -8,8 +8,8 @@ // Reason: cross-compilation fails to export native symbols use run_make_support::{ - bin_name, build_native_static_lib, cwd, filename_contains, is_msvc, llvm_ar, llvm_nm, rfs, - rust_lib_name, rustc, shallow_find_files, + bin_name, build_native_static_lib, cwd, filename_contains, is_windows_msvc, llvm_ar, llvm_nm, + rfs, rust_lib_name, rustc, shallow_find_files, }; fn main() { @@ -74,7 +74,7 @@ fn main() { .assert_stdout_contains_regex("native_dep_1.*native_dep_2.*native_dep_3"); // The binary "main" will not contain any symbols on MSVC. - if !is_msvc() { + if !is_windows_msvc() { llvm_nm().input(bin_name("main")).run().assert_stdout_contains_regex("T.*native_f1"); llvm_nm().input(bin_name("main")).run().assert_stdout_contains_regex("T.*native_f2"); llvm_nm().input(bin_name("main")).run().assert_stdout_contains_regex("T.*native_f3"); diff --git a/tests/run-make/split-debuginfo/rmake.rs b/tests/run-make/split-debuginfo/rmake.rs index 530a5d119f136..e8de5aed17260 100644 --- a/tests/run-make/split-debuginfo/rmake.rs +++ b/tests/run-make/split-debuginfo/rmake.rs @@ -61,8 +61,8 @@ use std::collections::BTreeSet; use run_make_support::rustc::Rustc; use run_make_support::{ - cwd, has_extension, is_darwin, is_msvc, is_windows, llvm_dwarfdump, run_in_tmpdir, rustc, - shallow_find_directories, shallow_find_files, uname, + cwd, has_extension, is_darwin, is_windows, is_windows_msvc, llvm_dwarfdump, run_in_tmpdir, + rustc, shallow_find_directories, shallow_find_files, uname, }; /// `-C debuginfo`. See . @@ -1296,7 +1296,7 @@ fn main() { // identify which combination isn't exercised with a 6-layers nested for loop iterating through // each of the cli flag enum variants. - if is_msvc() { + if is_windows_msvc() { // FIXME: the windows-msvc test coverage is sparse at best. windows_msvc_tests::split_debuginfo(SplitDebuginfo::Off, DebuginfoLevel::Unspecified); diff --git a/tests/run-make/static-dylib-by-default/rmake.rs b/tests/run-make/static-dylib-by-default/rmake.rs index 133210c74e75a..b1160c632972d 100644 --- a/tests/run-make/static-dylib-by-default/rmake.rs +++ b/tests/run-make/static-dylib-by-default/rmake.rs @@ -9,7 +9,7 @@ // Reason: the compiled binary is executed use run_make_support::{ - cc, cwd, dynamic_lib_name, extra_c_flags, has_extension, is_msvc, rfs, run, rustc, + cc, cwd, dynamic_lib_name, extra_c_flags, has_extension, is_windows_msvc, rfs, run, rustc, shallow_find_files, }; @@ -22,13 +22,13 @@ fn main() { // bar.dll.exp // export library for the dylib // msvc's underlying link.exe requires the import library for the dynamic library as input. // That is why the library is bar.dll.lib, not bar.dll. - let library = if is_msvc() { "bar.dll.lib" } else { &dynamic_lib_name("bar") }; + let library = if is_windows_msvc() { "bar.dll.lib" } else { &dynamic_lib_name("bar") }; cc().input("main.c").out_exe("main").arg(library).args(extra_c_flags()).run(); for rlib in shallow_find_files(cwd(), |path| has_extension(path, "rlib")) { rfs::remove_file(rlib); } rfs::remove_file(dynamic_lib_name("foo")); - if is_msvc() { + if is_windows_msvc() { rfs::remove_file("foo.dll.lib"); } run("main"); diff --git a/tests/run-make/staticlib-dylib-linkage/rmake.rs b/tests/run-make/staticlib-dylib-linkage/rmake.rs index 8dd1ac0ffbdcd..9582ca19831c0 100644 --- a/tests/run-make/staticlib-dylib-linkage/rmake.rs +++ b/tests/run-make/staticlib-dylib-linkage/rmake.rs @@ -9,7 +9,7 @@ //@ ignore-wasm // Reason: WASM does not support dynamic libraries -use run_make_support::{cc, is_msvc, regex, run, rustc, static_lib_name}; +use run_make_support::{cc, is_windows_msvc, regex, run, rustc, static_lib_name}; fn main() { rustc().arg("-Cprefer-dynamic").input("bar.rs").run(); @@ -27,7 +27,7 @@ fn main() { let (_, native_link_args) = libs.split_once("note: native-static-libs: ").unwrap(); // divide the command-line arguments in a vec let mut native_link_args = native_link_args.split(' ').collect::>(); - if is_msvc() { + if is_windows_msvc() { // For MSVC pass the arguments on to the linker. native_link_args.insert(0, "-link"); } diff --git a/tests/run-make/symbol-visibility/rmake.rs b/tests/run-make/symbol-visibility/rmake.rs index 49c8e87707b64..e3d276d6da89b 100644 --- a/tests/run-make/symbol-visibility/rmake.rs +++ b/tests/run-make/symbol-visibility/rmake.rs @@ -9,7 +9,7 @@ // See https://github.com/rust-lang/rust/issues/37530 use run_make_support::object::read::Object; -use run_make_support::{bin_name, dynamic_lib_name, is_msvc, object, regex, rfs, rustc}; +use run_make_support::{bin_name, dynamic_lib_name, is_windows_msvc, object, regex, rfs, rustc}; fn main() { let cdylib_name = dynamic_lib_name("a_cdylib"); @@ -64,7 +64,7 @@ fn main() { ); // FIXME(nbdd0121): This is broken in MinGW, see https://github.com/rust-lang/rust/pull/95604#issuecomment-1101564032 - if is_msvc() { + if is_windows_msvc() { // Check that an executable does not export any dynamic symbols symbols_check(&exe_name, SymbolCheckType::StrSymbol("public_c_function_from_rlib"), false); symbols_check( @@ -130,7 +130,7 @@ fn main() { ); // FIXME(nbdd0121): This is broken in MinGW, see https://github.com/rust-lang/rust/pull/95604#issuecomment-1101564032 - if is_msvc() { + if is_windows_msvc() { // Check that an executable does not export any dynamic symbols symbols_check(&exe_name, SymbolCheckType::StrSymbol("public_c_function_from_rlib"), false); symbols_check( diff --git a/tests/ui-fulldeps/auxiliary/obtain-borrowck-input.rs b/tests/ui-fulldeps/auxiliary/obtain-borrowck-input.rs index 7213e06792a4a..9cfc901eabe5d 100644 --- a/tests/ui-fulldeps/auxiliary/obtain-borrowck-input.rs +++ b/tests/ui-fulldeps/auxiliary/obtain-borrowck-input.rs @@ -28,6 +28,10 @@ const fn foo() -> usize { 1 } +fn with_nested_body(opt: Option) -> Option { + opt.map(|x| x + 1) +} + fn main() { let bar: [Bar; foo()] = [Bar::new()]; assert_eq!(bar[0].provided(), foo()); diff --git a/tests/ui-fulldeps/obtain-borrowck.rs b/tests/ui-fulldeps/obtain-borrowck.rs index 84f6970c83a04..08213fd75880f 100644 --- a/tests/ui-fulldeps/obtain-borrowck.rs +++ b/tests/ui-fulldeps/obtain-borrowck.rs @@ -9,16 +9,17 @@ //! This program implements a rustc driver that retrieves MIR bodies with //! borrowck information. This cannot be done in a straightforward way because -//! `get_body_with_borrowck_facts`–the function for retrieving a MIR body with -//! borrowck facts–can panic if the body is stolen before it is invoked. +//! `get_bodies_with_borrowck_facts`–the function for retrieving MIR bodies with +//! borrowck facts–can panic if the bodies are stolen before it is invoked. //! Therefore, the driver overrides `mir_borrowck` query (this is done in the -//! `config` callback), which retrieves the body that is about to be borrow -//! checked and stores it in a thread local `MIR_BODIES`. Then, `after_analysis` +//! `config` callback), which retrieves the bodies that are about to be borrow +//! checked and stores them in a thread local `MIR_BODIES`. Then, `after_analysis` //! callback triggers borrow checking of all MIR bodies by retrieving //! `optimized_mir` and pulls out the MIR bodies with the borrowck information //! from the thread local storage. extern crate rustc_borrowck; +extern crate rustc_data_structures; extern crate rustc_driver; extern crate rustc_hir; extern crate rustc_interface; @@ -30,6 +31,7 @@ use std::collections::HashMap; use std::thread_local; use rustc_borrowck::consumers::{self, BodyWithBorrowckFacts, ConsumerOptions}; +use rustc_data_structures::fx::FxHashMap; use rustc_driver::Compilation; use rustc_hir::def::DefKind; use rustc_hir::def_id::LocalDefId; @@ -129,13 +131,15 @@ thread_local! { fn mir_borrowck<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> ProvidedValue<'tcx> { let opts = ConsumerOptions::PoloniusInputFacts; - let body_with_facts = consumers::get_body_with_borrowck_facts(tcx, def_id, opts); + let bodies_with_facts = consumers::get_bodies_with_borrowck_facts(tcx, def_id, opts); // SAFETY: The reader casts the 'static lifetime to 'tcx before using it. - let body_with_facts: BodyWithBorrowckFacts<'static> = - unsafe { std::mem::transmute(body_with_facts) }; + let bodies_with_facts: FxHashMap> = + unsafe { std::mem::transmute(bodies_with_facts) }; MIR_BODIES.with(|state| { let mut map = state.borrow_mut(); - assert!(map.insert(def_id, body_with_facts).is_none()); + for (def_id, body_with_facts) in bodies_with_facts { + assert!(map.insert(def_id, body_with_facts).is_none()); + } }); let mut providers = Providers::default(); rustc_borrowck::provide(&mut providers); diff --git a/tests/ui-fulldeps/obtain-borrowck.run.stdout b/tests/ui-fulldeps/obtain-borrowck.run.stdout index e011622e6b2a3..09d3e50f42dc3 100644 --- a/tests/ui-fulldeps/obtain-borrowck.run.stdout +++ b/tests/ui-fulldeps/obtain-borrowck.run.stdout @@ -3,6 +3,8 @@ Bodies retrieved for: ::foo ::main ::main::{constant#0} +::with_nested_body +::with_nested_body::{closure#0} ::{impl#0}::new ::{impl#1}::provided ::{impl#1}::required diff --git a/tests/ui/async-await/issues/issue-54752-async-block.rs b/tests/ui/async-await/issues/issue-54752-async-block.rs index 452b6794bee06..164c1885da11c 100644 --- a/tests/ui/async-await/issues/issue-54752-async-block.rs +++ b/tests/ui/async-await/issues/issue-54752-async-block.rs @@ -4,4 +4,3 @@ //@ pp-exact fn main() { let _a = (async { }); } -//~^ WARNING unnecessary parentheses around assigned value diff --git a/tests/ui/async-await/issues/issue-54752-async-block.stderr b/tests/ui/async-await/issues/issue-54752-async-block.stderr deleted file mode 100644 index 8cc849dd98544..0000000000000 --- a/tests/ui/async-await/issues/issue-54752-async-block.stderr +++ /dev/null @@ -1,15 +0,0 @@ -warning: unnecessary parentheses around assigned value - --> $DIR/issue-54752-async-block.rs:6:22 - | -LL | fn main() { let _a = (async { }); } - | ^ ^ - | - = note: `#[warn(unused_parens)]` on by default -help: remove these parentheses - | -LL - fn main() { let _a = (async { }); } -LL + fn main() { let _a = async { }; } - | - -warning: 1 warning emitted - diff --git a/tests/ui/lint/unused/closure-body-issue-136741.fixed b/tests/ui/lint/unused/closure-body-issue-136741.fixed new file mode 100644 index 0000000000000..2ded52544b992 --- /dev/null +++ b/tests/ui/lint/unused/closure-body-issue-136741.fixed @@ -0,0 +1,36 @@ +//@ run-rustfix +// ignore-tidy-linelength +#![deny(unused_parens)] +#![deny(unused_braces)] + +fn long_expr_that_does_not_require_braces_long_expr_that_does_not_require_braces_long_expr_that_does_not_require_braces() +{} + +fn func(f: impl FnOnce()) { + f() +} + +pub fn main() { + let _closure = |x: i32, y: i32| { x * (x + (y * 2)) }; + let _ = || 0 == 0; //~ ERROR unnecessary parentheses around closure body + let _ = (0..).find(|n| n % 2 == 0); //~ ERROR unnecessary parentheses around closure body + let _ = (0..).find(|n| {n % 2 == 0}); + + // multiple lines of code will not lint with braces + let _ = (0..).find(|n| { + n % 2 == 0 + }); + + // multiple lines of code will lint with parentheses + let _ = (0..).find(|n| n % 2 == 0); + + let _ = || { + _ = 0; + 0 == 0 //~ ERROR unnecessary parentheses around block return value + }; + + // long expressions will not lint with braces + func(|| { + long_expr_that_does_not_require_braces_long_expr_that_does_not_require_braces_long_expr_that_does_not_require_braces() + }) +} diff --git a/tests/ui/lint/unused/closure-body-issue-136741.rs b/tests/ui/lint/unused/closure-body-issue-136741.rs new file mode 100644 index 0000000000000..4eac981ec2ede --- /dev/null +++ b/tests/ui/lint/unused/closure-body-issue-136741.rs @@ -0,0 +1,38 @@ +//@ run-rustfix +// ignore-tidy-linelength +#![deny(unused_parens)] +#![deny(unused_braces)] + +fn long_expr_that_does_not_require_braces_long_expr_that_does_not_require_braces_long_expr_that_does_not_require_braces() +{} + +fn func(f: impl FnOnce()) { + f() +} + +pub fn main() { + let _closure = |x: i32, y: i32| { x * (x + (y * 2)) }; + let _ = || (0 == 0); //~ ERROR unnecessary parentheses around closure body + let _ = (0..).find(|n| (n % 2 == 0)); //~ ERROR unnecessary parentheses around closure body + let _ = (0..).find(|n| {n % 2 == 0}); + + // multiple lines of code will not lint with braces + let _ = (0..).find(|n| { + n % 2 == 0 + }); + + // multiple lines of code will lint with parentheses + let _ = (0..).find(|n| ( //~ ERROR unnecessary parentheses around closure body + n % 2 == 0 + )); + + let _ = || { + _ = 0; + (0 == 0) //~ ERROR unnecessary parentheses around block return value + }; + + // long expressions will not lint with braces + func(|| { + long_expr_that_does_not_require_braces_long_expr_that_does_not_require_braces_long_expr_that_does_not_require_braces() + }) +} diff --git a/tests/ui/lint/unused/closure-body-issue-136741.stderr b/tests/ui/lint/unused/closure-body-issue-136741.stderr new file mode 100644 index 0000000000000..2ea872c08c7ac --- /dev/null +++ b/tests/ui/lint/unused/closure-body-issue-136741.stderr @@ -0,0 +1,62 @@ +error: unnecessary parentheses around closure body + --> $DIR/closure-body-issue-136741.rs:15:16 + | +LL | let _ = || (0 == 0); + | ^ ^ + | +note: the lint level is defined here + --> $DIR/closure-body-issue-136741.rs:3:9 + | +LL | #![deny(unused_parens)] + | ^^^^^^^^^^^^^ +help: remove these parentheses + | +LL - let _ = || (0 == 0); +LL + let _ = || 0 == 0; + | + +error: unnecessary parentheses around closure body + --> $DIR/closure-body-issue-136741.rs:16:28 + | +LL | let _ = (0..).find(|n| (n % 2 == 0)); + | ^ ^ + | +help: remove these parentheses + | +LL - let _ = (0..).find(|n| (n % 2 == 0)); +LL + let _ = (0..).find(|n| n % 2 == 0); + | + +error: unnecessary parentheses around closure body + --> $DIR/closure-body-issue-136741.rs:25:28 + | +LL | let _ = (0..).find(|n| ( + | _____________________________^ +LL | | n % 2 == 0 + | | ________^__________^ + | ||________| + | | +LL | | )); + | |_____^ + | +help: remove these parentheses + | +LL - let _ = (0..).find(|n| ( +LL - n % 2 == 0 +LL + let _ = (0..).find(|n| n % 2 == 0); + | + +error: unnecessary parentheses around block return value + --> $DIR/closure-body-issue-136741.rs:31:9 + | +LL | (0 == 0) + | ^ ^ + | +help: remove these parentheses + | +LL - (0 == 0) +LL + 0 == 0 + | + +error: aborting due to 4 previous errors + diff --git a/triagebot.toml b/triagebot.toml index 6b989102f1237..9f8ea2dad52fe 100644 --- a/triagebot.toml +++ b/triagebot.toml @@ -535,6 +535,9 @@ trigger_files = [ [autolabel."S-waiting-on-review"] new_pr = true +[autolabel."S-waiting-on-author"] +new_draft = true + [autolabel."needs-triage"] new_issue = true exclude_labels = [ @@ -1089,6 +1092,10 @@ cc = ["@jieyouxu"] message = "The list of allowed third-party dependencies may have been modified! You must ensure that any new dependencies have compatible licenses before merging." cc = ["@davidtwco", "@wesleywiser"] +[mentions."src/tools/tidy/src/ext_tool_checks.rs"] +message = "`tidy` extra checks were modified." +cc = ["@lolbinarycat"] + [mentions."src/bootstrap/src/core/config"] message = """ This PR modifies `src/bootstrap/src/core/config`.