diff --git a/Cargo.lock b/Cargo.lock index f8f3dfce90c4e..24e63f0798f95 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -879,6 +879,13 @@ dependencies = [ "windows 0.61.3", ] +[[package]] +name = "compiletest-lint-driver" +version = "0.1.0" +dependencies = [ + "libloading", +] + [[package]] name = "console" version = "0.16.3" diff --git a/Cargo.toml b/Cargo.toml index b785c566dc651..e65da085f8af9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,6 +16,7 @@ members = [ "src/tools/clippy/clippy_dev", "src/tools/collect-license-metadata", "src/tools/compiletest", + "src/tools/compiletest-lint-driver", "src/tools/coverage-dump", "src/tools/features-status-dump", "src/tools/generate-copyright", diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs index d4003a581c1f5..bc5ebc9a6ec14 100644 --- a/compiler/rustc_codegen_ssa/src/back/link.rs +++ b/compiler/rustc_codegen_ssa/src/back/link.rs @@ -390,6 +390,7 @@ pub fn link_binary( &crate_info, &metadata, path.as_ref(), + outputs, codegen_backend, ); } @@ -1234,6 +1235,7 @@ fn link_natively( crate_info: &CrateInfo, metadata: &EncodedMetadata, tmpdir: &Path, + outputs: &OutputFilenames, codegen_backend: &'static str, ) { info!("preparing {:?} to {:?}", crate_type, out_filename); @@ -1249,6 +1251,18 @@ fn link_natively( should_archive.then(|| tmpdir.join(out_filename.file_name().unwrap()).with_extension("so")); let temp_filename = archive_member.as_deref().unwrap_or(out_filename); + // Follow the same naming convention as regular codegen objects. + let metadata_object = outputs.temp_path_for_cgu(OutputType::Object, "rustc_link_metadata"); + let symbols_object = outputs.temp_path_for_cgu(OutputType::Object, "rustc_link_symbols"); + + // Clean up the generated linker inputs even if linking fails. + let _cleanup = rustc_data_structures::defer(|| { + if !sess.opts.cg.save_temps { + ensure_removed(sess.dcx(), &metadata_object); + ensure_removed(sess.dcx(), &symbols_object); + } + }); + let (mut cmd, jobserver_tokens) = linker_with_args( &linker_path, flavor, @@ -1257,6 +1271,8 @@ fn link_natively( rmeta_link_cache, crate_type, tmpdir, + &metadata_object, + &symbols_object, temp_filename, compiled_modules, crate_info, @@ -2532,7 +2548,7 @@ fn add_post_link_args(cmd: &mut dyn Linker, sess: &Session, flavor: LinkerFlavor fn add_linked_symbol_object( cmd: &mut dyn Linker, sess: &Session, - tmpdir: &Path, + symbols_path: &Path, crate_type: CrateType, linked_symbols: &[(String, SymbolExportKind)], exported_symbols: &[SymbolExport], @@ -2667,12 +2683,11 @@ fn add_linked_symbol_object( file.append_section_data(section, drectve.as_bytes(), 1); } - let path = tmpdir.join("symbols.o"); - let result = std::fs::write(&path, file.write().unwrap()); - if let Err(error) = result { - sess.dcx().emit_fatal(diagnostics::FailedToWrite { path, error }); - } - cmd.add_object(&path); + fs::write(symbols_path, file.write().unwrap()).unwrap_or_else(|error| { + sess.dcx() + .emit_fatal(diagnostics::FailedToWrite { path: symbols_path.to_path_buf(), error }) + }); + cmd.add_object(symbols_path); } /// Add object files containing code from the current crate. @@ -2712,7 +2727,7 @@ fn add_local_crate_metadata_objects( sess: &Session, archive_builder_builder: &dyn ArchiveBuilderBuilder, crate_type: CrateType, - tmpdir: &Path, + metadata_path: &Path, crate_info: &CrateInfo, metadata: &EncodedMetadata, ) { @@ -2725,9 +2740,11 @@ fn add_local_crate_metadata_objects( &metadata, &crate_info.metadata_symbol, ); - let obj = emit_wrapper_file(sess, &data, tmpdir, "rmeta.o"); - - cmd.add_object(&obj); + fs::write(metadata_path, data).unwrap_or_else(|error| { + sess.dcx() + .emit_fatal(diagnostics::FailedToWrite { path: metadata_path.to_path_buf(), error }) + }); + cmd.add_object(metadata_path); } } @@ -2910,6 +2927,8 @@ fn linker_with_args( rmeta_link_cache: &mut RmetaLinkCache, crate_type: CrateType, tmpdir: &Path, + metadata_object: &Path, + symbols_object: &Path, out_filename: &Path, compiled_modules: &CompiledModules, crate_info: &CrateInfo, @@ -2970,7 +2989,7 @@ fn linker_with_args( add_linked_symbol_object( cmd, sess, - tmpdir, + symbols_object, crate_type, &crate_info.linked_symbols[&crate_type], &export_symbols, @@ -3012,7 +3031,7 @@ fn linker_with_args( sess, archive_builder_builder, crate_type, - tmpdir, + metadata_object, crate_info, metadata, ); 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 68cb87655f38f..9d7d92ecf5c7d 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_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/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index d61e2bcbdd221..a4579580b2559 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 354140a794615..e24699a955207 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/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/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_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index d53e8c7d25482..bda700a4a7f0d 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -2208,6 +2208,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, @@ -2221,6 +2222,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 fd9f76fbeded6..e25fa56a2448b 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; @@ -1123,17 +1123,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) => { @@ -1167,7 +1160,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) { @@ -1175,6 +1168,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) { @@ -1186,7 +1204,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()); } @@ -3288,6 +3307,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. @@ -3836,6 +3875,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>, @@ -3859,12 +3930,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))) => { @@ -3883,6 +3949,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/src/core/build_steps/check.rs b/src/bootstrap/src/core/build_steps/check.rs index fc7d0a386a60f..508c7f7baf70a 100644 --- a/src/bootstrap/src/core/build_steps/check.rs +++ b/src/bootstrap/src/core/build_steps/check.rs @@ -905,6 +905,13 @@ tool_check_step!(Compiletest { default: false, }); +tool_check_step!(CompiletestLintDriver { + path: "src/tools/compiletest-lint-driver", + mode: Mode::ToolRustcPrivate, + allow_features: "rustc_private", + default: false, +}); + // As with compiletest, rustdoc-gui-test is automatically built when running // relevant tests. So being able to check it is mainly useful for people // working on on rustdoc-gui-test itself, or on its compiletest dependency. diff --git a/src/bootstrap/src/core/build_steps/clippy.rs b/src/bootstrap/src/core/build_steps/clippy.rs index 99648425a8987..86dc080e512d4 100644 --- a/src/bootstrap/src/core/build_steps/clippy.rs +++ b/src/bootstrap/src/core/build_steps/clippy.rs @@ -502,6 +502,7 @@ lint_any!( Clippy, "src/tools/clippy", "clippy", Mode::ToolRustcPrivate; CollectLicenseMetadata, "src/tools/collect-license-metadata", "collect-license-metadata", Mode::ToolTarget; Compiletest, "src/tools/compiletest", "compiletest", Mode::ToolTarget; + CompiletestLintDriver, "src/tools/compiletest-lint-driver", "compiletest-lint-driver", Mode::ToolRustcPrivate; CoverageDump, "src/tools/coverage-dump", "coverage-dump", Mode::ToolTarget; Jsondocck, "src/tools/jsondocck", "jsondocck", Mode::ToolTarget; Jsondoclint, "src/tools/jsondoclint", "jsondoclint", Mode::ToolTarget; diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs index 9c930c201b20d..5841fc7196773 100644 --- a/src/bootstrap/src/core/build_steps/test.rs +++ b/src/bootstrap/src/core/build_steps/test.rs @@ -2394,6 +2394,12 @@ NOTE: if you're sure you want to do this, please open an issue as to why. In the builder.ensure(compile::Rustc::new(test_compiler, target)); } + let lint_driver_compiler = query_compiler.unwrap_or(test_compiler); + if suite == "ui-fulldeps" { + builder.std(lint_driver_compiler, target); + builder.std(lint_driver_compiler, lint_driver_compiler.host); + } + // Build the standard library for wasm32-wasip2 (current target for wasm proc macros). if builder.config.wasm_proc_macros { builder.ensure(compile::Std::new( @@ -2467,6 +2473,17 @@ NOTE: if you're sure you want to do this, please open an issue as to why. In the cmd.arg("--compile-lib-path").arg(builder.rustc_libdir(test_compiler)); cmd.arg("--run-lib-path").arg(builder.sysroot_target_libdir(test_compiler, target)); cmd.arg("--rustc-path").arg(builder.rustc(test_compiler)); + if suite == "ui-fulldeps" { + let lint_driver: PathBuf = builder + .ensure(tool::CompiletestLintDriver { + compiler: test_compiler, + target: test_compiler.host, + }) + .tool_path; + cmd.arg("--rustc-lint-driver-path").arg(lint_driver); + cmd.arg("--rustc-lint-driver-lib-path").arg(builder.rustc_libdir(lint_driver_compiler)); + cmd.arg("--rustc-lint-driver-sysroot").arg(builder.sysroot(lint_driver_compiler)); + } if let Some(query_compiler) = query_compiler { cmd.arg("--query-rustc-path").arg(builder.rustc(query_compiler)); cmd.arg("--query-rustc-lib-path").arg(builder.rustc_libdir(query_compiler)); diff --git a/src/bootstrap/src/core/build_steps/tool.rs b/src/bootstrap/src/core/build_steps/tool.rs index c4fae69645e85..52ebefb5a9057 100644 --- a/src/bootstrap/src/core/build_steps/tool.rs +++ b/src/bootstrap/src/core/build_steps/tool.rs @@ -662,6 +662,47 @@ impl CommandLineStep for ErrorIndex { } } +#[derive(Debug, Clone, Hash, PartialEq, Eq)] +pub struct CompiletestLintDriver { + pub compiler: Compiler, + pub target: TargetSelection, +} + +impl CommandLineStep for CompiletestLintDriver { + type Output = ToolBuildResult; + fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { + run.path("src/tools/compiletest-lint-driver") + } + + fn make_run(run: RunConfig<'_>) { + run.builder.ensure(CompiletestLintDriver { + compiler: run.builder.compiler(0, run.builder.host_target), + target: run.target, + }); + } + + fn run(self, builder: &Builder<'_>) -> ToolBuildResult { + builder.std(self.compiler, self.target); + builder.ensure(compile::Rustc::new(self.compiler, self.target)); + builder.ensure(ToolBuild { + build_compiler: self.compiler, + target: self.target, + tool: "compiletest-lint-driver", + mode: Mode::ToolRustcPrivate, + path: "src/tools/compiletest-lint-driver", + source_type: SourceType::InTree, + extra_features: Vec::new(), + allow_features: "rustc_private", + cargo_args: Vec::new(), + artifact_kind: ToolArtifactKind::Binary, + }) + } + + fn metadata(&self) -> Option { + Some(StepMetadata::build("CompiletestLintDriver", self.target).built_by(self.compiler)) + } +} + #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct RemoteTestServer { pub build_compiler: Compiler, diff --git a/src/bootstrap/src/core/builder/mod.rs b/src/bootstrap/src/core/builder/mod.rs index 44445fe74d3b0..aaaad9798ccb3 100644 --- a/src/bootstrap/src/core/builder/mod.rs +++ b/src/bootstrap/src/core/builder/mod.rs @@ -786,6 +786,7 @@ impl<'a> Builder<'a> { tool::Linkchecker, tool::CargoTest, tool::Compiletest, + tool::CompiletestLintDriver, tool::RemoteTestServer, tool::RemoteTestClient, tool::RustInstaller, @@ -827,6 +828,7 @@ impl<'a> Builder<'a> { clippy::CodegenGcc, clippy::CollectLicenseMetadata, clippy::Compiletest, + clippy::CompiletestLintDriver, clippy::CoverageDump, clippy::Jsondocck, clippy::Jsondoclint, @@ -860,6 +862,7 @@ impl<'a> Builder<'a> { check::Bootstrap, check::RunMakeSupport, check::Compiletest, + check::CompiletestLintDriver, check::RustdocGuiTest, check::FeaturesStatusDump, check::CoverageDump, diff --git a/src/bootstrap/src/core/builder/tests.rs b/src/bootstrap/src/core/builder/tests.rs index 92cd34fb72b73..9be30acb19252 100644 --- a/src/bootstrap/src/core/builder/tests.rs +++ b/src/bootstrap/src/core/builder/tests.rs @@ -1727,6 +1727,7 @@ mod snapshot { [test] compiletest-assembly-llvm 1 [test] compiletest-incremental 1 [test] compiletest-debuginfo 1 + [build] rustc 0 -> CompiletestLintDriver 1 [test] compiletest-ui-fulldeps 1 [build] rustdoc 1 [test] compiletest-rustdoc-html 1 @@ -1805,6 +1806,7 @@ mod snapshot { [build] rustc 1 -> std 1 [build] rustc 0 -> Compiletest 1 [test] compiletest-ui 1 + [build] rustc 0 -> CompiletestLintDriver 1 [test] compiletest-ui-fulldeps 1 [build] rustc 0 -> RunMakeSupport 1 [build] rustdoc 1 @@ -1839,6 +1841,7 @@ mod snapshot { [build] rustc 0 -> Compiletest 1 [test] compiletest-ui 2 [build] rustc 2 -> rustc 3 + [build] rustc 2 -> CompiletestLintDriver 3 [test] compiletest-ui-fulldeps 2 [build] rustc 0 -> RunMakeSupport 1 [build] rustdoc 2 @@ -1877,6 +1880,8 @@ mod snapshot { [test] compiletest-ui 2 [build] llvm [build] rustc 2 -> rustc 3 + [build] rustc 2 -> rustc 3 + [build] rustc 2 -> CompiletestLintDriver 3 [test] compiletest-ui-fulldeps 2 [build] rustc 0 -> RunMakeSupport 1 [build] rustdoc 2 @@ -1925,6 +1930,7 @@ mod snapshot { [test] compiletest-incremental 2 [test] compiletest-debuginfo 2 [build] rustc 2 -> rustc 3 + [build] rustc 2 -> CompiletestLintDriver 3 [test] compiletest-ui-fulldeps 2 [build] rustdoc 2 [test] compiletest-rustdoc-html 2 diff --git a/src/doc/rustc-dev-guide/src/tests/compiletest.md b/src/doc/rustc-dev-guide/src/tests/compiletest.md index 6312d06d99f7a..037b5b2929afb 100644 --- a/src/doc/rustc-dev-guide/src/tests/compiletest.md +++ b/src/doc/rustc-dev-guide/src/tests/compiletest.md @@ -807,6 +807,64 @@ pub fn identity(ts: TokenStream) -> TokenStream { > the `aux-build` header, and use `#![crate_type="proc_macro"]`, and `//@ > force-host` and `//@ no-prefer-dynamic` headers in the proc-macro. +### Auxiliary lint + +By using an `aux-lint` directive in a `ui-fulldeps` test, you can build a 'lint library' file which will be loaded into rustc's lints when running your test. + +```rs +// tests/ui-fulldeps/lint_test.rs + +//@ aux-lint: my_lint.rs + +fn main() { + trigger_lint(); //~ ERROR this triggered the lint +} +``` + +```rs +// tests/ui-fulldeps/auxiliary/my_lint.rs + +#![feature(rustc_private)] + +extern crate rustc_driver; +extern crate rustc_errors; +extern crate rustc_hir; +extern crate rustc_lint; +extern crate rustc_macros; +extern crate rustc_session; + +use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_macros::Diagnostic; +use rustc_session::{declare_lint_pass, declare_tool_lint}; + +declare_tool_lint! { + pub example::EXAMPLE_LINT, + Deny, + "some example lint" +} +declare_lint_pass!(ExampleLint => [EXAMPLE_LINT]); + +#[derive(Diagnostic)] +#[diag("this triggered the lint")] +pub(crate) struct Example; + +impl LateLintPass<'_> for ExampleLint { + // lint implementation +} + +#[unsafe(no_mangle)] +unsafe extern "C" fn register_lints( + sess: &rustc_session::Session, + lint_store: &mut rustc_lint::LintStore, +) { + lint_store.register_lints(&[HELLO_LINT]); + lint_store.register_late_pass(|_| Box::new(HelloLint)); +} +``` + +> **Note**: The `register_lints` signature must match _exactly_, +> as it will be dynamically loaded by the test runner. + ## Revisions Revisions allow a single test file to be used for multiple tests. diff --git a/src/tools/compiletest-lint-driver/Cargo.toml b/src/tools/compiletest-lint-driver/Cargo.toml new file mode 100644 index 0000000000000..c1107100c086d --- /dev/null +++ b/src/tools/compiletest-lint-driver/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "compiletest-lint-driver" +version = "0.1.0" +edition = "2024" + +[package.metadata.rust-analyzer] +rustc_private = true + +[dependencies] +libloading = "0.9.0" diff --git a/src/tools/compiletest-lint-driver/src/main.rs b/src/tools/compiletest-lint-driver/src/main.rs new file mode 100644 index 0000000000000..38d461a384c57 --- /dev/null +++ b/src/tools/compiletest-lint-driver/src/main.rs @@ -0,0 +1,49 @@ +#![feature(rustc_private)] +#![warn(unused_extern_crates)] + +use std::process::ExitCode; +use std::sync::OnceLock; + +use rustc_lint::LintStore; +use rustc_session::Session; + +extern crate rustc_driver; +extern crate rustc_interface; +extern crate rustc_lint; +extern crate rustc_session; + +struct Callbacks; + +type LintRegisterFunc = unsafe extern "C" fn(&Session, &mut LintStore); + +static LINT_LIBRARIES: OnceLock> = OnceLock::new(); + +impl rustc_driver::Callbacks for Callbacks { + fn config(&mut self, config: &mut rustc_interface::Config) { + let previous = config.register_lints.take(); + config.register_lints = Some(Box::new(move |sess, lint_store| { + if let Some(previous) = &previous { + previous(sess, lint_store); + } + for library in LINT_LIBRARIES.get().unwrap() { + unsafe { + let register = library.get::(b"register_lints").unwrap(); + (*register)(sess, lint_store); + } + } + })) + } +} + +fn main() -> ExitCode { + rustc_driver::catch_with_exit_code(|| { + let libraries = std::env::var("COMPILETEST_LINT_DRIVER_PATHS") + .expect("`COMPILETEST_LINT_DRIVER_PATHS` not provided") + .split(':') + .map(|path| unsafe { libloading::Library::new(path).unwrap() }) + .collect(); + LINT_LIBRARIES.set(libraries).unwrap(); + let args = std::env::args().collect::>(); + rustc_driver::compiler_entrypoint(&args, &mut Callbacks); + }) +} diff --git a/src/tools/compiletest/src/cli.rs b/src/tools/compiletest/src/cli.rs index 778d53f1d8d4f..7a5e3c1b15e0b 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. @@ -43,6 +132,15 @@ struct Args { /// Path to rustc to use for compiling. #[arg(long)] rustc_path: Utf8PathBuf, + /// Path to the aux-lint rustc driver. + #[arg(long)] + rustc_lint_driver_path: Option, + /// Path to the aux-lint rustc driver libdir. + #[arg(long)] + rustc_lint_driver_lib_path: Option, + /// Path to the aux-lint rustc driver sysroot. + #[arg(long)] + rustc_lint_driver_sysroot: Option, /// Path to python to use for doc tests. #[arg(long)] python: String, @@ -497,6 +595,9 @@ pub(crate) fn parse_config(args: Vec) -> Config { run_make_support_rmeta: args.run_make_support_rmeta, runner: args.runner, rust_randomized_layout: args.rust_randomized_layout, + rustc_lint_driver_lib_path: args.rustc_lint_driver_lib_path, + rustc_lint_driver_path: args.rustc_lint_driver_path, + rustc_lint_driver_sysroot: args.rustc_lint_driver_sysroot, rustc_path: args.rustc_path, rustdoc_path: args.rustdoc_path, rustfix_coverage: args.rustfix_coverage, diff --git a/src/tools/compiletest/src/common.rs b/src/tools/compiletest/src/common.rs index bc953dd30bb38..1f1071f2588a4 100644 --- a/src/tools/compiletest/src/common.rs +++ b/src/tools/compiletest/src/common.rs @@ -329,6 +329,15 @@ pub(crate) struct Config { /// bootstrap option `build.compiletest-allow-stage0=true` and specifying `--stage=0`. pub(crate) rustc_path: Utf8PathBuf, + /// Path to the `compiletest-lint-driver` binary. + pub(crate) rustc_lint_driver_path: Option, + + /// Path to the libdir for the `compiletest-lint-driver` binary. + pub(crate) rustc_lint_driver_lib_path: Option, + + /// Path to the sysroot for the `compiletest-lint-driver` binary. + pub(crate) rustc_lint_driver_sysroot: Option, + /// Path to a *staged* **host** platform cargo executable (unless stage 0 is forced). This /// staged `cargo` is only used within `run-make` test recipes during recipe run time (and is /// *not* used to compile the test recipes), and so must be staged as there may be differences diff --git a/src/tools/compiletest/src/directives.rs b/src/tools/compiletest/src/directives.rs index 4e99ab99f6059..ced1641d94f6a 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}; @@ -240,6 +240,7 @@ mod directives { pub(crate) const AUX_BIN: &str = "aux-bin"; pub(crate) const AUX_BUILD: &str = "aux-build"; pub(crate) const AUX_CRATE: &str = "aux-crate"; + pub(crate) const AUX_LINT: &str = "aux-lint"; pub(crate) const PROC_MACRO: &str = "proc-macro"; pub(crate) const AUX_CODEGEN_BACKEND: &str = "aux-codegen-backend"; pub(crate) const EXEC_ENV: &str = "exec-env"; @@ -1218,7 +1219,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/directives/auxiliary.rs b/src/tools/compiletest/src/directives/auxiliary.rs index b88ddc00a535a..40941159015d8 100644 --- a/src/tools/compiletest/src/directives/auxiliary.rs +++ b/src/tools/compiletest/src/directives/auxiliary.rs @@ -3,7 +3,7 @@ use std::iter; -use super::directives::{AUX_BIN, AUX_BUILD, AUX_CODEGEN_BACKEND, AUX_CRATE, PROC_MACRO}; +use super::directives::{AUX_BIN, AUX_BUILD, AUX_CODEGEN_BACKEND, AUX_CRATE, AUX_LINT, PROC_MACRO}; use crate::common::Config; use crate::directives::DirectiveLine; use crate::util::static_regex; @@ -52,17 +52,20 @@ pub(crate) struct AuxProps { /// Similar to `builds`, but also uses the resulting dylib as a /// `-Zcodegen-backend` when compiling the test file. pub(crate) codegen_backend: Option, + /// Similar to `builds`, with the resulting dylibs passed to the lint test driver + pub(crate) lints: Vec, } impl AuxProps { /// Yields all of the paths (relative to `./auxiliary/`) that have been /// specified in `aux-*` directives for this test. pub(crate) fn all_aux_path_strings(&self) -> impl Iterator { - let Self { builds, bins, crates, proc_macros, codegen_backend } = self; + let Self { builds, bins, crates, proc_macros, codegen_backend, lints } = self; iter::empty() .chain(builds.iter().map(String::as_str)) .chain(bins.iter().map(String::as_str)) + .chain(lints.iter().map(String::as_str)) .chain(crates.iter().map(|c| c.path.as_str())) .chain(proc_macros.iter().map(|p| p.path.as_str())) .chain(codegen_backend.iter().map(String::as_str)) @@ -84,6 +87,7 @@ pub(super) fn parse_and_update_aux( config.push_name_value_directive(ln, AUX_BUILD, &mut aux.builds, |r| r.trim().to_string()); config.push_name_value_directive(ln, AUX_BIN, &mut aux.bins, |r| r.trim().to_string()); + config.push_name_value_directive(ln, AUX_LINT, &mut aux.lints, |r| r.trim().to_string()); config.push_name_value_directive(ln, AUX_CRATE, &mut aux.crates, parse_aux_crate); config.push_name_value_directive(ln, PROC_MACRO, &mut aux.proc_macros, parse_proc_macro); diff --git a/src/tools/compiletest/src/directives/directive_names.rs b/src/tools/compiletest/src/directives/directive_names.rs index e86e23a9505dd..c181e65e8e361 100644 --- a/src/tools/compiletest/src/directives/directive_names.rs +++ b/src/tools/compiletest/src/directives/directive_names.rs @@ -16,6 +16,7 @@ pub(crate) const KNOWN_DIRECTIVE_NAMES: &[&str] = &[ "aux-build", "aux-codegen-backend", "aux-crate", + "aux-lint", "build-aux-docs", "build-fail", "build-pass", diff --git a/src/tools/compiletest/src/directives/handlers.rs b/src/tools/compiletest/src/directives/handlers.rs index 0e80d6d865f22..053e8d64f7462 100644 --- a/src/tools/compiletest/src/directives/handlers.rs +++ b/src/tools/compiletest/src/directives/handlers.rs @@ -174,7 +174,7 @@ fn make_directive_handlers_map() -> HashMap<&'static str, Handler> { config.set_name_directive(ln, PRETTY_COMPARE_ONLY, &mut props.pretty_compare_only); }), multi_handler( - &[AUX_BUILD, AUX_BIN, AUX_CRATE, PROC_MACRO, AUX_CODEGEN_BACKEND], + &[AUX_BUILD, AUX_BIN, AUX_CRATE, AUX_LINT, PROC_MACRO, AUX_CODEGEN_BACKEND], |config, ln, props| { // Call a helper method to deal with aux-related directives. parse_and_update_aux(config, ln, &mut props.aux); 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..202d248966e05 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 @@ -102,7 +102,7 @@ fn get_lib_name(name: &str, aux_type: AuxType, wasm_proc_macros: bool) -> Option AuxType::Lib => Some(format!("lib{name}.rlib")), // FIXME maybe use `rustc --print file-names` instead? AuxType::ProcMacro if wasm_proc_macros => Some(format!("{name}.wasm")), - AuxType::Dylib | AuxType::ProcMacro => Some(dylib_name(name)), + AuxType::Dylib | AuxType::ProcMacro | AuxType::Lint => Some(dylib_name(name)), } } @@ -262,11 +262,12 @@ enum Emit { LinkArgsAsm, } -/// Indicates whether we are using `rustc` or `rustdoc` to compile an input file. +/// Indicates whether we are using `rustc`, `rustdoc` or `compiletest-lint-driver`` to compile an input file. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum CompilerKind { Rustc, Rustdoc, + LintDriver, } /// Unstable compiler flags that compiletest passes to UI tests on its own, i.e. without specific @@ -1283,6 +1284,7 @@ impl<'test> TestCx<'test> { !self.props.aux.builds.is_empty() || !self.props.aux.crates.is_empty() || !self.props.aux.proc_macros.is_empty() + || !self.props.aux.lints.is_empty() } fn aux_output_dir(&self) -> Utf8PathBuf { @@ -1316,6 +1318,10 @@ impl<'test> TestCx<'test> { self.build_auxiliary(rel_ab, &aux_dir, Some(AuxType::Bin)); } + for lint in &self.props.aux.lints { + self.build_auxiliary(lint, &aux_dir, Some(AuxType::Lint)); + } + let path_to_crate_name = |path: &str| -> String { path.rsplit_once('/') .map_or(path, |(_, tail)| tail) @@ -1323,6 +1329,27 @@ impl<'test> TestCx<'test> { .replace('-', "_") }; + let lint_lib_paths = self + .props + .aux + .lints + .iter() + .filter_map(|p| { + if let Some(lib_name) = get_lib_name( + &path_to_crate_name(p), + AuxType::Lint, + self.config.wasm_proc_macros, + ) { + Some(aux_dir.join(lib_name).to_string()) + } else { + None + } + }) + .collect::>(); + if !lint_lib_paths.is_empty() { + rustc.env("COMPILETEST_LINT_DRIVER_PATHS", lint_lib_paths.join(":")); + } + let add_extern = |rustc: &mut Command, extern_modifiers: Option<&str>, aux_name: &str, @@ -1462,6 +1489,8 @@ impl<'test> TestCx<'test> { } else { aux_props.force_host = true; } + } else if aux_type == Some(AuxType::Lint) { + aux_props.force_host = true; } let mut aux_dir = aux_dir.to_path_buf(); if aux_type == Some(AuxType::Bin) { @@ -1503,6 +1532,8 @@ impl<'test> TestCx<'test> { (AuxType::Bin, Some("bin")) } else if aux_type == Some(AuxType::ProcMacro) { (AuxType::ProcMacro, Some("proc-macro")) + } else if aux_type == Some(AuxType::Lint) { + (AuxType::Lint, Some("dylib")) } else if aux_type.is_some() { panic!("aux_type {aux_type:?} not expected"); } else if aux_props.no_prefer_dynamic { @@ -1605,9 +1636,16 @@ impl<'test> TestCx<'test> { command.stdout(Stdio::piped()).stderr(Stdio::piped()).stdin(Stdio::piped()); + let lint_driver_path = + self.config.rustc_lint_driver_lib_path.as_ref().map(Utf8PathBuf::as_path); // Need to be sure to put both the lib_path and the aux path in the dylib // search path for the child. - add_dylib_path(&mut command, iter::once(lib_path).chain(aux_path)); + add_dylib_path( + &mut command, + iter::once(lib_path) + .chain(aux_path) + .chain(lint_driver_path.filter(|_| !self.props.aux.lints.is_empty())), + ); let mut child = disable_error_reporting(|| command.spawn()) .unwrap_or_else(|e| panic!("failed to exec `{command:?}`: {e:?}")); @@ -1638,6 +1676,9 @@ impl<'test> TestCx<'test> { /// Choose a compiler kind (rustc or rustdoc) for compiling test files, /// based on the test suite being tested. fn compiler_kind_for_non_aux(&self) -> CompilerKind { + if !self.props.aux.lints.is_empty() { + return CompilerKind::LintDriver; + } match self.config.suite { TestSuite::RustdocJs | TestSuite::RustdocJson | TestSuite::RustdocUi => { CompilerKind::Rustdoc @@ -1686,6 +1727,9 @@ impl<'test> TestCx<'test> { CompilerKind::Rustdoc => { Command::new(&self.config.rustdoc_path.clone().expect("no rustdoc built yet")) } + CompilerKind::LintDriver => Command::new( + self.config.rustc_lint_driver_path.as_ref().expect("no rustc lint driver provided"), + ), }; compiler.arg(input_file); @@ -1737,8 +1781,14 @@ impl<'test> TestCx<'test> { if !self.props.compile_flags.iter().any(|flag| flag.starts_with("--sysroot")) && !self.config.host_rustcflags.iter().any(|flag| flag == "--sysroot") { - // In stage 0, make sure we use `stage0-sysroot` instead of the bootstrap sysroot. - compiler.arg("--sysroot").arg(&self.config.sysroot_base); + if compiler_kind == CompilerKind::LintDriver { + compiler + .arg("--sysroot") + .arg(self.config.rustc_lint_driver_sysroot.as_ref().unwrap()); + } else { + // In stage 0, make sure we use `stage0-sysroot` instead of the bootstrap sysroot. + compiler.arg("--sysroot").arg(&self.config.sysroot_base); + } } // If the provided codegen backend is not LLVM, we need to pass it. @@ -1992,7 +2042,7 @@ impl<'test> TestCx<'test> { // `rustdoc` uses `-o` for the output directory. compiler.arg("-o").arg(path); } - CompilerKind::Rustc => { + CompilerKind::Rustc | CompilerKind::LintDriver => { compiler.arg("--out-dir").arg(path); } }, @@ -3121,7 +3171,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(); } @@ -3211,6 +3262,7 @@ enum AuxType { Lib, Dylib, ProcMacro, + Lint, } /// Outcome of comparing a stream to a blessed file, diff --git a/src/tools/compiletest/src/rustdoc_gui_test.rs b/src/tools/compiletest/src/rustdoc_gui_test.rs index 03bc48b340f4b..3146c4a17badc 100644 --- a/src/tools/compiletest/src/rustdoc_gui_test.rs +++ b/src/tools/compiletest/src/rustdoc_gui_test.rs @@ -62,6 +62,9 @@ fn incomplete_config_for_rustdoc_gui_test() -> Config { host_compile_lib_path: Utf8PathBuf::default(), target_run_lib_path: Utf8PathBuf::default(), rustc_path: Utf8PathBuf::default(), + rustc_lint_driver_path: None, + rustc_lint_driver_lib_path: None, + rustc_lint_driver_sysroot: None, cargo_path: Default::default(), stage0_rustc_path: Default::default(), run_make_support_rlib: Default::default(), 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/tests/run-make/comment-section/rmake.rs b/tests/run-make/comment-section/rmake.rs index 22b0e2b3b3fb9..a5a33e9989a82 100644 --- a/tests/run-make/comment-section/rmake.rs +++ b/tests/run-make/comment-section/rmake.rs @@ -29,10 +29,15 @@ fn main() { .run() .assert_stdout_contains("rustc version 1."); - // Check all object files (including temporary outputs) have a `.comment` + // Check codegen object files (including temporary outputs) have a `.comment` // section with the expected content. rfs::read_dir_entries(cwd(), |f| { - if !f.extension().is_some_and(|ext| ext == "o") { + // Synthetic linker inputs are not codegen objects and have no `.comment`. + let name = f.file_name().unwrap().to_string_lossy(); + if !f.extension().is_some_and(|ext| ext == "o") + || name.contains(".rustc_link_metadata.") + || name.contains(".rustc_link_symbols.") + { return; } diff --git a/tests/run-make/linker-map-determinism/lib.rs b/tests/run-make/linker-map-determinism/lib.rs new file mode 100644 index 0000000000000..432593368f902 --- /dev/null +++ b/tests/run-make/linker-map-determinism/lib.rs @@ -0,0 +1,3 @@ +pub fn answer() -> u32 { + 42 +} diff --git a/tests/run-make/linker-map-determinism/rmake.rs b/tests/run-make/linker-map-determinism/rmake.rs new file mode 100644 index 0000000000000..d5d927fde11ea --- /dev/null +++ b/tests/run-make/linker-map-determinism/rmake.rs @@ -0,0 +1,86 @@ +// Repeated dylib links must produce identical linker maps. +// +// Regression test for #142989: rustc used to pass a metadata object +// from a randomly named temporary directory to the linker, leaking +// that directory name into the map file. +// +//@ only-linux +//@ ignore-cross-compile +//@ ignore-backends: gcc + +use std::fs; + +use run_make_support::rustc; + +fn main() { + let build = |map: &str| -> Vec { + let map_arg = format!("-Wl,-Map={map}"); + + rustc().input("lib.rs").crate_type("dylib").output("libfoo.so").link_arg(&map_arg).run(); + + fs::read("libfoo.so").unwrap() + }; + + let first_binary = build("first.map"); + let second_binary = build("second.map"); + + // GNU ld records paths to both metadata and linked-symbol objects. + // Neither pathname should vary between otherwise identical builds. + assert!( + fs::read("first.map").unwrap() == fs::read("second.map").unwrap(), + "complete linker maps differ between identical builds" + ); + + let metadata_input = |map: &str| -> String { + let map = fs::read_to_string(map).unwrap(); + map.lines() + .find(|line| line.trim_start().starts_with(".rustc ") && line.contains(".o")) + .expect("metadata object missing from linker map") + .to_owned() + }; + + assert_eq!( + metadata_input("first.map"), + metadata_input("second.map"), + "metadata object path differs between identical builds" + ); + + // Both synthetic linker inputs must use regular object filenames. + let metadata = "libfoo.rustc_link_metadata.rcgu.o"; + let symbols = "libfoo.rustc_link_symbols.rcgu.o"; + + for map in ["first.map", "second.map"] { + let contents = fs::read_to_string(map).unwrap(); + assert!(contents.contains(metadata), "metadata object missing from {map}"); + assert!(contents.contains(symbols), "symbols object missing from {map}"); + } + + assert_eq!(first_binary, second_binary, "linked dylibs differ between identical builds"); + + // Normal linking removes synthetic objects. + assert!(!fs::exists(metadata).unwrap()); + assert!(!fs::exists(symbols).unwrap()); + + // -C save-temps retains them. + rustc().input("lib.rs").crate_type("dylib").output("libfoo.so").arg("-Csave-temps").run(); + + assert!(fs::exists(metadata).unwrap()); + assert!(fs::exists(symbols).unwrap()); + + // A subsequent normal build removes them again. + rustc().input("lib.rs").crate_type("dylib").output("libfoo.so").run(); + + assert!(!fs::exists(metadata).unwrap()); + assert!(!fs::exists(symbols).unwrap()); + + // A linker failure must also clean up the generated objects. + rustc() + .input("lib.rs") + .crate_type("dylib") + .output("libfoo.so") + .arg("-Clink-arg=-Wl,--invalid-linker-map-test-option") + .run_fail(); + + assert!(!fs::exists(metadata).unwrap()); + assert!(!fs::exists(symbols).unwrap()); +} diff --git a/tests/run-make/linker-warning/rmake.rs b/tests/run-make/linker-warning/rmake.rs index 8b0c22b0fb940..0c42ee0455319 100644 --- a/tests/run-make/linker-warning/rmake.rs +++ b/tests/run-make/linker-warning/rmake.rs @@ -82,7 +82,6 @@ fn main() { "/build-root", ) .normalize("libpanic_abort", "libpanic_unwind") - .normalize(r#""[^"]*\/symbols.o""#, "\"/symbols.o\"") .normalize(r#""[^"]*\/raw-dylibs""#, "\"/raw-dylibs\"") .normalize("\"-fno-lto\" ", "") .run(); diff --git a/tests/run-make/linker-warning/short-error.txt b/tests/run-make/linker-warning/short-error.txt index 31b8254162180..6441a378d8eb1 100644 --- a/tests/run-make/linker-warning/short-error.txt +++ b/tests/run-make/linker-warning/short-error.txt @@ -1,6 +1,6 @@ error: linking with `./fake-linker` failed: exit status: 1 | - = note: "./fake-linker" "-m64" "/symbols.o" "<2 object files omitted>" "-Wl,--as-needed" "-Wl,-Bstatic" "/build-root/test/run-make/linker-warning/rmake_out/{libfoo,libbar}.rlib" "/lib/rustlib/x86_64-unknown-linux-gnu/lib/{libstd-*,libpanic_unwind-*,libobject-*,libmemchr-*,libaddr2line-*,libgimli-*,libcfg_if-*,librustc_demangle-*,libstd_detect-*,libhashbrown-*,librustc_std_workspace_alloc-*,libminiz_oxide-*,libadler2-*,libunwind-*,liblibc-*,librustc_std_workspace_core-*,liballoc-*,libcore-*,libcompiler_builtins-*}.rlib" "-Wl,-Bdynamic" "-lgcc_s" "-lutil" "-lrt" "-lpthread" "-lm" "-ldl" "-lc" "-L" "/raw-dylibs" "-Wl,--eh-frame-hdr" "-Wl,-z,noexecstack" "-L" "/build-root/test/run-make/linker-warning/rmake_out" "-L" "/lib/rustlib/x86_64-unknown-linux-gnu/lib" "-o" "main" "-Wl,--gc-sections" "-pie" "-Wl,-z,relro,-z,now" "-nodefaultlibs" "run_make_error" + = note: "./fake-linker" "-m64" "<3 object files omitted>" "-Wl,--as-needed" "-Wl,-Bstatic" "/build-root/test/run-make/linker-warning/rmake_out/{libfoo,libbar}.rlib" "/lib/rustlib/x86_64-unknown-linux-gnu/lib/{libstd-*,libpanic_unwind-*,libobject-*,libmemchr-*,libaddr2line-*,libgimli-*,libcfg_if-*,librustc_demangle-*,libstd_detect-*,libhashbrown-*,librustc_std_workspace_alloc-*,libminiz_oxide-*,libadler2-*,libunwind-*,liblibc-*,librustc_std_workspace_core-*,liballoc-*,libcore-*,libcompiler_builtins-*}.rlib" "-Wl,-Bdynamic" "-lgcc_s" "-lutil" "-lrt" "-lpthread" "-lm" "-ldl" "-lc" "-L" "/raw-dylibs" "-Wl,--eh-frame-hdr" "-Wl,-z,noexecstack" "-L" "/build-root/test/run-make/linker-warning/rmake_out" "-L" "/lib/rustlib/x86_64-unknown-linux-gnu/lib" "-o" "main" "-Wl,--gc-sections" "-pie" "-Wl,-z,relro,-z,now" "-nodefaultlibs" "run_make_error" = note: some arguments are omitted. use `--verbose` to show all linker arguments = note: error: baz diff --git a/tests/ui-fulldeps/session-diagnostic/auxiliary/hello_lint.rs b/tests/ui-fulldeps/session-diagnostic/auxiliary/hello_lint.rs new file mode 100644 index 0000000000000..8fb0ac3c31d33 --- /dev/null +++ b/tests/ui-fulldeps/session-diagnostic/auxiliary/hello_lint.rs @@ -0,0 +1,43 @@ +#![feature(default_field_values)] // cfg(bootstrap) FIXME: Remove on bump +#![feature(rustc_private)] + +extern crate rustc_driver; +extern crate rustc_errors; +extern crate rustc_hir; +extern crate rustc_lint; +extern crate rustc_lint_defs; +extern crate rustc_macros; +extern crate rustc_session; + +use rustc_lint::{LateContext, LateLintPass, LintContext}; +use rustc_lint_defs::{declare_lint_pass, declare_tool_lint}; +use rustc_macros::Diagnostic; + +declare_tool_lint! { + /// Test lint to test the lint testing. + pub hello::HELLO_LINT, + Deny, + "warns on an binary expression" +} +declare_lint_pass!(HelloLint => [HELLO_LINT]); + +#[derive(Diagnostic)] +#[diag("this is a binary expression")] +pub(crate) struct Expression; + +impl LateLintPass<'_> for HelloLint { + fn check_expr(&mut self, cx: &LateContext<'_>, expr: &'_ rustc_hir::Expr<'_>) { + if let rustc_hir::ExprKind::Binary(..) = expr.kind { + cx.emit_span_lint(HELLO_LINT, expr.span, Expression) + } + } +} + +#[unsafe(no_mangle)] +unsafe extern "C" fn register_lints( + _sess: &rustc_session::Session, + lint_store: &mut rustc_lint::LintStore, +) { + lint_store.register_lints(&[HELLO_LINT]); + lint_store.register_late_lint_pass(Box::new(|_| Box::new(HelloLint))); +} diff --git a/tests/ui-fulldeps/session-diagnostic/diagnostic-derive-compiletime.rs b/tests/ui-fulldeps/session-diagnostic/diagnostic-derive-compiletime.rs new file mode 100644 index 0000000000000..f5983eb69043a --- /dev/null +++ b/tests/ui-fulldeps/session-diagnostic/diagnostic-derive-compiletime.rs @@ -0,0 +1,5 @@ +//@ aux-lint:hello_lint.rs + +fn main() { + let _a = 1+1; //~ ERROR this is a binary expression +} diff --git a/tests/ui-fulldeps/session-diagnostic/diagnostic-derive-compiletime.stderr b/tests/ui-fulldeps/session-diagnostic/diagnostic-derive-compiletime.stderr new file mode 100644 index 0000000000000..eca6851e6e241 --- /dev/null +++ b/tests/ui-fulldeps/session-diagnostic/diagnostic-derive-compiletime.stderr @@ -0,0 +1,10 @@ +error: this is a binary expression + --> $DIR/diagnostic-derive-compiletime.rs:4:14 + | +LL | let _a = 1+1; + | ^^^ + | + = note: `#[deny(hello::hello_lint)]` on by default + +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/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/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/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`.