diff --git a/.github/workflows/post-merge.yml b/.github/workflows/post-merge.yml index 7200aa22a4162..f47d490839f88 100644 --- a/.github/workflows/post-merge.yml +++ b/.github/workflows/post-merge.yml @@ -1,7 +1,10 @@ -# Workflow that runs after a merge to the default branch, analyses changes in test executions -# and posts the result to the merged PR. +# Workflow that runs after a merge to the default branch. +# It performs two things: +# 1) Analyses changes in test executions and posts the result to the merged PR. +# 2) Performs a cargo publish on crates published from the `rust-lang/rust` repository, and if a +# publish happened, post the result to the merged PR. -name: Post merge analysis +name: Post merge workflow on: push: @@ -13,7 +16,7 @@ jobs: runs-on: ubuntu-26.04 if: github.repository == 'rust-lang/rust' permissions: - pull-requests: write + pull-requests: write # For sending a PR comment steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -21,6 +24,7 @@ jobs: # Since all merges should be through merge commits, fetching two commits # should be enough to get the parent bors merge commit. fetch-depth: 2 + persist-credentials: false - name: Perform analysis and send PR env: GH_TOKEN: ${{ github.token }} @@ -51,3 +55,27 @@ jobs: cat output.log gh pr comment ${HEAD_PR} -F output.log + publish: + runs-on: ubuntu-26.04 + if: github.repository == 'rust-lang/rust' + environment: publish-crates-io + permissions: + id-token: write # For OIDC crates.io publishing + pull-requests: write # For sending a PR comment + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: rust-lang/crates-io-auth-action@3268eb413133e2960fa4ae0e963ca76380c54cd9 # v1.0.6 + id: auth + - run: | + # Give GitHub some time to propagate the information that the PR was merged + sleep 60 + + # Publish backtrace + ./src/ci/publish_backtrace.sh + env: + CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }} + GH_TOKEN: ${{ github.token }} + GITHUB_SHA: ${{ github.sha }} + TEMPDIR: ${{ runner.temp }} diff --git a/Cargo.lock b/Cargo.lock index 8b041958d58b4..bae8add757e7f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -360,7 +360,7 @@ dependencies = [ "serde_json", "sha2", "tar", - "toml 0.7.8", + "toml 0.8.23", "xz2", ] @@ -5780,7 +5780,7 @@ dependencies = [ "similar", "tempfile", "termcolor", - "toml 0.7.8", + "toml 0.8.23", "walkdir", ] @@ -5824,18 +5824,6 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" -[[package]] -name = "toml" -version = "0.7.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd79e69d3b627db300ff956027cc6c3798cef26d22526befdfcd12feeb6d2257" -dependencies = [ - "serde", - "serde_spanned 0.6.9", - "toml_datetime 0.6.11", - "toml_edit 0.19.15", -] - [[package]] name = "toml" version = "0.8.23" @@ -5845,7 +5833,7 @@ dependencies = [ "serde", "serde_spanned 0.6.9", "toml_datetime 0.6.11", - "toml_edit 0.22.27", + "toml_edit", ] [[package]] @@ -5881,19 +5869,6 @@ dependencies = [ "serde_core", ] -[[package]] -name = "toml_edit" -version = "0.19.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" -dependencies = [ - "indexmap", - "serde", - "serde_spanned 0.6.9", - "toml_datetime 0.6.11", - "winnow 0.5.40", -] - [[package]] name = "toml_edit" version = "0.22.27" @@ -6776,15 +6751,6 @@ dependencies = [ "windows-link 0.2.1", ] -[[package]] -name = "winnow" -version = "0.5.40" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f593a95398737aeed53e489c785df13f3618e41dbcd6718c6addbf1395aa6876" -dependencies = [ - "memchr", -] - [[package]] name = "winnow" version = "0.7.13" diff --git a/bootstrap.example.toml b/bootstrap.example.toml index 6740de03eb800..fd1dd589b5b79 100644 --- a/bootstrap.example.toml +++ b/bootstrap.example.toml @@ -474,9 +474,13 @@ # linked or not. #build.cargo-native-static = false -# Run the build with low priority, by setting the process group's "nice" value -# to +10 on Unix platforms, and by using a "low priority" job object on Windows. -#build.low-priority = false +# Run the build with low priority, by setting the process's "nice" value to +10 +# on Unix platforms, and by using a "low priority" job object on Windows. +# This will improve the responsiveness of foreground tasks and will not slow the +# build down unless there are competing CPU-saturating jobs, so there is +# typically no reason to opt out of this behavior. See the discussion in +# https://github.com/rust-lang/rust/pull/165707 for more details. +#build.low-priority = true # Arguments passed to the `./configure` script, used during distcheck. You # probably won't fill this in but rather it's filled in by the `./configure` diff --git a/compiler/rustc_attr_ir/src/data_structures.rs b/compiler/rustc_attr_ir/src/data_structures.rs index 0f78810054963..26db9819bb7ca 100644 --- a/compiler/rustc_attr_ir/src/data_structures.rs +++ b/compiler/rustc_attr_ir/src/data_structures.rs @@ -960,7 +960,7 @@ pub enum AttributeKind { InstrumentFn(InstrumentFnAttr), /// Represents `#[lang]` - Lang(LangItem), + Lang(LangItem, Span), /// Represents `#[link]`. Link(ThinVec, Span), diff --git a/compiler/rustc_attr_ir/src/encode_cross_crate.rs b/compiler/rustc_attr_ir/src/encode_cross_crate.rs index 73c7c5598f36a..ca9b79ccc8a51 100644 --- a/compiler/rustc_attr_ir/src/encode_cross_crate.rs +++ b/compiler/rustc_attr_ir/src/encode_cross_crate.rs @@ -262,7 +262,7 @@ impl AttributeKind { Inline(..) => false, InstructionSet(..) => false, InstrumentFn(..) => false, - Lang(item) => item.link_name().is_some(), + Lang(item, _) => item.link_name().is_some(), Link(..) => false, LinkName { .. } => false, LinkOrdinal { .. } => false, diff --git a/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs b/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs index a09431fcbced9..ffd48612d0ec3 100644 --- a/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs +++ b/compiler/rustc_attr_parsing/src/attributes/codegen_attrs.rs @@ -390,7 +390,7 @@ impl NoArgsAttributeParser for TrackCallerParser { Target::Fn => { // `#[track_caller]` is not valid on weak lang items because they are called via // `extern` declarations and `#[track_caller]` would alter their ABI. - if let Some(item) = find_attr!(cx.parsed_attrs, Lang(item) => item) + if let Some(item) = find_attr!(cx.parsed_attrs, Lang(item, _) => item) && item.is_weak() { cx.emit_err(TrackCallerOnLangItem { diff --git a/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs b/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs index cf1209f717d22..629a4ba305584 100644 --- a/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs +++ b/compiler/rustc_attr_parsing/src/attributes/rustc_internal.rs @@ -569,7 +569,7 @@ impl SingleAttributeParser for LangParser { let allowed_targets: &[_] = &[Allow(lang_item.target())]; cx.check_target(&format!(" = \"{name}\""), &AllowedTargets::AllowList(allowed_targets)); - Some(AttributeKind::Lang(lang_item)) + Some(AttributeKind::Lang(lang_item, cx.attr_span)) } } @@ -594,7 +594,7 @@ impl NoArgsAttributeParser for PanicHandlerParser { const PATH: &[Symbol] = &[sym::panic_handler]; const ALLOWED_TARGETS: AllowedTargets<'_> = AllowedTargets::AllowList(&[Allow(Target::Fn)]); const STABILITY: AttributeStability = AttributeStability::Stable; - const CREATE: fn(Span) -> AttributeKind = |_| AttributeKind::Lang(LangItem::PanicImpl); + const CREATE: fn(Span) -> AttributeKind = |s| AttributeKind::Lang(LangItem::PanicImpl, s); } pub(crate) struct RustcNounwindParser; diff --git a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs index 8f7970da96402..6b58ffff687bd 100644 --- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs +++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs @@ -563,7 +563,7 @@ fn handle_lang_items( attrs: &[Attribute], codegen_fn_attrs: &mut CodegenFnAttrs, ) { - let lang_item = find_attr!(attrs, Lang(lang) => lang); + let lang_item = find_attr!(attrs, Lang(lang, _) => lang); // Weak lang items have the same semantics as "std internal" symbols in the // sense that they're preserved through all our LTO passes and only diff --git a/compiler/rustc_const_eval/src/const_eval/machine.rs b/compiler/rustc_const_eval/src/const_eval/machine.rs index 3e6329cfe0a12..11e463727d838 100644 --- a/compiler/rustc_const_eval/src/const_eval/machine.rs +++ b/compiler/rustc_const_eval/src/const_eval/machine.rs @@ -838,6 +838,50 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> { }; } + sym::type_id_docs => { + let ty = ecx.read_type_id(&args[0])?; + let attrs = match ty.kind() { + ty::Adt(def, args) + if let Some(FieldInfo { base, variant_idx, field_idx, .. }) = + def.field_representing_type_info(ecx.tcx(), *args) => + { + match base.kind() { + ty::Adt(base_def, _) => { + let field = &base_def.variants()[variant_idx].fields[field_idx]; + Some(field.did) + } + ty::Tuple(_) => None, + _ => { + // only adts and tuples have fields + span_bug!(ecx.cur_span(), "expected adt or tuple type, got {ty}"); + } + } + } + ty::Adt(def, _) => Some(def.did()), + _ => None, + }; + + ecx.write_doc_attributes(dest, attrs)?; + } + + sym::type_id_variant_docs => { + let base = ecx.read_type_id(&args[0])?; + + if let ty::Adt(def, _) = base.kind() { + let variant_idx = ecx.read_target_usize(&args[1])? as usize; + if variant_idx >= def.variants().len() { + throw_ub!(BoundsCheckFailed { + len: def.variants().len() as u64, + index: variant_idx as u64 + }); + } + let var = def.variant(VariantIdx::from_usize(variant_idx)).def_id; + ecx.write_doc_attributes(dest, Some(var))?; + } else { + span_bug!(ecx.cur_span(), "expected enum type, got {base}") + }; + } + sym::type_id_variant_non_exhaustive => { let base = ecx.read_type_id(&args[0])?; diff --git a/compiler/rustc_const_eval/src/const_eval/type_info.rs b/compiler/rustc_const_eval/src/const_eval/type_info.rs index b31fb5904e7d1..f1700e57e6585 100644 --- a/compiler/rustc_const_eval/src/const_eval/type_info.rs +++ b/compiler/rustc_const_eval/src/const_eval/type_info.rs @@ -3,13 +3,14 @@ mod adt; use std::borrow::Cow; use rustc_abi::{ExternAbi, FieldIdx}; -use rustc_attr_ir::AttrItem; use rustc_attr_ir::Attribute::Tool; use rustc_attr_ir::lang_items::LangItem; +use rustc_attr_ir::{AttrItem, Attribute, AttributeKind, HasAttrs}; use rustc_hir::intravisit::HirTyCtxt; use rustc_lint_defs::{Reflectiveness, ToolOptions}; use rustc_middle::ty::layout::{HasTyCtxt, TyAndLayout}; use rustc_middle::ty::{self, FnHeader, FnSigKind, FnSigTys, ScalarInt, Ty, TyCtxt}; +use rustc_span::def_id::DefId; use rustc_span::{Symbol, span_bug, sym}; use crate::const_eval::CompileTimeMachine; @@ -393,4 +394,44 @@ impl<'tcx> InterpCx<'tcx, CompileTimeMachine<'tcx>> { ) }) } + + pub(crate) fn write_doc_attributes( + &mut self, + place: &impl Writeable<'tcx, CtfeProvenance>, + def_id: Option, + ) -> InterpResult<'tcx> { + // only the doc comments of exported items are encoded in cross-crate metadata + // see `rustc_metadata::rmeta::encoder::EncodeContext::encode_attrs` + // this mirrors the check so that we return the same comments regardless of crate + let attrs = if let Some(d) = def_id + && d.as_local().map_or(true, |d| { + !self.tcx.needs_metadata() || self.tcx.effective_visibilities(()).is_exported(d) + }) { + d.get_attrs(&self.tcx) + } else { + &[] + }; + + let docs = attrs + .iter() + .filter_map(|x| match x { + Attribute::Parsed(AttributeKind::DocComment { comment, .. }) => Some(*comment), + _ => None, + }) + .collect::>(); + + self.allocate_fill_and_write_slice_ptr(place, docs.len() as _, |this, i, place| { + let doc = docs[i as usize]; + + let ptr = this.allocate_bytes_dedup(doc.as_str().as_bytes())?; + + this.write_immediate( + Immediate::ScalarPair( + Scalar::from_pointer(ptr, this), + Scalar::from_target_usize(doc.as_str().len() as u64, this), + ), + &place, + ) + }) + } } diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs index e797133ac2025..fa9e5b2be679b 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs @@ -14,6 +14,7 @@ use rustc_middle::ty::{ }; use rustc_span::def_id::ModId; use rustc_span::{Span, span_bug}; +use rustc_trait_selection::error_reporting::traits::suggest_new_overflow_limit; use rustc_trait_selection::regions::InferCtxtRegionExt; use rustc_trait_selection::traits::{ObligationCtxt, elaborate, normalize_param_env_or_error}; @@ -286,10 +287,12 @@ impl<'tcx> TypeVisitor> for ImplTraitInTraitCollector<'tcx> { && self.tcx.is_impl_trait_in_trait(proj.kind) { if !self.tcx.recursion_limit().value_within_limit(self.depth) { - self.tcx.dcx().span_delayed_bug( + let mut err = self.tcx.dcx().struct_span_err( self.tcx.def_span(proj.kind), "recursion limit exceeded while collecting implied RPITIT bounds", ); + suggest_new_overflow_limit(self.tcx, &mut err); + err.emit(); return ControlFlow::Break(()); } if self.types.insert(proj) { diff --git a/compiler/rustc_hir_analysis/src/check/intrinsic.rs b/compiler/rustc_hir_analysis/src/check/intrinsic.rs index 9595d1cbb9428..f15febe2c1633 100644 --- a/compiler/rustc_hir_analysis/src/check/intrinsic.rs +++ b/compiler/rustc_hir_analysis/src/check/intrinsic.rs @@ -156,6 +156,7 @@ fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: LocalDefId) -> hi | sym::trunc | sym::type_id | sym::type_id_array_len + | sym::type_id_docs | sym::type_id_element_ty | sym::type_id_eq | sym::type_id_field_representing_type @@ -169,6 +170,7 @@ fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: LocalDefId) -> hi | sym::type_id_reflected_attrs | sym::type_id_size_of | sym::type_id_type_of + | sym::type_id_variant_docs | sym::type_id_variant_name | sym::type_id_variant_non_exhaustive | sym::type_id_variant_reflected_attrs @@ -323,6 +325,26 @@ pub(crate) fn check_intrinsic_type( sym::type_id_variant_name => { (0, 0, vec![type_id_ty(), tcx.types.usize], Ty::new_static_str(tcx)) } + sym::type_id_variant_docs => ( + 0, + 0, + vec![type_id_ty(), tcx.types.usize], + Ty::new_imm_ref( + tcx, + tcx.lifetimes.re_static, + Ty::new_slice(tcx, Ty::new_static_str(tcx)), + ), + ), + sym::type_id_docs => ( + 0, + 0, + vec![type_id_ty()], + Ty::new_imm_ref( + tcx, + tcx.lifetimes.re_static, + Ty::new_slice(tcx, Ty::new_static_str(tcx)), + ), + ), sym::type_id_variant_non_exhaustive => { (0, 0, vec![type_id_ty(), tcx.types.usize], tcx.types.bool) } diff --git a/compiler/rustc_hir_typeck/src/intrinsicck.rs b/compiler/rustc_hir_typeck/src/intrinsicck.rs index 364b7e35ae920..5d54d150c9fef 100644 --- a/compiler/rustc_hir_typeck/src/intrinsicck.rs +++ b/compiler/rustc_hir_typeck/src/intrinsicck.rs @@ -57,6 +57,13 @@ fn skeleton_string<'tcx>( bug!("{:?} overflow for u128", size) } } + Ok(SizeSkeleton::Array { base, const_lens, .. }) => { + let base_bits = u128::from(base.bytes()) + .checked_mul(8) + .unwrap_or_else(|| bug!("{:?} overflow for u128", base)); + let lens = const_lens.iter().map(|l| format!("({l})")).collect::>().join(" * "); + format!("{base_bits} * {lens} bits") + } Err(LayoutError::TooGeneric(bad)) => { if *bad == ty { "this type does not have a fixed size".to_owned() @@ -97,10 +104,10 @@ fn check_transmute<'tcx>( trace!(?sk_from, ?sk_to); // Check for same size using the skeletons. - if let Ok(sk_from) = sk_from - && let Ok(sk_to) = sk_to + if let Ok(sk_from) = &sk_from + && let Ok(sk_to) = &sk_to { - if sk_from.same_size(sk_to) { + if sk_from.same_size(&sk_to) { return Ok(()); } @@ -109,7 +116,7 @@ fn check_transmute<'tcx>( let from = unpack_option_like(tcx, from); if let ty::FnDef(..) = from.kind() && let SizeSkeleton::Known(size_to, _) = sk_to - && size_to == Pointer(tcx.data_layout.instruction_address_space).size(&tcx) + && *size_to == Pointer(tcx.data_layout.instruction_address_space).size(&tcx) { struct_span_code_err!(tcx.sess.dcx(), span, E0591, "can't transmute zero-sized type") .with_note(format!("source type: {from}")) diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index b66e06a93a074..35d8cfda63644 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -982,7 +982,7 @@ pub(crate) fn repr_nullable_ptr<'tcx>( // being applied (and we've got a problem somewhere). let compute_size_skeleton = |t| SizeSkeleton::compute(t, tcx, typing_env, DUMMY_SP).ok(); - if !compute_size_skeleton(ty)?.same_size(compute_size_skeleton(field_ty)?) { + if !compute_size_skeleton(ty)?.same_size(&compute_size_skeleton(field_ty)?) { bug!("improper_ctypes: Option nonnull optimization not applied?"); } diff --git a/compiler/rustc_middle/src/middle/lang_items.rs b/compiler/rustc_middle/src/middle/lang_items.rs index 9d07c2edeb386..85b1150bc96c5 100644 --- a/compiler/rustc_middle/src/middle/lang_items.rs +++ b/compiler/rustc_middle/src/middle/lang_items.rs @@ -12,7 +12,7 @@ use rustc_hir::def_id::DefId; use rustc_span::Span; use rustc_target::spec::PanicStrategy; -use crate::ty::{self, TyCtxt}; +use crate::ty::{self, Asyncness, TyCtxt}; impl<'tcx> TyCtxt<'tcx> { /// Returns the `DefId` for a given `LangItem`. @@ -44,6 +44,22 @@ impl<'tcx> TyCtxt<'tcx> { } } + /// Given a [`DefId`] of one of the [`Fn`], [`FnMut`], [`FnOnce`], [`AsyncFn`], [`AsyncFnMut`], or [`AsyncFnOnce`] traits, + /// returns a corresponding [`ty::ClosureKind`] and [`Asyncness`]. + /// For any other [`DefId`] return `None`. + pub fn maybe_async_fn_trait_kind_from_def_id( + self, + id: DefId, + ) -> Option<(Asyncness, ty::ClosureKind)> { + if let Some(kind) = self.fn_trait_kind_from_def_id(id) { + Some((Asyncness::No, kind)) + } else if let Some(kind) = self.async_fn_trait_kind_from_def_id(id) { + Some((Asyncness::Yes, kind)) + } else { + return None; + } + } + /// Given a [`DefId`] of one of the `AsyncFn`, `AsyncFnMut` or `AsyncFnOnce` traits, /// returns a corresponding [`ty::ClosureKind`]. /// For any other [`DefId`] return `None`. diff --git a/compiler/rustc_middle/src/ty/layout.rs b/compiler/rustc_middle/src/ty/layout.rs index 57ac2b672f43c..33b6cbde77437 100644 --- a/compiler/rustc_middle/src/ty/layout.rs +++ b/compiler/rustc_middle/src/ty/layout.rs @@ -16,6 +16,7 @@ use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, Spanned, Symbol, bug, span_bug use rustc_structures::Limit; use rustc_target::callconv::FnAbi; use rustc_target::spec::{HasTargetSpec, HasX86AbiOpt, Target, X86Abi}; +use rustc_type_ir::Const; use tracing::debug; use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags; @@ -333,12 +334,21 @@ impl<'tcx> LayoutCx<'tcx> { /// While this is conservative, (aside from constant sizes, only pointers, /// newtypes thereof and null pointer optimized enums are allowed), it is /// enough to statically check common use cases of transmute. -#[derive(Copy, Clone, Debug)] +#[derive(Clone, Debug)] pub enum SizeSkeleton<'tcx> { /// Any statically computable Layout. /// Alignment can be `None` if unknown. Known(Size, Option), + /// An array with unevaluated const lengths. + Array { + /// The base size, including the element size and all known array + /// lengths accumulated. + base: Size, + align: Option, + const_lens: Vec>>, + }, + /// A potentially-wide pointer. Pointer { /// If true, this pointer is never null. @@ -471,9 +481,25 @@ impl<'tcx> SizeSkeleton<'tcx> { .checked_mul(c) .ok_or_else(|| &*tcx.arena.alloc(LayoutError::SizeOverflow(ty)))?; // Alignment is unchanged by arrays. - return Ok(SizeSkeleton::Known(Size::from_bytes(size), a)); + Ok(SizeSkeleton::Known(Size::from_bytes(size), a)) + } else if s.bytes() == 0 { + Ok(SizeSkeleton::Known(s, a)) + } else { + Ok(SizeSkeleton::Array { base: s, align: a, const_lens: vec![len] }) + } + } + SizeSkeleton::Array { mut base, align, mut const_lens } => { + match len_eval { + Some(c) => { + base = Size::from_bytes(base.bytes().checked_mul(c).ok_or_else( + || &*tcx.arena.alloc(LayoutError::SizeOverflow(ty)), + )?); + } + None => { + const_lens.push(len); + } } - Err(err) + Ok(SizeSkeleton::Array { base, align, const_lens }) } SizeSkeleton::Pointer { .. } => Err(err), } @@ -537,6 +563,9 @@ impl<'tcx> SizeSkeleton<'tcx> { return Err(err); } } + SizeSkeleton::Array { .. } => { + return Err(err); + } SizeSkeleton::Pointer { .. } => { if ptr.is_some() { return Err(err); @@ -590,7 +619,8 @@ impl<'tcx> SizeSkeleton<'tcx> { // But in the case of `!null` patterns we need to note that in the // raw pointer. ty::PatternKind::NotNull => match base? { - SizeSkeleton::Known(..) => base, + known @ SizeSkeleton::Known(..) => Ok(known), + array @ SizeSkeleton::Array { .. } => Ok(array), SizeSkeleton::Pointer { non_zero: _, tail } => { Ok(SizeSkeleton::Pointer { non_zero: true, tail }) } @@ -602,12 +632,16 @@ impl<'tcx> SizeSkeleton<'tcx> { } } - pub fn same_size(self, other: SizeSkeleton<'tcx>) -> bool { + pub fn same_size(&self, other: &SizeSkeleton<'tcx>) -> bool { match (self, other) { (SizeSkeleton::Known(a, _), SizeSkeleton::Known(b, _)) => a == b, (SizeSkeleton::Pointer { tail: a, .. }, SizeSkeleton::Pointer { tail: b, .. }) => { a == b } + ( + SizeSkeleton::Array { base: a, const_lens: al, .. }, + SizeSkeleton::Array { base: b, const_lens: bl, .. }, + ) => a == b && al == bl, _ => false, } } diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 89cb8ee4bd38d..53e4cf0f92e89 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -243,6 +243,14 @@ impl Asyncness { pub fn is_async(self) -> bool { matches!(self, Asyncness::Yes) } + + /// Returns "Async" if [`Self::Yes`], otherwise returns an empty string slice. + pub fn as_trait_prefix_str(&self) -> &'static str { + match self { + Asyncness::Yes => "Async", + Asyncness::No => "", + } + } } #[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, Encodable, BlobDecodable, StableHash)] diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index 892e7f78c4624..ea16cb64123e8 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -1038,9 +1038,40 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { ty::View(def, args, fields) => { write!(self, "view_type!(")?; self.print_def_path(def.did(), args)?; - write!(self, ".{{ ")?; - self.print_type(fields)?; - write!(self, " }})")?; + write!(self, ".{{")?; + match fields.kind() { + ty::Tuple(fields) => { + let mut first = true; + if !fields.is_empty() { + write!(self, " ")?; + } + for field in fields.iter() { + if first { + first = false; + } else { + write!(self, ", ")?; + } + + match field.kind() { + ty::Adt(def_, args_) + if let Some(FieldInfo { variant, name, .. }) = + def_.field_representing_type_info(self.tcx(), *args_) => + { + // sanity check: view types on enums are not a thing. + debug_assert!(variant.is_none()); + write!(self, "{name}")?; + } + _ => self.print_type(field)?, + } + } + if !fields.is_empty() { + write!(self, " ")?; + } + } + + _ => self.print_type(fields)?, + } + write!(self, "}})")?; } } diff --git a/compiler/rustc_mir_transform/src/check_enums.rs b/compiler/rustc_mir_transform/src/check_enums.rs index 6cc12f48debb8..82945c8974827 100644 --- a/compiler/rustc_mir_transform/src/check_enums.rs +++ b/compiler/rustc_mir_transform/src/check_enums.rs @@ -347,8 +347,32 @@ fn insert_direct_enum_check<'tcx>( source_info: SourceInfo, new_block: BasicBlock, ) { + // Local for masked out bits of the discriminant type. + let discr_masked = + local_decls.push(LocalDecl::with_source_info(tcx.types.u128, source_info)).into(); + // Insert a new target block that is branched to in case of an invalid discriminant. - let invalid_discr_block_data = BasicBlockData::maybe_unterminated(None, false); + let invalid_discr_block_data = BasicBlockData::new( + Terminator { + source_info, + kind: TerminatorKind::Assert { + cond: Operand::Constant(Box::new(ConstOperand { + span: source_info.span, + user_ty: None, + const_: Const::Val(ConstValue::from_bool(false), tcx.types.bool), + })), + expected: true, + target: new_block, + msg: Box::new(AssertKind::InvalidEnumConstruction(Operand::Copy(discr_masked))), + // This calls panic_invalid_enum_construction, which is #[rustc_nounwind]. + // We never want to insert an unwind into unsafe code, because unwinding could + // make a failing UB check turn into much worse UB when we start unwinding. + unwind: UnwindAction::Unreachable, + }, + }, + false, + ); + let invalid_discr_block = basic_blocks.push(invalid_discr_block_data); let block_data = &mut basic_blocks[current_block]; let discr_place = insert_discr_cast_to_u128( @@ -364,8 +388,6 @@ fn insert_direct_enum_check<'tcx>( // Mask out the bits of the discriminant type. let mask = discr.size.unsigned_int_max(); - let discr_masked = - local_decls.push(LocalDecl::with_source_info(tcx.types.u128, source_info)).into(); let rvalue = Rvalue::BinaryOp( BinOp::BitAnd, Box::new(( @@ -394,25 +416,6 @@ fn insert_direct_enum_check<'tcx>( ), }, }); - - // Abort in case of an invalid enum discriminant. - basic_blocks[invalid_discr_block].terminator = Some(Terminator { - source_info, - kind: TerminatorKind::Assert { - cond: Operand::Constant(Box::new(ConstOperand { - span: source_info.span, - user_ty: None, - const_: Const::Val(ConstValue::from_bool(false), tcx.types.bool), - })), - expected: true, - target: new_block, - msg: Box::new(AssertKind::InvalidEnumConstruction(Operand::Copy(discr_masked))), - // This calls panic_invalid_enum_construction, which is #[rustc_nounwind]. - // We never want to insert an unwind into unsafe code, because unwinding could - // make a failing UB check turn into much worse UB when we start unwinding. - unwind: UnwindAction::Unreachable, - }, - }); } fn insert_uninhabited_enum_check<'tcx>( diff --git a/compiler/rustc_mir_transform/src/check_pointers.rs b/compiler/rustc_mir_transform/src/check_pointers.rs index 0c73e3af0eb00..079ceefae65e2 100644 --- a/compiler/rustc_mir_transform/src/check_pointers.rs +++ b/compiler/rustc_mir_transform/src/check_pointers.rs @@ -88,34 +88,56 @@ pub(crate) fn check_pointers<'tcx, F>( for (local, ty, context) in finder.into_found_pointers() { debug!("Inserting check for {:?}", ty); - let new_block = split_block(basic_blocks, location); - - // Invoke `on_finding` which appends to `local_decls` and the - // blocks statements. It returns information about the assert - // we're performing in the Terminator. - let block_data = &mut basic_blocks[block]; - let pointer_check = on_finding( - tcx, - local, - ty, - context, - local_decls, - &mut block_data.statements, - source_info, - ); - block_data.terminator = Some(Terminator { - source_info, - kind: TerminatorKind::Assert { - cond: pointer_check.cond, - expected: true, - target: new_block, - msg: pointer_check.assert_kind, - // This calls a panic function associated with the pointer check, which - // is #[rustc_nounwind]. We never want to insert an unwind into unsafe - // code, because unwinding could make a failing UB check turn into much - // worse UB when we start unwinding. - unwind: UnwindAction::Unreachable, - }, + + let mut insert_check = |block_data: &mut BasicBlockData<'tcx>, new_block_idx| { + // Invoke `on_finding` which appends to `local_decls` and the + // blocks statements. It returns information about the assert + // we're performing in the Terminator. + let pointer_check = on_finding( + tcx, + local, + ty, + context, + local_decls, + &mut block_data.statements, + source_info, + ); + let new_terminator = Terminator { + source_info, + kind: TerminatorKind::Assert { + cond: pointer_check.cond, + expected: true, + // new_block_idx will contain the rest of the original block + target: new_block_idx, + msg: pointer_check.assert_kind, + // This calls a panic function associated with the pointer check, which + // is #[rustc_nounwind]. We never want to insert an unwind into unsafe + // code, because unwinding could make a failing UB check turn into much + // worse UB when we start unwinding. + unwind: UnwindAction::Unreachable, + }, + }; + + // Terminate the split block with the new terminator + // and return the original terminator + std::mem::replace(block_data.terminator_mut(), new_terminator) + }; + + basic_blocks.push_with(|new_block_idx, basic_blocks| { + let block_data = &mut basic_blocks[location.block]; + + // Drain every statement after this one + let remaining_stmts = block_data.statements.split_off(location.statement_index); + + // insert the check (push statements and replace old terminator) + let old_terminator = insert_check(block_data, new_block_idx); + + // move the rest to a new block + BasicBlockData::new_stmts( + remaining_stmts, + old_terminator, + block_data.is_cleanup, + ) }); } } @@ -227,19 +249,3 @@ impl<'a, 'tcx> Visitor<'tcx> for PointerFinder<'a, 'tcx> { self.super_place(place, context, location); } } - -fn split_block( - basic_blocks: &mut IndexVec>, - location: Location, -) -> BasicBlock { - let block_data = &mut basic_blocks[location.block]; - - // Drain every statement after this one and move the current terminator to a new basic block. - let new_block = BasicBlockData::maybe_unterminated_stmts( - block_data.statements.split_off(location.statement_index), - block_data.terminator.take(), - block_data.is_cleanup, - ); - - basic_blocks.push(new_block) -} diff --git a/compiler/rustc_mir_transform/src/simplify.rs b/compiler/rustc_mir_transform/src/simplify.rs index c0281871f2a73..bd2f82ae0d267 100644 --- a/compiler/rustc_mir_transform/src/simplify.rs +++ b/compiler/rustc_mir_transform/src/simplify.rs @@ -35,6 +35,7 @@ //! pre-"runtime" MIR! use itertools::Itertools as _; +use rustc_data_structures::thin_vec::ThinVec; use rustc_index::bit_set::DenseBitSet; use rustc_index::{Idx, IndexSlice, IndexVec}; use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor}; @@ -158,8 +159,7 @@ impl<'a, 'tcx> CfgSimplifier<'a, 'tcx> { debug!("simplifying {:?}", bb); - let mut terminator = - self.basic_blocks[bb].terminator.take().expect("invalid terminator state"); + let mut terminator = self.take_terminator(bb).expect("invalid terminator state"); terminator.successors_mut(|successor| { self.collapse_goto_chain(successor, &mut changed); @@ -207,6 +207,18 @@ impl<'a, 'tcx> CfgSimplifier<'a, 'tcx> { outer_changed } + /// Replaces the terminator of a basic block with a dummy value. + fn take_terminator(&mut self, bb: BasicBlock) -> Option> { + if has_dummy_terminator(&self.basic_blocks[bb]) { + return None; + } + let dummy_terminator = Terminator { + source_info: SourceInfo { span: DUMMY_SP, scope: SourceScope::ZERO }, + kind: TerminatorKind::Goto { target: BasicBlock::MAX, loop_hint_attrs: ThinVec::new() }, + }; + std::mem::replace(&mut self.basic_blocks[bb].terminator, Some(dummy_terminator)) + } + /// This function will return `None` if /// * the block has statements /// * the block has a terminator other than `goto` @@ -218,7 +230,7 @@ impl<'a, 'tcx> CfgSimplifier<'a, 'tcx> { terminator: ref mut terminator @ Some(Terminator { kind: TerminatorKind::Goto { .. }, .. }), .. - } if statements.is_empty() => terminator.take(), + } if statements.is_empty() => self.take_terminator(bb), // if `terminator` is None, this means we are in a loop. In that // case, let all the loop collapse to its entry. _ => None, @@ -289,7 +301,7 @@ impl<'a, 'tcx> CfgSimplifier<'a, 'tcx> { }; debug!("merging block {:?} into {:?}", target, terminator); - *terminator = match self.basic_blocks[target].terminator.take() { + *terminator = match self.take_terminator(target) { Some(terminator) => terminator, None => { // unreachable loop - this should not be possible, as we @@ -350,12 +362,12 @@ pub(super) fn simplify_duplicate_switch_targets(terminator: &mut Terminator<'_>) pub(super) fn remove_dead_blocks(body: &mut Body<'_>) { let should_deduplicate_unreachable = |bbdata: &BasicBlockData<'_>| { - // CfgSimplifier::simplify leaves behind some unreachable basic blocks without a - // terminator. Those blocks will be deleted by remove_dead_blocks, but we run just + // CfgSimplifier::simplify leaves behind some unreachable basic blocks with + // dummy terminator. Those blocks will be deleted by remove_dead_blocks, but we run just // before then so we need to handle missing terminators. // We also need to prevent confusing cleanup and non-cleanup blocks. In practice we // don't emit empty unreachable cleanup blocks, so this simple check suffices. - bbdata.terminator.is_some() && bbdata.is_empty_unreachable() && !bbdata.is_cleanup + !has_dummy_terminator(bbdata) && bbdata.is_empty_unreachable() && !bbdata.is_cleanup }; let reachable = traversal::reachable_as_bitset(body); @@ -414,6 +426,13 @@ pub(super) fn remove_dead_blocks(body: &mut Body<'_>) { } } +fn has_dummy_terminator(bbdata: &BasicBlockData<'_>) -> bool { + match bbdata.terminator().kind { + TerminatorKind::Goto { target, .. } => target == BasicBlock::MAX, + _ => false, + } +} + pub(super) enum SimplifyLocals { BeforeConstProp, AfterGVN, diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index 9e6a92d4bbdae..5b858cfacd2e2 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -2008,11 +2008,12 @@ impl<'a> Parser<'a> { ) -> Option { // If we find a pattern followed by an identifier, it could be an (incorrect) // C-style parameter declaration. - if self.check_ident() + if let Some((ident, kind)) = self.token.ident() + && (ident.name == kw::SelfLower || !token::ident_of_kind_is_reserved(ident, kind)) && self.look_ahead(1, |t| *t == token::Comma || *t == token::CloseParen) { // `fn foo(String s) {}` - let ident = self.parse_ident_common(true).unwrap(); + self.bump(); // ident let span = pat.span.with_hi(ident.span.hi()); err.span_suggestion_verbose( diff --git a/compiler/rustc_parse/src/parser/item.rs b/compiler/rustc_parse/src/parser/item.rs index 27646bac1c21e..58788cf4504e8 100644 --- a/compiler/rustc_parse/src/parser/item.rs +++ b/compiler/rustc_parse/src/parser/item.rs @@ -507,12 +507,13 @@ impl<'a> Parser<'a> { let span = if is_pub { self.prev_token.span.to(ident_span) } else { ident_span }; let insert_span = ident_span.shrink_to_lo(); - let ident = if self.token.is_ident() + let ident = if let Some(ident) = self.token.non_reserved_ident() && (!is_const || self.look_ahead(1, |t| *t == token::OpenParen)) && self.look_ahead(1, |t| { matches!(t.kind, token::Lt | token::OpenBrace | token::OpenParen) }) { - self.parse_ident_common(true).unwrap() + self.bump(); // ident + ident } else { return Ok(()); }; diff --git a/compiler/rustc_parse/src/parser/mod.rs b/compiler/rustc_parse/src/parser/mod.rs index 10f4d73e3e4cd..f5bb585628b3d 100644 --- a/compiler/rustc_parse/src/parser/mod.rs +++ b/compiler/rustc_parse/src/parser/mod.rs @@ -883,6 +883,10 @@ impl<'a> Parser<'a> { break; } Err(mut expect_err) => { + if !self.may_recover() { + return Err(expect_err); + } + let sp = self.prev_token.span.shrink_to_hi(); let token_str = pprust::token_kind_to_string(&exp.tok); diff --git a/compiler/rustc_resolve/src/diagnostics/mod.rs b/compiler/rustc_resolve/src/diagnostics/mod.rs index 4a54269a30137..c2a053fc0e731 100644 --- a/compiler/rustc_resolve/src/diagnostics/mod.rs +++ b/compiler/rustc_resolve/src/diagnostics/mod.rs @@ -837,7 +837,7 @@ pub(crate) struct CannotBeReexportedPrivateNS { pub(crate) span: Span, pub(crate) ident: Ident, #[note("consider declaring {$descr} `{$ident}` with `pub`")] - pub(crate) parent: Span, + pub(crate) parent: Option, pub(crate) descr: &'static str, } @@ -849,7 +849,7 @@ pub(crate) struct CannotBeReexportedCratePublicNS { pub(crate) span: Span, pub(crate) ident: Ident, #[note("consider declaring {$descr} `{$ident}` with `pub`")] - pub(crate) parent: Span, + pub(crate) parent: Option, pub(crate) descr: &'static str, } diff --git a/compiler/rustc_resolve/src/imports.rs b/compiler/rustc_resolve/src/imports.rs index f7e86925800a3..68f07e204c092 100644 --- a/compiler/rustc_resolve/src/imports.rs +++ b/compiler/rustc_resolve/src/imports.rs @@ -1685,9 +1685,15 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { diagnostic: diagnostic.into(), }); } else if ns == TypeNS { - let def_id = decl.res().def_id(); - let parent = if !def_id.is_crate_root() { self.def_span(def_id) } else { DUMMY_SP }; - let descr = self.tcx().def_descr(def_id); + let res = decl.res(); + let (parent, descr) = match res.opt_def_id() { + Some(def_id) => { + let parent = + if !def_id.is_crate_root() { self.def_span(def_id) } else { DUMMY_SP }; + (Some(parent), self.tcx().def_descr(def_id)) + } + None => (None, res.descr()), + }; if crate_private_reexport { self.dcx().emit_err(CannotBeReexportedCratePublicNS { diff --git a/compiler/rustc_resolve/src/late/lang_items.rs b/compiler/rustc_resolve/src/late/lang_items.rs index b53928df24dc8..b3aff17afbaae 100644 --- a/compiler/rustc_resolve/src/late/lang_items.rs +++ b/compiler/rustc_resolve/src/late/lang_items.rs @@ -9,7 +9,8 @@ use rustc_ast as ast; use rustc_attr_ir::target::Target; -use rustc_attr_ir::{GenericRequirement, LangItem, LanguageItems}; +use rustc_attr_ir::{AttributeKind, GenericRequirement, LangItem, LanguageItems}; +use rustc_attr_parsing::AttributeParser; use rustc_crate_store::ExternCrate; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_middle::ty::TyCtxt; @@ -34,51 +35,40 @@ impl<'tcx> LateResolutionVisitor<'_, '_, '_, 'tcx> { item_span: Span, generics: Option<&ast::Generics>, ) { - let attrs = attrs.iter().find_map(|attr| { - Some(match attr { - _ if attr.has_name(sym::lang) => (attr.value_str()?, attr.span), - _ if attr.has_name(sym::panic_handler) => (sym::panic_impl, attr.span), - _ => return None, + if let Some(rustc_attr_ir::Attribute::Parsed(AttributeKind::Lang(lang_item, attr_span))) = + AttributeParser::parse_limited(self.r.tcx.sess, attrs, &|attr| { + attr.has_any_name(&[sym::lang, sym::panic_handler]) }) - }); - if let Some((name, attr_span)) = attrs { - match LangItem::from_name(name) { - // Known lang item - Some(lang_item) => { - if actual_target != lang_item.target() { - // `#[panic_handler]` is turned into `#[lang = "panic_impl"]`, but in contrast - // to the actual lang item attr, is applied to `Fn` instead of `ForeignFn`. - if !(lang_item.is_weak() - && actual_target == Target::Fn - && lang_item.target() == Target::ForeignFn - && matches!(lang_item, LangItem::PanicImpl)) - { - self.r.tcx - .dcx() - .delayed_bug(format!("lang item target is checked in attribute parser: {:?} has {} but expected {}", def_id, actual_target, lang_item.target())); - return; - } - } - // Weak lang items are handled separately - if lang_item.is_weak() && actual_target == Target::ForeignFn { - self.r.lang_items.missing.push(lang_item); - } else { - // Weak only lang items are always handled here - self.collect_item_extended( - lang_item, - def_id, - item_span, - attr_span, - generics, - actual_target, - ); - } - } - // Unknown lang item. - _ => { - self.r.tcx.dcx().delayed_bug("unknown lang item"); + { + if actual_target != lang_item.target() { + // `#[panic_handler]` is turned into `#[lang = "panic_impl"]`, but in contrast + // to the actual lang item attr, is applied to `Fn` instead of `ForeignFn`. + if !(lang_item.is_weak() + && actual_target == Target::Fn + && lang_item.target() == Target::ForeignFn + && matches!(lang_item, LangItem::PanicImpl)) + { + self.r.tcx + .dcx() + .delayed_bug(format!("lang item target is checked in attribute parser: {:?} has {} but expected {}", def_id, actual_target, lang_item.target())); + return; } } + + // Weak lang items are handled separately + if lang_item.is_weak() && actual_target == Target::ForeignFn { + self.r.lang_items.missing.push(lang_item); + } else { + // Weak only lang items are always handled here + self.collect_item_extended( + lang_item, + def_id, + item_span, + attr_span, + generics, + actual_target, + ); + } } } diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index c150c4023e0d4..70adbf6d7fee5 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -2210,6 +2210,7 @@ symbols! { type_changing_struct_update, type_id, type_id_array_len, + type_id_docs, type_id_element_ty, type_id_eq, type_id_field_representing_type, @@ -2223,6 +2224,7 @@ symbols! { type_id_reflected_attrs, type_id_size_of, type_id_type_of, + type_id_variant_docs, type_id_variant_name, type_id_variant_non_exhaustive, type_id_variant_reflected_attrs, diff --git a/compiler/rustc_trait_selection/src/diagnostics.rs b/compiler/rustc_trait_selection/src/diagnostics.rs index 5c6c97bd1b883..97bdc231c3cf3 100644 --- a/compiler/rustc_trait_selection/src/diagnostics.rs +++ b/compiler/rustc_trait_selection/src/diagnostics.rs @@ -141,6 +141,19 @@ pub(crate) struct ClosureKindMismatch { pub fn_mut_label: Option, } +#[derive(Diagnostic)] +#[diag("expected `{$trait_prefix}FnOnce`, found reference", code = E0525)] +#[note("`{$trait_prefix}FnOnce` isn't implemented for references")] +pub(crate) struct RefToFnOnce { + #[primary_span] + #[label("closure passed by reference here")] + pub cause_span: Span, + pub trait_prefix: &'static str, + + #[subdiagnostic] + pub fn_once_label: Option, +} + #[derive(Subdiagnostic)] #[label( "closure is `{$trait_prefix}FnOnce` because it moves the variable `{$place}` out of its environment" diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs index e1ce21590b19a..7c9d8ee17254c 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs @@ -43,7 +43,7 @@ use super::suggestions::get_explanation_based_on_obligation; use super::{ArgKind, CandidateSimilarity, GetSafeTransmuteErrorAndReason, ImplCandidate}; use crate::diagnostics::{ AssocTypeWithSameName, ClosureFnMutLabel, ClosureFnOnceLabel, ClosureKindMismatch, - CoroClosureNotFn, + CoroClosureNotFn, RefToFnOnce, }; use crate::error_reporting::TypeErrCtxt; use crate::error_reporting::infer::TyCategory; @@ -1124,17 +1124,10 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { let self_ty = if is_ref_to_closure { peeled_self_ty } else { original_self_ty }; - let (expected_kind, is_async) = - if let Some(expected_kind) = self.tcx.fn_trait_kind_from_def_id(trait_pred.def_id()) { - (expected_kind, false) - } else if let Some(expected_kind) = - self.tcx.async_fn_trait_kind_from_def_id(trait_pred.def_id()) - { - (expected_kind, true) - } else { - return None; - }; - let trait_prefix = if is_async { "Async" } else { "" }; + let (asyncness, expected_kind) = + self.tcx.maybe_async_fn_trait_kind_from_def_id(trait_pred.def_id())?; + + let trait_prefix = asyncness.as_trait_prefix_str(); let (closure_def_id, found_args, has_self_borrows) = match *self_ty.kind() { ty::Closure(def_id, args) => { @@ -1168,7 +1161,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { if found_kind.is_none() && is_ref_to_closure - && !is_async + && !asyncness.is_async() && let Some(local_def_id) = closure_def_id.as_local() && let Some((inferred_kind, origin)) = (self.infer_closure_kind)(local_def_id) { @@ -1176,6 +1169,31 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { kind_origin = origin; } + let (_, root_trait_pred) = obligation.cause.code().peel_derives_with_predicate(); + let root_expected = root_trait_pred + .and_then(|pred| self.tcx.maybe_async_fn_trait_kind_from_def_id(pred.def_id())); + + // Prevent confusing errors when `&FnOnce` was provided when `FnOnce` was expected + // in function arguments + if let ty::ClosureKind::Fn | ty::ClosureKind::FnMut = expected_kind + && let Some(ty::ClosureKind::FnOnce) = found_kind + && let Some((root_asyncness, ty::ClosureKind::FnOnce)) = root_expected + && let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code() + && let arg = self.tcx.hir_expect_expr(*arg_hir_id) + && asyncness == root_asyncness + { + let mut err = self.report_ref_to_fn_once_error( + closure_def_id, + trait_prefix, + kind_origin, + arg.span, + ); + + self.suggest_remove_ref_for_closure(&mut err, obligation); + self.note_obligation_cause(&mut err, obligation); + return Some(err.emit_err()); + } + if let Some(found_kind) = found_kind && !found_kind.extends(expected_kind) { @@ -1187,7 +1205,8 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { trait_prefix, kind_origin, ); - self.suggest_change_mut_ref_for_closure(&mut err, &obligation); + + self.suggest_change_mut_ref_for_closure(&mut err, obligation); self.note_obligation_cause(&mut err, &obligation); return Some(err.emit_err()); } @@ -3289,6 +3308,26 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } } + fn suggest_remove_ref_for_closure( + &self, + err: &mut Diag<'_>, + obligation: &PredicateObligation<'tcx>, + ) { + if let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code() + && let (_, Some(root_trait_pred)) = + obligation.cause.code().peel_derives_with_predicate() + && let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id) + && let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, _) = arg.kind + { + let mut obligation = obligation.clone(); + // Error reporting may narrow the cause span to the borrow's operand. + // Use the whole argument so `suggest_remove_reference` can replace the borrow. + obligation.cause.span = arg.span; + + self.suggest_remove_reference(&obligation, err, root_trait_pred); + } + } + /// Register when multiple obligations come from the same statement and only emit one. /// /// This can significantly reduce the number of `_: Sized` failures on method chains. @@ -3837,6 +3876,38 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } } + fn infer_closure_origin( + &self, + closure_def_id: DefId, + ) -> Option<(Span, rustc_middle::hir::place::Place<'tcx>)> { + let typeck_results = self.typeck_results.as_ref()?; + let local_def_id = closure_def_id.as_local()?; + let hir_id = self.tcx.local_def_id_to_hir_id(local_def_id); + typeck_results.closure_kind_origins().get(hir_id).cloned() + } + + fn report_ref_to_fn_once_error( + &self, + closure_def_id: DefId, + trait_prefix: &'static str, + kind_origin: Option<(Span, rustc_middle::hir::place::Place<'tcx>)>, + cause_span: Span, + ) -> Diag<'a> { + let origin = kind_origin.or_else(|| self.infer_closure_origin(closure_def_id)); + + let err = RefToFnOnce { + cause_span, + trait_prefix, + fn_once_label: origin.map(|(span, place)| ClosureFnOnceLabel { + span, + place: ty::place_to_string_for_capture(self.tcx, &place), + trait_prefix, + }), + }; + + self.dcx().create_err(err) + } + fn report_closure_error( &self, obligation: &PredicateObligation<'tcx>, @@ -3860,12 +3931,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { // Additional context information explaining why the closure only implements // a particular trait. - let origin = kind_origin.or_else(|| { - let typeck_results = self.typeck_results.as_ref()?; - let local_def_id = closure_def_id.as_local()?; - let hir_id = self.tcx.local_def_id_to_hir_id(local_def_id); - typeck_results.closure_kind_origins().get(hir_id).cloned() - }); + let origin = kind_origin.or_else(|| self.infer_closure_origin(closure_def_id)); match (found_kind, origin) { (ty::ClosureKind::FnOnce, Some((span, place))) => { @@ -3884,6 +3950,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } _ => {} } + self.dcx().create_err(err) } diff --git a/library/core/src/intrinsics/reflection.rs b/library/core/src/intrinsics/reflection.rs index 0054cd32cdc03..700bb1f307dcc 100644 --- a/library/core/src/intrinsics/reflection.rs +++ b/library/core/src/intrinsics/reflection.rs @@ -118,6 +118,19 @@ pub fn type_id_variant_reflected_attrs( _variant_index: usize, ) -> &'static [&'static str]; +/// Gets the raw documentation attributes of the variant represented by the base `TypeId` and variant_idx. +/// +/// The more user-friendly version of this intrinsic is [`core::mem::type_info::VariantId::docs`]. +/// +/// [`TypeId`]: crate::any::TypeId +#[rustc_intrinsic] +#[unstable(feature = "core_intrinsics", issue = "none")] +#[rustc_comptime] +pub fn type_id_variant_docs( + _base: crate::any::TypeId, + _variant_index: usize, +) -> &'static [&'static str]; + /// Returns true when the variant represented by the base `TypeId` and variant_idx is non /// exhaustive. /// @@ -190,3 +203,11 @@ pub fn type_id_function_ptr(_type_id: crate::any::TypeId) -> Option &'static [&'static str]; + +/// Returns the raw documentation attributes given a `TypeId` which represents a structure, enumeration, union or `FieldId`. +/// +/// The more user-friendly version of this intrinsic is [`core::any::TypeId::docs`]. +#[rustc_intrinsic] +#[unstable(feature = "core_intrinsics", issue = "none")] +#[rustc_comptime] +pub fn type_id_docs(_type_id: crate::any::TypeId) -> &'static [&'static str]; diff --git a/library/core/src/mem/type_info.rs b/library/core/src/mem/type_info.rs index 1ad39e3c2f3ac..a4374ce5e70eb 100644 --- a/library/core/src/mem/type_info.rs +++ b/library/core/src/mem/type_info.rs @@ -679,6 +679,26 @@ impl TypeId { pub fn reflected_attrs(self) -> &'static [&'static str] { intrinsics::reflection::type_id_reflected_attrs(self) } + + /// Returns the raw documentation attributes when given a `TypeId` which represents a structure, enumeration or union. + /// ``` + /// #![feature(type_info)] + /// # use std::any::TypeId; + /// + /// #[doc = "first"] + /// /** second + /// * third + /// */ + /// struct A; + /// + /// assert_eq!(const { TypeId::of::().docs() }, ["first", " second\n* third\n"]); + /// ``` + #[unstable(feature = "type_info", issue = "146922")] + #[rustc_const_unstable(feature = "type_info", issue = "146922")] + #[rustc_comptime] + pub fn docs(self) -> &'static [&'static str] { + intrinsics::reflection::type_id_docs(self) + } } /// Variant representing type ID. Representing a variant of an enum. @@ -721,6 +741,28 @@ impl VariantId { intrinsics::reflection::type_id_variant_name(self.base, self.variant) } + /// Returns the raw documentation attributes when given a `VariantId`. + /// ``` + /// #![feature(type_info)] + /// # use std::any::TypeId; + /// + /// enum A { + /// #[doc = "first"] + /// /** second + /// * third*/ + /// B, + /// C, + /// } + /// + /// assert_eq!(const { TypeId::of::().variant(0).docs() }, ["first", " second\n * third"]); + /// ``` + #[unstable(feature = "type_info", issue = "146922")] + #[rustc_const_unstable(feature = "type_info", issue = "146922")] + #[rustc_comptime] + pub fn docs(self) -> &'static [&'static str] { + intrinsics::reflection::type_id_variant_docs(self.base, self.variant) + } + /// Returns whether this variant is marked with `#[non_exhaustive]`. #[unstable(feature = "type_info", issue = "146922")] #[rustc_const_unstable(feature = "type_info", issue = "146922")] @@ -815,6 +857,27 @@ impl FieldId { pub fn name(self) -> &'static str { intrinsics::field_representing_type_name(self.frt_type_id) } + + /// Returns the raw documentation attributes when given a `FieldId`. + /// ``` + /// #![feature(type_info)] + /// # use std::any::TypeId; + /// + /// struct A { + /// #[doc = "first"] + /// /// second + /// first: u8, + /// } + /// + /// assert_eq!(const { TypeId::of::().field(0, 0).docs() }, ["first", " second"]); + /// ``` + #[unstable(feature = "type_info", issue = "146922")] + #[rustc_const_unstable(feature = "type_info", issue = "146922")] + #[rustc_comptime] + pub fn docs(self) -> &'static [&'static str] { + intrinsics::reflection::type_id_docs(self.frt_type_id) + } + /// Returns the offset of the field wrt to its containing type. /// /// ``` diff --git a/library/core/src/ub_checks.rs b/library/core/src/ub_checks.rs index f25781ea8ce5a..63393c58ef636 100644 --- a/library/core/src/ub_checks.rs +++ b/library/core/src/ub_checks.rs @@ -102,9 +102,9 @@ pub(crate) const fn check_language_ub() -> bool { false } else { // Disable UB checks in Miri. - !cfg!(miri) + !cfg!(miri) && intrinsics::ub_checks() } - ) && intrinsics::ub_checks() + ) } /// Checks whether `ptr` is properly aligned with respect to the given alignment, and diff --git a/library/coretests/tests/mem/type_info.rs b/library/coretests/tests/mem/type_info.rs index 76e2adad18f1c..c8f547a20d1af 100644 --- a/library/coretests/tests/mem/type_info.rs +++ b/library/coretests/tests/mem/type_info.rs @@ -58,11 +58,15 @@ fn test_tuples() { fn test_structs() { const { #[reflective_tool::TestStruct] + ///test-doc struct TestStruct { #[reflective_tool::first(1)] #[reflective_tool::first(2)] + #[doc = "first-doc 1"] + ///first-doc 2 first: u8, #[reflective_tool::second] + /// second-doc second: u16, reference: &'static u16, } @@ -71,6 +75,7 @@ fn test_structs() { assert!(!ty_id.non_exhaustive()); assert!(ty_id.size() == Some(size_of::())); assert!(ty_id.reflected_attrs() == &["#[reflective_tool::TestStruct]"]); + assert!(ty_id.docs() == &["test-doc"]); assert!(ty_id.variants() == 1); assert!(ty_id.fields(0) == 3); assert!(ty_id.field(0, 0).type_id() == TypeId::of::()); @@ -80,13 +85,16 @@ fn test_structs() { ty_id.field(0, 0).reflected_attrs() == &["#[reflective_tool::first(1)]", "#[reflective_tool::first(2)]"] ); + assert!(ty_id.field(0, 0).docs() == &["first-doc 1", "first-doc 2"]); assert!(ty_id.field(0, 1).type_id() == TypeId::of::()); assert!(ty_id.field(0, 1).offset() == offset_of!(TestStruct, second)); assert!(ty_id.field(0, 1).name() == "second"); assert!(ty_id.field(0, 1).reflected_attrs() == &["#[reflective_tool::second]"]); + assert!(ty_id.field(0, 1).docs() == &[" second-doc"]); assert!(ty_id.field(0, 2).type_id() == TypeId::of::<&u16>()); assert!(ty_id.field(0, 2).offset() == offset_of!(TestStruct, reference)); assert!(ty_id.field(0, 2).name() == "reference"); + assert!(ty_id.field(0, 2).docs() == &[""; 0]); } const { @@ -107,17 +115,21 @@ fn test_structs() { assert!(ty_id.fields(0) == 2); assert!(ty_id.field(0, 0).type_id() == TypeId::of::()); assert!(ty_id.field(0, 0).name() == "0"); + assert!(ty_id.field(0, 0).docs() == &[""; 0]); assert!(ty_id.field(0, 1).type_id() == TypeId::of::()); assert!(ty_id.field(0, 1).name() == "1"); + assert!(ty_id.field(0, 1).docs() == &[""; 0]); } const { #[reflective_tool::a] + ///doc struct Generics<'a, T, const C: u64> { a: &'a T, } let ty_id = TypeId::of::>(); + assert!(ty_id.docs() == &["doc"]); assert!(ty_id.fields(0) == 1); assert!(ty_id.generics().len() == 3); assert!(ty_id.reflected_attrs() == &["#[reflective_tool::a]"]); @@ -136,34 +148,43 @@ fn test_structs() { fn test_unions() { const { #[reflective_tool::a] + ///test-doc 1 + ///test-doc 2 union TestUnion { #[reflective_tool::first] + #[doc = "first-doc"] first: i16, #[reflective_tool::second] + ///second-doc second: u16, } let ty_id = TypeId::of::(); assert!(ty_id.size() == Some(size_of::())); + assert!(ty_id.docs() == &["test-doc 1", "test-doc 2"]); assert!(ty_id.variants() == 1); assert!(ty_id.fields(0) == 2); assert!(ty_id.reflected_attrs() == &["#[reflective_tool::a]"]); assert!(ty_id.field(0, 0).name() == "first"); + assert!(ty_id.field(0, 0).docs() == &["first-doc"]); assert!(ty_id.field(0, 0).type_id() == TypeId::of::()); assert!(ty_id.field(0, 0).reflected_attrs() == &["#[reflective_tool::first]"]); assert!(ty_id.field(0, 1).name() == "second"); + assert!(ty_id.field(0, 1).docs() == &["second-doc"]); assert!(ty_id.field(0, 1).type_id() == TypeId::of::()); assert!(ty_id.field(0, 1).reflected_attrs() == &["#[reflective_tool::second]"]); } const { #[reflective_tool::a] + ///doc union Generics<'a, T: Copy, const C: u64> { a: T, z: &'a (), } let ty_id = TypeId::of::>(); + assert!(ty_id.docs() == &["doc"]); assert!(ty_id.fields(0) == 2); assert!(ty_id.reflected_attrs() == &["#[reflective_tool::a]"]); assert!(ty_id.field(0, 1).offset() == offset_of!(Generics<'static, i32, 1_u64>, a)); @@ -184,16 +205,21 @@ fn test_unions() { fn test_enums() { const { #[reflective_tool::a] + ///doc enum E { #[reflective_tool::some] + ///somedoc Some(u32), #[reflective_tool::none] + ///nonedoc None, #[reflective_tool::foomp] #[non_exhaustive] + ///foompdoc Foomp { a: (), #[reflective_tool::b] + ///bdoc b: &'static str, }, } @@ -202,27 +228,32 @@ fn test_enums() { assert!(!ty_id.non_exhaustive()); assert!(ty_id.size() == Some(size_of::())); assert!(ty_id.reflected_attrs() == &["#[reflective_tool::a]"]); + assert!(ty_id.docs() == &["doc"]); assert!(ty_id.variants() == 3); assert!(ty_id.variant(0).name() == "Some"); assert!(ty_id.variant(0).reflected_attrs() == &["#[reflective_tool::some]"]); + assert!(ty_id.variant(0).docs() == &["somedoc"]); assert!(!ty_id.variant(0).non_exhaustive()); assert!(ty_id.fields(0) == 1); assert!(ty_id.field(0, 0).type_id() == TypeId::of::()); assert!(ty_id.variant(1).name() == "None"); assert!(ty_id.variant(1).reflected_attrs() == &["#[reflective_tool::none]"]); + assert!(ty_id.variant(1).docs() == &["nonedoc"]); assert!(!ty_id.variant(1).non_exhaustive()); assert!(ty_id.fields(1) == 0); assert!(ty_id.variant(2).name() == "Foomp"); assert!(ty_id.variant(2).reflected_attrs() == &["#[reflective_tool::foomp]"]); + assert!(ty_id.variant(2).docs() == &["foompdoc"]); assert!(ty_id.variant(2).non_exhaustive()); assert!(ty_id.fields(2) == 2); assert!(ty_id.field(2, 0).type_id() == TypeId::of::<()>()); assert!(ty_id.field(2, 1).type_id() == TypeId::of::<&str>()); assert!(ty_id.field(2, 1).name() == "b"); assert!(ty_id.field(2, 1).reflected_attrs() == &["#[reflective_tool::b]"]); + assert!(ty_id.field(2, 1).docs() == &["bdoc"]); assert!(ty_id.generics().is_empty()); } @@ -255,12 +286,14 @@ fn test_primitives() { let ty_id = TypeId::of::(); assert!(ty_id.size() == Some(size_of::())); assert!(ty_id.reflected_attrs() == &[""; 0]); + assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); let Type { kind: Char, .. } = (const { Type::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(ty_id.size() == Some(size_of::())); assert!(ty_id.reflected_attrs() == &[""; 0]); + assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); let Type { kind: Int, .. } = (const { Type::of::() }) else { panic!() }; @@ -268,6 +301,7 @@ fn test_primitives() { assert!(ty_id.is_signed()); assert!(ty_id.size() == Some(size_of::())); assert!(ty_id.reflected_attrs() == &[""; 0]); + assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); let Type { kind: Int, .. } = (const { Type::of::() }) else { panic!() }; @@ -275,6 +309,7 @@ fn test_primitives() { assert!(ty_id.is_signed()); assert!(ty_id.size() == Some(size_of::())); assert!(ty_id.reflected_attrs() == &[""; 0]); + assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); let Type { kind: Int, .. } = (const { Type::of::() }) else { panic!() }; @@ -282,6 +317,7 @@ fn test_primitives() { assert!(!ty_id.is_signed()); assert!(ty_id.size() == Some(size_of::())); assert!(ty_id.reflected_attrs() == &[""; 0]); + assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); let Type { kind: Int, .. } = (const { Type::of::() }) else { panic!() }; @@ -289,18 +325,21 @@ fn test_primitives() { assert!(!ty_id.is_signed()); assert!(ty_id.size() == Some(size_of::())); assert!(ty_id.reflected_attrs() == &[""; 0]); + assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); let Type { kind: Float, .. } = (const { Type::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(ty_id.size() == Some(size_of::())); assert!(ty_id.reflected_attrs() == &[""; 0]); + assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); let Type { kind: Str(_ty), .. } = (const { Type::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(ty_id.size() == None); assert!(ty_id.reflected_attrs() == &[""; 0]); + assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); } } diff --git a/library/std/src/io/stdio.rs b/library/std/src/io/stdio.rs index f72a55366bfdd..0e630fc976e8a 100644 --- a/library/std/src/io/stdio.rs +++ b/library/std/src/io/stdio.rs @@ -97,15 +97,15 @@ const fn stderr_raw() -> StderrRaw { impl Read for StdinRaw { fn read(&mut self, buf: &mut [u8]) -> io::Result { - handle_ebadf(self.0.read(buf), || Ok(0)) + self.0.read(buf) } fn read_buf(&mut self, buf: BorrowedCursor<'_, u8>) -> io::Result<()> { - handle_ebadf(self.0.read_buf(buf), || Ok(())) + self.0.read_buf(buf) } fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result { - handle_ebadf(self.0.read_vectored(bufs), || Ok(0)) + self.0.read_vectored(bufs) } #[inline] @@ -117,33 +117,32 @@ impl Read for StdinRaw { if buf.is_empty() { return Ok(()); } - handle_ebadf(self.0.read_exact(buf), || Err(io::Error::READ_EXACT_EOF)) + self.0.read_exact(buf) } fn read_buf_exact(&mut self, buf: BorrowedCursor<'_, u8>) -> io::Result<()> { if buf.capacity() == 0 { return Ok(()); } - handle_ebadf(self.0.read_buf_exact(buf), || Err(io::Error::READ_EXACT_EOF)) + self.0.read_buf_exact(buf) } fn read_to_end(&mut self, buf: &mut Vec) -> io::Result { - handle_ebadf(self.0.read_to_end(buf), || Ok(0)) + self.0.read_to_end(buf) } fn read_to_string(&mut self, buf: &mut String) -> io::Result { - handle_ebadf(self.0.read_to_string(buf), || Ok(0)) + self.0.read_to_string(buf) } } impl Write for StdoutRaw { fn write(&mut self, buf: &[u8]) -> io::Result { - handle_ebadf(self.0.write(buf), || Ok(buf.len())) + self.0.write(buf) } fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result { - let total = || Ok(bufs.iter().map(|b| b.len()).sum()); - handle_ebadf(self.0.write_vectored(bufs), total) + self.0.write_vectored(bufs) } #[inline] @@ -152,30 +151,29 @@ impl Write for StdoutRaw { } fn flush(&mut self) -> io::Result<()> { - handle_ebadf(self.0.flush(), || Ok(())) + self.0.flush() } fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { - handle_ebadf(self.0.write_all(buf), || Ok(())) + self.0.write_all(buf) } fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> { - handle_ebadf(self.0.write_all_vectored(bufs), || Ok(())) + self.0.write_all_vectored(bufs) } fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> { - handle_ebadf(self.0.write_fmt(fmt), || Ok(())) + self.0.write_fmt(fmt) } } impl Write for StderrRaw { fn write(&mut self, buf: &[u8]) -> io::Result { - handle_ebadf(self.0.write(buf), || Ok(buf.len())) + self.0.write(buf) } fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result { - let total = || Ok(bufs.iter().map(|b| b.len()).sum()); - handle_ebadf(self.0.write_vectored(bufs), total) + self.0.write_vectored(bufs) } #[inline] @@ -184,26 +182,19 @@ impl Write for StderrRaw { } fn flush(&mut self) -> io::Result<()> { - handle_ebadf(self.0.flush(), || Ok(())) + self.0.flush() } fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { - handle_ebadf(self.0.write_all(buf), || Ok(())) + self.0.write_all(buf) } fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> io::Result<()> { - handle_ebadf(self.0.write_all_vectored(bufs), || Ok(())) + self.0.write_all_vectored(bufs) } fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> io::Result<()> { - handle_ebadf(self.0.write_fmt(fmt), || Ok(())) - } -} - -fn handle_ebadf(r: io::Result, default: impl FnOnce() -> io::Result) -> io::Result { - match r { - Err(ref e) if stdio::is_ebadf(e) => default(), - r => r, + self.0.write_fmt(fmt) } } @@ -1158,7 +1149,9 @@ where return; } - if let Err(e) = global_s().write_fmt(args) { + if let Err(e) = global_s().write_fmt(args) + && !stdio::is_ebadf(&e) + { panic!("failed printing to {label}: {e}"); } } diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index 192f1931fb69d..fc22eaecc0043 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -269,6 +269,7 @@ // // Language features: // tidy-alphabetical-start +#![feature(abort_immediate)] #![feature(alloc_error_handler)] #![feature(allocator_internals)] #![feature(allow_internal_unsafe)] @@ -279,6 +280,7 @@ #![feature(cfg_target_has_threads)] #![feature(cfg_target_thread_local)] #![feature(cfi_encoding)] +#![feature(const_eval_select)] #![feature(const_trait_impl)] #![feature(decl_macro)] #![feature(deprecated_suggestion)] diff --git a/library/std/src/process.rs b/library/std/src/process.rs index cc7fab7aba9d1..fb3b72607e4d8 100644 --- a/library/std/src/process.rs +++ b/library/std/src/process.rs @@ -174,6 +174,8 @@ ))] mod tests; +use core::intrinsics; + use crate::ffi::OsStr; use crate::io::prelude::*; use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut}; @@ -2642,11 +2644,15 @@ pub fn exit(code: i32) -> ! { /// /// [panic hook]: crate::panic::set_hook #[stable(feature = "process_abort", since = "1.17.0")] +#[rustc_const_unstable(feature = "const_abort", issue = "166193")] #[cold] #[cfg_attr(not(test), rustc_diagnostic_item = "process_abort")] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces -pub fn abort() -> ! { - crate::sys::abort_internal(); +pub const fn abort() -> ! { + // Some code uses `abort` as a non-unwinding alternative to `panic`. That + // should work in const, but `sys` code invokes native host functions. So we + // invoke `intrinsics::crash` instead to safely hard-abort execution. + intrinsics::const_eval_select((), crash, crate::sys::abort_internal) } #[doc(inline)] diff --git a/library/std/src/sys/process/windows.rs b/library/std/src/sys/process/windows.rs index db2e2373adf95..1a520b76cdbd4 100644 --- a/library/std/src/sys/process/windows.rs +++ b/library/std/src/sys/process/windows.rs @@ -618,14 +618,14 @@ fn program_exists(path: &Path) -> Option> { impl Stdio { fn to_handle(&self, stdio_id: u32, pipe: &mut Option) -> io::Result { let use_stdio_id = |stdio_id| match stdio::get_handle(stdio_id) { - Ok(io) => unsafe { + Some(io) => unsafe { let io = Handle::from_raw_handle(io); let ret = io.duplicate(0, true, c::DUPLICATE_SAME_ACCESS); let _ = io.into_raw_handle(); // Don't close the handle ret }, // If no stdio handle is available, then propagate the null value. - Err(..) => unsafe { Ok(Handle::from_raw_handle(ptr::null_mut())) }, + None => unsafe { Ok(Handle::from_raw_handle(ptr::null_mut())) }, }; match *self { Stdio::Inherit => use_stdio_id(stdio_id), diff --git a/library/std/src/sys/stdio/windows.rs b/library/std/src/sys/stdio/windows.rs index f669527352246..c7c7a1ea3817f 100644 --- a/library/std/src/sys/stdio/windows.rs +++ b/library/std/src/sys/stdio/windows.rs @@ -70,15 +70,9 @@ pub const STDIN_BUF_SIZE: usize = MAX_BUFFER_SIZE / 2 * 3; #[cfg(not(target_vendor = "win7"))] const MAX_WRITE_HEAP_LEN: usize = 64 * 1024; // In u16 -> 128KiB -pub fn get_handle(handle_id: u32) -> io::Result { +pub fn get_handle(handle_id: u32) -> Option { let handle = unsafe { c::GetStdHandle(handle_id) }; - if handle == c::INVALID_HANDLE_VALUE { - Err(io::Error::last_os_error()) - } else if handle.is_null() { - Err(io::Error::from_raw_os_error(c::ERROR_INVALID_HANDLE as i32)) - } else { - Ok(handle) - } + if handle.is_null() || handle == c::INVALID_HANDLE_VALUE { None } else { Some(handle) } } /// Returns true if `handle` refers to a proper console (aka conhost). @@ -115,7 +109,8 @@ fn write(handle_id: u32, data: &[u8], incomplete_utf8: &mut IncompleteUtf8) -> i return Ok(0); } - let handle = get_handle(handle_id)?; + // If no handle is available, treat it like writing to NUL + let Some(handle) = get_handle(handle_id) else { return Ok(data.len()) }; // At the time of writing, console IO on Windows is high latency: // Windows has no TTY buffers, making every call a fully synchronous RPC. @@ -267,7 +262,8 @@ impl Stdin { impl io::Read for Stdin { fn read(&mut self, buf: &mut [u8]) -> io::Result { - let handle = get_handle(c::STD_INPUT_HANDLE)?; + // If no handle is available then treat it as if reading from NUL + let Some(handle) = get_handle(c::STD_INPUT_HANDLE) else { return Ok(0) }; if !is_console(handle) { unsafe { let handle = Handle::from_raw_handle(handle); diff --git a/library/stdarch/crates/simd-test-macro/src/lib.rs b/library/stdarch/crates/simd-test-macro/src/lib.rs index 286b36d3dd249..7b903723664fe 100644 --- a/library/stdarch/crates/simd-test-macro/src/lib.rs +++ b/library/stdarch/crates/simd-test-macro/src/lib.rs @@ -142,7 +142,7 @@ pub fn simd_test( } any( target_arch = "mips", - target_arch = "mips32r6" + target_arch = "mips32r6", target_arch = "mips64", target_arch = "mips64r6", ) => { diff --git a/src/bootstrap/Cargo.lock b/src/bootstrap/Cargo.lock index 0b37202089cd6..b31d58887ebd3 100644 --- a/src/bootstrap/Cargo.lock +++ b/src/bootstrap/Cargo.lock @@ -48,6 +48,7 @@ dependencies = [ "clap", "clap_complete", "cmake", + "errno", "expect-test", "home", "ignore", diff --git a/src/bootstrap/Cargo.toml b/src/bootstrap/Cargo.toml index c7bef3a36eaeb..7f352b01bf7db 100644 --- a/src/bootstrap/Cargo.toml +++ b/src/bootstrap/Cargo.toml @@ -39,6 +39,7 @@ cmake = "=0.1.54" build_helper = { path = "../build_helper" } clap = { version = "4.4", default-features = false, features = ["std", "usage", "help", "derive", "error-context"] } clap_complete = "4.4" +errno = "0.3.14" home = "0.5" ignore = "0.4" libc = "0.2" diff --git a/src/bootstrap/defaults/bootstrap.dist.toml b/src/bootstrap/defaults/bootstrap.dist.toml index 03e012079b079..c7f551aa68d51 100644 --- a/src/bootstrap/defaults/bootstrap.dist.toml +++ b/src/bootstrap/defaults/bootstrap.dist.toml @@ -7,6 +7,9 @@ test-stage = 2 doc-stage = 2 # When compiling from source, you usually want all tools. extended = true +# Builds for distribution typically run beneath some other build +# system that is expected to perform its own priority lowering. +low-priority = false # Most users installing from source want to build all parts of the project from source. [llvm] diff --git a/src/bootstrap/src/core/build_steps/compile.rs b/src/bootstrap/src/core/build_steps/compile.rs index c7af07210cc57..d9545aa2846d0 100644 --- a/src/bootstrap/src/core/build_steps/compile.rs +++ b/src/bootstrap/src/core/build_steps/compile.rs @@ -195,8 +195,10 @@ impl CommandLineStep for Std { return None; } - if builder.config.keep_stage.contains(&build_compiler.stage) - || builder.config.keep_stage_std.contains(&build_compiler.stage) + // Reuse std for `--keep-stage-std` if it was built before, otherwise build it. + if (builder.config.keep_stage.contains(&build_compiler.stage) + || builder.config.keep_stage_std.contains(&build_compiler.stage)) + && build_stamp::libstd_stamp(builder, build_compiler, target).path().exists() { trace!(keep_stage = ?builder.config.keep_stage); trace!(keep_stage_std = ?builder.config.keep_stage_std); diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 82728eebbdd16..c9b673edea236 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -1526,7 +1526,7 @@ NOTE: Please add `--stage 2` to your command line, or if you're sure you want to llvm_version_suffix, local_rebuild, locked_deps: build_locked_deps.unwrap_or(false), - low_priority: build_low_priority.unwrap_or(false), + low_priority: build_low_priority.unwrap_or(true), mandir: install_mandir.map(PathBuf::from), miri_info, musl_root: rust_musl_root.map(PathBuf::from), diff --git a/src/bootstrap/src/core/session.rs b/src/bootstrap/src/core/session.rs index 848b3e52de9f0..4a6cf789598b2 100644 --- a/src/bootstrap/src/core/session.rs +++ b/src/bootstrap/src/core/session.rs @@ -563,9 +563,7 @@ impl Session { #[cfg_attr(feature = "tracing", instrument(level = "debug", name = "Session::build", skip_all))] pub(crate) fn build(&mut self) { trace!("setting up job management"); - unsafe { - crate::utils::job::setup(self); - } + crate::utils::job::setup(self); // Handle hard-coded subcommands. { diff --git a/src/bootstrap/src/utils/change_tracker.rs b/src/bootstrap/src/utils/change_tracker.rs index 3db429b5f5124..78d0b22b0cbfc 100644 --- a/src/bootstrap/src/utils/change_tracker.rs +++ b/src/bootstrap/src/utils/change_tracker.rs @@ -686,4 +686,9 @@ pub const CONFIG_CHANGE_HISTORY: &[ChangeInfo] = &[ severity: ChangeSeverity::Info, summary: "A new option `llvm.tpde` has been added to control whether the TPDE pass plugin should be built as an experimental alternative LLVM backend.", }, + ChangeInfo { + change_id: 165707, + severity: ChangeSeverity::Info, + summary: "`low-priority` is now enabled by default aside from `bootstrap.dist.toml`, which is optimal for the overwhelming majority of situations.", + }, ]; diff --git a/src/bootstrap/src/utils/job.rs b/src/bootstrap/src/utils/job.rs index 45cff7c716ba9..b370bed36006b 100644 --- a/src/bootstrap/src/utils/job.rs +++ b/src/bootstrap/src/utils/job.rs @@ -1,15 +1,47 @@ +#[cfg(all(unix, not(any(target_os = "haiku", target_os = "hermit"))))] +pub(crate) use self::for_unix::setup; #[cfg(windows)] pub(crate) use self::for_windows::setup; use crate::core::session::Session; #[cfg(any(target_os = "haiku", target_os = "hermit", not(any(unix, windows))))] -pub(crate) unsafe fn setup(_sess: &Session) {} +pub(crate) fn setup(_sess: &Session) {} -#[cfg(all(unix, not(target_os = "haiku")))] -pub(crate) unsafe fn setup(sess: &Session) { - if sess.config.low_priority { - unsafe { - libc::setpriority(libc::PRIO_PGRP as _, 0, 10); +#[cfg(all(unix, not(any(target_os = "haiku", target_os = "hermit"))))] +mod for_unix { + use std::ffi::c_int; + use std::io; + + use libc::id_t; + + fn get_priority(which: c_int, who: id_t) -> io::Result { + // Genius design: `getpriority` can return -1 on success if the nice value is literally -1. + // Per `getpriority`'s docs, clear `errno` beforehand and check it afterward regardless of + // return value. + errno::set_errno(errno::Errno(0)); + // SAFETY: empty safety contract + let nice = unsafe { libc::getpriority(which as _, who) }; + let new_errno = errno::errno().0; + if new_errno == 0 { Ok(nice) } else { Err(io::Error::from_raw_os_error(new_errno)) } + } + fn set_priority(which: c_int, who: id_t, prio: c_int) -> io::Result<()> { + // SAFETY: empty safety contract + if unsafe { libc::setpriority(which as _, who, prio) != -1 } { + Ok(()) + } else { + Err(io::Error::last_os_error()) + } + } + + pub(crate) fn setup(sess: &super::Session) { + const TARGET_NICE: c_int = 10; + // The processes that spawn the build are all descendants of the + // current thread. + let (which, who) = (libc::PRIO_PROCESS as _, 0); + // Unwrap both of those to alert users to ridiculous Seccomp-BPF setups messing up their + // performance. + if sess.config.low_priority && get_priority(which, who).unwrap() < TARGET_NICE { + set_priority(which, who, TARGET_NICE).unwrap(); } } } @@ -59,7 +91,7 @@ mod for_windows { use windows::Win32::System::Threading::{BELOW_NORMAL_PRIORITY_CLASS, GetCurrentProcess}; use windows::core::PCWSTR; - pub(crate) unsafe fn setup(sess: &super::Session) { + pub(crate) fn setup(sess: &super::Session) { // SAFETY: pretty much everything below is unsafe unsafe { // Enable the Windows Error Reporting dialog which msys disables, diff --git a/src/ci/publish_backtrace.sh b/src/ci/publish_backtrace.sh new file mode 100755 index 0000000000000..783b2f08877a4 --- /dev/null +++ b/src/ci/publish_backtrace.sh @@ -0,0 +1,60 @@ +#!/bin/bash + +# Publish the backtrace crate to crates.io +# Should be called from a CI workflow +# Expects the following environment variables as input: +# - GITHUB_SHA: SHA of the currently merged commit from which backtrace should be published +# - TEMPDIR: scratch directory for temporary files + +set -euxo pipefail + +# Find PR for the current commit +HEAD_PR=$(gh pr list --search "${GITHUB_SHA}" --state merged --json number --jq '.[0].number') +if [ -z "${HEAD_PR}" ]; then + echo "PR for commit SHA ${GITHUB_SHA} not found, exiting" + exit 1 +fi +echo "HEAD: ${GITHUB_SHA} (#${HEAD_PR})" + +git submodule update --init library/backtrace +cd library/backtrace + +# Find the version of backtrace +VERSION=$( + cargo metadata --no-deps --format-version 1 | + jq -r '.packages[] | select(.name == "backtrace") | .version' +) +CRATE=backtrace + +# Check if the version already exists on crates.io with a HEAD request to the CDN +code=$( + curl --head --silent -o /dev/null --write-out '%{http_code}' \ + "https://static.crates.io/crates/${CRATE}/${CRATE}-${VERSION}.crate" +) + +# If the crate version already exists, then there is nothing left to do +if [[ $code == 200 ]]; then + exit 0 +fi + +set +e +cargo publish --locked &> "${TEMPDIR}"/cargo-log.txt +STATUS=$? +set -e + +COMMENT_FILE=${TEMPDIR}/comment.txt + +if [[ ${STATUS} == 0 ]]; then + echo "backtrace \`${VERSION}\` published to crates.io" > "${COMMENT_FILE}" +else + echo "backtrace \`${VERSION}\` could not be published to crates.io" > "${COMMENT_FILE}" + printf "
\nCargo publish log\n\n" >> "${COMMENT_FILE}" + printf '```\n' >> "${COMMENT_FILE}" + cat "${TEMPDIR}/cargo-log.txt" >> "${COMMENT_FILE}" + printf '\n```\n' >> "${COMMENT_FILE}" + printf "
\n\n" >> "${COMMENT_FILE}" +fi + +# Comment on the PR to let it know how it went +gh pr comment "${HEAD_PR}" -F "${COMMENT_FILE}" +exit "${STATUS}" diff --git a/src/tools/build-manifest/Cargo.toml b/src/tools/build-manifest/Cargo.toml index 0900afd6594fe..dca1d01221563 100644 --- a/src/tools/build-manifest/Cargo.toml +++ b/src/tools/build-manifest/Cargo.toml @@ -4,7 +4,7 @@ version = "0.1.0" edition = "2021" [dependencies] -toml = "0.7" +toml = "0.8" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" anyhow = "1.0.32" diff --git a/src/tools/compiletest/src/cli.rs b/src/tools/compiletest/src/cli.rs index 778d53f1d8d4f..e5c42e503fdf2 100644 --- a/src/tools/compiletest/src/cli.rs +++ b/src/tools/compiletest/src/cli.rs @@ -1,33 +1,122 @@ //! Isolates the APIs used by `bin/main.rs`, to help minimize the surface area //! of public exports from the compiletest library crate. -use std::env; +use std::fmt::Write; use std::io::IsTerminal; use std::sync::{Arc, OnceLock}; +use std::{env, fs}; use camino::{Utf8Path, Utf8PathBuf}; use clap::Parser; use crate::common::{CodegenBackend, CompareMode, Config, ForcePassMode, TestMode, TestSuite}; use crate::edition::Edition; -use crate::{debuggers, directives, early_config_check, run_tests}; +use crate::{ + debuggers, directives, discovery, executor, help, panic_hook, raise_fd_limit, warning, +}; pub fn main() { + // sadly osx needs some file descriptor limits raised for running tests in + // parallel (especially when we have lots and lots of child processes). + // For context, see #8904 + unsafe { raise_fd_limit::raise_fd_limit() }; + + // Prevent issue #21352 UAC blocking .exe containing 'patch' etc. on Windows + // If #11207 is resolved (adding manifest to .exe) this becomes unnecessary + // + // SAFETY: at this point we're still single-threaded. + unsafe { env::set_var("__COMPAT_LAYER", "RunAsInvoker") }; + tracing_subscriber::fmt::init(); + panic_hook::install_panic_hook(); // colored checks stdout by default, but for some reason only stderr is a terminal. // compiletest *does* print many things to stdout, but it doesn't really matter. if std::io::stderr().is_terminal() - && matches!(std::env::var("NO_COLOR").as_deref(), Err(_) | Ok("0")) + && matches!(env::var("NO_COLOR").as_deref(), Err(_) | Ok("0")) { colored::control::set_override(true); } let config = Arc::new(parse_config(env::args().collect())); - early_config_check(&config); - run_tests(config); + // If we want to collect rustfix coverage information, + // we first make sure that the coverage file does not exist. + // It will be created later on. + if config.rustfix_coverage { + let mut coverage_file_path = config.build_test_suite_root.clone(); + coverage_file_path.push("rustfix_missing_coverage.txt"); + if coverage_file_path.exists() { + fs::remove_file(&coverage_file_path) + .unwrap_or_else(|e| panic!("Could not delete {coverage_file_path} due to {e}")); + } + } + + // FIXME: this should ideally happen somewhere else.. + if config.mode == TestMode::DebugInfo && config.target.contains("android") { + println!("{} debug-info test uses tcp 5039 port. please reserve it", config.target); + + // android debug-info test uses remote debugger so, we test 1 thread + // at once as they're all sharing the same TCP port to communicate + // over. + // + // we should figure out how to lift this restriction! (run them all + // on different ports allocated dynamically). + // + // SAFETY: at this point we are still single-threaded. + unsafe { env::set_var("RUST_TEST_THREADS", "1") }; + } + + // Scan the test directory for tests, and create a test struct for each test/variant. + let tests = discovery::discover_tests(&config); + + // Delegate to the executor to filter and run the big list of test structures + // created during test discovery. When the executor decides to run a test, + // it will return control to the rest of compiletest by calling `runtest::run`. + let ok = executor::run_tests(&config, tests); + + // Check the outcome reported by the executor. + if !ok { + // We want to report that the tests failed, but we also want to give + // some indication of just what tests we were running. Especially on + // CI, where there can be cross-compiled tests for a lot of + // architectures, without this critical information it can be quite + // easy to miss which tests failed, and as such fail to reproduce + // the failure locally. + + let mut msg = String::from("Some tests failed in compiletest"); + write!(msg, " suite={}", config.suite).unwrap(); + + if let Some(compare_mode) = config.compare_mode.as_ref() { + write!(msg, " compare_mode={}", compare_mode).unwrap(); + } + + if let Some(pass_mode) = config.force_pass_mode.as_ref() { + write!(msg, " pass_mode={}", pass_mode).unwrap(); + } + + write!(msg, " mode={}", config.mode).unwrap(); + write!(msg, " host={}", config.host).unwrap(); + write!(msg, " target={}", config.target).unwrap(); + + println!("{msg}"); + + std::process::exit(1); + } +} + +fn early_config_check(config: &Config) { + if !config.profiler_runtime && config.mode == TestMode::CoverageRun { + let actioned = if config.bless { "blessed" } else { "checked" }; + warning!("profiler runtime is not available, so `.coverage` files won't be {actioned}"); + help!("try setting `profiler = true` in the `[build]` section of `bootstrap.toml`"); + } + + // `RUST_TEST_NOCAPTURE` is a libtest env var, but we don't callout to libtest. + if env::var("RUST_TEST_NOCAPTURE").is_ok() { + warning!("`RUST_TEST_NOCAPTURE` is not supported; use the `--no-capture` flag instead"); + } } /// Compiletest command-line arguments. diff --git a/src/tools/compiletest/src/directives.rs b/src/tools/compiletest/src/directives.rs index 4e99ab99f6059..1f0cc0577b082 100644 --- a/src/tools/compiletest/src/directives.rs +++ b/src/tools/compiletest/src/directives.rs @@ -7,7 +7,7 @@ use camino::{Utf8Path, Utf8PathBuf}; use semver::Version; use tracing::*; -use crate::common::{Config, Debugger, PassFailMode, TestMode}; +use crate::common::{CodegenBackend, Config, Debugger, PassFailMode, TestMode}; use crate::debuggers::{LldbVersion, extract_cdb_version, extract_gdb_version}; use crate::directives::auxiliary::parse_and_update_aux; pub(crate) use crate::directives::auxiliary::{AuxCrate, AuxProps}; @@ -1218,7 +1218,7 @@ fn needs_backends(config: &Config, line: &DirectiveLine<'_>) -> IgnoreDecision { /// When using the GCC backend, ignore tests for which we did not find a libgccjit.so. fn ignore_unsupported_backend_target(config: &Config, line: &DirectiveLine<'_>) -> IgnoreDecision { - if config.default_codegen_backend != crate::CodegenBackend::Gcc { + if config.default_codegen_backend != CodegenBackend::Gcc { return IgnoreDecision::Continue; } diff --git a/src/tools/compiletest/src/discovery.rs b/src/tools/compiletest/src/discovery.rs new file mode 100644 index 0000000000000..9609f7ac173be --- /dev/null +++ b/src/tools/compiletest/src/discovery.rs @@ -0,0 +1,620 @@ +use core::panic; +use std::collections::HashSet; +use std::io::{self, ErrorKind}; +use std::sync::Arc; +use std::time::SystemTime; +use std::{fs, vec}; + +use build_helper::git::{get_git_modified_files, get_git_untracked_files}; +use camino::{Utf8Component, Utf8Path, Utf8PathBuf}; +use rayon::iter::{ParallelBridge, ParallelIterator}; +use tracing::debug; +use walkdir::WalkDir; + +use crate::common::{ + CodegenBackend, Config, Debugger, TestMode, TestPaths, UI_EXTENSIONS, expected_output_path, + output_base_dir, output_relative_path, +}; +use crate::directives::{ + self, AuxProps, DirectivesCache, EarlyProps, FileDirectives, make_test_description, +}; +use crate::executor::{CollectedTest, TestVariant}; +use crate::{fatal, runtest, warning}; + +/// Called by `main` after the config has been parsed. +pub(crate) fn discover_tests(config: &Arc) -> Vec { + debug!(?config, "run_tests"); + + // Debugging emscripten code doesn't make sense today + let ignore_tests = config.mode == TestMode::DebugInfo && config.target.contains("emscripten"); + + // Discover all of the tests in the test suite directory, and build a `CollectedTest` + // structure for each test (or each revision of a multi-revision test). + let mut tests = Vec::new(); + if !ignore_tests { + tests.extend(collect_and_make_tests(config.clone())); + } + + tests.sort_by(|a, b| Ord::cmp(&a.desc.name, &b.desc.name)); + + tests +} + +/// Read-only context data used during test collection. +struct TestCollectorCx { + config: Arc, + cache: DirectivesCache, + common_inputs_stamp: Stamp, + modified_tests: Vec, +} + +/// Mutable state used during test collection. +struct TestCollector { + tests: Vec, + found_path_stems: HashSet, + poisoned: bool, +} + +impl TestCollector { + fn new() -> Self { + TestCollector { tests: vec![], found_path_stems: HashSet::new(), poisoned: false } + } + + fn merge(&mut self, mut other: Self) { + self.tests.append(&mut other.tests); + self.found_path_stems.extend(other.found_path_stems); + self.poisoned |= other.poisoned; + } +} + +/// Creates test structures for every test/revision in the test suite directory. +/// +/// This always inspects _all_ test files in the suite (e.g. all 17k+ ui tests), +/// regardless of whether any filters/tests were specified on the command-line, +/// because filtering is handled later by code that was copied from libtest. +/// +/// FIXME(Zalathar): Now that we no longer rely on libtest, try to overhaul +/// test discovery to take into account the filters/tests specified on the +/// command-line, instead of having to enumerate everything. +fn collect_and_make_tests(config: Arc) -> Vec { + debug!("making tests from {}", config.src_test_suite_root); + let common_inputs_stamp = common_inputs_stamp(&config); + let modified_tests = + modified_tests(&config, &config.src_test_suite_root).unwrap_or_else(|err| { + fatal!("modified_tests: {}: {err}", config.src_test_suite_root); + }); + let cache = DirectivesCache::load(&config); + + let cx = TestCollectorCx { config, cache, common_inputs_stamp, modified_tests }; + let collector = collect_tests_from_dir(&cx, &cx.config.src_test_suite_root, Utf8Path::new("")) + .unwrap_or_else(|reason| { + panic!("Could not read tests from {}: {reason}", cx.config.src_test_suite_root) + }); + + let TestCollector { tests, found_path_stems, poisoned } = collector; + + if poisoned { + eprintln!(); + panic!("there are errors in tests"); + } + + check_for_overlapping_test_paths(&found_path_stems); + + tests +} + +/// Returns the most recent last-modified timestamp from among the input files +/// that are considered relevant to all tests (e.g. the compiler, std, and +/// compiletest itself). +/// +/// (Some of these inputs aren't actually relevant to _all_ tests, but they are +/// common to some subset of tests, and are hopefully unlikely to be modified +/// while working on other tests.) +fn common_inputs_stamp(config: &Config) -> Stamp { + let src_root = &config.src_root; + + let mut stamp = Stamp::from_path(&config.rustc_path); + + // Relevant pretty printer files + let pretty_printer_files = [ + "src/etc/rust_types.py", + "src/etc/gdb_load_rust_pretty_printers.py", + "src/etc/gdb_lookup.py", + "src/etc/gdb_providers.py", + "src/etc/lldb_lookup.py", + "src/etc/lldb_providers.py", + ]; + for file in &pretty_printer_files { + let path = src_root.join(file); + stamp.add_path(&path); + } + + stamp.add_dir(&src_root.join("src/etc/debugger_tester")); + stamp.add_dir(&src_root.join("src/etc/natvis")); + + stamp.add_dir(&config.target_run_lib_path); + + if let Some(ref rustdoc_path) = config.rustdoc_path { + stamp.add_path(&rustdoc_path); + stamp.add_path(&src_root.join("src/etc/htmldocck.py")); + } + + // Re-run coverage tests if the `coverage-dump` tool was modified, + // because its output format might have changed. + if let Some(coverage_dump_path) = &config.coverage_dump_path { + stamp.add_path(coverage_dump_path) + } + + stamp.add_dir(&src_root.join("src/tools/run-make-support")); + + // Compiletest itself. + stamp.add_dir(&src_root.join("src/tools/compiletest")); + + stamp +} + +/// Returns a list of modified/untracked test files that should be run when +/// the `--only-modified` flag is in use. +/// +/// (Might be inaccurate in some cases.) +fn modified_tests(config: &Config, dir: &Utf8Path) -> Result, String> { + // If `--only-modified` wasn't passed, the list of modified tests won't be + // used for anything, so avoid some work and just return an empty list. + if !config.only_modified { + return Ok(vec![]); + } + + let files = get_git_modified_files( + &config.git_config(), + Some(dir.as_std_path()), + &vec!["rs", "stderr", "fixed"], + )?; + // Add new test cases to the list, it will be convenient in daily development. + let untracked_files = get_git_untracked_files(Some(dir.as_std_path()))?.unwrap_or(vec![]); + + let all_paths = [&files[..], &untracked_files[..]].concat(); + let full_paths = { + let mut full_paths: Vec = all_paths + .into_iter() + .map(|f| Utf8PathBuf::from(f).with_extension("").with_extension("rs")) + .filter_map( + |f| if Utf8Path::new(&f).exists() { f.canonicalize_utf8().ok() } else { None }, + ) + .collect(); + full_paths.dedup(); + full_paths.sort_unstable(); + full_paths + }; + Ok(full_paths) +} + +/// Recursively scans a directory to find test files and create test structures +/// that will be handed over to the executor. +fn collect_tests_from_dir( + cx: &TestCollectorCx, + dir: &Utf8Path, + relative_dir_path: &Utf8Path, +) -> io::Result { + // Ignore directories that contain a file named `compiletest-ignore-dir`. + if dir.join("compiletest-ignore-dir").exists() { + return Ok(TestCollector::new()); + } + + let mut components = dir.components().rev(); + if let Some(Utf8Component::Normal(last)) = components.next() + && let Some(("assembly" | "codegen", backend)) = last.split_once('-') + && let Some(Utf8Component::Normal(parent)) = components.next() + && parent == "tests" + && let Ok(backend) = backend.parse::() + && backend != cx.config.default_codegen_backend + { + // We ignore asm tests which don't match the current codegen backend. + warning!( + "Ignoring tests in `{dir}` because they don't match the configured codegen \ + backend (`{}`)", + cx.config.default_codegen_backend.as_str(), + ); + return Ok(TestCollector::new()); + } + + // For run-make tests, a "test file" is actually a directory that contains an `rmake.rs`. + if cx.config.mode == TestMode::RunMake { + let mut collector = TestCollector::new(); + if dir.join("rmake.rs").exists() { + let paths = TestPaths { + file: dir.to_path_buf(), + relative_dir: relative_dir_path.parent().unwrap().to_path_buf(), + }; + make_test(cx, &mut collector, &paths); + // This directory is a test, so don't try to find other tests inside it. + return Ok(collector); + } + } + + // If we find a test foo/bar.rs, we have to build the + // output directory `$build/foo` so we can write + // `$build/foo/bar` into it. We do this *now* in this + // sequential loop because otherwise, if we do it in the + // tests themselves, they race for the privilege of + // creating the directories and sometimes fail randomly. + let build_dir = output_relative_path(&cx.config, relative_dir_path); + fs::create_dir_all(&build_dir).unwrap(); + + // Add each `.rs` file as a test, and recurse further on any + // subdirectories we find, except for `auxiliary` directories. + // FIXME: this walks full tests tree, even if we have something to ignore + // use walkdir/ignore like in tidy? + fs::read_dir(dir.as_std_path())? + .par_bridge() + .map(|file| { + let mut collector = TestCollector::new(); + let file = file?; + let file_path = Utf8PathBuf::try_from(file.path()).unwrap(); + let file_name = file_path.file_name().unwrap(); + + if is_test(file_name) + && (!cx.config.only_modified || cx.modified_tests.contains(&file_path)) + { + // We found a test file, so create the corresponding test structures. + debug!(%file_path, "found test file"); + + // Record the stem of the test file, to check for overlaps later. + let rel_test_path = relative_dir_path.join(file_path.file_stem().unwrap()); + collector.found_path_stems.insert(rel_test_path); + + let paths = + TestPaths { file: file_path, relative_dir: relative_dir_path.to_path_buf() }; + make_test(cx, &mut collector, &paths); + } else if file_path.is_dir() { + // Recurse to find more tests in a subdirectory. + let relative_file_path = relative_dir_path.join(file_name); + if file_name != "auxiliary" { + debug!(%file_path, "found directory"); + collector.merge(collect_tests_from_dir(cx, &file_path, &relative_file_path)?); + } + } else { + debug!(%file_path, "found other file/directory"); + } + Ok(collector) + }) + .reduce( + || Ok(TestCollector::new()), + |a, b| { + let mut a = a?; + a.merge(b?); + Ok(a) + }, + ) +} + +/// Returns true if `file_name` looks like a proper test file name. +pub(crate) fn is_test(file_name: &str) -> bool { + if !file_name.ends_with(".rs") { + return false; + } + + // `.`, `#`, and `~` are common temp-file prefixes. + let invalid_prefixes = &[".", "#", "~"]; + !invalid_prefixes.iter().any(|p| file_name.starts_with(p)) +} + +/// For a single test file, creates one or more test structures (one per revision) that can be +/// handed over to the executor to run, possibly in parallel. +fn make_test(cx: &TestCollectorCx, collector: &mut TestCollector, testpaths: &TestPaths) { + // For run-make tests, each "test file" is actually a _directory_ containing an `rmake.rs`. But + // for the purposes of directive parsing, we want to look at that recipe file, not the directory + // itself. + let test_path = if cx.config.mode == TestMode::RunMake { + testpaths.file.join("rmake.rs") + } else { + testpaths.file.clone() + }; + + // Scan the test file to discover its revisions, if any. + let file_contents = + fs::read_to_string(&test_path).expect("reading test file for directives should succeed"); + let file_directives = FileDirectives::from_file_contents(&test_path, &file_contents); + + if let Err(message) = directives::do_early_directives_check(cx.config.mode, &file_directives) { + // FIXME(Zalathar): Overhaul compiletest error handling so that we + // don't have to resort to ad-hoc panics everywhere. + panic!("directives check failed:\n{message}"); + } + let early_props = EarlyProps::from_file_directives(&cx.config, &file_directives); + + // Normally we create one structure per revision, with two exceptions: + // - If a test doesn't use revisions, create a dummy revision (None) so that + // the test can still run. + // - Incremental tests inherently can't run their revisions in parallel, so + // we treat them like non-revisioned tests here. Incremental revisions are + // handled internally by `runtest::run` instead. + let revisions = if early_props.revisions.is_empty() || cx.config.mode == TestMode::Incremental { + vec![None] + } else { + early_props.revisions.iter().map(|r| Some(r.as_str())).collect() + }; + + // For debuginfo tests, we have to run them once for each debugger. + // We thus create a cartesian product of each revision and each supported debugger here. + let debuggers = if cx.config.mode == TestMode::DebugInfo { + vec![Some(Debugger::Cdb), Some(Debugger::Gdb), Some(Debugger::Lldb)] + } else { + vec![None] + }; + + // For each revision (or the sole dummy revision) and each debugger, create and append a + // `CollectedTest` that can be handed over to the test executor. + for debugger in debuggers { + collector.tests.extend(revisions.iter().map(|&revision| { + let revision = revision.map(str::to_owned); + let variant = TestVariant { revision, debugger }; + + // Create a test name and description to hand over to the executor. + let (test_name, filterable_path) = + make_test_name_and_filterable_path(&cx.config, testpaths, &variant); + + // While scanning for ignore/only/needs directives, also collect aux + // paths for up-to-date checking. + let mut aux_props = AuxProps::default(); + + // Create a description struct for the test/revision. + // This is where `ignore-*`/`only-*`/`needs-*` directives are handled, + // because they historically needed to set the libtest ignored flag. + let mut desc = make_test_description( + &cx.config, + &cx.cache, + test_name, + &test_path, + &filterable_path, + &file_directives, + &variant, + &mut collector.poisoned, + &mut aux_props, + ); + + // If a test's inputs haven't changed since the last time it ran, + // mark it as ignored so that the executor will skip it. + if !desc.is_ignored() + && !cx.config.force_rerun + && is_up_to_date(cx, testpaths, &aux_props, &variant) + { + // Keep this in sync with the "up-to-date" message detected by bootstrap. + // FIXME(Zalathar): Now that we are no longer tied to libtest, we could + // find a less fragile way to communicate this status to bootstrap. + desc.ignore_message = Some("up-to-date".into()); + } + + let config = Arc::clone(&cx.config); + let testpaths = testpaths.clone(); + + CollectedTest { desc, config, testpaths, variant } + })); + } +} + +/// The path of the `stamp` file that gets created or updated whenever a +/// particular test completes successfully. +pub(crate) fn stamp_file_path( + config: &Config, + testpaths: &TestPaths, + variant: &TestVariant, +) -> Utf8PathBuf { + output_base_dir(config, testpaths, variant).join("stamp") +} + +/// Returns a list of files that, if modified, would cause this test to no +/// longer be up-to-date. +/// +/// (Might be inaccurate in some cases.) +fn files_related_to_test( + config: &Config, + testpaths: &TestPaths, + aux_props: &AuxProps, + variant: &TestVariant, +) -> Vec { + let mut related = vec![]; + + if testpaths.file.is_dir() { + // run-make tests use their individual directory + for entry in WalkDir::new(&testpaths.file) { + let path = entry.unwrap().into_path(); + if path.is_file() { + related.push(Utf8PathBuf::try_from(path).unwrap()); + } + } + } else { + related.push(testpaths.file.clone()); + } + + for aux in aux_props.all_aux_path_strings() { + // FIXME(Zalathar): Perform all `auxiliary` path resolution in one place. + // FIXME(Zalathar): This only finds auxiliary files used _directly_ by + // the test file; if a transitive auxiliary is modified, the test might + // be treated as "up-to-date" even though it should run. + let path = testpaths.file.parent().unwrap().join("auxiliary").join(aux); + related.push(path); + } + + // UI test files. + for extension in UI_EXTENSIONS { + let path = + expected_output_path(testpaths, variant.revision(), &config.compare_mode, extension); + related.push(path); + } + + // `minicore.rs` test auxiliary: we need to make sure tests get rerun if this changes. + related.push(config.src_root.join("tests").join("auxiliary").join("minicore.rs")); + + // `tests/debuginfo` blessed files + match variant.debugger { + Some(debugger @ Debugger::Lldb | debugger @ Debugger::Gdb) => { + let bless_path: Utf8PathBuf = + testpaths.file.parent().unwrap().join(format!("{}_input", debugger.to_str())); + if bless_path.is_dir() { + related.extend( + WalkDir::new(bless_path) + .into_iter() + .map(|entry| Utf8PathBuf::from(entry.unwrap().path().to_str().unwrap())), + ); + } + } + Some(Debugger::Cdb) | None => {} + } + + related +} + +/// Checks whether a particular test/revision is "up-to-date", meaning that no +/// relevant files/settings have changed since the last time the test succeeded. +/// +/// (This is not very reliable in some circumstances, so the `--force-rerun` +/// flag can be used to ignore up-to-date checking and always re-run tests.) +fn is_up_to_date( + cx: &TestCollectorCx, + testpaths: &TestPaths, + aux_props: &AuxProps, + variant: &TestVariant, +) -> bool { + let stamp_file_path = stamp_file_path(&cx.config, testpaths, variant); + // Check the config hash inside the stamp file. + let contents = match fs::read_to_string(&stamp_file_path) { + Ok(f) => f, + Err(ref e) if e.kind() == ErrorKind::InvalidData => panic!("Can't read stamp contents"), + // The test hasn't succeeded yet, so it is not up-to-date. + Err(_) => return false, + }; + let expected_hash = runtest::compute_stamp_hash(&cx.config, variant); + if contents != expected_hash { + // Some part of compiletest configuration has changed since the test + // last succeeded, so it is not up-to-date. + return false; + } + + // Check the timestamp of the stamp file against the last modified time + // of all files known to be relevant to the test. + let mut inputs_stamp = cx.common_inputs_stamp.clone(); + for path in files_related_to_test(&cx.config, testpaths, aux_props, variant) { + inputs_stamp.add_path(&path); + } + + // If no relevant files have been modified since the stamp file was last + // written, the test is up-to-date. + inputs_stamp < Stamp::from_path(&stamp_file_path) +} + +/// The maximum of a set of file-modified timestamps. +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +struct Stamp { + time: SystemTime, +} + +impl Stamp { + /// Creates a timestamp holding the last-modified time of the specified file. + fn from_path(path: &Utf8Path) -> Self { + let mut stamp = Stamp { time: SystemTime::UNIX_EPOCH }; + stamp.add_path(path); + stamp + } + + /// Updates this timestamp to the last-modified time of the specified file, + /// if it is later than the currently-stored timestamp. + fn add_path(&mut self, path: &Utf8Path) { + let modified = fs::metadata(path.as_std_path()) + .and_then(|metadata| metadata.modified()) + .unwrap_or(SystemTime::UNIX_EPOCH); + self.time = self.time.max(modified); + } + + /// Updates this timestamp to the most recent last-modified time of all files + /// recursively contained in the given directory, if it is later than the + /// currently-stored timestamp. + fn add_dir(&mut self, path: &Utf8Path) { + let path = path.as_std_path(); + for entry in WalkDir::new(path) { + let entry = entry.unwrap(); + if entry.file_type().is_file() { + let modified = entry + .metadata() + .ok() + .and_then(|metadata| metadata.modified().ok()) + .unwrap_or(SystemTime::UNIX_EPOCH); + self.time = self.time.max(modified); + } + } + } +} + +/// Creates a name for this test/revision that can be handed over to the executor. +fn make_test_name_and_filterable_path( + config: &Config, + testpaths: &TestPaths, + variant: &TestVariant, +) -> (String, Utf8PathBuf) { + // Print the name of the file, relative to the sources root. + let path = testpaths.file.strip_prefix(&config.src_root).unwrap(); + let debugger = match variant.debugger.as_ref() { + Some(d) => format!("-{d}"), + None => String::new(), + }; + let mode_suffix = match config.compare_mode { + Some(ref mode) => format!(" ({})", mode.to_str()), + None => String::new(), + }; + + let name = format!( + "[{}{}{}] {}{}", + config.mode, + debugger, + mode_suffix, + path, + variant.revision().map_or("".to_string(), |rev| format!("#{}", rev)) + ); + + // `path` is the full path from the repo root like, `tests/ui/foo/bar.rs`. + // Filtering is applied without the `tests/ui/` part, so strip that off. + // First strip off "tests" to make sure we don't have some unexpected path. + let mut filterable_path = path.strip_prefix("tests").unwrap().to_owned(); + // Now strip off e.g. "ui" or "run-make" component. + filterable_path = filterable_path.components().skip(1).collect(); + + (name, filterable_path) +} + +/// Checks that test discovery didn't find any tests whose name stem is a prefix +/// of some other tests's name. +/// +/// For example, suppose the test suite contains these two test files: +/// - `tests/rustdoc-html/primitive.rs` +/// - `tests/rustdoc-html/primitive/no_std.rs` +/// +/// The test runner might put the output from those tests in these directories: +/// - `$build/test/rustdoc/primitive/` +/// - `$build/test/rustdoc/primitive/no_std/` +/// +/// Because one output path is a subdirectory of the other, the two tests might +/// interfere with each other in unwanted ways, especially if the test runner +/// decides to delete test output directories to clean them between runs. +/// To avoid problems, we forbid test names from overlapping in this way. +/// +/// See for more context. +fn check_for_overlapping_test_paths(found_path_stems: &HashSet) { + let mut collisions = Vec::new(); + for path in found_path_stems { + for ancestor in path.ancestors().skip(1) { + if found_path_stems.contains(ancestor) { + collisions.push((path, ancestor)); + } + } + } + if !collisions.is_empty() { + collisions.sort(); + let collisions: String = collisions + .into_iter() + .map(|(path, check_parent)| format!("test {path} clashes with {check_parent}\n")) + .collect(); + panic!( + "{collisions}\n\ + Tests cannot have overlapping names. Make sure they use unique prefixes." + ); + } +} diff --git a/src/tools/compiletest/src/lib.rs b/src/tools/compiletest/src/lib.rs index 8b5ec7c3ed531..c8c39900fc645 100644 --- a/src/tools/compiletest/src/lib.rs +++ b/src/tools/compiletest/src/lib.rs @@ -12,6 +12,7 @@ mod common; mod debuggers; mod diagnostics; mod directives; +mod discovery; mod edition; mod errors; mod executor; @@ -22,708 +23,3 @@ mod raise_fd_limit; mod read2; mod runtest; mod util; - -use core::panic; -use std::collections::HashSet; -use std::fmt::Write; -use std::io::{self, ErrorKind}; -use std::sync::Arc; -use std::time::SystemTime; -use std::{env, fs, vec}; - -use build_helper::git::{get_git_modified_files, get_git_untracked_files}; -use camino::{Utf8Component, Utf8Path, Utf8PathBuf}; -use rayon::iter::{ParallelBridge, ParallelIterator}; -use tracing::debug; -use walkdir::WalkDir; - -use self::directives::{EarlyProps, make_test_description}; -use crate::common::{ - CodegenBackend, Config, Debugger, TestMode, TestPaths, UI_EXTENSIONS, expected_output_path, - output_base_dir, output_relative_path, -}; -use crate::directives::{AuxProps, DirectivesCache, FileDirectives}; -use crate::executor::{CollectedTest, TestVariant}; - -/// Called by `main` after the config has been parsed. -fn run_tests(config: Arc) { - debug!(?config, "run_tests"); - - panic_hook::install_panic_hook(); - - // If we want to collect rustfix coverage information, - // we first make sure that the coverage file does not exist. - // It will be created later on. - if config.rustfix_coverage { - let mut coverage_file_path = config.build_test_suite_root.clone(); - coverage_file_path.push("rustfix_missing_coverage.txt"); - if coverage_file_path.exists() { - if let Err(e) = fs::remove_file(&coverage_file_path) { - panic!("Could not delete {} due to {}", coverage_file_path, e) - } - } - } - - // sadly osx needs some file descriptor limits raised for running tests in - // parallel (especially when we have lots and lots of child processes). - // For context, see #8904 - unsafe { - raise_fd_limit::raise_fd_limit(); - } - // Prevent issue #21352 UAC blocking .exe containing 'patch' etc. on Windows - // If #11207 is resolved (adding manifest to .exe) this becomes unnecessary - // - // SAFETY: at this point we're still single-threaded. - unsafe { env::set_var("__COMPAT_LAYER", "RunAsInvoker") }; - - // Debugging emscripten code doesn't make sense today - let ignore_tests = config.mode == TestMode::DebugInfo && config.target.contains("emscripten"); - - if let TestMode::DebugInfo = config.mode { - // FIXME: this should ideally happen somewhere else.. - if config.target.contains("android") { - println!("{} debug-info test uses tcp 5039 port. please reserve it", config.target); - - // android debug-info test uses remote debugger so, we test 1 thread - // at once as they're all sharing the same TCP port to communicate - // over. - // - // we should figure out how to lift this restriction! (run them all - // on different ports allocated dynamically). - // - // SAFETY: at this point we are still single-threaded. - unsafe { env::set_var("RUST_TEST_THREADS", "1") }; - } - }; - - // Discover all of the tests in the test suite directory, and build a `CollectedTest` - // structure for each test (or each revision of a multi-revision test). - let mut tests = Vec::new(); - if !ignore_tests { - tests.extend(collect_and_make_tests(config.clone())); - } - - tests.sort_by(|a, b| Ord::cmp(&a.desc.name, &b.desc.name)); - - // Delegate to the executor to filter and run the big list of test structures - // created during test discovery. When the executor decides to run a test, - // it will return control to the rest of compiletest by calling `runtest::run`. - let ok = executor::run_tests(&config, tests); - - // Check the outcome reported by the executor. - if !ok { - // We want to report that the tests failed, but we also want to give - // some indication of just what tests we were running. Especially on - // CI, where there can be cross-compiled tests for a lot of - // architectures, without this critical information it can be quite - // easy to miss which tests failed, and as such fail to reproduce - // the failure locally. - - let mut msg = String::from("Some tests failed in compiletest"); - write!(msg, " suite={}", config.suite).unwrap(); - - if let Some(compare_mode) = config.compare_mode.as_ref() { - write!(msg, " compare_mode={}", compare_mode).unwrap(); - } - - if let Some(pass_mode) = config.force_pass_mode.as_ref() { - write!(msg, " pass_mode={}", pass_mode).unwrap(); - } - - write!(msg, " mode={}", config.mode).unwrap(); - write!(msg, " host={}", config.host).unwrap(); - write!(msg, " target={}", config.target).unwrap(); - - println!("{msg}"); - - std::process::exit(1); - } -} - -/// Read-only context data used during test collection. -struct TestCollectorCx { - config: Arc, - cache: DirectivesCache, - common_inputs_stamp: Stamp, - modified_tests: Vec, -} - -/// Mutable state used during test collection. -struct TestCollector { - tests: Vec, - found_path_stems: HashSet, - poisoned: bool, -} - -impl TestCollector { - fn new() -> Self { - TestCollector { tests: vec![], found_path_stems: HashSet::new(), poisoned: false } - } - - fn merge(&mut self, mut other: Self) { - self.tests.append(&mut other.tests); - self.found_path_stems.extend(other.found_path_stems); - self.poisoned |= other.poisoned; - } -} - -/// Creates test structures for every test/revision in the test suite directory. -/// -/// This always inspects _all_ test files in the suite (e.g. all 17k+ ui tests), -/// regardless of whether any filters/tests were specified on the command-line, -/// because filtering is handled later by code that was copied from libtest. -/// -/// FIXME(Zalathar): Now that we no longer rely on libtest, try to overhaul -/// test discovery to take into account the filters/tests specified on the -/// command-line, instead of having to enumerate everything. -fn collect_and_make_tests(config: Arc) -> Vec { - debug!("making tests from {}", config.src_test_suite_root); - let common_inputs_stamp = common_inputs_stamp(&config); - let modified_tests = - modified_tests(&config, &config.src_test_suite_root).unwrap_or_else(|err| { - fatal!("modified_tests: {}: {err}", config.src_test_suite_root); - }); - let cache = DirectivesCache::load(&config); - - let cx = TestCollectorCx { config, cache, common_inputs_stamp, modified_tests }; - let collector = collect_tests_from_dir(&cx, &cx.config.src_test_suite_root, Utf8Path::new("")) - .unwrap_or_else(|reason| { - panic!("Could not read tests from {}: {reason}", cx.config.src_test_suite_root) - }); - - let TestCollector { tests, found_path_stems, poisoned } = collector; - - if poisoned { - eprintln!(); - panic!("there are errors in tests"); - } - - check_for_overlapping_test_paths(&found_path_stems); - - tests -} - -/// Returns the most recent last-modified timestamp from among the input files -/// that are considered relevant to all tests (e.g. the compiler, std, and -/// compiletest itself). -/// -/// (Some of these inputs aren't actually relevant to _all_ tests, but they are -/// common to some subset of tests, and are hopefully unlikely to be modified -/// while working on other tests.) -fn common_inputs_stamp(config: &Config) -> Stamp { - let src_root = &config.src_root; - - let mut stamp = Stamp::from_path(&config.rustc_path); - - // Relevant pretty printer files - let pretty_printer_files = [ - "src/etc/rust_types.py", - "src/etc/gdb_load_rust_pretty_printers.py", - "src/etc/gdb_lookup.py", - "src/etc/gdb_providers.py", - "src/etc/lldb_lookup.py", - "src/etc/lldb_providers.py", - ]; - for file in &pretty_printer_files { - let path = src_root.join(file); - stamp.add_path(&path); - } - - stamp.add_dir(&src_root.join("src/etc/debugger_tester")); - stamp.add_dir(&src_root.join("src/etc/natvis")); - - stamp.add_dir(&config.target_run_lib_path); - - if let Some(ref rustdoc_path) = config.rustdoc_path { - stamp.add_path(&rustdoc_path); - stamp.add_path(&src_root.join("src/etc/htmldocck.py")); - } - - // Re-run coverage tests if the `coverage-dump` tool was modified, - // because its output format might have changed. - if let Some(coverage_dump_path) = &config.coverage_dump_path { - stamp.add_path(coverage_dump_path) - } - - stamp.add_dir(&src_root.join("src/tools/run-make-support")); - - // Compiletest itself. - stamp.add_dir(&src_root.join("src/tools/compiletest")); - - stamp -} - -/// Returns a list of modified/untracked test files that should be run when -/// the `--only-modified` flag is in use. -/// -/// (Might be inaccurate in some cases.) -fn modified_tests(config: &Config, dir: &Utf8Path) -> Result, String> { - // If `--only-modified` wasn't passed, the list of modified tests won't be - // used for anything, so avoid some work and just return an empty list. - if !config.only_modified { - return Ok(vec![]); - } - - let files = get_git_modified_files( - &config.git_config(), - Some(dir.as_std_path()), - &vec!["rs", "stderr", "fixed"], - )?; - // Add new test cases to the list, it will be convenient in daily development. - let untracked_files = get_git_untracked_files(Some(dir.as_std_path()))?.unwrap_or(vec![]); - - let all_paths = [&files[..], &untracked_files[..]].concat(); - let full_paths = { - let mut full_paths: Vec = all_paths - .into_iter() - .map(|f| Utf8PathBuf::from(f).with_extension("").with_extension("rs")) - .filter_map( - |f| if Utf8Path::new(&f).exists() { f.canonicalize_utf8().ok() } else { None }, - ) - .collect(); - full_paths.dedup(); - full_paths.sort_unstable(); - full_paths - }; - Ok(full_paths) -} - -/// Recursively scans a directory to find test files and create test structures -/// that will be handed over to the executor. -fn collect_tests_from_dir( - cx: &TestCollectorCx, - dir: &Utf8Path, - relative_dir_path: &Utf8Path, -) -> io::Result { - // Ignore directories that contain a file named `compiletest-ignore-dir`. - if dir.join("compiletest-ignore-dir").exists() { - return Ok(TestCollector::new()); - } - - let mut components = dir.components().rev(); - if let Some(Utf8Component::Normal(last)) = components.next() - && let Some(("assembly" | "codegen", backend)) = last.split_once('-') - && let Some(Utf8Component::Normal(parent)) = components.next() - && parent == "tests" - && let Ok(backend) = backend.parse::() - && backend != cx.config.default_codegen_backend - { - // We ignore asm tests which don't match the current codegen backend. - warning!( - "Ignoring tests in `{dir}` because they don't match the configured codegen \ - backend (`{}`)", - cx.config.default_codegen_backend.as_str(), - ); - return Ok(TestCollector::new()); - } - - // For run-make tests, a "test file" is actually a directory that contains an `rmake.rs`. - if cx.config.mode == TestMode::RunMake { - let mut collector = TestCollector::new(); - if dir.join("rmake.rs").exists() { - let paths = TestPaths { - file: dir.to_path_buf(), - relative_dir: relative_dir_path.parent().unwrap().to_path_buf(), - }; - make_test(cx, &mut collector, &paths); - // This directory is a test, so don't try to find other tests inside it. - return Ok(collector); - } - } - - // If we find a test foo/bar.rs, we have to build the - // output directory `$build/foo` so we can write - // `$build/foo/bar` into it. We do this *now* in this - // sequential loop because otherwise, if we do it in the - // tests themselves, they race for the privilege of - // creating the directories and sometimes fail randomly. - let build_dir = output_relative_path(&cx.config, relative_dir_path); - fs::create_dir_all(&build_dir).unwrap(); - - // Add each `.rs` file as a test, and recurse further on any - // subdirectories we find, except for `auxiliary` directories. - // FIXME: this walks full tests tree, even if we have something to ignore - // use walkdir/ignore like in tidy? - fs::read_dir(dir.as_std_path())? - .par_bridge() - .map(|file| { - let mut collector = TestCollector::new(); - let file = file?; - let file_path = Utf8PathBuf::try_from(file.path()).unwrap(); - let file_name = file_path.file_name().unwrap(); - - if is_test(file_name) - && (!cx.config.only_modified || cx.modified_tests.contains(&file_path)) - { - // We found a test file, so create the corresponding test structures. - debug!(%file_path, "found test file"); - - // Record the stem of the test file, to check for overlaps later. - let rel_test_path = relative_dir_path.join(file_path.file_stem().unwrap()); - collector.found_path_stems.insert(rel_test_path); - - let paths = - TestPaths { file: file_path, relative_dir: relative_dir_path.to_path_buf() }; - make_test(cx, &mut collector, &paths); - } else if file_path.is_dir() { - // Recurse to find more tests in a subdirectory. - let relative_file_path = relative_dir_path.join(file_name); - if file_name != "auxiliary" { - debug!(%file_path, "found directory"); - collector.merge(collect_tests_from_dir(cx, &file_path, &relative_file_path)?); - } - } else { - debug!(%file_path, "found other file/directory"); - } - Ok(collector) - }) - .reduce( - || Ok(TestCollector::new()), - |a, b| { - let mut a = a?; - a.merge(b?); - Ok(a) - }, - ) -} - -/// Returns true if `file_name` looks like a proper test file name. -fn is_test(file_name: &str) -> bool { - if !file_name.ends_with(".rs") { - return false; - } - - // `.`, `#`, and `~` are common temp-file prefixes. - let invalid_prefixes = &[".", "#", "~"]; - !invalid_prefixes.iter().any(|p| file_name.starts_with(p)) -} - -/// For a single test file, creates one or more test structures (one per revision) that can be -/// handed over to the executor to run, possibly in parallel. -fn make_test(cx: &TestCollectorCx, collector: &mut TestCollector, testpaths: &TestPaths) { - // For run-make tests, each "test file" is actually a _directory_ containing an `rmake.rs`. But - // for the purposes of directive parsing, we want to look at that recipe file, not the directory - // itself. - let test_path = if cx.config.mode == TestMode::RunMake { - testpaths.file.join("rmake.rs") - } else { - testpaths.file.clone() - }; - - // Scan the test file to discover its revisions, if any. - let file_contents = - fs::read_to_string(&test_path).expect("reading test file for directives should succeed"); - let file_directives = FileDirectives::from_file_contents(&test_path, &file_contents); - - if let Err(message) = directives::do_early_directives_check(cx.config.mode, &file_directives) { - // FIXME(Zalathar): Overhaul compiletest error handling so that we - // don't have to resort to ad-hoc panics everywhere. - panic!("directives check failed:\n{message}"); - } - let early_props = EarlyProps::from_file_directives(&cx.config, &file_directives); - - // Normally we create one structure per revision, with two exceptions: - // - If a test doesn't use revisions, create a dummy revision (None) so that - // the test can still run. - // - Incremental tests inherently can't run their revisions in parallel, so - // we treat them like non-revisioned tests here. Incremental revisions are - // handled internally by `runtest::run` instead. - let revisions = if early_props.revisions.is_empty() || cx.config.mode == TestMode::Incremental { - vec![None] - } else { - early_props.revisions.iter().map(|r| Some(r.as_str())).collect() - }; - - // For debuginfo tests, we have to run them once for each debugger. - // We thus create a cartesian product of each revision and each supported debugger here. - let debuggers = if cx.config.mode == TestMode::DebugInfo { - vec![Some(Debugger::Cdb), Some(Debugger::Gdb), Some(Debugger::Lldb)] - } else { - vec![None] - }; - - // For each revision (or the sole dummy revision) and each debugger, create and append a - // `CollectedTest` that can be handed over to the test executor. - for debugger in debuggers { - collector.tests.extend(revisions.iter().map(|&revision| { - let revision = revision.map(str::to_owned); - let variant = TestVariant { revision, debugger }; - - // Create a test name and description to hand over to the executor. - let (test_name, filterable_path) = - make_test_name_and_filterable_path(&cx.config, testpaths, &variant); - - // While scanning for ignore/only/needs directives, also collect aux - // paths for up-to-date checking. - let mut aux_props = AuxProps::default(); - - // Create a description struct for the test/revision. - // This is where `ignore-*`/`only-*`/`needs-*` directives are handled, - // because they historically needed to set the libtest ignored flag. - let mut desc = make_test_description( - &cx.config, - &cx.cache, - test_name, - &test_path, - &filterable_path, - &file_directives, - &variant, - &mut collector.poisoned, - &mut aux_props, - ); - - // If a test's inputs haven't changed since the last time it ran, - // mark it as ignored so that the executor will skip it. - if !desc.is_ignored() - && !cx.config.force_rerun - && is_up_to_date(cx, testpaths, &aux_props, &variant) - { - // Keep this in sync with the "up-to-date" message detected by bootstrap. - // FIXME(Zalathar): Now that we are no longer tied to libtest, we could - // find a less fragile way to communicate this status to bootstrap. - desc.ignore_message = Some("up-to-date".into()); - } - - let config = Arc::clone(&cx.config); - let testpaths = testpaths.clone(); - - CollectedTest { desc, config, testpaths, variant } - })); - } -} - -/// The path of the `stamp` file that gets created or updated whenever a -/// particular test completes successfully. -fn stamp_file_path(config: &Config, testpaths: &TestPaths, variant: &TestVariant) -> Utf8PathBuf { - output_base_dir(config, testpaths, variant).join("stamp") -} - -/// Returns a list of files that, if modified, would cause this test to no -/// longer be up-to-date. -/// -/// (Might be inaccurate in some cases.) -fn files_related_to_test( - config: &Config, - testpaths: &TestPaths, - aux_props: &AuxProps, - variant: &TestVariant, -) -> Vec { - let mut related = vec![]; - - if testpaths.file.is_dir() { - // run-make tests use their individual directory - for entry in WalkDir::new(&testpaths.file) { - let path = entry.unwrap().into_path(); - if path.is_file() { - related.push(Utf8PathBuf::try_from(path).unwrap()); - } - } - } else { - related.push(testpaths.file.clone()); - } - - for aux in aux_props.all_aux_path_strings() { - // FIXME(Zalathar): Perform all `auxiliary` path resolution in one place. - // FIXME(Zalathar): This only finds auxiliary files used _directly_ by - // the test file; if a transitive auxiliary is modified, the test might - // be treated as "up-to-date" even though it should run. - let path = testpaths.file.parent().unwrap().join("auxiliary").join(aux); - related.push(path); - } - - // UI test files. - for extension in UI_EXTENSIONS { - let path = - expected_output_path(testpaths, variant.revision(), &config.compare_mode, extension); - related.push(path); - } - - // `minicore.rs` test auxiliary: we need to make sure tests get rerun if this changes. - related.push(config.src_root.join("tests").join("auxiliary").join("minicore.rs")); - - // `tests/debuginfo` blessed files - match variant.debugger { - Some(debugger @ Debugger::Lldb | debugger @ Debugger::Gdb) => { - let bless_path: Utf8PathBuf = - testpaths.file.parent().unwrap().join(format!("{}_input", debugger.to_str())); - if bless_path.is_dir() { - related.extend( - WalkDir::new(bless_path) - .into_iter() - .map(|entry| Utf8PathBuf::from(entry.unwrap().path().to_str().unwrap())), - ); - } - } - Some(Debugger::Cdb) | None => {} - } - - related -} - -/// Checks whether a particular test/revision is "up-to-date", meaning that no -/// relevant files/settings have changed since the last time the test succeeded. -/// -/// (This is not very reliable in some circumstances, so the `--force-rerun` -/// flag can be used to ignore up-to-date checking and always re-run tests.) -fn is_up_to_date( - cx: &TestCollectorCx, - testpaths: &TestPaths, - aux_props: &AuxProps, - variant: &TestVariant, -) -> bool { - let stamp_file_path = stamp_file_path(&cx.config, testpaths, variant); - // Check the config hash inside the stamp file. - let contents = match fs::read_to_string(&stamp_file_path) { - Ok(f) => f, - Err(ref e) if e.kind() == ErrorKind::InvalidData => panic!("Can't read stamp contents"), - // The test hasn't succeeded yet, so it is not up-to-date. - Err(_) => return false, - }; - let expected_hash = runtest::compute_stamp_hash(&cx.config, variant); - if contents != expected_hash { - // Some part of compiletest configuration has changed since the test - // last succeeded, so it is not up-to-date. - return false; - } - - // Check the timestamp of the stamp file against the last modified time - // of all files known to be relevant to the test. - let mut inputs_stamp = cx.common_inputs_stamp.clone(); - for path in files_related_to_test(&cx.config, testpaths, aux_props, variant) { - inputs_stamp.add_path(&path); - } - - // If no relevant files have been modified since the stamp file was last - // written, the test is up-to-date. - inputs_stamp < Stamp::from_path(&stamp_file_path) -} - -/// The maximum of a set of file-modified timestamps. -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] -struct Stamp { - time: SystemTime, -} - -impl Stamp { - /// Creates a timestamp holding the last-modified time of the specified file. - fn from_path(path: &Utf8Path) -> Self { - let mut stamp = Stamp { time: SystemTime::UNIX_EPOCH }; - stamp.add_path(path); - stamp - } - - /// Updates this timestamp to the last-modified time of the specified file, - /// if it is later than the currently-stored timestamp. - fn add_path(&mut self, path: &Utf8Path) { - let modified = fs::metadata(path.as_std_path()) - .and_then(|metadata| metadata.modified()) - .unwrap_or(SystemTime::UNIX_EPOCH); - self.time = self.time.max(modified); - } - - /// Updates this timestamp to the most recent last-modified time of all files - /// recursively contained in the given directory, if it is later than the - /// currently-stored timestamp. - fn add_dir(&mut self, path: &Utf8Path) { - let path = path.as_std_path(); - for entry in WalkDir::new(path) { - let entry = entry.unwrap(); - if entry.file_type().is_file() { - let modified = entry - .metadata() - .ok() - .and_then(|metadata| metadata.modified().ok()) - .unwrap_or(SystemTime::UNIX_EPOCH); - self.time = self.time.max(modified); - } - } - } -} - -/// Creates a name for this test/revision that can be handed over to the executor. -fn make_test_name_and_filterable_path( - config: &Config, - testpaths: &TestPaths, - variant: &TestVariant, -) -> (String, Utf8PathBuf) { - // Print the name of the file, relative to the sources root. - let path = testpaths.file.strip_prefix(&config.src_root).unwrap(); - let debugger = match variant.debugger.as_ref() { - Some(d) => format!("-{d}"), - None => String::new(), - }; - let mode_suffix = match config.compare_mode { - Some(ref mode) => format!(" ({})", mode.to_str()), - None => String::new(), - }; - - let name = format!( - "[{}{}{}] {}{}", - config.mode, - debugger, - mode_suffix, - path, - variant.revision().map_or("".to_string(), |rev| format!("#{}", rev)) - ); - - // `path` is the full path from the repo root like, `tests/ui/foo/bar.rs`. - // Filtering is applied without the `tests/ui/` part, so strip that off. - // First strip off "tests" to make sure we don't have some unexpected path. - let mut filterable_path = path.strip_prefix("tests").unwrap().to_owned(); - // Now strip off e.g. "ui" or "run-make" component. - filterable_path = filterable_path.components().skip(1).collect(); - - (name, filterable_path) -} - -/// Checks that test discovery didn't find any tests whose name stem is a prefix -/// of some other tests's name. -/// -/// For example, suppose the test suite contains these two test files: -/// - `tests/rustdoc-html/primitive.rs` -/// - `tests/rustdoc-html/primitive/no_std.rs` -/// -/// The test runner might put the output from those tests in these directories: -/// - `$build/test/rustdoc/primitive/` -/// - `$build/test/rustdoc/primitive/no_std/` -/// -/// Because one output path is a subdirectory of the other, the two tests might -/// interfere with each other in unwanted ways, especially if the test runner -/// decides to delete test output directories to clean them between runs. -/// To avoid problems, we forbid test names from overlapping in this way. -/// -/// See for more context. -fn check_for_overlapping_test_paths(found_path_stems: &HashSet) { - let mut collisions = Vec::new(); - for path in found_path_stems { - for ancestor in path.ancestors().skip(1) { - if found_path_stems.contains(ancestor) { - collisions.push((path, ancestor)); - } - } - } - if !collisions.is_empty() { - collisions.sort(); - let collisions: String = collisions - .into_iter() - .map(|(path, check_parent)| format!("test {path} clashes with {check_parent}\n")) - .collect(); - panic!( - "{collisions}\n\ - Tests cannot have overlapping names. Make sure they use unique prefixes." - ); - } -} - -fn early_config_check(config: &Config) { - if !config.profiler_runtime && config.mode == TestMode::CoverageRun { - let actioned = if config.bless { "blessed" } else { "checked" }; - warning!("profiler runtime is not available, so `.coverage` files won't be {actioned}"); - help!("try setting `profiler = true` in the `[build]` section of `bootstrap.toml`"); - } - - // `RUST_TEST_NOCAPTURE` is a libtest env var, but we don't callout to libtest. - if env::var("RUST_TEST_NOCAPTURE").is_ok() { - warning!("`RUST_TEST_NOCAPTURE` is not supported; use the `--no-capture` flag instead"); - } -} diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index 2092a0077088f..4cb7401a51262 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -26,7 +26,7 @@ use crate::output_capture::ConsoleOut; use crate::read2::{Truncated, read2_abbreviated}; use crate::runtest::compute_diff::{DiffLine, diff_by_lines, make_diff, write_diff}; use crate::util::{ArgFileCommand, Utf8PathBufExt, add_dylib_path, static_regex}; -use crate::{json, stamp_file_path}; +use crate::{discovery, json}; // Helper modules that implement test running logic for each test suite. // tidy-alphabetical-start @@ -3121,7 +3121,8 @@ impl<'test> TestCx<'test> { } fn create_stamp(&self) { - let stamp_file_path = stamp_file_path(&self.config, self.testpaths, self.variant); + let stamp_file_path = + discovery::stamp_file_path(&self.config, self.testpaths, self.variant); fs::write(&stamp_file_path, compute_stamp_hash(&self.config, self.variant)).unwrap(); } diff --git a/src/tools/compiletest/src/tests.rs b/src/tools/compiletest/src/tests.rs index 59bed76bdb510..9289a66d5d148 100644 --- a/src/tools/compiletest/src/tests.rs +++ b/src/tools/compiletest/src/tests.rs @@ -1,7 +1,7 @@ use semver::Version; use crate::debuggers::{LldbVersion, extract_gdb_version, extract_lldb_version}; -use crate::is_test; +use crate::discovery::is_test; #[test] fn test_extract_gdb_version() { diff --git a/src/tools/tidy/Cargo.toml b/src/tools/tidy/Cargo.toml index 4b38f9479fbc6..e452be545e508 100644 --- a/src/tools/tidy/Cargo.toml +++ b/src/tools/tidy/Cargo.toml @@ -17,7 +17,7 @@ serde = { version = "1.0.125", features = ["derive"], optional = true } termcolor = "1.1.3" rustc-hash = "2.0.0" similar = "2.5.0" -toml = "0.7.8" +toml = "0.8" tempfile = "3.15.0" clap = "4.5.54" diff --git a/tests/ui/async-await/in-trait/bad-signatures.rs b/tests/ui/async-await/in-trait/bad-signatures.rs index 57a0ccb0d18e0..a74d35b1c77a4 100644 --- a/tests/ui/async-await/in-trait/bad-signatures.rs +++ b/tests/ui/async-await/in-trait/bad-signatures.rs @@ -3,8 +3,7 @@ trait MyTrait { async fn bar(&abc self); - //~^ ERROR expected identifier, found keyword `self` - //~| ERROR expected one of `:`, `@`, or `|`, found keyword `self` + //~^ ERROR expected one of `:`, `@`, or `|`, found keyword `self` } impl MyTrait for () { diff --git a/tests/ui/async-await/in-trait/bad-signatures.stderr b/tests/ui/async-await/in-trait/bad-signatures.stderr index 1f2f0537af3d1..2e5cb2e2faa57 100644 --- a/tests/ui/async-await/in-trait/bad-signatures.stderr +++ b/tests/ui/async-await/in-trait/bad-signatures.stderr @@ -1,9 +1,3 @@ -error: expected identifier, found keyword `self` - --> $DIR/bad-signatures.rs:5:23 - | -LL | async fn bar(&abc self); - | ^^^^ expected identifier, found keyword - error: expected one of `:`, `@`, or `|`, found keyword `self` --> $DIR/bad-signatures.rs:5:23 | @@ -16,5 +10,5 @@ LL - async fn bar(&abc self); LL + async fn bar(: ); | -error: aborting due to 2 previous errors +error: aborting due to 1 previous error diff --git a/tests/ui/closures/ref-to-fn-once.rs b/tests/ui/closures/ref-to-fn-once.rs new file mode 100644 index 0000000000000..383920768decb --- /dev/null +++ b/tests/ui/closures/ref-to-fn-once.rs @@ -0,0 +1,58 @@ +// Provide clear diagnostics when `&FnOnce` was provided +// when `FnOnce` was expected in function arguments. +// Related issue: #47648 +//@ edition:2024 + +struct Foo {} + +fn call Foo>(f: F) { + call(&f); + //~^ ERROR expected `FnOnce()` signature, found `&F` +} + +fn async_call Foo>(f: F) { + async_call(&f); + //~^ ERROR the trait bound `&F: AsyncFnOnce()` is not satisfied +} + +fn main() { + let foo = Foo {}; + let once = move || foo; + + call(&once); + //~^ ERROR expected `FnOnce`, found reference [E0525] + call(&mut once); + //~^ ERROR expected `FnOnce`, found reference [E0525] + + let foo = Foo {}; + let once = &move || foo; + + call(once); + //~^ ERROR expected `FnOnce`, found reference [E0525] + + let foo = Foo {}; + let once = &mut move || foo; + + call(once); + //~^ ERROR expected `FnOnce`, found reference [E0525] + + let foo = Foo {}; + let async_once = async move || foo; + + async_call(&async_once); + //~^ ERROR expected `AsyncFnOnce`, found reference [E0525] + async_call(&mut async_once); + //~^ ERROR expected `AsyncFnOnce`, found reference [E0525] + + let foo = Foo {}; + let async_once = &async move || foo; + + async_call(async_once); + //~^ ERROR expected `AsyncFnOnce`, found reference [E0525] + + let foo = Foo {}; + let async_once = &mut async move || foo; + + async_call(async_once); + //~^ ERROR expected `AsyncFnOnce`, found reference [E0525] +} diff --git a/tests/ui/closures/ref-to-fn-once.stderr b/tests/ui/closures/ref-to-fn-once.stderr new file mode 100644 index 0000000000000..c8753f44f71ff --- /dev/null +++ b/tests/ui/closures/ref-to-fn-once.stderr @@ -0,0 +1,212 @@ +error[E0277]: expected `FnOnce()` signature, found `&F` + --> $DIR/ref-to-fn-once.rs:9:11 + | +LL | call(&f); + | ---- ^ expected `FnOnce()` signature, found `&F` + | | + | required by a bound introduced by this call + | + = note: wrap the `&F` in a closure with no arguments: `|| { /* code */ }` + = note: `F` implements `FnOnce`, but it must implement `Fn`, which is more general + = note: required for `&F` to implement `FnOnce()` +note: required by a bound in `call` + --> $DIR/ref-to-fn-once.rs:8:12 + | +LL | fn call Foo>(f: F) { + | ^^^^^^^^^^^^^^^ required by this bound in `call` + +error[E0277]: the trait bound `&F: AsyncFnOnce()` is not satisfied + --> $DIR/ref-to-fn-once.rs:14:17 + | +LL | async_call(&f); + | ---------- ^ the trait `AsyncFn()` is not implemented for `F` + | | + | required by a bound introduced by this call + | + = note: required for `&F` to implement `AsyncFnOnce()` +note: required by a bound in `async_call` + --> $DIR/ref-to-fn-once.rs:13:18 + | +LL | fn async_call Foo>(f: F) { + | ^^^^^^^^^^^^^^^^^^^^ required by this bound in `async_call` +help: consider further restricting type parameter `F` with trait `AsyncFn` + | +LL | fn async_call Foo + AsyncFn()>(f: F) { + | +++++++++++ + +error[E0525]: expected `FnOnce`, found reference + --> $DIR/ref-to-fn-once.rs:22:10 + | +LL | let once = move || foo; + | --- closure is `FnOnce` because it moves the variable `foo` out of its environment +LL | +LL | call(&once); + | ---- ^^^^^ closure passed by reference here + | | + | required by a bound introduced by this call + | + = note: `FnOnce` isn't implemented for references + = note: required for `&{closure@$DIR/ref-to-fn-once.rs:20:16: 20:23}` to implement `FnOnce()` +note: required by a bound in `call` + --> $DIR/ref-to-fn-once.rs:8:12 + | +LL | fn call Foo>(f: F) { + | ^^^^^^^^^^^^^^^ required by this bound in `call` +help: consider removing the leading `&`-reference + | +LL - call(&once); +LL + call(once); + | + +error[E0525]: expected `FnOnce`, found reference + --> $DIR/ref-to-fn-once.rs:24:10 + | +LL | let once = move || foo; + | --- closure is `FnOnce` because it moves the variable `foo` out of its environment +... +LL | call(&mut once); + | ---- ^^^^^^^^^ closure passed by reference here + | | + | required by a bound introduced by this call + | + = note: `FnOnce` isn't implemented for references + = note: required for `&mut {closure@$DIR/ref-to-fn-once.rs:20:16: 20:23}` to implement `FnOnce()` +note: required by a bound in `call` + --> $DIR/ref-to-fn-once.rs:8:12 + | +LL | fn call Foo>(f: F) { + | ^^^^^^^^^^^^^^^ required by this bound in `call` +help: consider removing the leading `&`-reference + | +LL - call(&mut once); +LL + call(once); + | + +error[E0525]: expected `FnOnce`, found reference + --> $DIR/ref-to-fn-once.rs:30:10 + | +LL | let once = &move || foo; + | --- closure is `FnOnce` because it moves the variable `foo` out of its environment +LL | +LL | call(once); + | ---- ^^^^ closure passed by reference here + | | + | required by a bound introduced by this call + | + = note: `FnOnce` isn't implemented for references + = note: required for `&{closure@$DIR/ref-to-fn-once.rs:28:17: 28:24}` to implement `FnOnce()` +note: required by a bound in `call` + --> $DIR/ref-to-fn-once.rs:8:12 + | +LL | fn call Foo>(f: F) { + | ^^^^^^^^^^^^^^^ required by this bound in `call` + +error[E0525]: expected `FnOnce`, found reference + --> $DIR/ref-to-fn-once.rs:36:10 + | +LL | let once = &mut move || foo; + | --- closure is `FnOnce` because it moves the variable `foo` out of its environment +LL | +LL | call(once); + | ---- ^^^^ closure passed by reference here + | | + | required by a bound introduced by this call + | + = note: `FnOnce` isn't implemented for references + = note: required for `&mut {closure@$DIR/ref-to-fn-once.rs:34:21: 34:28}` to implement `FnOnce()` +note: required by a bound in `call` + --> $DIR/ref-to-fn-once.rs:8:12 + | +LL | fn call Foo>(f: F) { + | ^^^^^^^^^^^^^^^ required by this bound in `call` + +error[E0525]: expected `AsyncFnOnce`, found reference + --> $DIR/ref-to-fn-once.rs:42:16 + | +LL | let async_once = async move || foo; + | --- closure is `AsyncFnOnce` because it moves the variable `foo` out of its environment +LL | +LL | async_call(&async_once); + | ---------- ^^^^^^^^^^^ closure passed by reference here + | | + | required by a bound introduced by this call + | + = note: `AsyncFnOnce` isn't implemented for references + = note: required for `&{async closure@$DIR/ref-to-fn-once.rs:40:22: 40:35}` to implement `AsyncFnOnce()` +note: required by a bound in `async_call` + --> $DIR/ref-to-fn-once.rs:13:18 + | +LL | fn async_call Foo>(f: F) { + | ^^^^^^^^^^^^^^^^^^^^ required by this bound in `async_call` +help: consider removing the leading `&`-reference + | +LL - async_call(&async_once); +LL + async_call(async_once); + | + +error[E0525]: expected `AsyncFnOnce`, found reference + --> $DIR/ref-to-fn-once.rs:44:16 + | +LL | let async_once = async move || foo; + | --- closure is `AsyncFnOnce` because it moves the variable `foo` out of its environment +... +LL | async_call(&mut async_once); + | ---------- ^^^^^^^^^^^^^^^ closure passed by reference here + | | + | required by a bound introduced by this call + | + = note: `AsyncFnOnce` isn't implemented for references + = note: required for `&mut {async closure@$DIR/ref-to-fn-once.rs:40:22: 40:35}` to implement `AsyncFnOnce()` +note: required by a bound in `async_call` + --> $DIR/ref-to-fn-once.rs:13:18 + | +LL | fn async_call Foo>(f: F) { + | ^^^^^^^^^^^^^^^^^^^^ required by this bound in `async_call` +help: consider removing the leading `&`-reference + | +LL - async_call(&mut async_once); +LL + async_call(async_once); + | + +error[E0525]: expected `AsyncFnOnce`, found reference + --> $DIR/ref-to-fn-once.rs:50:16 + | +LL | let async_once = &async move || foo; + | --- closure is `AsyncFnOnce` because it moves the variable `foo` out of its environment +LL | +LL | async_call(async_once); + | ---------- ^^^^^^^^^^ closure passed by reference here + | | + | required by a bound introduced by this call + | + = note: `AsyncFnOnce` isn't implemented for references + = note: required for `&{async closure@$DIR/ref-to-fn-once.rs:48:23: 48:36}` to implement `AsyncFnOnce()` +note: required by a bound in `async_call` + --> $DIR/ref-to-fn-once.rs:13:18 + | +LL | fn async_call Foo>(f: F) { + | ^^^^^^^^^^^^^^^^^^^^ required by this bound in `async_call` + +error[E0525]: expected `AsyncFnOnce`, found reference + --> $DIR/ref-to-fn-once.rs:56:16 + | +LL | let async_once = &mut async move || foo; + | --- closure is `AsyncFnOnce` because it moves the variable `foo` out of its environment +LL | +LL | async_call(async_once); + | ---------- ^^^^^^^^^^ closure passed by reference here + | | + | required by a bound introduced by this call + | + = note: `AsyncFnOnce` isn't implemented for references + = note: required for `&mut {async closure@$DIR/ref-to-fn-once.rs:54:27: 54:40}` to implement `AsyncFnOnce()` +note: required by a bound in `async_call` + --> $DIR/ref-to-fn-once.rs:13:18 + | +LL | fn async_call Foo>(f: F) { + | ^^^^^^^^^^^^^^^^^^^^ required by this bound in `async_call` + +error: aborting due to 10 previous errors + +Some errors have detailed explanations: E0277, E0525. +For more information about an error, try `rustc --explain E0277`. diff --git a/tests/ui/const-generics/transmute-fail.rs b/tests/ui/const-generics/transmute-fail.rs index cf9064bd8f4ba..46f1d343070b5 100644 --- a/tests/ui/const-generics/transmute-fail.rs +++ b/tests/ui/const-generics/transmute-fail.rs @@ -1,7 +1,6 @@ // ignore-tidy-linelength //@ normalize-stderr: "values of the type `[^`]+` are too big" -> "values of the type $$REALLY_TOO_BIG are too big" - #![feature(transmute_generic_consts)] #![feature(generic_const_exprs)] #![allow(incomplete_features)] @@ -39,7 +38,6 @@ fn overflow_more(v: [[[u32; 8888888]; 9999999]; 777777777]) -> [[[u32; 9999999]; unsafe { std::mem::transmute(v) } //~ ERROR cannot transmute between types of different sizes } - fn transpose(v: [[u32; H]; W]) -> [[u32; W]; H] { unsafe { std::mem::transmute(v) @@ -97,13 +95,6 @@ fn condense_bytes(v: [u8; L * 2]) -> [u16; L] { } } -fn singleton_each(v: [u8; L]) -> [[u8; 1]; L] { - unsafe { - std::mem::transmute(v) - //~^ ERROR: cannot transmute between types of different sizes, or dependently-sized types - } -} - fn transpose_with_const( v: [[u32; 2 * H]; W + W], ) -> [[u32; W + W]; 2 * H] { diff --git a/tests/ui/const-generics/transmute-fail.stderr b/tests/ui/const-generics/transmute-fail.stderr index 30541e539b63a..9780d6ae6f325 100644 --- a/tests/ui/const-generics/transmute-fail.stderr +++ b/tests/ui/const-generics/transmute-fail.stderr @@ -1,5 +1,5 @@ error: the constant `W` is not of type `usize` - --> $DIR/transmute-fail.rs:16:53 + --> $DIR/transmute-fail.rs:15:53 | LL | fn bar(v: [[u32; H]; W]) -> [[u32; W]; H] { | ------------- `W` defined here ^ array length expected `usize`, found `bool` @@ -7,7 +7,7 @@ LL | fn bar(v: [[u32; H]; W]) -> [[u32; W]; H] { = note: the length of array `[[u32; H]; W]` must be type `usize` error: the constant `W` is not of type `usize` - --> $DIR/transmute-fail.rs:19:9 + --> $DIR/transmute-fail.rs:18:9 | LL | fn bar(v: [[u32; H]; W]) -> [[u32; W]; H] { | ------------- `W` defined here @@ -18,25 +18,25 @@ LL | std::mem::transmute(v) = note: the length of array `[[u32; H]; W]` must be type `usize` error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> $DIR/transmute-fail.rs:11:9 + --> $DIR/transmute-fail.rs:10:9 | LL | std::mem::transmute(v) | ^^^^^^^^^^^^^^^^^^^ | - = note: source type: `[[u32; H + 1]; W]` (size can vary because of [u32; H + 1]) - = note: target type: `[[u32; W + 1]; H]` (size can vary because of [u32; W + 1]) + = note: source type: `[[u32; H + 1]; W]` (32 * (H + 1) * (W) bits) + = note: target type: `[[u32; W + 1]; H]` (32 * (W + 1) * (H) bits) error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> $DIR/transmute-fail.rs:26:9 + --> $DIR/transmute-fail.rs:25:9 | LL | std::mem::transmute(v) | ^^^^^^^^^^^^^^^^^^^ | - = note: source type: `[[u32; H]; W]` (size can vary because of [u32; H]) - = note: target type: `[u32; W * H * H]` (this type does not have a fixed size) + = note: source type: `[[u32; H]; W]` (32 * (H) * (W) bits) + = note: target type: `[u32; W * H * H]` (32 * (W * H * H) bits) error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> $DIR/transmute-fail.rs:33:9 + --> $DIR/transmute-fail.rs:32:9 | LL | std::mem::transmute(v) | ^^^^^^^^^^^^^^^^^^^ @@ -45,7 +45,7 @@ LL | std::mem::transmute(v) = note: target type: `[[[u32; 9999999]; 777777777]; 8888888]` (values of the type $REALLY_TOO_BIG are too big for the target architecture) error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> $DIR/transmute-fail.rs:39:14 + --> $DIR/transmute-fail.rs:38:14 | LL | unsafe { std::mem::transmute(v) } | ^^^^^^^^^^^^^^^^^^^ @@ -54,67 +54,67 @@ LL | unsafe { std::mem::transmute(v) } = note: target type: `[[[u32; 9999999]; 777777777]; 239]` (values of the type $REALLY_TOO_BIG are too big for the target architecture) error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> $DIR/transmute-fail.rs:45:9 + --> $DIR/transmute-fail.rs:43:9 | LL | std::mem::transmute(v) | ^^^^^^^^^^^^^^^^^^^ | - = note: source type: `[[u32; H]; W]` (size can vary because of [u32; H]) - = note: target type: `[[u32; W]; H]` (size can vary because of [u32; W]) + = note: source type: `[[u32; H]; W]` (32 * (H) * (W) bits) + = note: target type: `[[u32; W]; H]` (32 * (W) * (H) bits) error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> $DIR/transmute-fail.rs:56:9 + --> $DIR/transmute-fail.rs:54:9 | LL | std::mem::transmute(v) | ^^^^^^^^^^^^^^^^^^^ | - = note: source type: `[[u32; H]; W]` (size can vary because of [u32; H]) - = note: target type: `[u32; W * H]` (this type does not have a fixed size) + = note: source type: `[[u32; H]; W]` (32 * (H) * (W) bits) + = note: target type: `[u32; W * H]` (32 * (W * H) bits) error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> $DIR/transmute-fail.rs:63:9 + --> $DIR/transmute-fail.rs:61:9 | LL | std::mem::transmute(v) | ^^^^^^^^^^^^^^^^^^^ | - = note: source type: `[u32; H * W]` (this type does not have a fixed size) - = note: target type: `[[u32; W]; H]` (size can vary because of [u32; W]) + = note: source type: `[u32; H * W]` (32 * (H * W) bits) + = note: target type: `[[u32; W]; H]` (32 * (W) * (H) bits) error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> $DIR/transmute-fail.rs:72:9 + --> $DIR/transmute-fail.rs:70:9 | LL | std::mem::transmute(v) | ^^^^^^^^^^^^^^^^^^^ | - = note: source type: `[[[u32; D]; H]; W]` (size can vary because of [u32; D]) - = note: target type: `[u32; D * W * H]` (this type does not have a fixed size) + = note: source type: `[[[u32; D]; H]; W]` (32 * (D) * (H) * (W) bits) + = note: target type: `[u32; D * W * H]` (32 * (D * W * H) bits) error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> $DIR/transmute-fail.rs:81:9 + --> $DIR/transmute-fail.rs:79:9 | LL | std::mem::transmute(v) | ^^^^^^^^^^^^^^^^^^^ | - = note: source type: `[[[u32; D]; H]; W]` (size can vary because of [u32; D]) - = note: target type: `[[u32; D * W]; H]` (size can vary because of [u32; D * W]) + = note: source type: `[[[u32; D]; H]; W]` (32 * (D) * (H) * (W) bits) + = note: target type: `[[u32; D * W]; H]` (32 * (D * W) * (H) bits) error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> $DIR/transmute-fail.rs:88:9 + --> $DIR/transmute-fail.rs:86:9 | LL | std::mem::transmute(v) | ^^^^^^^^^^^^^^^^^^^ | - = note: source type: `[u16; L]` (this type does not have a fixed size) - = note: target type: `[u8; L * 2]` (this type does not have a fixed size) + = note: source type: `[u16; L]` (16 * (L) bits) + = note: target type: `[u8; L * 2]` (8 * (L * 2) bits) error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> $DIR/transmute-fail.rs:95:9 + --> $DIR/transmute-fail.rs:93:9 | LL | std::mem::transmute(v) | ^^^^^^^^^^^^^^^^^^^ | - = note: source type: `[u8; L * 2]` (this type does not have a fixed size) - = note: target type: `[u16; L]` (this type does not have a fixed size) + = note: source type: `[u8; L * 2]` (8 * (L * 2) bits) + = note: target type: `[u16; L]` (16 * (L) bits) error[E0512]: cannot transmute between types of different sizes, or dependently-sized types --> $DIR/transmute-fail.rs:102:9 @@ -122,18 +122,9 @@ error[E0512]: cannot transmute between types of different sizes, or dependently- LL | std::mem::transmute(v) | ^^^^^^^^^^^^^^^^^^^ | - = note: source type: `[u8; L]` (this type does not have a fixed size) - = note: target type: `[[u8; 1]; L]` (this type does not have a fixed size) + = note: source type: `[[u32; 2 * H]; W + W]` (32 * (2 * H) * (W + W) bits) + = note: target type: `[[u32; W + W]; 2 * H]` (32 * (W + W) * (2 * H) bits) -error[E0512]: cannot transmute between types of different sizes, or dependently-sized types - --> $DIR/transmute-fail.rs:111:9 - | -LL | std::mem::transmute(v) - | ^^^^^^^^^^^^^^^^^^^ - | - = note: source type: `[[u32; 2 * H]; W + W]` (size can vary because of [u32; 2 * H]) - = note: target type: `[[u32; W + W]; 2 * H]` (size can vary because of [u32; W + W]) - -error: aborting due to 15 previous errors +error: aborting due to 14 previous errors For more information about this error, try `rustc --explain E0512`. diff --git a/tests/ui/const-generics/transmute.rs b/tests/ui/const-generics/transmute.rs index 6108139f3ce5c..e58600d9533c0 100644 --- a/tests/ui/const-generics/transmute.rs +++ b/tests/ui/const-generics/transmute.rs @@ -1,13 +1,75 @@ //@ run-pass #![feature(generic_const_exprs)] +#![feature(transmute_generic_consts)] #![allow(incomplete_features)] fn ident(v: [[u32; H]; W]) -> [[u32; H]; W] { - unsafe { - std::mem::transmute(v) - } + unsafe { std::mem::transmute(v) } +} + +fn singleton_each(v: [u8; L]) -> [[u8; 1]; L] { + unsafe { std::mem::transmute(v) } +} + +#[derive(Clone, Copy)] +#[repr(C)] +struct T(u8); + +fn element(v: [T; N]) -> [u8; N] { + unsafe { std::mem::transmute::<_, _>(v) } +} + +fn element2(v: [[T; N]; M]) -> [[u8; N]; M] { + unsafe { std::mem::transmute::<_, _>(v) } +} + +fn element3_mixed(v: [[[T; N]; 42]; M]) -> [[[u8; N]; 42]; M] { + unsafe { std::mem::transmute::<_, _>(v) } +} + +fn element4_swap_lit( + v: [[[[T; N]; 3]; 7]; M], +) -> [[[[u8; 7]; N]; M]; 3] { + unsafe { std::mem::transmute::<_, _>(v) } +} + +fn zst(v: [(); N]) -> () { + unsafe { std::mem::transmute::<_, _>(v) } +} + +fn zero_len(v: [[u8; N]; 0]) -> () { + unsafe { std::mem::transmute::<_, _>(v) } +} + +fn zst_zero_len(v: [(); N]) -> [[u8; N]; 0] { + unsafe { std::mem::transmute::<_, _>(v) } +} + +const L1: usize = 42; +const L2: usize = L1; +const L3: usize = 42; + +fn len_normalized_alias(v: [u8; L1]) -> [u8; L2] { + unsafe { std::mem::transmute::<_, _>(v) } +} + +fn len_normalized_equal(v: [u8; L1]) -> [u8; L3] { + unsafe { std::mem::transmute::<_, _>(v) } } fn main() { - let _ = ident([[0; 8]; 16]); + let _ = ident([[0; 8]; 16]); + let _ = singleton_each([0; 8]); + + let _ = element([T(0); 8]); + let _ = element2([[T(0); 8]; 16]); + let _ = element3_mixed([[[T(0); 8]; 42]; 16]); + let _ = element4_swap_lit([[[[T(0); 8]; 3]; 7]; 16]); + + let _ = zst([(); 8]); + let _ = zero_len([[0; 8]; 0]); + let _ = zst_zero_len([(); 8]); + + let _ = len_normalized_alias([2; L1]); + let _ = len_normalized_equal([2; L1]); } diff --git a/tests/ui/consts/const-eval/const_panic.rs b/tests/ui/consts/const-eval/const_panic.rs index a3f299decd0ba..60dbf35f71217 100644 --- a/tests/ui/consts/const-eval/const_panic.rs +++ b/tests/ui/consts/const-eval/const_panic.rs @@ -1,5 +1,6 @@ //@ edition:2015..2021 #![feature(abort_immediate)] +#![feature(const_abort)] #![allow(non_fmt_panics)] #![crate_type = "lib"] @@ -41,5 +42,8 @@ const W_CORE: () = core::panic!(MSG); const W2_CORE: () = core::panic!("{}", MSG); //~^ ERROR evaluation panicked -const ABORT: () = core::process::crash(); +const ABORT: () = std::process::abort(); +//~^ ERROR the program aborted execution + +const CRASH: () = core::process::crash(); //~^ ERROR the program aborted execution diff --git a/tests/ui/consts/const-eval/const_panic.stderr b/tests/ui/consts/const-eval/const_panic.stderr index 16facaa2d4962..65dafb7dd6df7 100644 --- a/tests/ui/consts/const-eval/const_panic.stderr +++ b/tests/ui/consts/const-eval/const_panic.stderr @@ -1,84 +1,95 @@ error[E0080]: evaluation panicked: cheese - --> $DIR/const_panic.rs:8:15 + --> $DIR/const_panic.rs:9:15 | LL | const Z: () = std::panic!("cheese"); | ^^^^^^^^^^^^^^^^^^^^^ evaluation of `Z` failed here error[E0080]: evaluation panicked: explicit panic - --> $DIR/const_panic.rs:11:16 + --> $DIR/const_panic.rs:12:16 | LL | const Z2: () = std::panic!(); | ^^^^^^^^^^^^^ evaluation of `Z2` failed here error[E0080]: evaluation panicked: internal error: entered unreachable code - --> $DIR/const_panic.rs:14:15 + --> $DIR/const_panic.rs:15:15 | LL | const Y: () = std::unreachable!(); | ^^^^^^^^^^^^^^^^^^^ evaluation of `Y` failed here error[E0080]: evaluation panicked: not implemented - --> $DIR/const_panic.rs:17:15 + --> $DIR/const_panic.rs:18:15 | LL | const X: () = std::unimplemented!(); | ^^^^^^^^^^^^^^^^^^^^^ evaluation of `X` failed here error[E0080]: evaluation panicked: hello - --> $DIR/const_panic.rs:20:15 + --> $DIR/const_panic.rs:21:15 | LL | const W: () = std::panic!(MSG); | ^^^^^^^^^^^^^^^^ evaluation of `W` failed here error[E0080]: evaluation panicked: hello - --> $DIR/const_panic.rs:23:16 + --> $DIR/const_panic.rs:24:16 | LL | const W2: () = std::panic!("{}", MSG); | ^^^^^^^^^^^^^^^^^^^^^^ evaluation of `W2` failed here error[E0080]: evaluation panicked: cheese - --> $DIR/const_panic.rs:26:20 + --> $DIR/const_panic.rs:27:20 | LL | const Z_CORE: () = core::panic!("cheese"); | ^^^^^^^^^^^^^^^^^^^^^^ evaluation of `Z_CORE` failed here error[E0080]: evaluation panicked: explicit panic - --> $DIR/const_panic.rs:29:21 + --> $DIR/const_panic.rs:30:21 | LL | const Z2_CORE: () = core::panic!(); | ^^^^^^^^^^^^^^ evaluation of `Z2_CORE` failed here error[E0080]: evaluation panicked: internal error: entered unreachable code - --> $DIR/const_panic.rs:32:20 + --> $DIR/const_panic.rs:33:20 | LL | const Y_CORE: () = core::unreachable!(); | ^^^^^^^^^^^^^^^^^^^^ evaluation of `Y_CORE` failed here error[E0080]: evaluation panicked: not implemented - --> $DIR/const_panic.rs:35:20 + --> $DIR/const_panic.rs:36:20 | LL | const X_CORE: () = core::unimplemented!(); | ^^^^^^^^^^^^^^^^^^^^^^ evaluation of `X_CORE` failed here error[E0080]: evaluation panicked: hello - --> $DIR/const_panic.rs:38:20 + --> $DIR/const_panic.rs:39:20 | LL | const W_CORE: () = core::panic!(MSG); | ^^^^^^^^^^^^^^^^^ evaluation of `W_CORE` failed here error[E0080]: evaluation panicked: hello - --> $DIR/const_panic.rs:41:21 + --> $DIR/const_panic.rs:42:21 | LL | const W2_CORE: () = core::panic!("{}", MSG); | ^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `W2_CORE` failed here error[E0080]: the program aborted execution - --> $DIR/const_panic.rs:44:19 + --> $DIR/const_panic.rs:45:19 | -LL | const ABORT: () = core::process::crash(); - | ^^^^^^^^^^^^^^^^^^^^^^ evaluation of `ABORT` failed inside this call +LL | const ABORT: () = std::process::abort(); + | ^^^^^^^^^^^^^^^^^^^^^ evaluation of `ABORT` failed inside this call | +note: inside `abort` + --> $SRC_DIR/std/src/process.rs:LL:COL note: inside `crash` --> $SRC_DIR/core/src/process.rs:LL:COL -error: aborting due to 13 previous errors +error[E0080]: the program aborted execution + --> $DIR/const_panic.rs:48:19 + | +LL | const CRASH: () = core::process::crash(); + | ^^^^^^^^^^^^^^^^^^^^^^ evaluation of `CRASH` failed inside this call + | +note: inside `crash` + --> $SRC_DIR/core/src/process.rs:LL:COL + +error: aborting due to 14 previous errors For more information about this error, try `rustc --explain E0080`. diff --git a/tests/ui/impl-trait/in-trait/refine-self-referential-rtn-self-ty.rs b/tests/ui/impl-trait/in-trait/refine-self-referential-rtn-self-ty.rs new file mode 100644 index 0000000000000..72f96dc845f70 --- /dev/null +++ b/tests/ui/impl-trait/in-trait/refine-self-referential-rtn-self-ty.rs @@ -0,0 +1,14 @@ +#![feature(return_type_notation)] + +trait IntFactory { + fn stream(&self) -> impl IntFactory; + //~^ ERROR recursion limit exceeded while collecting implied RPITIT bounds +} + +impl IntFactory for u32 { + fn stream(&self) -> Self { + todo!() + } +} + +fn main() {} diff --git a/tests/ui/impl-trait/in-trait/refine-self-referential-rtn-self-ty.stderr b/tests/ui/impl-trait/in-trait/refine-self-referential-rtn-self-ty.stderr new file mode 100644 index 0000000000000..a7aab3cee692b --- /dev/null +++ b/tests/ui/impl-trait/in-trait/refine-self-referential-rtn-self-ty.stderr @@ -0,0 +1,10 @@ +error: recursion limit exceeded while collecting implied RPITIT bounds + --> $DIR/refine-self-referential-rtn-self-ty.rs:4:25 + | +LL | fn stream(&self) -> impl IntFactory; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: consider increasing the recursion limit by adding a `#![recursion_limit = "256"]` attribute to your crate (`refine_self_referential_rtn_self_ty`) + +error: aborting due to 1 previous error + diff --git a/tests/ui/impl-trait/in-trait/refine-self-referential-rtn.rs b/tests/ui/impl-trait/in-trait/refine-self-referential-rtn.rs index 0936f6e33635f..b52e3b8117292 100644 --- a/tests/ui/impl-trait/in-trait/refine-self-referential-rtn.rs +++ b/tests/ui/impl-trait/in-trait/refine-self-referential-rtn.rs @@ -2,6 +2,7 @@ trait IntFactory { fn stream(&self) -> impl IntFactory; + //~^ ERROR recursion limit exceeded while collecting implied RPITIT bounds } struct S; diff --git a/tests/ui/impl-trait/in-trait/refine-self-referential-rtn.stderr b/tests/ui/impl-trait/in-trait/refine-self-referential-rtn.stderr index 35c9cfd19408c..3c9896877468b 100644 --- a/tests/ui/impl-trait/in-trait/refine-self-referential-rtn.stderr +++ b/tests/ui/impl-trait/in-trait/refine-self-referential-rtn.stderr @@ -1,5 +1,5 @@ error[E0277]: the trait bound `!: IntFactory` is not satisfied - --> $DIR/refine-self-referential-rtn.rs:10:25 + --> $DIR/refine-self-referential-rtn.rs:11:25 | LL | fn stream(&self) -> impl IntFactory { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `IntFactory` is not implemented for `!` @@ -8,7 +8,7 @@ LL | todo!() | ------- return type was inferred to be `!` here | help: the trait `IntFactory` is implemented for `S` - --> $DIR/refine-self-referential-rtn.rs:9:1 + --> $DIR/refine-self-referential-rtn.rs:10:1 | LL | impl IntFactory for S { | ^^^^^^^^^^^^^^^^^^^^^ @@ -17,6 +17,14 @@ help: `!` can be coerced to any type; consider casting it to a concrete type tha LL | todo!() as /* Type */ | +++++++++++++ -error: aborting due to 1 previous error +error: recursion limit exceeded while collecting implied RPITIT bounds + --> $DIR/refine-self-referential-rtn.rs:4:25 + | +LL | fn stream(&self) -> impl IntFactory; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = help: consider increasing the recursion limit by adding a `#![recursion_limit = "256"]` attribute to your crate (`refine_self_referential_rtn`) + +error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/imports/reexport-private-import-of-primitive-type.rs b/tests/ui/imports/reexport-private-import-of-primitive-type.rs new file mode 100644 index 0000000000000..c718e27509b0e --- /dev/null +++ b/tests/ui/imports/reexport-private-import-of-primitive-type.rs @@ -0,0 +1,9 @@ +// Regression test for https://github.com/rust-lang/rust/issues/165827 + +//@ edition: 2024 + +use str; +pub use str as b; +//~^ ERROR `str` is only public within the crate, and cannot be re-exported outside + +fn main() {} diff --git a/tests/ui/imports/reexport-private-import-of-primitive-type.stderr b/tests/ui/imports/reexport-private-import-of-primitive-type.stderr new file mode 100644 index 0000000000000..29afdc30e72c6 --- /dev/null +++ b/tests/ui/imports/reexport-private-import-of-primitive-type.stderr @@ -0,0 +1,9 @@ +error[E0365]: `str` is only public within the crate, and cannot be re-exported outside + --> $DIR/reexport-private-import-of-primitive-type.rs:6:9 + | +LL | pub use str as b; + | ^^^^^^^^ re-export of crate public `str` + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0365`. diff --git a/tests/ui/intrinsics/auxiliary/const-eval-doc-attrs.rs b/tests/ui/intrinsics/auxiliary/const-eval-doc-attrs.rs new file mode 100644 index 0000000000000..6686a2092bee6 --- /dev/null +++ b/tests/ui/intrinsics/auxiliary/const-eval-doc-attrs.rs @@ -0,0 +1,19 @@ +#![feature(type_info)] + +use std::any::TypeId; + +///CCC +#[doc = "DDD"] +pub struct C; + +pub const N: usize = { + struct TestStruct { + /// aaa + #[doc = "bbb"] + field: u8, + } + let ty_id = TypeId::of::(); + ty_id.field(0, 0).docs().len() +}; + +const _: () = assert!( N == 0 ); diff --git a/tests/ui/intrinsics/const-eval-doc-attrs.rs b/tests/ui/intrinsics/const-eval-doc-attrs.rs new file mode 100644 index 0000000000000..57273deb958c7 --- /dev/null +++ b/tests/ui/intrinsics/const-eval-doc-attrs.rs @@ -0,0 +1,20 @@ +//@ aux-crate: dep=const-eval-doc-attrs.rs +//@ run-pass + +#![feature(type_info, const_cmp, const_trait_impl)] +use std::any::TypeId; + + +// should be encoded since UI test is of CrateType::Executable +///AAA +#[doc = "BBB"] +struct A; + +const _: () = assert!( dep::N == 0 ) ; +const _: () = const { assert!( TypeId::of::
().docs() == &["AAA", "BBB"] ) }; +const _: () = const { assert!( TypeId::of::().docs() == &["CCC", "DDD"] ) }; + + + +fn main() { +} diff --git a/tests/ui/lint/pre-expansion-parsing.rs b/tests/ui/lint/pre-expansion-parsing.rs index 772c61b8e212f..08f0cd3cf4885 100644 --- a/tests/ui/lint/pre-expansion-parsing.rs +++ b/tests/ui/lint/pre-expansion-parsing.rs @@ -8,5 +8,6 @@ #[expect[helix::]] // OK #[allow = 1u7] // OK #[allow = "x"suffix] // OK +#[allow(foo(a b))] // OK #[cfg(false)] const _: () = (); diff --git a/tests/ui/parser/forced-keywords/missing-kw-before-item.rs b/tests/ui/parser/forced-keywords/missing-kw-before-item.rs new file mode 100644 index 0000000000000..ca113b9233d82 --- /dev/null +++ b/tests/ui/parser/forced-keywords/missing-kw-before-item.rs @@ -0,0 +1,10 @@ +// Check that we don't ICE when recovering a missing `fn`/`struct` keyword before a forced keyword. +// +//@ edition: 2021.. +#![feature(forced_keywords)] + +pub k#self() {} +//~^ ERROR visibility `pub` is not followed by an item +//~| ERROR expected item, found keyword `k#self` + +fn main() {} diff --git a/tests/ui/parser/forced-keywords/missing-kw-before-item.stderr b/tests/ui/parser/forced-keywords/missing-kw-before-item.stderr new file mode 100644 index 0000000000000..c6585157c8090 --- /dev/null +++ b/tests/ui/parser/forced-keywords/missing-kw-before-item.stderr @@ -0,0 +1,18 @@ +error: visibility `pub` is not followed by an item + --> $DIR/missing-kw-before-item.rs:6:1 + | +LL | pub k#self() {} + | ^^^ the visibility + | + = help: you likely meant to define an item, e.g., `pub fn foo() {}` + +error: expected item, found keyword `k#self` + --> $DIR/missing-kw-before-item.rs:6:5 + | +LL | pub k#self() {} + | ^^^^^^ expected item + | + = note: for a full list of items that can appear in modules, see + +error: aborting due to 2 previous errors + diff --git a/tests/ui/parser/forced-keywords/param-without-type.rs b/tests/ui/parser/forced-keywords/param-without-type.rs new file mode 100644 index 0000000000000..2bcc584283e3a --- /dev/null +++ b/tests/ui/parser/forced-keywords/param-without-type.rs @@ -0,0 +1,13 @@ +// Regression test for . +// +//@ edition: 2021.. +#![feature(forced_keywords)] + +fn foo(S k#self) {} +//~^ ERROR expected one of `:`, `@`, or `|`, found keyword `k#self` +//~| ERROR `self` parameter is only allowed in associated functions + +fn bar(S k#not_a_keyword) {} +//~^ ERROR expected one of `:`, `@`, or `|`, found `k#not_a_keyword` + +fn main() {} diff --git a/tests/ui/parser/forced-keywords/param-without-type.stderr b/tests/ui/parser/forced-keywords/param-without-type.stderr new file mode 100644 index 0000000000000..9c92f77ad9c4f --- /dev/null +++ b/tests/ui/parser/forced-keywords/param-without-type.stderr @@ -0,0 +1,28 @@ +error: expected one of `:`, `@`, or `|`, found keyword `k#self` + --> $DIR/param-without-type.rs:6:10 + | +LL | fn foo(S k#self) {} + | ^^^^^^ expected one of `:`, `@`, or `|` + | +help: declare the type after the parameter binding + | +LL - fn foo(S k#self) {} +LL + fn foo(: ) {} + | + +error: expected one of `:`, `@`, or `|`, found `k#not_a_keyword` + --> $DIR/param-without-type.rs:10:10 + | +LL | fn bar(S k#not_a_keyword) {} + | ^^^^^^^^^^^^^^^ expected one of `:`, `@`, or `|` + +error: `self` parameter is only allowed in associated functions + --> $DIR/param-without-type.rs:6:8 + | +LL | fn foo(S k#self) {} + | ^ not semantically valid as function parameter + | + = note: associated functions are those in `impl` or `trait` definitions + +error: aborting due to 3 previous errors + diff --git a/tests/ui/parser/issues/issue-70549-resolve-after-recovered-self-ctor.rs b/tests/ui/parser/issues/issue-70549-resolve-after-recovered-self-ctor.rs index ada10fcda27d9..292019a5c46fd 100644 --- a/tests/ui/parser/issues/issue-70549-resolve-after-recovered-self-ctor.rs +++ b/tests/ui/parser/issues/issue-70549-resolve-after-recovered-self-ctor.rs @@ -2,14 +2,10 @@ struct S {} impl S { fn foo(&mur Self) {} - //~^ ERROR expected identifier, found keyword `Self` - //~| ERROR expected one of `:`, `@` - //~| ERROR expected unit struct, found self constructor `Self` + //~^ ERROR expected one of `:`, `@` fn bar(&'static mur Self) {} //~^ ERROR unexpected lifetime - //~| ERROR expected identifier, found keyword `Self` //~| ERROR expected one of `:`, `@` - //~| ERROR expected unit struct, found self constructor `Self` fn baz(&mur Self @ _) {} //~^ ERROR expected one of `:`, `@` diff --git a/tests/ui/parser/issues/issue-70549-resolve-after-recovered-self-ctor.stderr b/tests/ui/parser/issues/issue-70549-resolve-after-recovered-self-ctor.stderr index 9c632a8332a19..cb0f514f40c93 100644 --- a/tests/ui/parser/issues/issue-70549-resolve-after-recovered-self-ctor.stderr +++ b/tests/ui/parser/issues/issue-70549-resolve-after-recovered-self-ctor.stderr @@ -1,9 +1,3 @@ -error: expected identifier, found keyword `Self` - --> $DIR/issue-70549-resolve-after-recovered-self-ctor.rs:4:17 - | -LL | fn foo(&mur Self) {} - | ^^^^ expected identifier, found keyword - error: expected one of `:`, `@`, or `|`, found keyword `Self` --> $DIR/issue-70549-resolve-after-recovered-self-ctor.rs:4:17 | @@ -17,7 +11,7 @@ LL + fn foo(&mut Self) {} | error: unexpected lifetime `'static` in pattern - --> $DIR/issue-70549-resolve-after-recovered-self-ctor.rs:8:13 + --> $DIR/issue-70549-resolve-after-recovered-self-ctor.rs:6:13 | LL | fn bar(&'static mur Self) {} | ^^^^^^^ @@ -28,14 +22,8 @@ LL - fn bar(&'static mur Self) {} LL + fn bar(&mur Self) {} | -error: expected identifier, found keyword `Self` - --> $DIR/issue-70549-resolve-after-recovered-self-ctor.rs:8:25 - | -LL | fn bar(&'static mur Self) {} - | ^^^^ expected identifier, found keyword - error: expected one of `:`, `@`, or `|`, found keyword `Self` - --> $DIR/issue-70549-resolve-after-recovered-self-ctor.rs:8:25 + --> $DIR/issue-70549-resolve-after-recovered-self-ctor.rs:6:25 | LL | fn bar(&'static mur Self) {} | ^^^^ expected one of `:`, `@`, or `|` @@ -47,7 +35,7 @@ LL + fn bar(&'static mut Self) {} | error: expected one of `:`, `@`, or `|`, found keyword `Self` - --> $DIR/issue-70549-resolve-after-recovered-self-ctor.rs:14:17 + --> $DIR/issue-70549-resolve-after-recovered-self-ctor.rs:10:17 | LL | fn baz(&mur Self @ _) {} | ^^^^ expected one of `:`, `@`, or `|` @@ -58,18 +46,5 @@ LL - fn baz(&mur Self @ _) {} LL + fn baz(&mut Self @ _) {} | -error[E0533]: expected unit struct, found self constructor `Self` - --> $DIR/issue-70549-resolve-after-recovered-self-ctor.rs:4:17 - | -LL | fn foo(&mur Self) {} - | ^^^^ not a unit struct - -error[E0533]: expected unit struct, found self constructor `Self` - --> $DIR/issue-70549-resolve-after-recovered-self-ctor.rs:8:25 - | -LL | fn bar(&'static mur Self) {} - | ^^^^ not a unit struct - -error: aborting due to 8 previous errors +error: aborting due to 4 previous errors -For more information about this error, try `rustc --explain E0533`. diff --git a/tests/ui/parser/macro/kw-in-const-item-pos-recovery-149692.rs b/tests/ui/parser/macro/kw-in-const-item-pos-recovery-149692.rs index 8619856cad670..a92384cce3bfc 100644 --- a/tests/ui/parser/macro/kw-in-const-item-pos-recovery-149692.rs +++ b/tests/ui/parser/macro/kw-in-const-item-pos-recovery-149692.rs @@ -2,11 +2,10 @@ //! specifically for `const` items. macro_rules! m { - (const $id:item()) => {} + (const $id:item()) => {}; } m!(const Self()); -//~^ ERROR expected identifier, found keyword `Self` -//~^^ ERROR missing `fn` or `struct` for function or struct definition +//~^ ERROR expected one of `!` or `::`, found `(` fn main() {} diff --git a/tests/ui/parser/macro/kw-in-const-item-pos-recovery-149692.stderr b/tests/ui/parser/macro/kw-in-const-item-pos-recovery-149692.stderr index d412c59c4372a..4b7448458f3ce 100644 --- a/tests/ui/parser/macro/kw-in-const-item-pos-recovery-149692.stderr +++ b/tests/ui/parser/macro/kw-in-const-item-pos-recovery-149692.stderr @@ -1,22 +1,11 @@ -error: expected identifier, found keyword `Self` - --> $DIR/kw-in-const-item-pos-recovery-149692.rs:8:10 +error: expected one of `!` or `::`, found `(` + --> $DIR/kw-in-const-item-pos-recovery-149692.rs:8:14 | -LL | m!(const Self()); - | ^^^^ expected identifier, found keyword - -error: missing `fn` or `struct` for function or struct definition - --> $DIR/kw-in-const-item-pos-recovery-149692.rs:8:10 - | -LL | (const $id:item()) => {} +LL | (const $id:item()) => {}; | -------- while parsing argument for this `item` macro fragment ... LL | m!(const Self()); - | ^^^^ - | -help: if you meant to call a macro, try - | -LL | m!(const Self!()); - | + + | ^ expected one of `!` or `::` -error: aborting due to 2 previous errors +error: aborting due to 1 previous error diff --git a/tests/ui/parser/macro/kw-in-item-pos-recovery-149692.rs b/tests/ui/parser/macro/kw-in-item-pos-recovery-149692.rs index 77372ced09c42..ea14c4252fef1 100644 --- a/tests/ui/parser/macro/kw-in-item-pos-recovery-149692.rs +++ b/tests/ui/parser/macro/kw-in-item-pos-recovery-149692.rs @@ -4,19 +4,16 @@ //! See . macro_rules! m { - ($id:item()) => {} + ($id:item()) => {}; } m!(Self()); -//~^ ERROR expected identifier, found keyword `Self` -//~^^ ERROR missing `fn` or `struct` for function or struct definition +//~^ ERROR expected one of `!` or `::`, found `(` -m!(Self{}); -//~^ ERROR expected identifier, found keyword `Self` -//~^^ ERROR missing `enum` or `struct` for enum or struct definition +m!(Self {}); +//~^ ERROR expected one of `!` or `::`, found `{` m!(crate()); -//~^ ERROR expected identifier, found keyword `crate` -//~^^ ERROR missing `fn` or `struct` for function or struct definition +//~^ ERROR expected one of `!` or `::`, found `(` fn main() {} diff --git a/tests/ui/parser/macro/kw-in-item-pos-recovery-149692.stderr b/tests/ui/parser/macro/kw-in-item-pos-recovery-149692.stderr index 39f3e2d3a9ea5..25f3cdd918bc7 100644 --- a/tests/ui/parser/macro/kw-in-item-pos-recovery-149692.stderr +++ b/tests/ui/parser/macro/kw-in-item-pos-recovery-149692.stderr @@ -1,57 +1,29 @@ -error: expected identifier, found keyword `Self` - --> $DIR/kw-in-item-pos-recovery-149692.rs:10:4 +error: expected one of `!` or `::`, found `(` + --> $DIR/kw-in-item-pos-recovery-149692.rs:10:8 | -LL | m!(Self()); - | ^^^^ expected identifier, found keyword - -error: missing `fn` or `struct` for function or struct definition - --> $DIR/kw-in-item-pos-recovery-149692.rs:10:4 - | -LL | ($id:item()) => {} +LL | ($id:item()) => {}; | -------- while parsing argument for this `item` macro fragment ... LL | m!(Self()); - | ^^^^ - | -help: if you meant to call a macro, try - | -LL | m!(Self!()); - | + - -error: expected identifier, found keyword `Self` - --> $DIR/kw-in-item-pos-recovery-149692.rs:14:4 - | -LL | m!(Self{}); - | ^^^^ expected identifier, found keyword + | ^ expected one of `!` or `::` -error: missing `enum` or `struct` for enum or struct definition - --> $DIR/kw-in-item-pos-recovery-149692.rs:14:4 +error: expected one of `!` or `::`, found `{` + --> $DIR/kw-in-item-pos-recovery-149692.rs:13:9 | -LL | ($id:item()) => {} +LL | ($id:item()) => {}; | -------- while parsing argument for this `item` macro fragment ... -LL | m!(Self{}); - | ^^^^ - -error: expected identifier, found keyword `crate` - --> $DIR/kw-in-item-pos-recovery-149692.rs:18:4 - | -LL | m!(crate()); - | ^^^^^ expected identifier, found keyword +LL | m!(Self {}); + | ^ expected one of `!` or `::` -error: missing `fn` or `struct` for function or struct definition - --> $DIR/kw-in-item-pos-recovery-149692.rs:18:4 +error: expected one of `!` or `::`, found `(` + --> $DIR/kw-in-item-pos-recovery-149692.rs:16:9 | -LL | ($id:item()) => {} +LL | ($id:item()) => {}; | -------- while parsing argument for this `item` macro fragment ... LL | m!(crate()); - | ^^^^^ - | -help: if you meant to call a macro, try - | -LL | m!(crate!()); - | + + | ^ expected one of `!` or `::` -error: aborting due to 6 previous errors +error: aborting due to 3 previous errors diff --git a/tests/ui/parser/macro/kw-in-item-pos-recovery-151238.rs b/tests/ui/parser/macro/kw-in-item-pos-recovery-151238.rs index bd1785ba5b3c1..27bed26b959ce 100644 --- a/tests/ui/parser/macro/kw-in-item-pos-recovery-151238.rs +++ b/tests/ui/parser/macro/kw-in-item-pos-recovery-151238.rs @@ -5,9 +5,8 @@ macro_rules! x { } x! { trait MyTrait { fn bar(c self) } - //~^ ERROR expected identifier, found keyword `self` - //~^^ ERROR expected one of `:`, `@`, or `|`, found keyword `self` - //~^^^ ERROR expected one of `->`, `;`, `where`, or `{`, found `}` + //~^ ERROR expected one of `:`, `@`, or `|`, found keyword `self` + //~| ERROR expected one of `->`, `;`, `where`, or `{`, found `}` } fn main() {} diff --git a/tests/ui/parser/macro/kw-in-item-pos-recovery-151238.stderr b/tests/ui/parser/macro/kw-in-item-pos-recovery-151238.stderr index 3a7e4779aadfb..a27b7a2a7d921 100644 --- a/tests/ui/parser/macro/kw-in-item-pos-recovery-151238.stderr +++ b/tests/ui/parser/macro/kw-in-item-pos-recovery-151238.stderr @@ -1,9 +1,3 @@ -error: expected identifier, found keyword `self` - --> $DIR/kw-in-item-pos-recovery-151238.rs:7:28 - | -LL | trait MyTrait { fn bar(c self) } - | ^^^^ expected identifier, found keyword - error: expected one of `:`, `@`, or `|`, found keyword `self` --> $DIR/kw-in-item-pos-recovery-151238.rs:7:28 | @@ -24,5 +18,5 @@ LL | trait MyTrait { fn bar(c self) } | | | while parsing this `fn` -error: aborting due to 3 previous errors +error: aborting due to 2 previous errors diff --git a/tests/ui/parser/recover/recover-seperated-list.rs b/tests/ui/parser/recover/recover-seperated-list.rs new file mode 100644 index 0000000000000..25fb7fe6a5dfb --- /dev/null +++ b/tests/ui/parser/recover/recover-seperated-list.rs @@ -0,0 +1,14 @@ +macro_rules! probe { + ($ty:ty) => { + compile_error!("TY FRAGMENT MATCHED") + }; +} + +fn f<'a, 'b>() -> probe!(impl Sized + use<'a 'b>) { + //~^ ERROR expected one of `,` or `>`, found `'b` + loop {} +} + +fn main() { + +} diff --git a/tests/ui/parser/recover/recover-seperated-list.stderr b/tests/ui/parser/recover/recover-seperated-list.stderr new file mode 100644 index 0000000000000..74c105d3bbff3 --- /dev/null +++ b/tests/ui/parser/recover/recover-seperated-list.stderr @@ -0,0 +1,11 @@ +error: expected one of `,` or `>`, found `'b` + --> $DIR/recover-seperated-list.rs:7:46 + | +LL | ($ty:ty) => { + | ------ while parsing argument for this `ty` macro fragment +... +LL | fn f<'a, 'b>() -> probe!(impl Sized + use<'a 'b>) { + | ^^ expected one of `,` or `>` + +error: aborting due to 1 previous error + diff --git a/tests/ui/process/no-stdio.rs b/tests/ui/process/no-stdio.rs index 5cc7cacbb22f0..c41811b91d3e0 100644 --- a/tests/ui/process/no-stdio.rs +++ b/tests/ui/process/no-stdio.rs @@ -17,7 +17,7 @@ unsafe fn without_stdio R>(f: F) -> R { let doit = |a| { let r = libc::dup(a); assert!(r >= 0); - return r + return r; }; let a = doit(0); let b = doit(1); @@ -33,7 +33,7 @@ unsafe fn without_stdio R>(f: F) -> R { assert!(libc::dup2(b, 1) >= 0); assert!(libc::dup2(c, 2) >= 0); - return r + return r; } #[cfg(unix)] @@ -66,7 +66,7 @@ unsafe fn without_stdio R>(f: F) -> R { let handle = GetStdHandle(id); assert!(handle != INVALID_HANDLE_VALUE); assert!(SetStdHandle(id, INVALID_HANDLE_VALUE) != 0); - return handle + return handle; }; let a = doit(STD_INPUT_HANDLE); @@ -82,7 +82,7 @@ unsafe fn without_stdio R>(f: F) -> R { doit(STD_OUTPUT_HANDLE, b); doit(STD_ERROR_HANDLE, c); - return r + return r; } fn main() { @@ -99,10 +99,10 @@ fn main() { assert_fd_is_valid(0); assert_fd_is_valid(1); assert_fd_is_valid(2); - return + return; } - // First, make sure reads/writes without stdio work if stdio itself is + // First, make sure reads/writes without stdio error if stdio itself is // missing. let (a, b, c) = unsafe { without_stdio(|| { @@ -114,25 +114,32 @@ fn main() { }) }; - assert_eq!(a.unwrap(), 5); - assert_eq!(b.unwrap(), 5); - assert_eq!(c.unwrap(), 0); + if cfg!(windows) { + // On Windows it's not an error to write to unset stdio. + assert_eq!(a.unwrap(), 5); + assert_eq!(b.unwrap(), 5); + assert_eq!(c.unwrap(), 0); + } else { + // On Unix platforms it is. + assert!(a.is_err()); + assert!(b.is_err()); + assert!(c.is_err()); + } // Second, spawn a child and do some work with "null" descriptors to make // sure it's ok let me = env::current_exe().unwrap(); let status = Command::new(&me) - .arg("next") - .stdin(Stdio::null()) - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .status().unwrap(); + .arg("next") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .unwrap(); assert!(status.success(), "{} isn't a success", status); // Finally, close everything then spawn a child to make sure everything is // *still* ok. - let status = unsafe { - without_stdio(|| Command::new(&me).arg("next").status()) - }.unwrap(); + let status = unsafe { without_stdio(|| Command::new(&me).arg("next").status()) }.unwrap(); assert!(status.success(), "{} isn't a success", status); } diff --git a/tests/ui/view-types/unsized.rs b/tests/ui/view-types/unsized.rs new file mode 100644 index 0000000000000..a607ec0fdab85 --- /dev/null +++ b/tests/ui/view-types/unsized.rs @@ -0,0 +1,34 @@ +#![feature(view_types, sized_hierarchy)] + +use std::marker::{MetaSized, PointeeSized, Sized}; +use std::view::view_type; + +struct A { + b: (), + c: (), +} + +fn assert_sized() {} +fn assert_metasized() {} +fn assert_pointeesized() {} + +fn main() { + assert_sized::(); + //~^ ERROR the size for values of type `view_type!(A.{})` cannot be known at compilation time + assert_metasized::(); + //~^ ERROR the size for values of type `view_type!(A.{})` cannot be known + assert_pointeesized::(); + + // View types stay unsized even if they borrow some/all the fields. + assert_sized::(); + //~^ ERROR the size for values of type `view_type!(A.{ b })` cannot be known at compilation time + assert_metasized::(); + //~^ ERROR the size for values of type `view_type!(A.{ b })` cannot be known + assert_pointeesized::(); + + assert_sized::(); + //~^ ERROR the size for values of type `view_type!(A.{ b, c })` cannot be known at compilation time + assert_metasized::(); + //~^ ERROR the size for values of type `view_type!(A.{ b, c })` cannot be known + assert_pointeesized::(); +} diff --git a/tests/ui/view-types/unsized.stderr b/tests/ui/view-types/unsized.stderr new file mode 100644 index 0000000000000..7ce70c5ca198f --- /dev/null +++ b/tests/ui/view-types/unsized.stderr @@ -0,0 +1,93 @@ +error[E0277]: the size for values of type `view_type!(A.{})` cannot be known at compilation time + --> $DIR/unsized.rs:16:20 + | +LL | assert_sized::(); + | ^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time + | + = help: the trait `Sized` is not implemented for `view_type!(A.{})` +note: required by an implicit `Sized` bound in `assert_sized` + --> $DIR/unsized.rs:11:17 + | +LL | fn assert_sized() {} + | ^ required by the implicit `Sized` requirement on this type parameter in `assert_sized` +help: consider relaxing the implicit `Sized` restriction + | +LL | fn assert_sized() {} + | ++++++++ + +error[E0277]: the size for values of type `view_type!(A.{})` cannot be known + --> $DIR/unsized.rs:18:24 + | +LL | assert_metasized::(); + | ^^^^^^^^^^^^^^^^ doesn't have a known size + | + = help: the nightly-only, unstable trait `MetaSized` is not implemented for `view_type!(A.{})` +note: required by a bound in `assert_metasized` + --> $DIR/unsized.rs:12:24 + | +LL | fn assert_metasized() {} + | ^^^^^^^^^ required by this bound in `assert_metasized` + +error[E0277]: the size for values of type `view_type!(A.{ b })` cannot be known at compilation time + --> $DIR/unsized.rs:23:20 + | +LL | assert_sized::(); + | ^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time + | + = help: the trait `Sized` is not implemented for `view_type!(A.{ b })` +note: required by an implicit `Sized` bound in `assert_sized` + --> $DIR/unsized.rs:11:17 + | +LL | fn assert_sized() {} + | ^ required by the implicit `Sized` requirement on this type parameter in `assert_sized` +help: consider relaxing the implicit `Sized` restriction + | +LL | fn assert_sized() {} + | ++++++++ + +error[E0277]: the size for values of type `view_type!(A.{ b })` cannot be known + --> $DIR/unsized.rs:25:24 + | +LL | assert_metasized::(); + | ^^^^^^^^^^^^^^^^^^^ doesn't have a known size + | + = help: the nightly-only, unstable trait `MetaSized` is not implemented for `view_type!(A.{ b })` +note: required by a bound in `assert_metasized` + --> $DIR/unsized.rs:12:24 + | +LL | fn assert_metasized() {} + | ^^^^^^^^^ required by this bound in `assert_metasized` + +error[E0277]: the size for values of type `view_type!(A.{ b, c })` cannot be known at compilation time + --> $DIR/unsized.rs:29:20 + | +LL | assert_sized::(); + | ^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time + | + = help: the trait `Sized` is not implemented for `view_type!(A.{ b, c })` +note: required by an implicit `Sized` bound in `assert_sized` + --> $DIR/unsized.rs:11:17 + | +LL | fn assert_sized() {} + | ^ required by the implicit `Sized` requirement on this type parameter in `assert_sized` +help: consider relaxing the implicit `Sized` restriction + | +LL | fn assert_sized() {} + | ++++++++ + +error[E0277]: the size for values of type `view_type!(A.{ b, c })` cannot be known + --> $DIR/unsized.rs:31:24 + | +LL | assert_metasized::(); + | ^^^^^^^^^^^^^^^^^^^^^^ doesn't have a known size + | + = help: the nightly-only, unstable trait `MetaSized` is not implemented for `view_type!(A.{ b, c })` +note: required by a bound in `assert_metasized` + --> $DIR/unsized.rs:12:24 + | +LL | fn assert_metasized() {} + | ^^^^^^^^^ required by this bound in `assert_metasized` + +error: aborting due to 6 previous errors + +For more information about this error, try `rustc --explain E0277`.