diff options
569 files changed, 4989 insertions, 2984 deletions
diff --git a/compiler/rustc_abi/src/lib.rs b/compiler/rustc_abi/src/lib.rs index ea634d7485e..df29b3d54f0 100644 --- a/compiler/rustc_abi/src/lib.rs +++ b/compiler/rustc_abi/src/lib.rs @@ -1700,7 +1700,9 @@ impl<FieldIdx: Idx, VariantIdx: Idx> LayoutS<FieldIdx, VariantIdx> { /// Checks if these two `Layout` are equal enough to be considered "the same for all function /// call ABIs". Note however that real ABIs depend on more details that are not reflected in the - /// `Layout`; the `PassMode` need to be compared as well. + /// `Layout`; the `PassMode` need to be compared as well. Also note that we assume + /// aggregates are passed via `PassMode::Indirect` or `PassMode::Cast`; more strict + /// checks would otherwise be required. pub fn eq_abi(&self, other: &Self) -> bool { // The one thing that we are not capturing here is that for unsized types, the metadata must // also have the same ABI, and moreover that the same metadata leads to the same size. The diff --git a/compiler/rustc_arena/src/lib.rs b/compiler/rustc_arena/src/lib.rs index 84933540147..260c9fe44ba 100644 --- a/compiler/rustc_arena/src/lib.rs +++ b/compiler/rustc_arena/src/lib.rs @@ -21,7 +21,6 @@ #![feature(decl_macro)] #![feature(dropck_eyepatch)] #![feature(maybe_uninit_slice)] -#![feature(new_uninit)] #![feature(rustc_attrs)] #![feature(rustdoc_internals)] #![feature(strict_provenance)] diff --git a/compiler/rustc_ast_lowering/src/format.rs b/compiler/rustc_ast_lowering/src/format.rs index bf40c9b66c6..8c742d2aaf4 100644 --- a/compiler/rustc_ast_lowering/src/format.rs +++ b/compiler/rustc_ast_lowering/src/format.rs @@ -4,9 +4,10 @@ use std::borrow::Cow; use rustc_ast::visit::Visitor; use rustc_ast::*; use rustc_data_structures::fx::FxIndexMap; +use rustc_hir as hir; +use rustc_session::config::FmtDebug; use rustc_span::symbol::{kw, Ident}; use rustc_span::{sym, Span, Symbol}; -use {rustc_ast as ast, rustc_hir as hir}; use super::LoweringContext; @@ -243,7 +244,10 @@ fn make_argument<'hir>( hir::LangItem::FormatArgument, match ty { Format(Display) => sym::new_display, - Format(Debug) => sym::new_debug, + Format(Debug) => match ctx.tcx.sess.opts.unstable_opts.fmt_debug { + FmtDebug::Full | FmtDebug::Shallow => sym::new_debug, + FmtDebug::None => sym::new_debug_noop, + }, Format(LowerExp) => sym::new_lower_exp, Format(UpperExp) => sym::new_upper_exp, Format(Octal) => sym::new_octal, diff --git a/compiler/rustc_builtin_macros/src/deriving/debug.rs b/compiler/rustc_builtin_macros/src/deriving/debug.rs index 755e6ee0d3e..57d9c076150 100644 --- a/compiler/rustc_builtin_macros/src/deriving/debug.rs +++ b/compiler/rustc_builtin_macros/src/deriving/debug.rs @@ -1,5 +1,6 @@ use rustc_ast::{self as ast, EnumDef, MetaItem}; use rustc_expand::base::{Annotatable, ExtCtxt}; +use rustc_session::config::FmtDebug; use rustc_span::symbol::{sym, Ident, Symbol}; use rustc_span::Span; use thin_vec::{thin_vec, ThinVec}; @@ -49,6 +50,11 @@ fn show_substructure(cx: &ExtCtxt<'_>, span: Span, substr: &Substructure<'_>) -> // We want to make sure we have the ctxt set so that we can use unstable methods let span = cx.with_def_site_ctxt(span); + let fmt_detail = cx.sess.opts.unstable_opts.fmt_debug; + if fmt_detail == FmtDebug::None { + return BlockOrExpr::new_expr(cx.expr_ok(span, cx.expr_tuple(span, ThinVec::new()))); + } + let (ident, vdata, fields) = match substr.fields { Struct(vdata, fields) => (substr.type_ident, *vdata, fields), EnumMatching(_, v, fields) => (v.ident, &v.data, fields), @@ -61,6 +67,13 @@ fn show_substructure(cx: &ExtCtxt<'_>, span: Span, substr: &Substructure<'_>) -> let name = cx.expr_str(span, ident.name); let fmt = substr.nonselflike_args[0].clone(); + // Fieldless enums have been special-cased earlier + if fmt_detail == FmtDebug::Shallow { + let fn_path_write_str = cx.std_path(&[sym::fmt, sym::Formatter, sym::write_str]); + let expr = cx.expr_call_global(span, fn_path_write_str, thin_vec![fmt, name]); + return BlockOrExpr::new_expr(expr); + } + // Struct and tuples are similar enough that we use the same code for both, // with some extra pieces for structs due to the field names. let (is_struct, args_per_field) = match vdata { diff --git a/compiler/rustc_builtin_macros/src/deriving/smart_ptr.rs b/compiler/rustc_builtin_macros/src/deriving/smart_ptr.rs index c88c5bd35a5..bc41d33a609 100644 --- a/compiler/rustc_builtin_macros/src/deriving/smart_ptr.rs +++ b/compiler/rustc_builtin_macros/src/deriving/smart_ptr.rs @@ -11,7 +11,6 @@ use rustc_data_structures::flat_map_in_place::FlatMapInPlace; use rustc_expand::base::{Annotatable, ExtCtxt}; use rustc_span::symbol::{sym, Ident}; use rustc_span::{Span, Symbol}; -use smallvec::{smallvec, SmallVec}; use thin_vec::{thin_vec, ThinVec}; macro_rules! path { @@ -68,43 +67,63 @@ pub(crate) fn expand_deriving_smart_ptr( }; // Convert generic parameters (from the struct) into generic args. - let mut pointee_param = None; - let mut multiple_pointee_diag: SmallVec<[_; 2]> = smallvec![]; - let self_params = generics + let self_params: Vec<_> = generics .params .iter() - .enumerate() - .map(|(idx, p)| match p.kind { + .map(|p| match p.kind { GenericParamKind::Lifetime => GenericArg::Lifetime(cx.lifetime(p.span(), p.ident)), - GenericParamKind::Type { .. } => { - if p.attrs().iter().any(|attr| attr.has_name(sym::pointee)) { - if pointee_param.is_some() { - multiple_pointee_diag.push(cx.dcx().struct_span_err( - p.span(), - "`SmartPointer` can only admit one type as pointee", - )); - } else { - pointee_param = Some(idx); - } - } - GenericArg::Type(cx.ty_ident(p.span(), p.ident)) - } + GenericParamKind::Type { .. } => GenericArg::Type(cx.ty_ident(p.span(), p.ident)), GenericParamKind::Const { .. } => GenericArg::Const(cx.const_ident(p.span(), p.ident)), }) - .collect::<Vec<_>>(); - let Some(pointee_param_idx) = pointee_param else { + .collect(); + let type_params: Vec<_> = generics + .params + .iter() + .enumerate() + .filter_map(|(idx, p)| { + if let GenericParamKind::Type { .. } = p.kind { + Some((idx, p.span(), p.attrs().iter().any(|attr| attr.has_name(sym::pointee)))) + } else { + None + } + }) + .collect(); + + let pointee_param_idx = if type_params.is_empty() { + // `#[derive(SmartPointer)]` requires at least one generic type on the target `struct` cx.dcx().struct_span_err( span, - "At least one generic type should be designated as `#[pointee]` in order to derive `SmartPointer` traits", + "`SmartPointer` can only be derived on `struct`s that are generic over at least one type", ).emit(); return; - }; - if !multiple_pointee_diag.is_empty() { - for diag in multiple_pointee_diag { - diag.emit(); + } else if type_params.len() == 1 { + // Regardless of the only type param being designed as `#[pointee]` or not, we can just use it as such + type_params[0].0 + } else { + let mut pointees = type_params + .iter() + .filter_map(|&(idx, span, is_pointee)| is_pointee.then_some((idx, span))) + .fuse(); + match (pointees.next(), pointees.next()) { + (Some((idx, _span)), None) => idx, + (None, _) => { + cx.dcx().struct_span_err( + span, + "exactly one generic type parameter must be marked as #[pointee] to derive SmartPointer traits", + ).emit(); + return; + } + (Some((_, one)), Some((_, another))) => { + cx.dcx() + .struct_span_err( + vec![one, another], + "only one type parameter can be marked as `#[pointee]` when deriving SmartPointer traits", + ) + .emit(); + return; + } } - return; - } + }; // Create the type of `self`. let path = cx.path_all(span, false, vec![name_ident], self_params.clone()); diff --git a/compiler/rustc_codegen_llvm/src/attributes.rs b/compiler/rustc_codegen_llvm/src/attributes.rs index 317e970d704..92a857c2adc 100644 --- a/compiler/rustc_codegen_llvm/src/attributes.rs +++ b/compiler/rustc_codegen_llvm/src/attributes.rs @@ -521,13 +521,20 @@ pub(crate) fn llfn_attrs_from_instance<'ll, 'tcx>( let function_features = function_features .iter() - .flat_map(|feat| { - llvm_util::to_llvm_features(cx.tcx.sess, feat).into_iter().map(|f| format!("+{f}")) - }) + // Convert to LLVMFeatures and filter out unavailable ones + .flat_map(|feat| llvm_util::to_llvm_features(cx.tcx.sess, feat)) + // Convert LLVMFeatures & dependencies to +<feats>s + .flat_map(|feat| feat.into_iter().map(|f| format!("+{f}"))) .chain(codegen_fn_attrs.instruction_set.iter().map(|x| match x { InstructionSetAttr::ArmA32 => "-thumb-mode".to_string(), InstructionSetAttr::ArmT32 => "+thumb-mode".to_string(), })) + // HACK: LLVM versions 19+ do not have the FPMR feature and treat it as always enabled + // It only exists as a feature in LLVM 18, cannot be passed down for any other version + .chain(match &*cx.tcx.sess.target.arch { + "aarch64" if llvm_util::get_version().0 == 18 => vec!["+fpmr".to_string()], + _ => vec![], + }) .collect::<Vec<String>>(); if cx.tcx.sess.target.is_like_wasm { diff --git a/compiler/rustc_codegen_llvm/src/back/write.rs b/compiler/rustc_codegen_llvm/src/back/write.rs index adf7e933f43..a5c27d2282e 100644 --- a/compiler/rustc_codegen_llvm/src/back/write.rs +++ b/compiler/rustc_codegen_llvm/src/back/write.rs @@ -571,6 +571,7 @@ pub(crate) unsafe fn llvm_optimize( cgcx.opts.cg.linker_plugin_lto.enabled(), config.no_prepopulate_passes, config.verify_llvm_ir, + config.lint_llvm_ir, using_thin_buffers, config.merge_functions, unroll_loops, diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/ffi.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/ffi.rs index cabdd310d1f..d7a4f105f3c 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/ffi.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/ffi.rs @@ -1,5 +1,5 @@ use rustc_middle::mir::coverage::{ - CodeRegion, ConditionInfo, CounterId, CovTerm, DecisionInfo, ExpressionId, MappingKind, + ConditionInfo, CounterId, CovTerm, DecisionInfo, ExpressionId, MappingKind, SourceRegion, }; /// Must match the layout of `LLVMRustCounterKind`. @@ -236,9 +236,10 @@ impl CounterMappingRegion { pub(crate) fn from_mapping( mapping_kind: &MappingKind, local_file_id: u32, - code_region: &CodeRegion, + source_region: &SourceRegion, ) -> Self { - let &CodeRegion { file_name: _, start_line, start_col, end_line, end_col } = code_region; + let &SourceRegion { file_name: _, start_line, start_col, end_line, end_col } = + source_region; match *mapping_kind { MappingKind::Code(term) => Self::code_region( Counter::from_term(term), diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/map_data.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/map_data.rs index 44eafab6060..5ed640b840e 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/map_data.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/map_data.rs @@ -2,8 +2,8 @@ use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::FxIndexSet; use rustc_index::bit_set::BitSet; use rustc_middle::mir::coverage::{ - CodeRegion, CounterId, CovTerm, Expression, ExpressionId, FunctionCoverageInfo, Mapping, - MappingKind, Op, + CounterId, CovTerm, Expression, ExpressionId, FunctionCoverageInfo, Mapping, MappingKind, Op, + SourceRegion, }; use rustc_middle::ty::Instance; use rustc_span::Symbol; @@ -201,7 +201,7 @@ impl<'tcx> FunctionCoverage<'tcx> { /// Returns an iterator over all filenames used by this function's mappings. pub(crate) fn all_file_names(&self) -> impl Iterator<Item = Symbol> + Captures<'_> { - self.function_coverage_info.mappings.iter().map(|mapping| mapping.code_region.file_name) + self.function_coverage_info.mappings.iter().map(|mapping| mapping.source_region.file_name) } /// Convert this function's coverage expression data into a form that can be @@ -230,12 +230,12 @@ impl<'tcx> FunctionCoverage<'tcx> { /// that will be used by `mapgen` when preparing for FFI. pub(crate) fn counter_regions( &self, - ) -> impl Iterator<Item = (MappingKind, &CodeRegion)> + ExactSizeIterator { + ) -> impl Iterator<Item = (MappingKind, &SourceRegion)> + ExactSizeIterator { self.function_coverage_info.mappings.iter().map(move |mapping| { - let Mapping { kind, code_region } = mapping; + let Mapping { kind, source_region } = mapping; let kind = kind.map_terms(|term| if self.is_zero_term(term) { CovTerm::Zero } else { term }); - (kind, code_region) + (kind, source_region) }) } diff --git a/compiler/rustc_codegen_llvm/src/lib.rs b/compiler/rustc_codegen_llvm/src/lib.rs index 7f26bbd7f87..6a303e1e602 100644 --- a/compiler/rustc_codegen_llvm/src/lib.rs +++ b/compiler/rustc_codegen_llvm/src/lib.rs @@ -6,6 +6,7 @@ // tidy-alphabetical-start #![allow(internal_features)] +#![cfg_attr(bootstrap, feature(unsafe_extern_blocks))] #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] #![doc(rust_logo)] #![feature(assert_matches)] diff --git a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs index 7a495174ff1..138cc3219aa 100644 --- a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs +++ b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs @@ -564,12 +564,12 @@ pub enum ArchiveKind { } // LLVMRustThinLTOData -extern "C" { +unsafe extern "C" { pub type ThinLTOData; } // LLVMRustThinLTOBuffer -extern "C" { +unsafe extern "C" { pub type ThinLTOBuffer; } @@ -621,7 +621,7 @@ pub enum MemoryEffects { InaccessibleMemOnly, } -extern "C" { +unsafe extern "C" { type Opaque; } #[repr(C)] @@ -631,54 +631,54 @@ struct InvariantOpaque<'a> { } // Opaque pointer types -extern "C" { +unsafe extern "C" { pub type Module; } -extern "C" { +unsafe extern "C" { pub type Context; } -extern "C" { +unsafe extern "C" { pub type Type; } -extern "C" { +unsafe extern "C" { pub type Value; } -extern "C" { +unsafe extern "C" { pub type ConstantInt; } -extern "C" { +unsafe extern "C" { pub type Attribute; } -extern "C" { +unsafe extern "C" { pub type Metadata; } -extern "C" { +unsafe extern "C" { pub type BasicBlock; } #[repr(C)] pub struct Builder<'a>(InvariantOpaque<'a>); #[repr(C)] pub struct PassManager<'a>(InvariantOpaque<'a>); -extern "C" { +unsafe extern "C" { pub type Pass; } -extern "C" { +unsafe extern "C" { pub type TargetMachine; } -extern "C" { +unsafe extern "C" { pub type Archive; } #[repr(C)] pub struct ArchiveIterator<'a>(InvariantOpaque<'a>); #[repr(C)] pub struct ArchiveChild<'a>(InvariantOpaque<'a>); -extern "C" { +unsafe extern "C" { pub type Twine; } -extern "C" { +unsafe extern "C" { pub type DiagnosticInfo; } -extern "C" { +unsafe extern "C" { pub type SMDiagnostic; } #[repr(C)] @@ -688,7 +688,7 @@ pub struct OperandBundleDef<'a>(InvariantOpaque<'a>); #[repr(C)] pub struct Linker<'a>(InvariantOpaque<'a>); -extern "C" { +unsafe extern "C" { pub type DiagnosticHandler; } @@ -823,7 +823,7 @@ bitflags! { } } -extern "C" { +unsafe extern "C" { pub type ModuleBuffer; } @@ -834,7 +834,7 @@ pub type SelfProfileAfterPassCallback = unsafe extern "C" fn(*mut c_void); pub type GetSymbolsCallback = unsafe extern "C" fn(*mut c_void, *const c_char) -> *mut c_void; pub type GetSymbolsErrorCallback = unsafe extern "C" fn(*const c_char) -> *mut c_void; -extern "C" { +unsafe extern "C" { // Create and destroy contexts. pub fn LLVMContextDispose(C: &'static mut Context); pub fn LLVMGetMDKindIDInContext(C: &Context, Name: *const c_char, SLen: c_uint) -> c_uint; @@ -1518,7 +1518,7 @@ extern "C" { } #[link(name = "llvm-wrapper", kind = "static")] -extern "C" { +unsafe extern "C" { pub fn LLVMRustInstallErrorHandlers(); pub fn LLVMRustDisableSystemDialogsOnCrash(); @@ -2225,6 +2225,7 @@ extern "C" { IsLinkerPluginLTO: bool, NoPrepopulatePasses: bool, VerifyIR: bool, + LintIR: bool, UseThinLTOBuffers: bool, MergeFunctions: bool, UnrollLoops: bool, diff --git a/compiler/rustc_codegen_llvm/src/llvm_util.rs b/compiler/rustc_codegen_llvm/src/llvm_util.rs index 7af5eb9278f..618602ed70f 100644 --- a/compiler/rustc_codegen_llvm/src/llvm_util.rs +++ b/compiler/rustc_codegen_llvm/src/llvm_util.rs @@ -209,7 +209,7 @@ impl<'a> IntoIterator for LLVMFeature<'a> { // Though note that Rust can also be build with an external precompiled version of LLVM // which might lead to failures if the oldest tested / supported LLVM version // doesn't yet support the relevant intrinsics -pub(crate) fn to_llvm_features<'a>(sess: &Session, s: &'a str) -> LLVMFeature<'a> { +pub(crate) fn to_llvm_features<'a>(sess: &Session, s: &'a str) -> Option<LLVMFeature<'a>> { let arch = if sess.target.arch == "x86_64" { "x86" } else if sess.target.arch == "arm64ec" { @@ -218,40 +218,59 @@ pub(crate) fn to_llvm_features<'a>(sess: &Session, s: &'a str) -> LLVMFeature<'a &*sess.target.arch }; match (arch, s) { - ("x86", "sse4.2") => { - LLVMFeature::with_dependency("sse4.2", TargetFeatureFoldStrength::EnableOnly("crc32")) - } - ("x86", "pclmulqdq") => LLVMFeature::new("pclmul"), - ("x86", "rdrand") => LLVMFeature::new("rdrnd"), - ("x86", "bmi1") => LLVMFeature::new("bmi"), - ("x86", "cmpxchg16b") => LLVMFeature::new("cx16"), - ("x86", "lahfsahf") => LLVMFeature::new("sahf"), - ("aarch64", "rcpc2") => LLVMFeature::new("rcpc-immo"), - ("aarch64", "dpb") => LLVMFeature::new("ccpp"), - ("aarch64", "dpb2") => LLVMFeature::new("ccdp"), - ("aarch64", "frintts") => LLVMFeature::new("fptoint"), - ("aarch64", "fcma") => LLVMFeature::new("complxnum"), - ("aarch64", "pmuv3") => LLVMFeature::new("perfmon"), - ("aarch64", "paca") => LLVMFeature::new("pauth"), - ("aarch64", "pacg") => LLVMFeature::new("pauth"), + ("x86", "sse4.2") => Some(LLVMFeature::with_dependency( + "sse4.2", + TargetFeatureFoldStrength::EnableOnly("crc32"), + )), + ("x86", "pclmulqdq") => Some(LLVMFeature::new("pclmul")), + ("x86", "rdrand") => Some(LLVMFeature::new("rdrnd")), + ("x86", "bmi1") => Some(LLVMFeature::new("bmi")), + ("x86", "cmpxchg16b") => Some(LLVMFeature::new("cx16")), + ("x86", "lahfsahf") => Some(LLVMFeature::new("sahf")), + ("aarch64", "rcpc2") => Some(LLVMFeature::new("rcpc-immo")), + ("aarch64", "dpb") => Some(LLVMFeature::new("ccpp")), + ("aarch64", "dpb2") => Some(LLVMFeature::new("ccdp")), + ("aarch64", "frintts") => Some(LLVMFeature::new("fptoint")), + ("aarch64", "fcma") => Some(LLVMFeature::new("complxnum")), + ("aarch64", "pmuv3") => Some(LLVMFeature::new("perfmon")), + ("aarch64", "paca") => Some(LLVMFeature::new("pauth")), + ("aarch64", "pacg") => Some(LLVMFeature::new("pauth")), + ("aarch64", "sve-b16b16") => Some(LLVMFeature::new("b16b16")), + ("aarch64", "flagm2") => Some(LLVMFeature::new("altnzcv")), // Rust ties fp and neon together. ("aarch64", "neon") => { - LLVMFeature::with_dependency("neon", TargetFeatureFoldStrength::Both("fp-armv8")) + Some(LLVMFeature::with_dependency("neon", TargetFeatureFoldStrength::Both("fp-armv8"))) } // In LLVM neon implicitly enables fp, but we manually enable // neon when a feature only implicitly enables fp - ("aarch64", "fhm") => LLVMFeature::new("fp16fml"), - ("aarch64", "fp16") => LLVMFeature::new("fullfp16"), + ("aarch64", "fhm") => Some(LLVMFeature::new("fp16fml")), + ("aarch64", "fp16") => Some(LLVMFeature::new("fullfp16")), + // Filter out features that are not supported by the current LLVM version + ("aarch64", "faminmax") if get_version().0 < 18 => None, + ("aarch64", "fp8") if get_version().0 < 18 => None, + ("aarch64", "fp8dot2") if get_version().0 < 18 => None, + ("aarch64", "fp8dot4") if get_version().0 < 18 => None, + ("aarch64", "fp8fma") if get_version().0 < 18 => None, + ("aarch64", "fpmr") if get_version().0 != 18 => None, + ("aarch64", "lut") if get_version().0 < 18 => None, + ("aarch64", "sme-f8f16") if get_version().0 < 18 => None, + ("aarch64", "sme-f8f32") if get_version().0 < 18 => None, + ("aarch64", "sme-fa64") if get_version().0 < 18 => None, + ("aarch64", "sme-lutv2") if get_version().0 < 18 => None, + ("aarch64", "ssve-fp8dot2") if get_version().0 < 18 => None, + ("aarch64", "ssve-fp8dot4") if get_version().0 < 18 => None, + ("aarch64", "ssve-fp8fma") if get_version().0 < 18 => None, + ("aarch64", "v9.5a") if get_version().0 < 18 => None, // In LLVM 18, `unaligned-scalar-mem` was merged with `unaligned-vector-mem` into a single feature called // `fast-unaligned-access`. In LLVM 19, it was split back out. ("riscv32" | "riscv64", "unaligned-scalar-mem") if get_version().0 == 18 => { - LLVMFeature::new("fast-unaligned-access") + Some(LLVMFeature::new("fast-unaligned-access")) } // For LLVM 18, enable the evex512 target feature if a avx512 target feature is enabled. ("x86", s) if get_version().0 >= 18 && s.starts_with("avx512") => { - LLVMFeature::with_dependency(s, TargetFeatureFoldStrength::EnableOnly("evex512")) + Some(LLVMFeature::with_dependency(s, TargetFeatureFoldStrength::EnableOnly("evex512"))) } - (_, s) => LLVMFeature::new(s), + (_, s) => Some(LLVMFeature::new(s)), } } @@ -291,13 +310,17 @@ pub fn target_features(sess: &Session, allow_unstable: bool) -> Vec<Symbol> { return true; } // check that all features in a given smallvec are enabled - for llvm_feature in to_llvm_features(sess, feature) { - let cstr = SmallCStr::new(llvm_feature); - if !unsafe { llvm::LLVMRustHasFeature(&target_machine, cstr.as_ptr()) } { - return false; + if let Some(feat) = to_llvm_features(sess, feature) { + for llvm_feature in feat { + let cstr = SmallCStr::new(llvm_feature); + if !unsafe { llvm::LLVMRustHasFeature(&target_machine, cstr.as_ptr()) } { + return false; + } } + true + } else { + false } - true }) .map(|(feature, _, _)| Symbol::intern(feature)), ); @@ -386,9 +409,9 @@ fn print_target_features(out: &mut String, sess: &Session, tm: &llvm::TargetMach .target .supported_target_features() .iter() - .map(|(feature, _gate, _implied)| { + .filter_map(|(feature, _gate, _implied)| { // LLVM asserts that these are sorted. LLVM and Rust both use byte comparison for these strings. - let llvm_feature = to_llvm_features(sess, *feature).llvm_feature_name; + let llvm_feature = to_llvm_features(sess, *feature)?.llvm_feature_name; let desc = match llvm_target_features.binary_search_by_key(&llvm_feature, |(f, _d)| f).ok() { Some(index) => { @@ -398,7 +421,7 @@ fn print_target_features(out: &mut String, sess: &Session, tm: &llvm::TargetMach None => "", }; - (*feature, desc) + Some((*feature, desc)) }) .collect::<Vec<_>>(); @@ -595,7 +618,7 @@ pub(crate) fn global_llvm_features( if feature_state.is_none() { let rust_feature = supported_features.iter().find_map(|&(rust_feature, _, _)| { - let llvm_features = to_llvm_features(sess, rust_feature); + let llvm_features = to_llvm_features(sess, rust_feature)?; if llvm_features.contains(feature) && !llvm_features.contains(rust_feature) { @@ -641,7 +664,7 @@ pub(crate) fn global_llvm_features( // passing requests down to LLVM. This means that all in-language // features also work on the command line instead of having two // different names when the LLVM name and the Rust name differ. - let llvm_feature = to_llvm_features(sess, feature); + let llvm_feature = to_llvm_features(sess, feature)?; Some( std::iter::once(format!( @@ -691,6 +714,9 @@ fn backend_feature_name<'a>(sess: &Session, s: &'a str) -> Option<&'a str> { let feature = s .strip_prefix(&['+', '-'][..]) .unwrap_or_else(|| sess.dcx().emit_fatal(InvalidTargetFeaturePrefix { feature: s })); + if s.is_empty() { + return None; + } // Rustc-specific feature requests like `+crt-static` or `-crt-static` // are not passed down to LLVM. if RUSTC_SPECIFIC_FEATURES.contains(&feature) { diff --git a/compiler/rustc_codegen_ssa/src/back/write.rs b/compiler/rustc_codegen_ssa/src/back/write.rs index 7ad31802454..feb27c148a1 100644 --- a/compiler/rustc_codegen_ssa/src/back/write.rs +++ b/compiler/rustc_codegen_ssa/src/back/write.rs @@ -112,6 +112,7 @@ pub struct ModuleConfig { // Miscellaneous flags. These are mostly copied from command-line // options. pub verify_llvm_ir: bool, + pub lint_llvm_ir: bool, pub no_prepopulate_passes: bool, pub no_builtins: bool, pub time_module: bool, @@ -237,6 +238,7 @@ impl ModuleConfig { bc_cmdline: sess.target.bitcode_llvm_cmdline.to_string(), verify_llvm_ir: sess.verify_llvm_ir(), + lint_llvm_ir: sess.opts.unstable_opts.lint_llvm_ir, no_prepopulate_passes: sess.opts.cg.no_prepopulate_passes, no_builtins: no_builtins || sess.target.no_builtins, diff --git a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs index 4ab20c154cc..209750d6ba6 100644 --- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs +++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs @@ -1,5 +1,6 @@ use rustc_ast::{ast, attr, MetaItemKind, NestedMetaItem}; use rustc_attr::{list_contains_name, InlineAttr, InstructionSetAttr, OptimizeAttr}; +use rustc_data_structures::fx::FxHashSet; use rustc_errors::codes::*; use rustc_errors::{struct_span_code_err, DiagMessage, SubdiagMessage}; use rustc_hir as hir; @@ -8,7 +9,7 @@ use rustc_hir::def_id::{DefId, LocalDefId, LOCAL_CRATE}; use rustc_hir::weak_lang_items::WEAK_LANG_ITEMS; use rustc_hir::{lang_items, LangItem}; use rustc_middle::middle::codegen_fn_attrs::{ - CodegenFnAttrFlags, CodegenFnAttrs, PatchableFunctionEntry, + CodegenFnAttrFlags, CodegenFnAttrs, PatchableFunctionEntry, TargetFeature, }; use rustc_middle::mir::mono::Linkage; use rustc_middle::query::Providers; @@ -17,6 +18,7 @@ use rustc_session::lint; use rustc_session::parse::feature_err; use rustc_span::symbol::Ident; use rustc_span::{sym, Span}; +use rustc_target::abi::VariantIdx; use rustc_target::spec::{abi, SanitizerSet}; use crate::errors; @@ -78,6 +80,13 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs { let mut link_ordinal_span = None; let mut no_sanitize_span = None; + let fn_sig_outer = || { + use DefKind::*; + + let def_kind = tcx.def_kind(did); + if let Fn | AssocFn | Variant | Ctor(..) = def_kind { Some(tcx.fn_sig(did)) } else { None } + }; + for attr in attrs.iter() { // In some cases, attribute are only valid on functions, but it's the `check_attr` // pass that check that they aren't used anywhere else, rather this module. @@ -85,16 +94,12 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs { // functions (such as calling `fn_sig`, which ICEs if given a non-function). We also // report a delayed bug, just in case `check_attr` isn't doing its job. let fn_sig = || { - use DefKind::*; - - let def_kind = tcx.def_kind(did); - if let Fn | AssocFn | Variant | Ctor(..) = def_kind { - Some(tcx.fn_sig(did)) - } else { + let sig = fn_sig_outer(); + if sig.is_none() { tcx.dcx() .span_delayed_bug(attr.span, "this attribute can only be applied to functions"); - None } + sig }; let Some(Ident { name, .. }) = attr.ident() else { @@ -613,7 +618,93 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs { } } - // If a function uses #[target_feature] it can't be inlined into general + if let Some(sig) = fn_sig_outer() { + // Collect target features from types reachable from arguments. + // We define a type as "reachable" if: + // - it is a function argument + // - it is a field of a reachable struct + // - there is a reachable reference to it + // FIXME(struct_target_features): we may want to cache the result of this computation. + let mut visited_types = FxHashSet::default(); + let mut reachable_types: Vec<_> = sig.skip_binder().inputs().skip_binder().to_owned(); + let mut additional_tf = vec![]; + + while let Some(ty) = reachable_types.pop() { + if visited_types.contains(&ty) { + continue; + } + visited_types.insert(ty); + match ty.kind() { + ty::Alias(..) => { + if let Ok(t) = + tcx.try_normalize_erasing_regions(tcx.param_env(did.to_def_id()), ty) + { + reachable_types.push(t) + } + } + + ty::Ref(_, inner, _) => reachable_types.push(*inner), + ty::Tuple(tys) => reachable_types.extend(tys.iter()), + ty::Adt(adt_def, args) => { + additional_tf.extend_from_slice(tcx.struct_target_features(adt_def.did())); + // This only recurses into structs as i.e. an Option<TargetFeature> is an ADT + // that doesn't actually always contain a TargetFeature. + if adt_def.is_struct() { + reachable_types.extend( + adt_def + .variant(VariantIdx::from_usize(0)) + .fields + .iter() + .map(|field| field.ty(tcx, args)), + ); + } + } + ty::Bool + | ty::Char + | ty::Int(..) + | ty::Uint(..) + | ty::Float(..) + | ty::Foreign(..) + | ty::Str + | ty::Array(..) + | ty::Pat(..) + | ty::Slice(..) + | ty::RawPtr(..) + | ty::FnDef(..) + | ty::FnPtr(..) + | ty::Dynamic(..) + | ty::Closure(..) + | ty::CoroutineClosure(..) + | ty::Coroutine(..) + | ty::CoroutineWitness(..) + | ty::Never + | ty::Param(..) + | ty::Bound(..) + | ty::Placeholder(..) + | ty::Infer(..) + | ty::Error(..) => (), + } + } + + // FIXME(struct_target_features): is this really necessary? + if !additional_tf.is_empty() && sig.skip_binder().abi() != abi::Abi::Rust { + tcx.dcx().span_err( + tcx.hir().span(tcx.local_def_id_to_hir_id(did)), + "cannot use a struct with target features in a function with non-Rust ABI", + ); + } + if !additional_tf.is_empty() && codegen_fn_attrs.inline == InlineAttr::Always { + tcx.dcx().span_err( + tcx.hir().span(tcx.local_def_id_to_hir_id(did)), + "cannot use a struct with target features in a #[inline(always)] function", + ); + } + codegen_fn_attrs + .target_features + .extend(additional_tf.iter().map(|tf| TargetFeature { implied: true, ..*tf })); + } + + // If a function uses non-default target_features it can't be inlined into general // purpose functions as they wouldn't have the right target features // enabled. For that reason we also forbid #[inline(always)] as it can't be // respected. @@ -758,6 +849,20 @@ fn check_link_name_xor_ordinal( } } +fn struct_target_features(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &[TargetFeature] { + let mut features = vec![]; + let supported_features = tcx.supported_target_features(LOCAL_CRATE); + for attr in tcx.get_attrs(def_id, sym::target_feature) { + from_target_feature(tcx, attr, supported_features, &mut features); + } + tcx.arena.alloc_slice(&features) +} + pub fn provide(providers: &mut Providers) { - *providers = Providers { codegen_fn_attrs, should_inherit_track_caller, ..*providers }; + *providers = Providers { + codegen_fn_attrs, + should_inherit_track_caller, + struct_target_features, + ..*providers + }; } diff --git a/compiler/rustc_const_eval/messages.ftl b/compiler/rustc_const_eval/messages.ftl index d7d64180ec9..db788b6b151 100644 --- a/compiler/rustc_const_eval/messages.ftl +++ b/compiler/rustc_const_eval/messages.ftl @@ -402,9 +402,6 @@ const_eval_unallowed_mutable_refs = const_eval_unallowed_op_in_const_context = {$msg} -const_eval_unavailable_target_features_for_fn = - calling a function that requires unavailable target features: {$unavailable_feats} - const_eval_uninhabited_enum_variant_read = read discriminant of an uninhabited enum variant const_eval_uninhabited_enum_variant_written = diff --git a/compiler/rustc_const_eval/src/check_consts/post_drop_elaboration.rs b/compiler/rustc_const_eval/src/check_consts/post_drop_elaboration.rs index c4f06e5af0b..f0998300dc8 100644 --- a/compiler/rustc_const_eval/src/check_consts/post_drop_elaboration.rs +++ b/compiler/rustc_const_eval/src/check_consts/post_drop_elaboration.rs @@ -9,13 +9,19 @@ use super::check::Qualifs; use super::ops::{self, NonConstOp}; use super::qualifs::{NeedsNonConstDrop, Qualif}; use super::ConstCx; +use crate::check_consts::rustc_allow_const_fn_unstable; /// Returns `true` if we should use the more precise live drop checker that runs after drop /// elaboration. pub fn checking_enabled(ccx: &ConstCx<'_, '_>) -> bool { - // Const-stable functions must always use the stable live drop checker. + // Const-stable functions must always use the stable live drop checker... if ccx.is_const_stable_const_fn() { - return false; + // ...except if they have the feature flag set via `rustc_allow_const_fn_unstable`. + return rustc_allow_const_fn_unstable( + ccx.tcx, + ccx.body.source.def_id().expect_local(), + sym::const_precise_live_drops, + ); } ccx.tcx.features().const_precise_live_drops diff --git a/compiler/rustc_const_eval/src/interpret/call.rs b/compiler/rustc_const_eval/src/interpret/call.rs index 917a2fa7c6d..61e8007e10e 100644 --- a/compiler/rustc_const_eval/src/interpret/call.rs +++ b/compiler/rustc_const_eval/src/interpret/call.rs @@ -311,34 +311,6 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { Ok(()) } - fn check_fn_target_features(&self, instance: ty::Instance<'tcx>) -> InterpResult<'tcx, ()> { - // Calling functions with `#[target_feature]` is not unsafe on WASM, see #84988 - let attrs = self.tcx.codegen_fn_attrs(instance.def_id()); - if !self.tcx.sess.target.is_like_wasm - && attrs - .target_features - .iter() - .any(|feature| !self.tcx.sess.target_features.contains(&feature.name)) - { - throw_ub_custom!( - fluent::const_eval_unavailable_target_features_for_fn, - unavailable_feats = attrs - .target_features - .iter() - .filter(|&feature| !feature.implied - && !self.tcx.sess.target_features.contains(&feature.name)) - .fold(String::new(), |mut s, feature| { - if !s.is_empty() { - s.push_str(", "); - } - s.push_str(feature.name.as_str()); - s - }), - ); - } - Ok(()) - } - /// The main entry point for creating a new stack frame: performs ABI checks and initializes /// arguments. #[instrument(skip(self), level = "trace")] @@ -360,20 +332,18 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { throw_unsup_format!("calling a c-variadic function is not supported"); } - if M::enforce_abi(self) { - if caller_fn_abi.conv != callee_fn_abi.conv { - throw_ub_custom!( - fluent::const_eval_incompatible_calling_conventions, - callee_conv = format!("{:?}", callee_fn_abi.conv), - caller_conv = format!("{:?}", caller_fn_abi.conv), - ) - } + if caller_fn_abi.conv != callee_fn_abi.conv { + throw_ub_custom!( + fluent::const_eval_incompatible_calling_conventions, + callee_conv = format!("{:?}", callee_fn_abi.conv), + caller_conv = format!("{:?}", caller_fn_abi.conv), + ) } // Check that all target features required by the callee (i.e., from // the attribute `#[target_feature(enable = ...)]`) are enabled at // compile time. - self.check_fn_target_features(instance)?; + M::check_fn_target_features(self, instance)?; if !callee_fn_abi.can_unwind { // The callee cannot unwind, so force the `Unreachable` unwind handling. @@ -576,7 +546,6 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { | ty::InstanceKind::ReifyShim(..) | ty::InstanceKind::ClosureOnceShim { .. } | ty::InstanceKind::ConstructCoroutineInClosureShim { .. } - | ty::InstanceKind::CoroutineKindShim { .. } | ty::InstanceKind::FnPtrShim(..) | ty::InstanceKind::DropGlue(..) | ty::InstanceKind::CloneShim(..) diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics.rs b/compiler/rustc_const_eval/src/interpret/intrinsics.rs index aef39b9af2f..bedc56de0da 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics.rs @@ -684,19 +684,19 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { assert!(layout.is_sized()); let get_bytes = |this: &InterpCx<'tcx, M>, - op: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>, - size| + op: &OpTy<'tcx, <M as Machine<'tcx>>::Provenance>| -> InterpResult<'tcx, &[u8]> { let ptr = this.read_pointer(op)?; - let Some(alloc_ref) = self.get_ptr_alloc(ptr, size)? else { + this.check_ptr_align(ptr, layout.align.abi)?; + let Some(alloc_ref) = self.get_ptr_alloc(ptr, layout.size)? else { // zero-sized access return Ok(&[]); }; alloc_ref.get_bytes_strip_provenance() }; - let lhs_bytes = get_bytes(self, lhs, layout.size)?; - let rhs_bytes = get_bytes(self, rhs, layout.size)?; + let lhs_bytes = get_bytes(self, lhs)?; + let rhs_bytes = get_bytes(self, rhs)?; Ok(Scalar::from_bool(lhs_bytes == rhs_bytes)) } } diff --git a/compiler/rustc_const_eval/src/interpret/machine.rs b/compiler/rustc_const_eval/src/interpret/machine.rs index 761ab81e228..88453245b84 100644 --- a/compiler/rustc_const_eval/src/interpret/machine.rs +++ b/compiler/rustc_const_eval/src/interpret/machine.rs @@ -173,11 +173,6 @@ pub trait Machine<'tcx>: Sized { false } - /// Whether function calls should be [ABI](CallAbi)-checked. - fn enforce_abi(_ecx: &InterpCx<'tcx, Self>) -> bool { - true - } - /// Whether Assert(OverflowNeg) and Assert(Overflow) MIR terminators should actually /// check for overflow. fn ignore_optional_overflow_checks(_ecx: &InterpCx<'tcx, Self>) -> bool; @@ -238,6 +233,13 @@ pub trait Machine<'tcx>: Sized { unwind: mir::UnwindAction, ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>>; + /// Check whether the given function may be executed on the current machine, in terms of the + /// target features is requires. + fn check_fn_target_features( + _ecx: &InterpCx<'tcx, Self>, + _instance: ty::Instance<'tcx>, + ) -> InterpResult<'tcx>; + /// Called to evaluate `Assert` MIR terminators that trigger a panic. fn assert_panic( ecx: &mut InterpCx<'tcx, Self>, @@ -280,6 +282,9 @@ pub trait Machine<'tcx>: Sized { Ok(()) } + /// Determines the result of a `NullaryOp::UbChecks` invocation. + fn ub_checks(_ecx: &InterpCx<'tcx, Self>) -> InterpResult<'tcx, bool>; + /// Called when the interpreter encounters a `StatementKind::ConstEvalCounter` instruction. /// You can use this to detect long or endlessly running programs. #[inline] @@ -615,6 +620,16 @@ pub macro compile_time_machine(<$tcx: lifetime>) { } #[inline(always)] + fn check_fn_target_features( + _ecx: &InterpCx<$tcx, Self>, + _instance: ty::Instance<$tcx>, + ) -> InterpResult<$tcx> { + // For now we don't do any checking here. We can't use `tcx.sess` because that can differ + // between crates, and we need to ensure that const-eval always behaves the same. + Ok(()) + } + + #[inline(always)] fn call_extra_fn( _ecx: &mut InterpCx<$tcx, Self>, fn_val: !, @@ -628,6 +643,13 @@ pub macro compile_time_machine(<$tcx: lifetime>) { } #[inline(always)] + fn ub_checks(_ecx: &InterpCx<$tcx, Self>) -> InterpResult<$tcx, bool> { + // We can't look at `tcx.sess` here as that can differ across crates, which can lead to + // unsound differences in evaluating the same constant at different instantiation sites. + Ok(true) + } + + #[inline(always)] fn adjust_global_allocation<'b>( _ecx: &InterpCx<$tcx, Self>, _id: AllocId, diff --git a/compiler/rustc_const_eval/src/interpret/operator.rs b/compiler/rustc_const_eval/src/interpret/operator.rs index 2f860f9f942..e9ba12dbcc4 100644 --- a/compiler/rustc_const_eval/src/interpret/operator.rs +++ b/compiler/rustc_const_eval/src/interpret/operator.rs @@ -512,7 +512,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { self.tcx.offset_of_subfield(self.param_env, layout, fields.iter()).bytes(); ImmTy::from_uint(val, usize_layout()) } - UbChecks => ImmTy::from_bool(self.tcx.sess.ub_checks(), *self.tcx), + UbChecks => ImmTy::from_bool(M::ub_checks(self)?, *self.tcx), }) } } diff --git a/compiler/rustc_driver_impl/src/lib.rs b/compiler/rustc_driver_impl/src/lib.rs index 2b7dc040f64..e49ae60e890 100644 --- a/compiler/rustc_driver_impl/src/lib.rs +++ b/compiler/rustc_driver_impl/src/lib.rs @@ -7,6 +7,7 @@ // tidy-alphabetical-start #![allow(internal_features)] #![allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable +#![cfg_attr(bootstrap, feature(unsafe_extern_blocks))] #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] #![doc(rust_logo)] #![feature(decl_macro)] @@ -15,6 +16,7 @@ #![feature(panic_update_hook)] #![feature(result_flattening)] #![feature(rustdoc_internals)] +#![warn(unreachable_pub)] // tidy-alphabetical-end use std::cmp::max; @@ -391,13 +393,17 @@ fn run_compiler( let linker = compiler.enter(|queries| { let early_exit = || early_exit().map(|_| None); + + // Parse the crate root source code (doesn't parse submodules yet) + // Everything else is parsed during macro expansion. queries.parse()?; - if let Some(ppm) = &sess.opts.pretty { - if ppm.needs_ast_map() { + // If pretty printing is requested: Figure out the representation, print it and exit + if let Some(pp_mode) = sess.opts.pretty { + if pp_mode.needs_ast_map() { queries.global_ctxt()?.enter(|tcx| { tcx.ensure().early_lint_checks(()); - pretty::print(sess, *ppm, pretty::PrintExtra::NeedsAstMap { tcx }); + pretty::print(sess, pp_mode, pretty::PrintExtra::NeedsAstMap { tcx }); Ok(()) })?; @@ -408,7 +414,7 @@ fn run_compiler( let krate = queries.parse()?; pretty::print( sess, - *ppm, + pp_mode, pretty::PrintExtra::AfterParsing { krate: &*krate.borrow() }, ); } @@ -463,12 +469,8 @@ fn run_compiler( linker.link(sess, codegen_backend)? } - if sess.opts.unstable_opts.print_fuel.is_some() { - eprintln!( - "Fuel used by {}: {}", - sess.opts.unstable_opts.print_fuel.as_ref().unwrap(), - sess.print_fuel.load(Ordering::SeqCst) - ); + if let Some(fuel) = sess.opts.unstable_opts.print_fuel.as_deref() { + eprintln!("Fuel used by {}: {}", fuel, sess.print_fuel.load(Ordering::SeqCst)); } Ok(()) @@ -485,36 +487,43 @@ fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<OutFileNa (odir, ofile) } -// Extract input (string or file and optional path) from matches. +/// Extract input (string or file and optional path) from matches. +/// This handles reading from stdin if `-` is provided. fn make_input( early_dcx: &EarlyDiagCtxt, free_matches: &[String], ) -> Result<Option<Input>, ErrorGuaranteed> { - let [ifile] = free_matches else { return Ok(None) }; - if ifile == "-" { - let mut src = String::new(); - if io::stdin().read_to_string(&mut src).is_err() { - // Immediately stop compilation if there was an issue reading - // the input (for example if the input stream is not UTF-8). - let reported = - early_dcx.early_err("couldn't read from stdin, as it did not contain valid UTF-8"); - return Err(reported); - } - if let Ok(path) = env::var("UNSTABLE_RUSTDOC_TEST_PATH") { + let [input_file] = free_matches else { return Ok(None) }; + + if input_file != "-" { + // Normal `Input::File` + return Ok(Some(Input::File(PathBuf::from(input_file)))); + } + + // read from stdin as `Input::Str` + let mut input = String::new(); + if io::stdin().read_to_string(&mut input).is_err() { + // Immediately stop compilation if there was an issue reading + // the input (for example if the input stream is not UTF-8). + let reported = + early_dcx.early_err("couldn't read from stdin, as it did not contain valid UTF-8"); + return Err(reported); + } + + let name = match env::var("UNSTABLE_RUSTDOC_TEST_PATH") { + Ok(path) => { let line = env::var("UNSTABLE_RUSTDOC_TEST_LINE").expect( "when UNSTABLE_RUSTDOC_TEST_PATH is set \ UNSTABLE_RUSTDOC_TEST_LINE also needs to be set", ); let line = isize::from_str_radix(&line, 10) .expect("UNSTABLE_RUSTDOC_TEST_LINE needs to be an number"); - let file_name = FileName::doc_test_source_code(PathBuf::from(path), line); - Ok(Some(Input::Str { name: file_name, input: src })) - } else { - Ok(Some(Input::Str { name: FileName::anon_source_code(&src), input: src })) + FileName::doc_test_source_code(PathBuf::from(path), line) } - } else { - Ok(Some(Input::File(PathBuf::from(ifile)))) - } + Err(_) => FileName::anon_source_code(&input), + }; + + Ok(Some(Input::Str { name, input })) } /// Whether to stop or continue compilation. diff --git a/compiler/rustc_driver_impl/src/signal_handler.rs b/compiler/rustc_driver_impl/src/signal_handler.rs index 51f2a508cf9..e1f868c2522 100644 --- a/compiler/rustc_driver_impl/src/signal_handler.rs +++ b/compiler/rustc_driver_impl/src/signal_handler.rs @@ -6,7 +6,7 @@ use std::{fmt, mem, ptr}; use rustc_interface::util::{DEFAULT_STACK_SIZE, STACK_SIZE}; -extern "C" { +unsafe extern "C" { fn backtrace_symbols_fd(buffer: *const *mut libc::c_void, size: libc::c_int, fd: libc::c_int); } diff --git a/compiler/rustc_error_codes/src/lib.rs b/compiler/rustc_error_codes/src/lib.rs index 2a7bc2501c0..150f99a3ee7 100644 --- a/compiler/rustc_error_codes/src/lib.rs +++ b/compiler/rustc_error_codes/src/lib.rs @@ -6,6 +6,7 @@ #![deny(rustdoc::invalid_codeblock_attributes)] #![doc(rust_logo)] #![feature(rustdoc_internals)] +#![warn(unreachable_pub)] // tidy-alphabetical-end // This higher-order macro defines the error codes that are in use. It is used diff --git a/compiler/rustc_error_messages/src/lib.rs b/compiler/rustc_error_messages/src/lib.rs index 87dee2898da..e84d7be45d7 100644 --- a/compiler/rustc_error_messages/src/lib.rs +++ b/compiler/rustc_error_messages/src/lib.rs @@ -4,6 +4,7 @@ #![feature(rustc_attrs)] #![feature(rustdoc_internals)] #![feature(type_alias_impl_trait)] +#![warn(unreachable_pub)] // tidy-alphabetical-end use std::borrow::Cow; diff --git a/compiler/rustc_errors/src/diagnostic.rs b/compiler/rustc_errors/src/diagnostic.rs index fae8b5647fc..3303e4ee752 100644 --- a/compiler/rustc_errors/src/diagnostic.rs +++ b/compiler/rustc_errors/src/diagnostic.rs @@ -204,7 +204,7 @@ pub trait LintDiagnostic<'a, G: EmissionGuarantee> { } #[derive(Clone, Debug, Encodable, Decodable)] -pub struct DiagLocation { +pub(crate) struct DiagLocation { file: Cow<'static, str>, line: u32, col: u32, diff --git a/compiler/rustc_errors/src/emitter.rs b/compiler/rustc_errors/src/emitter.rs index 9ce5d77ef6c..2bc29dabd18 100644 --- a/compiler/rustc_errors/src/emitter.rs +++ b/compiler/rustc_errors/src/emitter.rs @@ -2387,7 +2387,7 @@ enum DisplaySuggestion { impl FileWithAnnotatedLines { /// Preprocess all the annotations so that they are grouped by file and by line number /// This helps us quickly iterate over the whole message (including secondary file spans) - pub fn collect_annotations( + pub(crate) fn collect_annotations( emitter: &dyn Emitter, args: &FluentArgs<'_>, msp: &MultiSpan, diff --git a/compiler/rustc_errors/src/lib.rs b/compiler/rustc_errors/src/lib.rs index fd203c38318..99ee8fb17d7 100644 --- a/compiler/rustc_errors/src/lib.rs +++ b/compiler/rustc_errors/src/lib.rs @@ -25,6 +25,7 @@ #![feature(trait_alias)] #![feature(try_blocks)] #![feature(yeet_expr)] +#![warn(unreachable_pub)] // tidy-alphabetical-end extern crate self as rustc_errors; @@ -1701,7 +1702,7 @@ impl DiagCtxtInner { } /// Translate `message` eagerly with `args` to `SubdiagMessage::Eager`. - pub fn eagerly_translate<'a>( + fn eagerly_translate<'a>( &self, message: DiagMessage, args: impl Iterator<Item = DiagArg<'a>>, @@ -1710,7 +1711,7 @@ impl DiagCtxtInner { } /// Translate `message` eagerly with `args` to `String`. - pub fn eagerly_translate_to_string<'a>( + fn eagerly_translate_to_string<'a>( &self, message: DiagMessage, args: impl Iterator<Item = DiagArg<'a>>, diff --git a/compiler/rustc_errors/src/lock.rs b/compiler/rustc_errors/src/lock.rs index 915542c9092..7557969f374 100644 --- a/compiler/rustc_errors/src/lock.rs +++ b/compiler/rustc_errors/src/lock.rs @@ -12,7 +12,7 @@ use std::any::Any; #[cfg(windows)] -pub fn acquire_global_lock(name: &str) -> Box<dyn Any> { +pub(crate) fn acquire_global_lock(name: &str) -> Box<dyn Any> { use std::ffi::CString; use std::io; @@ -80,6 +80,6 @@ pub fn acquire_global_lock(name: &str) -> Box<dyn Any> { } #[cfg(not(windows))] -pub fn acquire_global_lock(_name: &str) -> Box<dyn Any> { +pub(crate) fn acquire_global_lock(_name: &str) -> Box<dyn Any> { Box::new(()) } diff --git a/compiler/rustc_errors/src/markdown/parse.rs b/compiler/rustc_errors/src/markdown/parse.rs index 46f8959b6f2..b1db44dd215 100644 --- a/compiler/rustc_errors/src/markdown/parse.rs +++ b/compiler/rustc_errors/src/markdown/parse.rs @@ -74,7 +74,7 @@ enum ParseOpt { } /// Parse a buffer -pub fn entrypoint(txt: &str) -> MdStream<'_> { +pub(crate) fn entrypoint(txt: &str) -> MdStream<'_> { let ctx = Context { top_block: true, prev: Prev::Newline }; normalize(parse_recursive(txt.trim().as_bytes(), ctx), &mut Vec::new()) } diff --git a/compiler/rustc_errors/src/markdown/term.rs b/compiler/rustc_errors/src/markdown/term.rs index 06c1333d93d..579e00b8b85 100644 --- a/compiler/rustc_errors/src/markdown/term.rs +++ b/compiler/rustc_errors/src/markdown/term.rs @@ -15,7 +15,7 @@ thread_local! { } /// Print to terminal output to a buffer -pub fn entrypoint(stream: &MdStream<'_>, buf: &mut Buffer) -> io::Result<()> { +pub(crate) fn entrypoint(stream: &MdStream<'_>, buf: &mut Buffer) -> io::Result<()> { #[cfg(not(test))] if let Some((w, _)) = termize::dimensions() { WIDTH.with(|c| c.set(std::cmp::min(w, DEFAULT_COLUMN_WIDTH))); @@ -47,7 +47,7 @@ fn write_stream( Ok(()) } -pub fn write_tt(tt: &MdTree<'_>, buf: &mut Buffer, indent: usize) -> io::Result<()> { +fn write_tt(tt: &MdTree<'_>, buf: &mut Buffer, indent: usize) -> io::Result<()> { match tt { MdTree::CodeBlock { txt, lang: _ } => { buf.set_color(ColorSpec::new().set_dimmed(true))?; diff --git a/compiler/rustc_errors/src/snippet.rs b/compiler/rustc_errors/src/snippet.rs index 50abf8a49c2..8485d7087cf 100644 --- a/compiler/rustc_errors/src/snippet.rs +++ b/compiler/rustc_errors/src/snippet.rs @@ -5,13 +5,13 @@ use rustc_macros::{Decodable, Encodable}; use crate::{Level, Loc}; #[derive(Clone, Debug, PartialOrd, Ord, PartialEq, Eq)] -pub struct Line { +pub(crate) struct Line { pub line_index: usize, pub annotations: Vec<Annotation>, } #[derive(Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq, Default)] -pub struct AnnotationColumn { +pub(crate) struct AnnotationColumn { /// the (0-indexed) column for *display* purposes, counted in characters, not utf-8 bytes pub display: usize, /// the (0-indexed) column in the file, counted in characters, not utf-8 bytes. @@ -31,13 +31,13 @@ pub struct AnnotationColumn { } impl AnnotationColumn { - pub fn from_loc(loc: &Loc) -> AnnotationColumn { + pub(crate) fn from_loc(loc: &Loc) -> AnnotationColumn { AnnotationColumn { display: loc.col_display, file: loc.col.0 } } } #[derive(Clone, Debug, PartialOrd, Ord, PartialEq, Eq)] -pub struct MultilineAnnotation { +pub(crate) struct MultilineAnnotation { pub depth: usize, pub line_start: usize, pub line_end: usize, @@ -49,19 +49,19 @@ pub struct MultilineAnnotation { } impl MultilineAnnotation { - pub fn increase_depth(&mut self) { + pub(crate) fn increase_depth(&mut self) { self.depth += 1; } /// Compare two `MultilineAnnotation`s considering only the `Span` they cover. - pub fn same_span(&self, other: &MultilineAnnotation) -> bool { + pub(crate) fn same_span(&self, other: &MultilineAnnotation) -> bool { self.line_start == other.line_start && self.line_end == other.line_end && self.start_col == other.start_col && self.end_col == other.end_col } - pub fn as_start(&self) -> Annotation { + pub(crate) fn as_start(&self) -> Annotation { Annotation { start_col: self.start_col, end_col: AnnotationColumn { @@ -76,7 +76,7 @@ impl MultilineAnnotation { } } - pub fn as_end(&self) -> Annotation { + pub(crate) fn as_end(&self) -> Annotation { Annotation { start_col: AnnotationColumn { // these might not correspond to the same place anymore, @@ -91,7 +91,7 @@ impl MultilineAnnotation { } } - pub fn as_line(&self) -> Annotation { + pub(crate) fn as_line(&self) -> Annotation { Annotation { start_col: Default::default(), end_col: Default::default(), @@ -103,7 +103,7 @@ impl MultilineAnnotation { } #[derive(Clone, Debug, PartialOrd, Ord, PartialEq, Eq)] -pub enum AnnotationType { +pub(crate) enum AnnotationType { /// Annotation under a single line of code Singleline, @@ -129,7 +129,7 @@ pub enum AnnotationType { } #[derive(Clone, Debug, PartialOrd, Ord, PartialEq, Eq)] -pub struct Annotation { +pub(crate) struct Annotation { /// Start column. /// Note that it is important that this field goes /// first, so that when we sort, we sort orderings by start @@ -152,12 +152,12 @@ pub struct Annotation { impl Annotation { /// Whether this annotation is a vertical line placeholder. - pub fn is_line(&self) -> bool { + pub(crate) fn is_line(&self) -> bool { matches!(self.annotation_type, AnnotationType::MultilineLine(_)) } /// Length of this annotation as displayed in the stderr output - pub fn len(&self) -> usize { + pub(crate) fn len(&self) -> usize { // Account for usize underflows if self.end_col.display > self.start_col.display { self.end_col.display - self.start_col.display @@ -166,7 +166,7 @@ impl Annotation { } } - pub fn has_label(&self) -> bool { + pub(crate) fn has_label(&self) -> bool { if let Some(ref label) = self.label { // Consider labels with no text as effectively not being there // to avoid weird output with unnecessary vertical lines, like: @@ -184,7 +184,7 @@ impl Annotation { } } - pub fn takes_space(&self) -> bool { + pub(crate) fn takes_space(&self) -> bool { // Multiline annotations always have to keep vertical space. matches!( self.annotation_type, @@ -194,7 +194,7 @@ impl Annotation { } #[derive(Debug)] -pub struct StyledString { +pub(crate) struct StyledString { pub text: String, pub style: Style, } diff --git a/compiler/rustc_errors/src/styled_buffer.rs b/compiler/rustc_errors/src/styled_buffer.rs index 9aa14e1f214..5ca9e9b18f3 100644 --- a/compiler/rustc_errors/src/styled_buffer.rs +++ b/compiler/rustc_errors/src/styled_buffer.rs @@ -3,7 +3,7 @@ use crate::snippet::{Style, StyledString}; #[derive(Debug)] -pub struct StyledBuffer { +pub(crate) struct StyledBuffer { lines: Vec<Vec<StyledChar>>, } @@ -22,12 +22,12 @@ impl StyledChar { } impl StyledBuffer { - pub fn new() -> StyledBuffer { + pub(crate) fn new() -> StyledBuffer { StyledBuffer { lines: vec![] } } /// Returns content of `StyledBuffer` split by lines and line styles - pub fn render(&self) -> Vec<Vec<StyledString>> { + pub(crate) fn render(&self) -> Vec<Vec<StyledString>> { // Tabs are assumed to have been replaced by spaces in calling code. debug_assert!(self.lines.iter().all(|r| !r.iter().any(|sc| sc.chr == '\t'))); @@ -70,7 +70,7 @@ impl StyledBuffer { /// Sets `chr` with `style` for given `line`, `col`. /// If `line` does not exist in our buffer, adds empty lines up to the given /// and fills the last line with unstyled whitespace. - pub fn putc(&mut self, line: usize, col: usize, chr: char, style: Style) { + pub(crate) fn putc(&mut self, line: usize, col: usize, chr: char, style: Style) { self.ensure_lines(line); if col >= self.lines[line].len() { self.lines[line].resize(col + 1, StyledChar::SPACE); @@ -81,7 +81,7 @@ impl StyledBuffer { /// Sets `string` with `style` for given `line`, starting from `col`. /// If `line` does not exist in our buffer, adds empty lines up to the given /// and fills the last line with unstyled whitespace. - pub fn puts(&mut self, line: usize, col: usize, string: &str, style: Style) { + pub(crate) fn puts(&mut self, line: usize, col: usize, string: &str, style: Style) { let mut n = col; for c in string.chars() { self.putc(line, n, c, style); @@ -91,7 +91,7 @@ impl StyledBuffer { /// For given `line` inserts `string` with `style` before old content of that line, /// adding lines if needed - pub fn prepend(&mut self, line: usize, string: &str, style: Style) { + pub(crate) fn prepend(&mut self, line: usize, string: &str, style: Style) { self.ensure_lines(line); let string_len = string.chars().count(); @@ -107,7 +107,7 @@ impl StyledBuffer { /// For given `line` inserts `string` with `style` after old content of that line, /// adding lines if needed - pub fn append(&mut self, line: usize, string: &str, style: Style) { + pub(crate) fn append(&mut self, line: usize, string: &str, style: Style) { if line >= self.lines.len() { self.puts(line, 0, string, style); } else { @@ -116,14 +116,14 @@ impl StyledBuffer { } } - pub fn num_lines(&self) -> usize { + pub(crate) fn num_lines(&self) -> usize { self.lines.len() } /// Set `style` for `line`, `col_start..col_end` range if: /// 1. That line and column range exist in `StyledBuffer` /// 2. `overwrite` is `true` or existing style is `Style::NoStyle` or `Style::Quotation` - pub fn set_style_range( + pub(crate) fn set_style_range( &mut self, line: usize, col_start: usize, @@ -139,7 +139,7 @@ impl StyledBuffer { /// Set `style` for `line`, `col` if: /// 1. That line and column exist in `StyledBuffer` /// 2. `overwrite` is `true` or existing style is `Style::NoStyle` or `Style::Quotation` - pub fn set_style(&mut self, line: usize, col: usize, style: Style, overwrite: bool) { + fn set_style(&mut self, line: usize, col: usize, style: Style, overwrite: bool) { if let Some(ref mut line) = self.lines.get_mut(line) { if let Some(StyledChar { style: s, .. }) = line.get_mut(col) { if overwrite || matches!(s, Style::NoStyle | Style::Quotation) { diff --git a/compiler/rustc_expand/src/errors.rs b/compiler/rustc_expand/src/errors.rs index f6b5cd394b6..0fdccb08918 100644 --- a/compiler/rustc_expand/src/errors.rs +++ b/compiler/rustc_expand/src/errors.rs @@ -350,7 +350,7 @@ pub(crate) struct ModuleMultipleCandidates { #[derive(Diagnostic)] #[diag(expand_trace_macro)] -pub struct TraceMacro { +pub(crate) struct TraceMacro { #[primary_span] pub span: Span, } @@ -402,14 +402,14 @@ pub(crate) struct CustomAttributePanickedHelp { #[derive(Diagnostic)] #[diag(expand_proc_macro_derive_tokens)] -pub struct ProcMacroDeriveTokens { +pub(crate) struct ProcMacroDeriveTokens { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(expand_duplicate_matcher_binding)] -pub struct DuplicateMatcherBinding { +pub(crate) struct DuplicateMatcherBinding { #[primary_span] #[label] pub span: Span, @@ -421,7 +421,7 @@ pub struct DuplicateMatcherBinding { #[diag(expand_missing_fragment_specifier)] #[note] #[help(expand_valid)] -pub struct MissingFragmentSpecifier { +pub(crate) struct MissingFragmentSpecifier { #[primary_span] pub span: Span, #[suggestion( @@ -437,7 +437,7 @@ pub struct MissingFragmentSpecifier { #[derive(Diagnostic)] #[diag(expand_invalid_fragment_specifier)] #[help] -pub struct InvalidFragmentSpecifier { +pub(crate) struct InvalidFragmentSpecifier { #[primary_span] pub span: Span, pub fragment: Ident, @@ -446,7 +446,7 @@ pub struct InvalidFragmentSpecifier { #[derive(Diagnostic)] #[diag(expand_expected_paren_or_brace)] -pub struct ExpectedParenOrBrace<'a> { +pub(crate) struct ExpectedParenOrBrace<'a> { #[primary_span] pub span: Span, pub token: Cow<'a, str>, @@ -479,7 +479,7 @@ pub(crate) struct GlobDelegationTraitlessQpath { #[derive(Diagnostic)] #[diag(expand_proc_macro_back_compat)] #[note] -pub struct ProcMacroBackCompat { +pub(crate) struct ProcMacroBackCompat { pub crate_name: String, pub fixed_version: String, } diff --git a/compiler/rustc_expand/src/lib.rs b/compiler/rustc_expand/src/lib.rs index 4222c9fe906..777044e3f33 100644 --- a/compiler/rustc_expand/src/lib.rs +++ b/compiler/rustc_expand/src/lib.rs @@ -13,6 +13,7 @@ #![feature(rustdoc_internals)] #![feature(try_blocks)] #![feature(yeet_expr)] +#![warn(unreachable_pub)] // tidy-alphabetical-end extern crate proc_macro as pm; diff --git a/compiler/rustc_expand/src/mbe/diagnostics.rs b/compiler/rustc_expand/src/mbe/diagnostics.rs index 628c6bfeb79..5778f661622 100644 --- a/compiler/rustc_expand/src/mbe/diagnostics.rs +++ b/compiler/rustc_expand/src/mbe/diagnostics.rs @@ -196,13 +196,14 @@ impl<'dcx> CollectTrackerAndEmitter<'dcx, '_> { } } -/// Currently used by macro_rules! compilation to extract a little information from the `Failure` case. -pub struct FailureForwarder<'matcher> { +/// Currently used by macro_rules! compilation to extract a little information from the `Failure` +/// case. +pub(crate) struct FailureForwarder<'matcher> { expected_token: Option<&'matcher Token>, } impl<'matcher> FailureForwarder<'matcher> { - pub fn new() -> Self { + pub(crate) fn new() -> Self { Self { expected_token: None } } } diff --git a/compiler/rustc_expand/src/mbe/macro_parser.rs b/compiler/rustc_expand/src/mbe/macro_parser.rs index e5b9c627429..9011d02da33 100644 --- a/compiler/rustc_expand/src/mbe/macro_parser.rs +++ b/compiler/rustc_expand/src/mbe/macro_parser.rs @@ -407,7 +407,7 @@ fn token_name_eq(t1: &Token, t2: &Token) -> bool { // Note: the vectors could be created and dropped within `parse_tt`, but to avoid excess // allocations we have a single vector for each kind that is cleared and reused repeatedly. -pub struct TtParser { +pub(crate) struct TtParser { macro_name: Ident, /// The set of current mps to be processed. This should be empty by the end of a successful diff --git a/compiler/rustc_expand/src/mbe/quoted.rs b/compiler/rustc_expand/src/mbe/quoted.rs index b2f7c8f5183..5df0aebfe57 100644 --- a/compiler/rustc_expand/src/mbe/quoted.rs +++ b/compiler/rustc_expand/src/mbe/quoted.rs @@ -14,12 +14,11 @@ use crate::mbe::macro_parser::count_metavar_decls; use crate::mbe::{Delimited, KleeneOp, KleeneToken, MetaVarExpr, SequenceRepetition, TokenTree}; const VALID_FRAGMENT_NAMES_MSG: &str = "valid fragment specifiers are \ - `ident`, `block`, `stmt`, `expr`, `pat`, `ty`, `lifetime`, \ - `literal`, `path`, `meta`, `tt`, `item` and `vis`"; -pub const VALID_FRAGMENT_NAMES_MSG_2021: &str = "valid fragment specifiers are \ - `ident`, `block`, `stmt`, `expr`, `expr_2021`, `pat`, \ - `ty`, `lifetime`, `literal`, `path`, `meta`, `tt`, \ - `item` and `vis`"; + `ident`, `block`, `stmt`, `expr`, `pat`, `ty`, `lifetime`, `literal`, `path`, `meta`, `tt`, \ + `item` and `vis`"; +pub(crate) const VALID_FRAGMENT_NAMES_MSG_2021: &str = "valid fragment specifiers are \ + `ident`, `block`, `stmt`, `expr`, `expr_2021`, `pat`, `ty`, `lifetime`, `literal`, `path`, \ + `meta`, `tt`, `item` and `vis`"; /// Takes a `tokenstream::TokenStream` and returns a `Vec<self::TokenTree>`. Specifically, this /// takes a generic `TokenStream`, such as is used in the rest of the compiler, and returns a diff --git a/compiler/rustc_expand/src/placeholders.rs b/compiler/rustc_expand/src/placeholders.rs index 1e455d465e4..469bed3cd59 100644 --- a/compiler/rustc_expand/src/placeholders.rs +++ b/compiler/rustc_expand/src/placeholders.rs @@ -191,12 +191,12 @@ pub(crate) fn placeholder( } #[derive(Default)] -pub struct PlaceholderExpander { +pub(crate) struct PlaceholderExpander { expanded_fragments: FxHashMap<ast::NodeId, AstFragment>, } impl PlaceholderExpander { - pub fn add(&mut self, id: ast::NodeId, mut fragment: AstFragment) { + pub(crate) fn add(&mut self, id: ast::NodeId, mut fragment: AstFragment) { fragment.mut_visit_with(self); self.expanded_fragments.insert(id, fragment); } diff --git a/compiler/rustc_expand/src/proc_macro_server.rs b/compiler/rustc_expand/src/proc_macro_server.rs index 1438d1ad11f..4ff5da1a4bd 100644 --- a/compiler/rustc_expand/src/proc_macro_server.rs +++ b/compiler/rustc_expand/src/proc_macro_server.rs @@ -414,7 +414,7 @@ impl ToInternal<rustc_errors::Level> for Level { } } -pub struct FreeFunctions; +pub(crate) struct FreeFunctions; pub(crate) struct Rustc<'a, 'b> { ecx: &'a mut ExtCtxt<'b>, @@ -426,7 +426,7 @@ pub(crate) struct Rustc<'a, 'b> { } impl<'a, 'b> Rustc<'a, 'b> { - pub fn new(ecx: &'a mut ExtCtxt<'b>) -> Self { + pub(crate) fn new(ecx: &'a mut ExtCtxt<'b>) -> Self { let expn_data = ecx.current_expansion.id.expn_data(); Rustc { def_site: ecx.with_def_site_ctxt(expn_data.def_site), diff --git a/compiler/rustc_feature/src/builtin_attrs.rs b/compiler/rustc_feature/src/builtin_attrs.rs index 2747a14d60a..e2491922b8d 100644 --- a/compiler/rustc_feature/src/builtin_attrs.rs +++ b/compiler/rustc_feature/src/builtin_attrs.rs @@ -37,6 +37,8 @@ const GATED_CFGS: &[GatedCfg] = &[ (sym::relocation_model, sym::cfg_relocation_model, cfg_fn!(cfg_relocation_model)), (sym::sanitizer_cfi_generalize_pointers, sym::cfg_sanitizer_cfi, cfg_fn!(cfg_sanitizer_cfi)), (sym::sanitizer_cfi_normalize_integers, sym::cfg_sanitizer_cfi, cfg_fn!(cfg_sanitizer_cfi)), + // this is consistent with naming of the compiler flag it's for + (sym::fmt_debug, sym::fmt_debug, cfg_fn!(fmt_debug)), ]; /// Find a gated cfg determined by the `pred`icate which is given the cfg's name. diff --git a/compiler/rustc_feature/src/lib.rs b/compiler/rustc_feature/src/lib.rs index dcc1c3202ea..adaaba3cd23 100644 --- a/compiler/rustc_feature/src/lib.rs +++ b/compiler/rustc_feature/src/lib.rs @@ -15,6 +15,7 @@ #![allow(internal_features)] #![doc(rust_logo)] #![feature(rustdoc_internals)] +#![warn(unreachable_pub)] // tidy-alphabetical-end mod accepted; diff --git a/compiler/rustc_feature/src/unstable.rs b/compiler/rustc_feature/src/unstable.rs index 4524458023d..7ea037ca8b2 100644 --- a/compiler/rustc_feature/src/unstable.rs +++ b/compiler/rustc_feature/src/unstable.rs @@ -302,6 +302,7 @@ declare_features! ( // FIXME: Document these and merge with the list below. // Unstable `#[target_feature]` directives. + (unstable, aarch64_unstable_target_feature, "CURRENT_RUSTC_VERSION", Some(44839)), (unstable, aarch64_ver_target_feature, "1.27.0", Some(44839)), (unstable, arm_target_feature, "1.27.0", Some(44839)), (unstable, avx512_target_feature, "1.27.0", Some(44839)), @@ -470,6 +471,8 @@ declare_features! ( (unstable, ffi_const, "1.45.0", Some(58328)), /// Allows the use of `#[ffi_pure]` on foreign functions. (unstable, ffi_pure, "1.45.0", Some(58329)), + /// Controlling the behavior of fmt::Debug + (unstable, fmt_debug, "CURRENT_RUSTC_VERSION", Some(129709)), /// Allows using `#[repr(align(...))]` on function items (unstable, fn_align, "1.53.0", Some(82232)), /// Support delegating implementation of functions to other already implemented functions. @@ -594,6 +597,8 @@ declare_features! ( (unstable, strict_provenance, "1.61.0", Some(95228)), /// Allows string patterns to dereference values to match them. (unstable, string_deref_patterns, "1.67.0", Some(87121)), + /// Allows structs to carry target_feature information. + (incomplete, struct_target_features, "CURRENT_RUSTC_VERSION", Some(129107)), /// Allows the use of `#[target_feature]` on safe functions. (unstable, target_feature_11, "1.45.0", Some(69098)), /// Allows using `#[thread_local]` on `static` items. diff --git a/compiler/rustc_fluent_macro/src/lib.rs b/compiler/rustc_fluent_macro/src/lib.rs index 0a04e6743a8..6e5add24bcc 100644 --- a/compiler/rustc_fluent_macro/src/lib.rs +++ b/compiler/rustc_fluent_macro/src/lib.rs @@ -6,6 +6,7 @@ #![feature(proc_macro_diagnostic)] #![feature(proc_macro_span)] #![feature(rustdoc_internals)] +#![warn(unreachable_pub)] // tidy-alphabetical-end use proc_macro::TokenStream; diff --git a/compiler/rustc_graphviz/src/lib.rs b/compiler/rustc_graphviz/src/lib.rs index c8f8fd5be02..b5774f64b66 100644 --- a/compiler/rustc_graphviz/src/lib.rs +++ b/compiler/rustc_graphviz/src/lib.rs @@ -277,6 +277,7 @@ )] #![doc(rust_logo)] #![feature(rustdoc_internals)] +#![warn(unreachable_pub)] // tidy-alphabetical-end use std::borrow::Cow; diff --git a/compiler/rustc_hir/src/def.rs b/compiler/rustc_hir/src/def.rs index 59204d79928..36e29d2dcb2 100644 --- a/compiler/rustc_hir/src/def.rs +++ b/compiler/rustc_hir/src/def.rs @@ -133,6 +133,9 @@ pub enum DefKind { /// we treat them all the same, and code which needs to distinguish them can match /// or `hir::ClosureKind` or `type_of`. Closure, + /// The definition of a synthetic coroutine body created by the lowering of a + /// coroutine-closure, such as an async closure. + SyntheticCoroutineBody, } impl DefKind { @@ -177,6 +180,7 @@ impl DefKind { DefKind::Closure => "closure", DefKind::ExternCrate => "extern crate", DefKind::GlobalAsm => "global assembly block", + DefKind::SyntheticCoroutineBody => "synthetic mir body", } } @@ -236,7 +240,8 @@ impl DefKind { | DefKind::ForeignMod | DefKind::GlobalAsm | DefKind::Impl { .. } - | DefKind::OpaqueTy => None, + | DefKind::OpaqueTy + | DefKind::SyntheticCoroutineBody => None, } } @@ -276,6 +281,7 @@ impl DefKind { DefKind::GlobalAsm => DefPathData::GlobalAsm, DefKind::Impl { .. } => DefPathData::Impl, DefKind::Closure => DefPathData::Closure, + DefKind::SyntheticCoroutineBody => DefPathData::Closure, } } @@ -291,7 +297,8 @@ impl DefKind { | DefKind::AssocFn | DefKind::Ctor(..) | DefKind::Closure - | DefKind::Static { .. } => true, + | DefKind::Static { .. } + | DefKind::SyntheticCoroutineBody => true, DefKind::Mod | DefKind::Struct | DefKind::Union @@ -319,6 +326,41 @@ impl DefKind { | DefKind::ExternCrate => false, } } + + /// Whether `query struct_target_features` should be used with this definition. + pub fn has_struct_target_features(self) -> bool { + match self { + DefKind::Struct | DefKind::Union | DefKind::Enum => true, + DefKind::Fn + | DefKind::AssocFn + | DefKind::Ctor(..) + | DefKind::Closure + | DefKind::Static { .. } + | DefKind::Mod + | DefKind::Variant + | DefKind::Trait + | DefKind::TyAlias + | DefKind::ForeignTy + | DefKind::TraitAlias + | DefKind::AssocTy + | DefKind::Const + | DefKind::AssocConst + | DefKind::Macro(..) + | DefKind::Use + | DefKind::ForeignMod + | DefKind::OpaqueTy + | DefKind::Impl { .. } + | DefKind::Field + | DefKind::TyParam + | DefKind::ConstParam + | DefKind::LifetimeParam + | DefKind::AnonConst + | DefKind::InlineConst + | DefKind::SyntheticCoroutineBody + | DefKind::GlobalAsm + | DefKind::ExternCrate => false, + } + } } /// The resolution of a path or export. diff --git a/compiler/rustc_hir/src/lib.rs b/compiler/rustc_hir/src/lib.rs index e517c3fd07a..c1a4a4497c7 100644 --- a/compiler/rustc_hir/src/lib.rs +++ b/compiler/rustc_hir/src/lib.rs @@ -10,6 +10,7 @@ #![feature(never_type)] #![feature(rustc_attrs)] #![feature(variant_count)] +#![warn(unreachable_pub)] // tidy-alphabetical-end extern crate self as rustc_hir; diff --git a/compiler/rustc_hir_analysis/src/bounds.rs b/compiler/rustc_hir_analysis/src/bounds.rs index c30a6f1eeb9..d0b0c08aa79 100644 --- a/compiler/rustc_hir_analysis/src/bounds.rs +++ b/compiler/rustc_hir_analysis/src/bounds.rs @@ -26,13 +26,13 @@ use rustc_span::Span; /// Our representation is a bit mixed here -- in some cases, we /// include the self type (e.g., `trait_bounds`) but in others we do not #[derive(Default, PartialEq, Eq, Clone, Debug)] -pub struct Bounds<'tcx> { +pub(crate) struct Bounds<'tcx> { clauses: Vec<(ty::Clause<'tcx>, Span)>, effects_min_tys: FxIndexMap<Ty<'tcx>, Span>, } impl<'tcx> Bounds<'tcx> { - pub fn push_region_bound( + pub(crate) fn push_region_bound( &mut self, tcx: TyCtxt<'tcx>, region: ty::PolyTypeOutlivesPredicate<'tcx>, @@ -42,7 +42,7 @@ impl<'tcx> Bounds<'tcx> { .push((region.map_bound(|p| ty::ClauseKind::TypeOutlives(p)).upcast(tcx), span)); } - pub fn push_trait_bound( + pub(crate) fn push_trait_bound( &mut self, tcx: TyCtxt<'tcx>, defining_def_id: DefId, @@ -154,7 +154,7 @@ impl<'tcx> Bounds<'tcx> { self.clauses.push((bound_trait_ref.rebind(new_trait_ref).upcast(tcx), span)); } - pub fn push_projection_bound( + pub(crate) fn push_projection_bound( &mut self, tcx: TyCtxt<'tcx>, projection: ty::PolyProjectionPredicate<'tcx>, @@ -166,14 +166,14 @@ impl<'tcx> Bounds<'tcx> { )); } - pub fn push_sized(&mut self, tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, span: Span) { + pub(crate) fn push_sized(&mut self, tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, span: Span) { let sized_def_id = tcx.require_lang_item(LangItem::Sized, Some(span)); let trait_ref = ty::TraitRef::new(tcx, sized_def_id, [ty]); // Preferable to put this obligation first, since we report better errors for sized ambiguity. self.clauses.insert(0, (trait_ref.upcast(tcx), span)); } - pub fn clauses( + pub(crate) fn clauses( &self, // FIXME(effects): remove tcx _tcx: TyCtxt<'tcx>, @@ -181,7 +181,7 @@ impl<'tcx> Bounds<'tcx> { self.clauses.iter().cloned() } - pub fn effects_min_tys(&self) -> impl Iterator<Item = Ty<'tcx>> + '_ { + pub(crate) fn effects_min_tys(&self) -> impl Iterator<Item = Ty<'tcx>> + '_ { self.effects_min_tys.keys().copied() } } diff --git a/compiler/rustc_hir_analysis/src/check/check.rs b/compiler/rustc_hir_analysis/src/check/check.rs index 728c3790098..d414bcdb95b 100644 --- a/compiler/rustc_hir_analysis/src/check/check.rs +++ b/compiler/rustc_hir_analysis/src/check/check.rs @@ -1053,7 +1053,7 @@ fn check_impl_items_against_trait<'tcx>( } } -pub fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) { +fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) { let t = tcx.type_of(def_id).instantiate_identity(); if let ty::Adt(def, args) = t.kind() && def.is_struct() diff --git a/compiler/rustc_hir_analysis/src/check/errs.rs b/compiler/rustc_hir_analysis/src/check/errs.rs index 19a0476e630..22d7d1fea9c 100644 --- a/compiler/rustc_hir_analysis/src/check/errs.rs +++ b/compiler/rustc_hir_analysis/src/check/errs.rs @@ -6,7 +6,7 @@ use rustc_span::Span; use crate::errors; /// Check for shared or mutable references of `static mut` inside expression -pub fn maybe_expr_static_mut(tcx: TyCtxt<'_>, expr: hir::Expr<'_>) { +pub(crate) fn maybe_expr_static_mut(tcx: TyCtxt<'_>, expr: hir::Expr<'_>) { let span = expr.span; let hir_id = expr.hir_id; if let hir::ExprKind::AddrOf(borrow_kind, m, expr) = expr.kind @@ -26,7 +26,7 @@ pub fn maybe_expr_static_mut(tcx: TyCtxt<'_>, expr: hir::Expr<'_>) { } /// Check for shared or mutable references of `static mut` inside statement -pub fn maybe_stmt_static_mut(tcx: TyCtxt<'_>, stmt: hir::Stmt<'_>) { +pub(crate) fn maybe_stmt_static_mut(tcx: TyCtxt<'_>, stmt: hir::Stmt<'_>) { if let hir::StmtKind::Let(loc) = stmt.kind && let hir::PatKind::Binding(ba, _, _, _) = loc.pat.kind && let hir::ByRef::Yes(rmutbl) = ba.0 diff --git a/compiler/rustc_hir_analysis/src/check/region.rs b/compiler/rustc_hir_analysis/src/check/region.rs index bc6641c688c..48335173979 100644 --- a/compiler/rustc_hir_analysis/src/check/region.rs +++ b/compiler/rustc_hir_analysis/src/check/region.rs @@ -22,7 +22,7 @@ use rustc_span::source_map; use super::errs::{maybe_expr_static_mut, maybe_stmt_static_mut}; #[derive(Debug, Copy, Clone)] -pub struct Context { +struct Context { /// The scope that contains any new variables declared, plus its depth in /// the scope tree. var_parent: Option<(Scope, ScopeDepth)>, @@ -893,7 +893,7 @@ impl<'tcx> Visitor<'tcx> for RegionResolutionVisitor<'tcx> { /// re-use in incremental scenarios. We may sometimes need to rerun the /// type checker even when the HIR hasn't changed, and in those cases /// we can avoid reconstructing the region scope tree. -pub fn region_scope_tree(tcx: TyCtxt<'_>, def_id: DefId) -> &ScopeTree { +pub(crate) fn region_scope_tree(tcx: TyCtxt<'_>, def_id: DefId) -> &ScopeTree { let typeck_root_def_id = tcx.typeck_root_def_id(def_id); if typeck_root_def_id != def_id { return tcx.region_scope_tree(typeck_root_def_id); diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index fb9bcc113c6..cb66179ec80 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -2174,7 +2174,8 @@ fn lint_redundant_lifetimes<'tcx>( | DefKind::Field | DefKind::LifetimeParam | DefKind::GlobalAsm - | DefKind::Closure => return, + | DefKind::Closure + | DefKind::SyntheticCoroutineBody => return, } // The ordering of this lifetime map is a bit subtle. diff --git a/compiler/rustc_hir_analysis/src/check_unused.rs b/compiler/rustc_hir_analysis/src/check_unused.rs index ed23dc2a827..ca9e2e8a3cc 100644 --- a/compiler/rustc_hir_analysis/src/check_unused.rs +++ b/compiler/rustc_hir_analysis/src/check_unused.rs @@ -5,7 +5,7 @@ use rustc_middle::query::Providers; use rustc_middle::ty::TyCtxt; use rustc_session::lint; -pub fn provide(providers: &mut Providers) { +pub(crate) fn provide(providers: &mut Providers) { *providers = Providers { check_unused_traits, ..*providers }; } diff --git a/compiler/rustc_hir_analysis/src/coherence/builtin.rs b/compiler/rustc_hir_analysis/src/coherence/builtin.rs index fecd78bc38f..23f1adfe302 100644 --- a/compiler/rustc_hir_analysis/src/coherence/builtin.rs +++ b/compiler/rustc_hir_analysis/src/coherence/builtin.rs @@ -332,7 +332,7 @@ fn visit_implementation_of_dispatch_from_dyn(checker: &Checker<'_>) -> Result<() } } -pub fn coerce_unsized_info<'tcx>( +pub(crate) fn coerce_unsized_info<'tcx>( tcx: TyCtxt<'tcx>, impl_did: LocalDefId, ) -> Result<CoerceUnsizedInfo, ErrorGuaranteed> { diff --git a/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs b/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs index 89acb778d6c..bd8b43e28e5 100644 --- a/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs +++ b/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs @@ -19,7 +19,7 @@ use rustc_span::ErrorGuaranteed; use crate::errors; /// On-demand query: yields a map containing all types mapped to their inherent impls. -pub fn crate_inherent_impls( +pub(crate) fn crate_inherent_impls( tcx: TyCtxt<'_>, (): (), ) -> Result<&'_ CrateInherentImpls, ErrorGuaranteed> { @@ -32,7 +32,7 @@ pub fn crate_inherent_impls( Ok(tcx.arena.alloc(collect.impls_map)) } -pub fn crate_incoherent_impls( +pub(crate) fn crate_incoherent_impls( tcx: TyCtxt<'_>, simp: SimplifiedType, ) -> Result<&[DefId], ErrorGuaranteed> { @@ -43,7 +43,10 @@ pub fn crate_incoherent_impls( } /// On-demand query: yields a vector of the inherent impls for a specific type. -pub fn inherent_impls(tcx: TyCtxt<'_>, ty_def_id: LocalDefId) -> Result<&[DefId], ErrorGuaranteed> { +pub(crate) fn inherent_impls( + tcx: TyCtxt<'_>, + ty_def_id: LocalDefId, +) -> Result<&[DefId], ErrorGuaranteed> { let crate_map = tcx.crate_inherent_impls(())?; Ok(match crate_map.inherent_impls.get(&ty_def_id) { Some(v) => &v[..], diff --git a/compiler/rustc_hir_analysis/src/coherence/inherent_impls_overlap.rs b/compiler/rustc_hir_analysis/src/coherence/inherent_impls_overlap.rs index cd5cc33d65a..00bbbf7130f 100644 --- a/compiler/rustc_hir_analysis/src/coherence/inherent_impls_overlap.rs +++ b/compiler/rustc_hir_analysis/src/coherence/inherent_impls_overlap.rs @@ -11,7 +11,10 @@ use rustc_span::{ErrorGuaranteed, Symbol}; use rustc_trait_selection::traits::{self, SkipLeakCheck}; use smallvec::SmallVec; -pub fn crate_inherent_impls_overlap_check(tcx: TyCtxt<'_>, (): ()) -> Result<(), ErrorGuaranteed> { +pub(crate) fn crate_inherent_impls_overlap_check( + tcx: TyCtxt<'_>, + (): (), +) -> Result<(), ErrorGuaranteed> { let mut inherent_overlap_checker = InherentOverlapChecker { tcx }; let mut res = Ok(()); for id in tcx.hir().items() { diff --git a/compiler/rustc_hir_analysis/src/coherence/mod.rs b/compiler/rustc_hir_analysis/src/coherence/mod.rs index 8e4da90ca26..3d800bb165c 100644 --- a/compiler/rustc_hir_analysis/src/coherence/mod.rs +++ b/compiler/rustc_hir_analysis/src/coherence/mod.rs @@ -123,7 +123,7 @@ fn enforce_empty_impls_for_marker_traits( .emit()) } -pub fn provide(providers: &mut Providers) { +pub(crate) fn provide(providers: &mut Providers) { use self::builtin::coerce_unsized_info; use self::inherent_impls::{crate_incoherent_impls, crate_inherent_impls, inherent_impls}; use self::inherent_impls_overlap::crate_inherent_impls_overlap_check; diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index 9e6c431a6e6..3acf2c63145 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -34,7 +34,7 @@ use rustc_infer::traits::ObligationCause; use rustc_middle::hir::nested_filter; use rustc_middle::query::Providers; use rustc_middle::ty::util::{Discr, IntTypeExt}; -use rustc_middle::ty::{self, AdtKind, Const, IsSuggestable, Ty, TyCtxt, Upcast}; +use rustc_middle::ty::{self, AdtKind, Const, IsSuggestable, Ty, TyCtxt}; use rustc_middle::{bug, span_bug}; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::{Span, DUMMY_SP}; @@ -70,7 +70,6 @@ pub fn provide(providers: &mut Providers) { impl_super_outlives: item_bounds::impl_super_outlives, generics_of: generics_of::generics_of, predicates_of: predicates_of::predicates_of, - predicates_defined_on, explicit_predicates_of: predicates_of::explicit_predicates_of, explicit_super_predicates_of: predicates_of::explicit_super_predicates_of, explicit_implied_predicates_of: predicates_of::explicit_implied_predicates_of, @@ -1775,34 +1774,6 @@ fn early_bound_lifetimes_from_generics<'a, 'tcx: 'a>( }) } -/// Returns a list of type predicates for the definition with ID `def_id`, including inferred -/// lifetime constraints. This includes all predicates returned by `explicit_predicates_of`, plus -/// inferred constraints concerning which regions outlive other regions. -#[instrument(level = "debug", skip(tcx))] -fn predicates_defined_on(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> { - let mut result = tcx.explicit_predicates_of(def_id); - debug!("predicates_defined_on: explicit_predicates_of({:?}) = {:?}", def_id, result); - let inferred_outlives = tcx.inferred_outlives_of(def_id); - if !inferred_outlives.is_empty() { - debug!( - "predicates_defined_on: inferred_outlives_of({:?}) = {:?}", - def_id, inferred_outlives, - ); - let inferred_outlives_iter = - inferred_outlives.iter().map(|(clause, span)| ((*clause).upcast(tcx), *span)); - if result.predicates.is_empty() { - result.predicates = tcx.arena.alloc_from_iter(inferred_outlives_iter); - } else { - result.predicates = tcx.arena.alloc_from_iter( - result.predicates.into_iter().copied().chain(inferred_outlives_iter), - ); - } - } - - debug!("predicates_defined_on({:?}) = {:?}", def_id, result); - result -} - fn compute_sig_of_foreign_fn_decl<'tcx>( tcx: TyCtxt<'tcx>, def_id: LocalDefId, diff --git a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs index 6ac4802b195..bba8b0497be 100644 --- a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs @@ -18,10 +18,26 @@ use crate::delegation::inherit_predicates_for_delegation_item; use crate::hir_ty_lowering::{HirTyLowerer, OnlySelfBounds, PredicateFilter, RegionInferReason}; /// Returns a list of all type predicates (explicit and implicit) for the definition with -/// ID `def_id`. This includes all predicates returned by `predicates_defined_on`, plus -/// `Self: Trait` predicates for traits. +/// ID `def_id`. This includes all predicates returned by `explicit_predicates_of`, plus +/// inferred constraints concerning which regions outlive other regions. +#[instrument(level = "debug", skip(tcx))] pub(super) fn predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredicates<'_> { - let mut result = tcx.predicates_defined_on(def_id); + let mut result = tcx.explicit_predicates_of(def_id); + debug!("predicates_of: explicit_predicates_of({:?}) = {:?}", def_id, result); + + let inferred_outlives = tcx.inferred_outlives_of(def_id); + if !inferred_outlives.is_empty() { + debug!("predicates_of: inferred_outlives_of({:?}) = {:?}", def_id, inferred_outlives,); + let inferred_outlives_iter = + inferred_outlives.iter().map(|(clause, span)| ((*clause).upcast(tcx), *span)); + if result.predicates.is_empty() { + result.predicates = tcx.arena.alloc_from_iter(inferred_outlives_iter); + } else { + result.predicates = tcx.arena.alloc_from_iter( + result.predicates.into_iter().copied().chain(inferred_outlives_iter), + ); + } + } if tcx.is_trait(def_id) { // For traits, add `Self: Trait` predicate. This is @@ -51,7 +67,8 @@ pub(super) fn predicates_of(tcx: TyCtxt<'_>, def_id: DefId) -> ty::GenericPredic .chain(std::iter::once((ty::TraitRef::identity(tcx, def_id).upcast(tcx), span))), ); } - debug!("predicates_of(def_id={:?}) = {:?}", def_id, result); + + debug!("predicates_of({:?}) = {:?}", def_id, result); result } diff --git a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs index 0cf9e128bce..e38492d9e64 100644 --- a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs +++ b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs @@ -2071,7 +2071,7 @@ fn is_late_bound_map( } } -pub fn deny_non_region_late_bound( +fn deny_non_region_late_bound( tcx: TyCtxt<'_>, bound_vars: &mut FxIndexMap<LocalDefId, ResolvedArg>, where_: &str, diff --git a/compiler/rustc_hir_analysis/src/collect/type_of.rs b/compiler/rustc_hir_analysis/src/collect/type_of.rs index 8cb4ba6c669..96256b91b9f 100644 --- a/compiler/rustc_hir_analysis/src/collect/type_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/type_of.rs @@ -725,7 +725,7 @@ fn check_feature_inherent_assoc_ty(tcx: TyCtxt<'_>, span: Span) { } } -pub fn type_alias_is_lazy<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> bool { +pub(crate) fn type_alias_is_lazy<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> bool { use hir::intravisit::Visitor; if tcx.features().lazy_type_alias { return true; diff --git a/compiler/rustc_hir_analysis/src/constrained_generic_params.rs b/compiler/rustc_hir_analysis/src/constrained_generic_params.rs index 620170164f5..edf65245664 100644 --- a/compiler/rustc_hir_analysis/src/constrained_generic_params.rs +++ b/compiler/rustc_hir_analysis/src/constrained_generic_params.rs @@ -6,7 +6,7 @@ use rustc_span::Span; use rustc_type_ir::fold::TypeFoldable; #[derive(Clone, PartialEq, Eq, Hash, Debug)] -pub struct Parameter(pub u32); +pub(crate) struct Parameter(pub u32); impl From<ty::ParamTy> for Parameter { fn from(param: ty::ParamTy) -> Self { @@ -27,7 +27,7 @@ impl From<ty::ParamConst> for Parameter { } /// Returns the set of parameters constrained by the impl header. -pub fn parameters_for_impl<'tcx>( +pub(crate) fn parameters_for_impl<'tcx>( tcx: TyCtxt<'tcx>, impl_self_ty: Ty<'tcx>, impl_trait_ref: Option<ty::TraitRef<'tcx>>, @@ -44,7 +44,7 @@ pub fn parameters_for_impl<'tcx>( /// uniquely determined by `value` (see RFC 447). If it is true, return the list /// of parameters whose values are needed in order to constrain `value` - these /// differ, with the latter being a superset, in the presence of projections. -pub fn parameters_for<'tcx>( +pub(crate) fn parameters_for<'tcx>( tcx: TyCtxt<'tcx>, value: impl TypeFoldable<TyCtxt<'tcx>>, include_nonconstraining: bool, @@ -102,7 +102,7 @@ impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ParameterCollector { } } -pub fn identify_constrained_generic_params<'tcx>( +pub(crate) fn identify_constrained_generic_params<'tcx>( tcx: TyCtxt<'tcx>, predicates: ty::GenericPredicates<'tcx>, impl_trait_ref: Option<ty::TraitRef<'tcx>>, @@ -156,7 +156,7 @@ pub fn identify_constrained_generic_params<'tcx>( /// which is determined by 1, which requires `U`, that is determined /// by 0. I should probably pick a less tangled example, but I can't /// think of any. -pub fn setup_constraining_predicates<'tcx>( +pub(crate) fn setup_constraining_predicates<'tcx>( tcx: TyCtxt<'tcx>, predicates: &mut [(ty::Clause<'tcx>, Span)], impl_trait_ref: Option<ty::TraitRef<'tcx>>, diff --git a/compiler/rustc_hir_analysis/src/errors.rs b/compiler/rustc_hir_analysis/src/errors.rs index 821f79505f0..39df18ff658 100644 --- a/compiler/rustc_hir_analysis/src/errors.rs +++ b/compiler/rustc_hir_analysis/src/errors.rs @@ -11,15 +11,15 @@ use rustc_span::{Span, Symbol}; use crate::fluent_generated as fluent; mod pattern_types; -pub use pattern_types::*; -pub mod wrong_number_of_generic_args; +pub(crate) use pattern_types::*; +pub(crate) mod wrong_number_of_generic_args; mod precise_captures; pub(crate) use precise_captures::*; #[derive(Diagnostic)] #[diag(hir_analysis_ambiguous_assoc_item)] -pub struct AmbiguousAssocItem<'a> { +pub(crate) struct AmbiguousAssocItem<'a> { #[primary_span] #[label] pub span: Span, @@ -30,7 +30,7 @@ pub struct AmbiguousAssocItem<'a> { #[derive(Diagnostic)] #[diag(hir_analysis_assoc_kind_mismatch)] -pub struct AssocKindMismatch { +pub(crate) struct AssocKindMismatch { #[primary_span] #[label] pub span: Span, @@ -52,7 +52,7 @@ pub struct AssocKindMismatch { hir_analysis_assoc_kind_mismatch_wrap_in_braces_sugg, applicability = "maybe-incorrect" )] -pub struct AssocKindMismatchWrapInBracesSugg { +pub(crate) struct AssocKindMismatchWrapInBracesSugg { #[suggestion_part(code = "{{ ")] pub lo: Span, #[suggestion_part(code = " }}")] @@ -61,7 +61,7 @@ pub struct AssocKindMismatchWrapInBracesSugg { #[derive(Diagnostic)] #[diag(hir_analysis_assoc_item_is_private, code = E0624)] -pub struct AssocItemIsPrivate { +pub(crate) struct AssocItemIsPrivate { #[primary_span] #[label] pub span: Span, @@ -73,7 +73,7 @@ pub struct AssocItemIsPrivate { #[derive(Diagnostic)] #[diag(hir_analysis_assoc_item_not_found, code = E0220)] -pub struct AssocItemNotFound<'a> { +pub(crate) struct AssocItemNotFound<'a> { #[primary_span] pub span: Span, pub assoc_name: Ident, @@ -86,7 +86,7 @@ pub struct AssocItemNotFound<'a> { } #[derive(Subdiagnostic)] -pub enum AssocItemNotFoundLabel<'a> { +pub(crate) enum AssocItemNotFoundLabel<'a> { #[label(hir_analysis_assoc_item_not_found_label)] NotFound { #[primary_span] @@ -105,7 +105,7 @@ pub enum AssocItemNotFoundLabel<'a> { #[derive(Subdiagnostic)] -pub enum AssocItemNotFoundSugg<'a> { +pub(crate) enum AssocItemNotFoundSugg<'a> { #[suggestion( hir_analysis_assoc_item_not_found_similar_sugg, code = "{suggested_name}", @@ -162,7 +162,7 @@ pub enum AssocItemNotFoundSugg<'a> { #[derive(Diagnostic)] #[diag(hir_analysis_unrecognized_atomic_operation, code = E0092)] -pub struct UnrecognizedAtomicOperation<'a> { +pub(crate) struct UnrecognizedAtomicOperation<'a> { #[primary_span] #[label] pub span: Span, @@ -171,7 +171,7 @@ pub struct UnrecognizedAtomicOperation<'a> { #[derive(Diagnostic)] #[diag(hir_analysis_wrong_number_of_generic_arguments_to_intrinsic, code = E0094)] -pub struct WrongNumberOfGenericArgumentsToIntrinsic<'a> { +pub(crate) struct WrongNumberOfGenericArgumentsToIntrinsic<'a> { #[primary_span] #[label] pub span: Span, @@ -183,7 +183,7 @@ pub struct WrongNumberOfGenericArgumentsToIntrinsic<'a> { #[derive(Diagnostic)] #[diag(hir_analysis_unrecognized_intrinsic_function, code = E0093)] #[help] -pub struct UnrecognizedIntrinsicFunction { +pub(crate) struct UnrecognizedIntrinsicFunction { #[primary_span] #[label] pub span: Span, @@ -192,7 +192,7 @@ pub struct UnrecognizedIntrinsicFunction { #[derive(Diagnostic)] #[diag(hir_analysis_lifetimes_or_bounds_mismatch_on_trait, code = E0195)] -pub struct LifetimesOrBoundsMismatchOnTrait { +pub(crate) struct LifetimesOrBoundsMismatchOnTrait { #[primary_span] #[label] pub span: Span, @@ -208,14 +208,14 @@ pub struct LifetimesOrBoundsMismatchOnTrait { #[derive(Diagnostic)] #[diag(hir_analysis_drop_impl_on_wrong_item, code = E0120)] -pub struct DropImplOnWrongItem { +pub(crate) struct DropImplOnWrongItem { #[primary_span] #[label] pub span: Span, } #[derive(Diagnostic)] -pub enum FieldAlreadyDeclared { +pub(crate) enum FieldAlreadyDeclared { #[diag(hir_analysis_field_already_declared, code = E0124)] NotNested { field_name: Symbol, @@ -272,14 +272,14 @@ pub enum FieldAlreadyDeclared { #[derive(Subdiagnostic)] #[help(hir_analysis_field_already_declared_nested_help)] -pub struct FieldAlreadyDeclaredNestedHelp { +pub(crate) struct FieldAlreadyDeclaredNestedHelp { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(hir_analysis_copy_impl_on_type_with_dtor, code = E0184)] -pub struct CopyImplOnTypeWithDtor { +pub(crate) struct CopyImplOnTypeWithDtor { #[primary_span] #[label] pub span: Span, @@ -287,14 +287,14 @@ pub struct CopyImplOnTypeWithDtor { #[derive(Diagnostic)] #[diag(hir_analysis_multiple_relaxed_default_bounds, code = E0203)] -pub struct MultipleRelaxedDefaultBounds { +pub(crate) struct MultipleRelaxedDefaultBounds { #[primary_span] pub spans: Vec<Span>, } #[derive(Diagnostic)] #[diag(hir_analysis_copy_impl_on_non_adt, code = E0206)] -pub struct CopyImplOnNonAdt { +pub(crate) struct CopyImplOnNonAdt { #[primary_span] #[label] pub span: Span, @@ -302,7 +302,7 @@ pub struct CopyImplOnNonAdt { #[derive(Diagnostic)] #[diag(hir_analysis_const_param_ty_impl_on_unsized)] -pub struct ConstParamTyImplOnUnsized { +pub(crate) struct ConstParamTyImplOnUnsized { #[primary_span] #[label] pub span: Span, @@ -310,7 +310,7 @@ pub struct ConstParamTyImplOnUnsized { #[derive(Diagnostic)] #[diag(hir_analysis_const_param_ty_impl_on_non_adt)] -pub struct ConstParamTyImplOnNonAdt { +pub(crate) struct ConstParamTyImplOnNonAdt { #[primary_span] #[label] pub span: Span, @@ -318,7 +318,7 @@ pub struct ConstParamTyImplOnNonAdt { #[derive(Diagnostic)] #[diag(hir_analysis_trait_object_declared_with_no_traits, code = E0224)] -pub struct TraitObjectDeclaredWithNoTraits { +pub(crate) struct TraitObjectDeclaredWithNoTraits { #[primary_span] pub span: Span, #[label(hir_analysis_alias_span)] @@ -327,14 +327,14 @@ pub struct TraitObjectDeclaredWithNoTraits { #[derive(Diagnostic)] #[diag(hir_analysis_ambiguous_lifetime_bound, code = E0227)] -pub struct AmbiguousLifetimeBound { +pub(crate) struct AmbiguousLifetimeBound { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(hir_analysis_assoc_item_constraints_not_allowed_here, code = E0229)] -pub struct AssocItemConstraintsNotAllowedHere { +pub(crate) struct AssocItemConstraintsNotAllowedHere { #[primary_span] #[label] pub span: Span, @@ -383,7 +383,7 @@ pub(crate) struct EscapingBoundVarInTyOfAssocConstBinding<'tcx> { #[derive(Subdiagnostic)] #[help(hir_analysis_parenthesized_fn_trait_expansion)] -pub struct ParenthesizedFnTraitExpansion { +pub(crate) struct ParenthesizedFnTraitExpansion { #[primary_span] pub span: Span, @@ -392,7 +392,7 @@ pub struct ParenthesizedFnTraitExpansion { #[derive(Diagnostic)] #[diag(hir_analysis_typeof_reserved_keyword_used, code = E0516)] -pub struct TypeofReservedKeywordUsed<'tcx> { +pub(crate) struct TypeofReservedKeywordUsed<'tcx> { pub ty: Ty<'tcx>, #[primary_span] #[label] @@ -403,7 +403,7 @@ pub struct TypeofReservedKeywordUsed<'tcx> { #[derive(Diagnostic)] #[diag(hir_analysis_value_of_associated_struct_already_specified, code = E0719)] -pub struct ValueOfAssociatedStructAlreadySpecified { +pub(crate) struct ValueOfAssociatedStructAlreadySpecified { #[primary_span] #[label] pub span: Span, @@ -416,7 +416,7 @@ pub struct ValueOfAssociatedStructAlreadySpecified { #[derive(Diagnostic)] #[diag(hir_analysis_unconstrained_opaque_type)] #[note] -pub struct UnconstrainedOpaqueType { +pub(crate) struct UnconstrainedOpaqueType { #[primary_span] pub span: Span, pub name: Symbol, @@ -426,7 +426,7 @@ pub struct UnconstrainedOpaqueType { #[derive(Diagnostic)] #[diag(hir_analysis_tait_forward_compat)] #[note] -pub struct TaitForwardCompat { +pub(crate) struct TaitForwardCompat { #[primary_span] pub span: Span, #[note] @@ -436,7 +436,7 @@ pub struct TaitForwardCompat { #[derive(Diagnostic)] #[diag(hir_analysis_tait_forward_compat2)] #[note] -pub struct TaitForwardCompat2 { +pub(crate) struct TaitForwardCompat2 { #[primary_span] pub span: Span, #[note(hir_analysis_opaque)] @@ -444,7 +444,7 @@ pub struct TaitForwardCompat2 { pub opaque_type: String, } -pub struct MissingTypeParams { +pub(crate) struct MissingTypeParams { pub span: Span, pub def_span: Span, pub span_snippet: Option<String>, @@ -512,7 +512,7 @@ impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for MissingTypeParams { #[derive(Diagnostic)] #[diag(hir_analysis_manual_implementation, code = E0183)] #[help] -pub struct ManualImplementation { +pub(crate) struct ManualImplementation { #[primary_span] #[label] pub span: Span, @@ -521,14 +521,14 @@ pub struct ManualImplementation { #[derive(Diagnostic)] #[diag(hir_analysis_generic_args_on_overridden_impl)] -pub struct GenericArgsOnOverriddenImpl { +pub(crate) struct GenericArgsOnOverriddenImpl { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(hir_analysis_const_impl_for_non_const_trait)] -pub struct ConstImplForNonConstTrait { +pub(crate) struct ConstImplForNonConstTrait { #[primary_span] pub trait_ref_span: Span, pub trait_name: String, @@ -542,7 +542,7 @@ pub struct ConstImplForNonConstTrait { #[derive(Diagnostic)] #[diag(hir_analysis_const_bound_for_non_const_trait)] -pub struct ConstBoundForNonConstTrait { +pub(crate) struct ConstBoundForNonConstTrait { #[primary_span] pub span: Span, pub modifier: &'static str, @@ -550,7 +550,7 @@ pub struct ConstBoundForNonConstTrait { #[derive(Diagnostic)] #[diag(hir_analysis_self_in_impl_self)] -pub struct SelfInImplSelf { +pub(crate) struct SelfInImplSelf { #[primary_span] pub span: MultiSpan, #[note] @@ -567,7 +567,7 @@ pub(crate) struct LinkageType { #[derive(Diagnostic)] #[help] #[diag(hir_analysis_auto_deref_reached_recursion_limit, code = E0055)] -pub struct AutoDerefReachedRecursionLimit<'a> { +pub(crate) struct AutoDerefReachedRecursionLimit<'a> { #[primary_span] #[label] pub span: Span, @@ -736,7 +736,7 @@ pub(crate) struct InvalidUnionField { #[derive(Diagnostic)] #[diag(hir_analysis_invalid_unnamed_field_ty)] -pub struct InvalidUnnamedFieldTy { +pub(crate) struct InvalidUnnamedFieldTy { #[primary_span] pub span: Span, } @@ -894,7 +894,7 @@ pub(crate) struct SIMDFFIHighlyExperimental { } #[derive(Diagnostic)] -pub enum ImplNotMarkedDefault { +pub(crate) enum ImplNotMarkedDefault { #[diag(hir_analysis_impl_not_marked_default, code = E0520)] #[note] Ok { @@ -1137,7 +1137,7 @@ pub(crate) enum LateBoundInApit { #[derive(LintDiagnostic)] #[diag(hir_analysis_unused_associated_type_bounds)] #[note] -pub struct UnusedAssociatedTypeBounds { +pub(crate) struct UnusedAssociatedTypeBounds { #[suggestion(code = "")] pub span: Span, } @@ -1162,7 +1162,7 @@ pub(crate) struct ReturnPositionImplTraitInTraitRefined<'tcx> { #[derive(Diagnostic)] #[diag(hir_analysis_inherent_ty_outside, code = E0390)] #[help] -pub struct InherentTyOutside { +pub(crate) struct InherentTyOutside { #[primary_span] #[help(hir_analysis_span_help)] pub span: Span, @@ -1170,7 +1170,7 @@ pub struct InherentTyOutside { #[derive(Diagnostic)] #[diag(hir_analysis_coerce_unsized_may, code = E0378)] -pub struct DispatchFromDynCoercion<'a> { +pub(crate) struct DispatchFromDynCoercion<'a> { #[primary_span] pub span: Span, pub trait_name: &'a str, @@ -1182,7 +1182,7 @@ pub struct DispatchFromDynCoercion<'a> { #[derive(Diagnostic)] #[diag(hir_analysis_dispatch_from_dyn_repr, code = E0378)] -pub struct DispatchFromDynRepr { +pub(crate) struct DispatchFromDynRepr { #[primary_span] pub span: Span, } @@ -1190,7 +1190,7 @@ pub struct DispatchFromDynRepr { #[derive(Diagnostic)] #[diag(hir_analysis_inherent_ty_outside_relevant, code = E0390)] #[help] -pub struct InherentTyOutsideRelevant { +pub(crate) struct InherentTyOutsideRelevant { #[primary_span] pub span: Span, #[help(hir_analysis_span_help)] @@ -1200,7 +1200,7 @@ pub struct InherentTyOutsideRelevant { #[derive(Diagnostic)] #[diag(hir_analysis_inherent_ty_outside_new, code = E0116)] #[note] -pub struct InherentTyOutsideNew { +pub(crate) struct InherentTyOutsideNew { #[primary_span] #[label] pub span: Span, @@ -1209,7 +1209,7 @@ pub struct InherentTyOutsideNew { #[derive(Diagnostic)] #[diag(hir_analysis_inherent_ty_outside_primitive, code = E0390)] #[help] -pub struct InherentTyOutsidePrimitive { +pub(crate) struct InherentTyOutsidePrimitive { #[primary_span] pub span: Span, #[help(hir_analysis_span_help)] @@ -1219,7 +1219,7 @@ pub struct InherentTyOutsidePrimitive { #[derive(Diagnostic)] #[diag(hir_analysis_inherent_primitive_ty, code = E0390)] #[help] -pub struct InherentPrimitiveTy<'a> { +pub(crate) struct InherentPrimitiveTy<'a> { #[primary_span] pub span: Span, #[subdiagnostic] @@ -1228,14 +1228,14 @@ pub struct InherentPrimitiveTy<'a> { #[derive(Subdiagnostic)] #[note(hir_analysis_inherent_primitive_ty_note)] -pub struct InherentPrimitiveTyNote<'a> { +pub(crate) struct InherentPrimitiveTyNote<'a> { pub subty: Ty<'a>, } #[derive(Diagnostic)] #[diag(hir_analysis_inherent_dyn, code = E0785)] #[note] -pub struct InherentDyn { +pub(crate) struct InherentDyn { #[primary_span] #[label] pub span: Span, @@ -1244,7 +1244,7 @@ pub struct InherentDyn { #[derive(Diagnostic)] #[diag(hir_analysis_inherent_nominal, code = E0118)] #[note] -pub struct InherentNominal { +pub(crate) struct InherentNominal { #[primary_span] #[label] pub span: Span, @@ -1253,7 +1253,7 @@ pub struct InherentNominal { #[derive(Diagnostic)] #[diag(hir_analysis_dispatch_from_dyn_zst, code = E0378)] #[note] -pub struct DispatchFromDynZST<'a> { +pub(crate) struct DispatchFromDynZST<'a> { #[primary_span] pub span: Span, pub name: Symbol, @@ -1262,7 +1262,7 @@ pub struct DispatchFromDynZST<'a> { #[derive(Diagnostic)] #[diag(hir_analysis_coerce_unsized_may, code = E0378)] -pub struct DispatchFromDynSingle<'a> { +pub(crate) struct DispatchFromDynSingle<'a> { #[primary_span] pub span: Span, pub trait_name: &'a str, @@ -1273,7 +1273,7 @@ pub struct DispatchFromDynSingle<'a> { #[derive(Diagnostic)] #[diag(hir_analysis_dispatch_from_dyn_multi, code = E0378)] #[note] -pub struct DispatchFromDynMulti { +pub(crate) struct DispatchFromDynMulti { #[primary_span] pub span: Span, #[note(hir_analysis_coercions_note)] @@ -1284,7 +1284,7 @@ pub struct DispatchFromDynMulti { #[derive(Diagnostic)] #[diag(hir_analysis_coerce_unsized_may, code = E0376)] -pub struct DispatchFromDynStruct<'a> { +pub(crate) struct DispatchFromDynStruct<'a> { #[primary_span] pub span: Span, pub trait_name: &'a str, @@ -1292,7 +1292,7 @@ pub struct DispatchFromDynStruct<'a> { #[derive(Diagnostic)] #[diag(hir_analysis_coerce_unsized_may, code = E0377)] -pub struct DispatchFromDynSame<'a> { +pub(crate) struct DispatchFromDynSame<'a> { #[primary_span] pub span: Span, pub trait_name: &'a str, @@ -1304,7 +1304,7 @@ pub struct DispatchFromDynSame<'a> { #[derive(Diagnostic)] #[diag(hir_analysis_coerce_unsized_may, code = E0374)] -pub struct CoerceUnsizedOneField<'a> { +pub(crate) struct CoerceUnsizedOneField<'a> { #[primary_span] pub span: Span, pub trait_name: &'a str, @@ -1315,7 +1315,7 @@ pub struct CoerceUnsizedOneField<'a> { #[derive(Diagnostic)] #[diag(hir_analysis_coerce_unsized_multi, code = E0375)] #[note] -pub struct CoerceUnsizedMulti { +pub(crate) struct CoerceUnsizedMulti { #[primary_span] #[label] pub span: Span, @@ -1327,7 +1327,7 @@ pub struct CoerceUnsizedMulti { #[derive(Diagnostic)] #[diag(hir_analysis_coerce_unsized_may, code = E0378)] -pub struct CoerceUnsizedMay<'a> { +pub(crate) struct CoerceUnsizedMay<'a> { #[primary_span] pub span: Span, pub trait_name: &'a str, @@ -1335,7 +1335,7 @@ pub struct CoerceUnsizedMay<'a> { #[derive(Diagnostic)] #[diag(hir_analysis_trait_cannot_impl_for_ty, code = E0204)] -pub struct TraitCannotImplForTy { +pub(crate) struct TraitCannotImplForTy { #[primary_span] pub span: Span, pub trait_name: String, @@ -1347,7 +1347,7 @@ pub struct TraitCannotImplForTy { #[derive(Subdiagnostic)] #[note(hir_analysis_requires_note)] -pub struct ImplForTyRequires { +pub(crate) struct ImplForTyRequires { #[primary_span] pub span: MultiSpan, pub error_predicate: String, @@ -1358,7 +1358,7 @@ pub struct ImplForTyRequires { #[derive(Diagnostic)] #[diag(hir_analysis_traits_with_defualt_impl, code = E0321)] #[note] -pub struct TraitsWithDefaultImpl<'a> { +pub(crate) struct TraitsWithDefaultImpl<'a> { #[primary_span] pub span: Span, pub traits: String, @@ -1368,7 +1368,7 @@ pub struct TraitsWithDefaultImpl<'a> { #[derive(Diagnostic)] #[diag(hir_analysis_cross_crate_traits, code = E0321)] -pub struct CrossCrateTraits<'a> { +pub(crate) struct CrossCrateTraits<'a> { #[primary_span] #[label] pub span: Span, @@ -1378,7 +1378,7 @@ pub struct CrossCrateTraits<'a> { #[derive(Diagnostic)] #[diag(hir_analysis_cross_crate_traits_defined, code = E0321)] -pub struct CrossCrateTraitsDefined { +pub(crate) struct CrossCrateTraitsDefined { #[primary_span] #[label] pub span: Span, @@ -1390,7 +1390,7 @@ pub struct CrossCrateTraitsDefined { #[derive(Diagnostic)] #[diag(hir_analysis_ty_param_first_local, code = E0210)] #[note] -pub struct TyParamFirstLocal<'tcx> { +pub(crate) struct TyParamFirstLocal<'tcx> { #[primary_span] #[label] pub span: Span, @@ -1403,7 +1403,7 @@ pub struct TyParamFirstLocal<'tcx> { #[derive(LintDiagnostic)] #[diag(hir_analysis_ty_param_first_local, code = E0210)] #[note] -pub struct TyParamFirstLocalLint<'tcx> { +pub(crate) struct TyParamFirstLocalLint<'tcx> { #[label] pub span: Span, #[note(hir_analysis_case_note)] @@ -1415,7 +1415,7 @@ pub struct TyParamFirstLocalLint<'tcx> { #[derive(Diagnostic)] #[diag(hir_analysis_ty_param_some, code = E0210)] #[note] -pub struct TyParamSome { +pub(crate) struct TyParamSome { #[primary_span] #[label] pub span: Span, @@ -1427,7 +1427,7 @@ pub struct TyParamSome { #[derive(LintDiagnostic)] #[diag(hir_analysis_ty_param_some, code = E0210)] #[note] -pub struct TyParamSomeLint { +pub(crate) struct TyParamSomeLint { #[label] pub span: Span, #[note(hir_analysis_only_note)] @@ -1436,7 +1436,7 @@ pub struct TyParamSomeLint { } #[derive(Diagnostic)] -pub enum OnlyCurrentTraits { +pub(crate) enum OnlyCurrentTraits { #[diag(hir_analysis_only_current_traits_outside, code = E0117)] Outside { #[primary_span] @@ -1465,20 +1465,20 @@ pub enum OnlyCurrentTraits { #[derive(Subdiagnostic)] #[label(hir_analysis_only_current_traits_opaque)] -pub struct OnlyCurrentTraitsOpaque { +pub(crate) struct OnlyCurrentTraitsOpaque { #[primary_span] pub span: Span, } #[derive(Subdiagnostic)] #[label(hir_analysis_only_current_traits_foreign)] -pub struct OnlyCurrentTraitsForeign { +pub(crate) struct OnlyCurrentTraitsForeign { #[primary_span] pub span: Span, } #[derive(Subdiagnostic)] #[label(hir_analysis_only_current_traits_name)] -pub struct OnlyCurrentTraitsName<'a> { +pub(crate) struct OnlyCurrentTraitsName<'a> { #[primary_span] pub span: Span, pub name: &'a str, @@ -1486,7 +1486,7 @@ pub struct OnlyCurrentTraitsName<'a> { #[derive(Subdiagnostic)] #[label(hir_analysis_only_current_traits_pointer)] -pub struct OnlyCurrentTraitsPointer<'a> { +pub(crate) struct OnlyCurrentTraitsPointer<'a> { #[primary_span] pub span: Span, pub pointer: Ty<'a>, @@ -1494,7 +1494,7 @@ pub struct OnlyCurrentTraitsPointer<'a> { #[derive(Subdiagnostic)] #[label(hir_analysis_only_current_traits_ty)] -pub struct OnlyCurrentTraitsTy<'a> { +pub(crate) struct OnlyCurrentTraitsTy<'a> { #[primary_span] pub span: Span, pub ty: Ty<'a>, @@ -1502,7 +1502,7 @@ pub struct OnlyCurrentTraitsTy<'a> { #[derive(Subdiagnostic)] #[label(hir_analysis_only_current_traits_adt)] -pub struct OnlyCurrentTraitsAdt { +pub(crate) struct OnlyCurrentTraitsAdt { #[primary_span] pub span: Span, pub name: String, @@ -1513,11 +1513,11 @@ pub struct OnlyCurrentTraitsAdt { hir_analysis_only_current_traits_pointer_sugg, applicability = "maybe-incorrect" )] -pub struct OnlyCurrentTraitsPointerSugg<'a> { +pub(crate) struct OnlyCurrentTraitsPointerSugg<'a> { #[suggestion_part(code = "WrapperType")] pub wrapper_span: Span, #[suggestion_part(code = "struct WrapperType(*{mut_key}{ptr_ty});\n\n")] - pub struct_span: Span, + pub(crate) struct_span: Span, pub mut_key: &'a str, pub ptr_ty: Ty<'a>, } @@ -1525,7 +1525,7 @@ pub struct OnlyCurrentTraitsPointerSugg<'a> { #[derive(Diagnostic)] #[diag(hir_analysis_static_mut_ref, code = E0796)] #[note] -pub struct StaticMutRef<'a> { +pub(crate) struct StaticMutRef<'a> { #[primary_span] #[label] pub span: Span, @@ -1535,7 +1535,7 @@ pub struct StaticMutRef<'a> { } #[derive(Subdiagnostic)] -pub enum MutRefSugg { +pub(crate) enum MutRefSugg { #[multipart_suggestion( hir_analysis_suggestion, style = "verbose", @@ -1565,7 +1565,7 @@ pub enum MutRefSugg { #[diag(hir_analysis_static_mut_refs_lint)] #[note] #[note(hir_analysis_why_note)] -pub struct RefOfMutStatic<'a> { +pub(crate) struct RefOfMutStatic<'a> { #[label] pub span: Span, #[subdiagnostic] @@ -1575,7 +1575,7 @@ pub struct RefOfMutStatic<'a> { #[derive(Diagnostic)] #[diag(hir_analysis_not_supported_delegation)] -pub struct UnsupportedDelegation<'a> { +pub(crate) struct UnsupportedDelegation<'a> { #[primary_span] pub span: Span, pub descr: &'a str, @@ -1585,7 +1585,7 @@ pub struct UnsupportedDelegation<'a> { #[derive(Diagnostic)] #[diag(hir_analysis_method_should_return_future)] -pub struct MethodShouldReturnFuture { +pub(crate) struct MethodShouldReturnFuture { #[primary_span] pub span: Span, pub method_name: Symbol, @@ -1649,7 +1649,7 @@ pub(crate) struct UnconstrainedGenericParameter { } #[derive(Diagnostic)] -pub enum UnnamedFieldsRepr<'a> { +pub(crate) enum UnnamedFieldsRepr<'a> { #[diag(hir_analysis_unnamed_fields_repr_missing_repr_c)] MissingReprC { #[primary_span] @@ -1678,14 +1678,14 @@ pub enum UnnamedFieldsRepr<'a> { #[derive(Subdiagnostic)] #[note(hir_analysis_unnamed_fields_repr_field_defined)] -pub struct UnnamedFieldsReprFieldDefined { +pub(crate) struct UnnamedFieldsReprFieldDefined { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(hir_analysis_opaque_captures_higher_ranked_lifetime, code = E0657)] -pub struct OpaqueCapturesHigherRankedLifetime { +pub(crate) struct OpaqueCapturesHigherRankedLifetime { #[primary_span] pub span: Span, #[label] @@ -1697,7 +1697,7 @@ pub struct OpaqueCapturesHigherRankedLifetime { #[derive(Diagnostic)] #[diag(hir_analysis_pattern_type_non_const_range)] -pub struct NonConstRange { +pub(crate) struct NonConstRange { #[primary_span] pub span: Span, } @@ -1706,7 +1706,7 @@ pub struct NonConstRange { #[diag(hir_analysis_invalid_receiver_ty, code = E0307)] #[note] #[help(hir_analysis_invalid_receiver_ty_help)] -pub struct InvalidReceiverTy<'tcx> { +pub(crate) struct InvalidReceiverTy<'tcx> { #[primary_span] pub span: Span, pub receiver_ty: Ty<'tcx>, @@ -1716,12 +1716,12 @@ pub struct InvalidReceiverTy<'tcx> { #[diag(hir_analysis_effects_without_next_solver)] #[note] #[help] -pub struct EffectsWithoutNextSolver; +pub(crate) struct EffectsWithoutNextSolver; #[derive(Diagnostic)] #[diag(hir_analysis_cmse_call_inputs_stack_spill, code = E0798)] #[note] -pub struct CmseCallInputsStackSpill { +pub(crate) struct CmseCallInputsStackSpill { #[primary_span] #[label] pub span: Span, @@ -1732,7 +1732,7 @@ pub struct CmseCallInputsStackSpill { #[diag(hir_analysis_cmse_call_output_stack_spill, code = E0798)] #[note(hir_analysis_note1)] #[note(hir_analysis_note2)] -pub struct CmseCallOutputStackSpill { +pub(crate) struct CmseCallOutputStackSpill { #[primary_span] #[label] pub span: Span, @@ -1740,7 +1740,7 @@ pub struct CmseCallOutputStackSpill { #[derive(Diagnostic)] #[diag(hir_analysis_cmse_call_generic, code = E0798)] -pub struct CmseCallGeneric { +pub(crate) struct CmseCallGeneric { #[primary_span] pub span: Span, } diff --git a/compiler/rustc_hir_analysis/src/errors/pattern_types.rs b/compiler/rustc_hir_analysis/src/errors/pattern_types.rs index 008d2698989..bb771d6ea17 100644 --- a/compiler/rustc_hir_analysis/src/errors/pattern_types.rs +++ b/compiler/rustc_hir_analysis/src/errors/pattern_types.rs @@ -3,7 +3,7 @@ use rustc_span::Span; #[derive(Diagnostic)] #[diag(hir_analysis_pattern_type_wild_pat)] -pub struct WildPatTy { +pub(crate) struct WildPatTy { #[primary_span] pub span: Span, } diff --git a/compiler/rustc_hir_analysis/src/errors/precise_captures.rs b/compiler/rustc_hir_analysis/src/errors/precise_captures.rs index 8a9b5fe6369..af2bb053c0a 100644 --- a/compiler/rustc_hir_analysis/src/errors/precise_captures.rs +++ b/compiler/rustc_hir_analysis/src/errors/precise_captures.rs @@ -4,7 +4,7 @@ use rustc_span::{Span, Symbol}; #[derive(Diagnostic)] #[diag(hir_analysis_param_not_captured)] #[note] -pub struct ParamNotCaptured { +pub(crate) struct ParamNotCaptured { #[primary_span] pub opaque_span: Span, #[label] @@ -15,7 +15,7 @@ pub struct ParamNotCaptured { #[derive(Diagnostic)] #[diag(hir_analysis_self_ty_not_captured)] #[note] -pub struct SelfTyNotCaptured { +pub(crate) struct SelfTyNotCaptured { #[primary_span] pub opaque_span: Span, #[label] @@ -24,7 +24,7 @@ pub struct SelfTyNotCaptured { #[derive(Diagnostic)] #[diag(hir_analysis_lifetime_not_captured)] -pub struct LifetimeNotCaptured { +pub(crate) struct LifetimeNotCaptured { #[primary_span] pub use_span: Span, #[label(hir_analysis_param_label)] @@ -35,7 +35,7 @@ pub struct LifetimeNotCaptured { #[derive(Diagnostic)] #[diag(hir_analysis_bad_precise_capture)] -pub struct BadPreciseCapture { +pub(crate) struct BadPreciseCapture { #[primary_span] pub span: Span, pub kind: &'static str, @@ -44,7 +44,7 @@ pub struct BadPreciseCapture { #[derive(Diagnostic)] #[diag(hir_analysis_precise_capture_self_alias)] -pub struct PreciseCaptureSelfAlias { +pub(crate) struct PreciseCaptureSelfAlias { #[primary_span] pub span: Span, #[label] @@ -54,7 +54,7 @@ pub struct PreciseCaptureSelfAlias { #[derive(Diagnostic)] #[diag(hir_analysis_duplicate_precise_capture)] -pub struct DuplicatePreciseCapture { +pub(crate) struct DuplicatePreciseCapture { #[primary_span] pub first_span: Span, pub name: Symbol, @@ -64,7 +64,7 @@ pub struct DuplicatePreciseCapture { #[derive(Diagnostic)] #[diag(hir_analysis_lifetime_must_be_first)] -pub struct LifetimesMustBeFirst { +pub(crate) struct LifetimesMustBeFirst { #[primary_span] pub lifetime_span: Span, pub name: Symbol, diff --git a/compiler/rustc_hir_analysis/src/errors/wrong_number_of_generic_args.rs b/compiler/rustc_hir_analysis/src/errors/wrong_number_of_generic_args.rs index 8ecf53bfacb..f8b2469dfea 100644 --- a/compiler/rustc_hir_analysis/src/errors/wrong_number_of_generic_args.rs +++ b/compiler/rustc_hir_analysis/src/errors/wrong_number_of_generic_args.rs @@ -8,7 +8,7 @@ use rustc_span::def_id::DefId; use GenericArgsInfo::*; /// Handles the `wrong number of type / lifetime / ... arguments` family of error messages. -pub struct WrongNumberOfGenericArgs<'a, 'tcx> { +pub(crate) struct WrongNumberOfGenericArgs<'a, 'tcx> { pub(crate) tcx: TyCtxt<'tcx>, pub(crate) angle_brackets: AngleBrackets, @@ -49,7 +49,7 @@ pub(crate) enum AngleBrackets { // Information about the kind of arguments that are either missing or are unexpected #[derive(Debug)] -pub enum GenericArgsInfo { +pub(crate) enum GenericArgsInfo { MissingLifetimes { num_missing_args: usize, }, @@ -87,7 +87,7 @@ pub enum GenericArgsInfo { } impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> { - pub fn new( + pub(crate) fn new( tcx: TyCtxt<'tcx>, gen_args_info: GenericArgsInfo, path_segment: &'a hir::PathSegment<'_>, diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/cmse.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/cmse.rs index e99717ce00f..1b73cecd666 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/cmse.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/cmse.rs @@ -11,7 +11,7 @@ use crate::errors; /// Check conditions on inputs and outputs that the cmse ABIs impose: arguments and results MUST be /// returned via registers (i.e. MUST NOT spill to the stack). LLVM will also validate these /// conditions, but by checking them here rustc can emit nicer error messages. -pub fn validate_cmse_abi<'tcx>( +pub(crate) fn validate_cmse_abi<'tcx>( tcx: TyCtxt<'tcx>, dcx: DiagCtxtHandle<'_>, hir_id: HirId, diff --git a/compiler/rustc_hir_analysis/src/hir_wf_check.rs b/compiler/rustc_hir_analysis/src/hir_wf_check.rs index 7d2cabd3f2c..3ecf61501f6 100644 --- a/compiler/rustc_hir_analysis/src/hir_wf_check.rs +++ b/compiler/rustc_hir_analysis/src/hir_wf_check.rs @@ -11,7 +11,7 @@ use rustc_trait_selection::traits::{self, ObligationCtxt}; use crate::collect::ItemCtxt; -pub fn provide(providers: &mut Providers) { +pub(crate) fn provide(providers: &mut Providers) { *providers = Providers { diagnostic_hir_wf_check, ..*providers }; } diff --git a/compiler/rustc_hir_analysis/src/impl_wf_check.rs b/compiler/rustc_hir_analysis/src/impl_wf_check.rs index 02520c472b9..7f183324f04 100644 --- a/compiler/rustc_hir_analysis/src/impl_wf_check.rs +++ b/compiler/rustc_hir_analysis/src/impl_wf_check.rs @@ -53,7 +53,10 @@ mod min_specialization; /// impl<'a> Trait<Foo> for Bar { type X = &'a i32; } /// // ^ 'a is unused and appears in assoc type, error /// ``` -pub fn check_impl_wf(tcx: TyCtxt<'_>, impl_def_id: LocalDefId) -> Result<(), ErrorGuaranteed> { +pub(crate) fn check_impl_wf( + tcx: TyCtxt<'_>, + impl_def_id: LocalDefId, +) -> Result<(), ErrorGuaranteed> { let min_specialization = tcx.features().min_specialization; let mut res = Ok(()); debug_assert_matches!(tcx.def_kind(impl_def_id), DefKind::Impl { .. }); diff --git a/compiler/rustc_hir_analysis/src/lib.rs b/compiler/rustc_hir_analysis/src/lib.rs index 291d57f2a17..891e4fcd019 100644 --- a/compiler/rustc_hir_analysis/src/lib.rs +++ b/compiler/rustc_hir_analysis/src/lib.rs @@ -72,6 +72,7 @@ This API is completely unstable and subject to change. #![feature(slice_partition_dedup)] #![feature(try_blocks)] #![feature(unwrap_infallible)] +#![warn(unreachable_pub)] // tidy-alphabetical-end #[macro_use] @@ -200,10 +201,6 @@ pub fn check_crate(tcx: TyCtxt<'_>) { } }); - // Freeze definitions as we don't add new ones at this point. This improves performance by - // allowing lock-free access to them. - tcx.untracked().definitions.freeze(); - // FIXME: Remove this when we implement creating `DefId`s // for anon constants during their parents' typeck. // Typeck all body owners in parallel will produce queries diff --git a/compiler/rustc_hir_analysis/src/outlives/explicit.rs b/compiler/rustc_hir_analysis/src/outlives/explicit.rs index bbfadbb5c30..f576499ecac 100644 --- a/compiler/rustc_hir_analysis/src/outlives/explicit.rs +++ b/compiler/rustc_hir_analysis/src/outlives/explicit.rs @@ -5,12 +5,12 @@ use rustc_middle::ty::{self, OutlivesPredicate, TyCtxt}; use super::utils::*; #[derive(Debug)] -pub struct ExplicitPredicatesMap<'tcx> { +pub(crate) struct ExplicitPredicatesMap<'tcx> { map: FxIndexMap<DefId, ty::EarlyBinder<'tcx, RequiredPredicates<'tcx>>>, } impl<'tcx> ExplicitPredicatesMap<'tcx> { - pub fn new() -> ExplicitPredicatesMap<'tcx> { + pub(crate) fn new() -> ExplicitPredicatesMap<'tcx> { ExplicitPredicatesMap { map: FxIndexMap::default() } } diff --git a/compiler/rustc_hir_analysis/src/outlives/mod.rs b/compiler/rustc_hir_analysis/src/outlives/mod.rs index cb61ef7c64d..e3cdb1bf5f7 100644 --- a/compiler/rustc_hir_analysis/src/outlives/mod.rs +++ b/compiler/rustc_hir_analysis/src/outlives/mod.rs @@ -9,7 +9,7 @@ mod explicit; mod implicit_infer; mod utils; -pub fn provide(providers: &mut Providers) { +pub(crate) fn provide(providers: &mut Providers) { *providers = Providers { inferred_outlives_of, inferred_outlives_crate, ..*providers }; } diff --git a/compiler/rustc_hir_analysis/src/variance/constraints.rs b/compiler/rustc_hir_analysis/src/variance/constraints.rs index ce9e73bf245..4fb7a02f8c9 100644 --- a/compiler/rustc_hir_analysis/src/variance/constraints.rs +++ b/compiler/rustc_hir_analysis/src/variance/constraints.rs @@ -12,7 +12,7 @@ use rustc_middle::{bug, span_bug}; use super::terms::VarianceTerm::*; use super::terms::*; -pub struct ConstraintContext<'a, 'tcx> { +pub(crate) struct ConstraintContext<'a, 'tcx> { pub terms_cx: TermsContext<'a, 'tcx>, // These are pointers to common `ConstantTerm` instances @@ -27,7 +27,7 @@ pub struct ConstraintContext<'a, 'tcx> { /// Declares that the variable `decl_id` appears in a location with /// variance `variance`. #[derive(Copy, Clone)] -pub struct Constraint<'a> { +pub(crate) struct Constraint<'a> { pub inferred: InferredIndex, pub variance: &'a VarianceTerm<'a>, } @@ -41,11 +41,11 @@ pub struct Constraint<'a> { /// ``` /// then while we are visiting `Bar<T>`, the `CurrentItem` would have /// the `DefId` and the start of `Foo`'s inferreds. -pub struct CurrentItem { +struct CurrentItem { inferred_start: InferredIndex, } -pub fn add_constraints_from_crate<'a, 'tcx>( +pub(crate) fn add_constraints_from_crate<'a, 'tcx>( terms_cx: TermsContext<'a, 'tcx>, ) -> ConstraintContext<'a, 'tcx> { let tcx = terms_cx.tcx; diff --git a/compiler/rustc_hir_analysis/src/variance/mod.rs b/compiler/rustc_hir_analysis/src/variance/mod.rs index 8a4114c3e4b..e8e2caf7e62 100644 --- a/compiler/rustc_hir_analysis/src/variance/mod.rs +++ b/compiler/rustc_hir_analysis/src/variance/mod.rs @@ -28,7 +28,7 @@ pub(crate) mod dump; /// Code for transforming variances. mod xform; -pub fn provide(providers: &mut Providers) { +pub(crate) fn provide(providers: &mut Providers) { *providers = Providers { variances_of, crate_variances, ..*providers }; } diff --git a/compiler/rustc_hir_analysis/src/variance/solve.rs b/compiler/rustc_hir_analysis/src/variance/solve.rs index e64c6721fe0..4f1bac17e71 100644 --- a/compiler/rustc_hir_analysis/src/variance/solve.rs +++ b/compiler/rustc_hir_analysis/src/variance/solve.rs @@ -21,7 +21,7 @@ struct SolveContext<'a, 'tcx> { solutions: Vec<ty::Variance>, } -pub fn solve_constraints<'tcx>( +pub(crate) fn solve_constraints<'tcx>( constraints_cx: ConstraintContext<'_, 'tcx>, ) -> ty::CrateVariancesMap<'tcx> { let ConstraintContext { terms_cx, constraints, .. } = constraints_cx; diff --git a/compiler/rustc_hir_analysis/src/variance/terms.rs b/compiler/rustc_hir_analysis/src/variance/terms.rs index 36bff60e019..597699b37b1 100644 --- a/compiler/rustc_hir_analysis/src/variance/terms.rs +++ b/compiler/rustc_hir_analysis/src/variance/terms.rs @@ -18,13 +18,13 @@ use rustc_middle::ty::{self, TyCtxt}; use self::VarianceTerm::*; -pub type VarianceTermPtr<'a> = &'a VarianceTerm<'a>; +pub(crate) type VarianceTermPtr<'a> = &'a VarianceTerm<'a>; #[derive(Copy, Clone, Debug)] -pub struct InferredIndex(pub usize); +pub(crate) struct InferredIndex(pub usize); #[derive(Copy, Clone)] -pub enum VarianceTerm<'a> { +pub(crate) enum VarianceTerm<'a> { ConstantTerm(ty::Variance), TransformTerm(VarianceTermPtr<'a>, VarianceTermPtr<'a>), InferredTerm(InferredIndex), @@ -45,7 +45,7 @@ impl<'a> fmt::Debug for VarianceTerm<'a> { /// The first pass over the crate simply builds up the set of inferreds. -pub struct TermsContext<'a, 'tcx> { +pub(crate) struct TermsContext<'a, 'tcx> { pub tcx: TyCtxt<'tcx>, pub arena: &'a DroplessArena, @@ -62,7 +62,7 @@ pub struct TermsContext<'a, 'tcx> { pub inferred_terms: Vec<VarianceTermPtr<'a>>, } -pub fn determine_parameters_to_be_inferred<'a, 'tcx>( +pub(crate) fn determine_parameters_to_be_inferred<'a, 'tcx>( tcx: TyCtxt<'tcx>, arena: &'a DroplessArena, ) -> TermsContext<'a, 'tcx> { diff --git a/compiler/rustc_hir_analysis/src/variance/xform.rs b/compiler/rustc_hir_analysis/src/variance/xform.rs index 027f0859fcd..2e9964788e6 100644 --- a/compiler/rustc_hir_analysis/src/variance/xform.rs +++ b/compiler/rustc_hir_analysis/src/variance/xform.rs @@ -1,6 +1,6 @@ use rustc_middle::ty; -pub fn glb(v1: ty::Variance, v2: ty::Variance) -> ty::Variance { +pub(crate) fn glb(v1: ty::Variance, v2: ty::Variance) -> ty::Variance { // Greatest lower bound of the variance lattice as // defined in The Paper: // diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index cff21173f79..ac6707f9316 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -3,6 +3,7 @@ // tidy-alphabetical-start #![recursion_limit = "256"] +#![warn(unreachable_pub)] // tidy-alphabetical-end use std::cell::Cell; diff --git a/compiler/rustc_hir_typeck/src/_match.rs b/compiler/rustc_hir_typeck/src/_match.rs index bc0ed4a7fa9..7427fb14716 100644 --- a/compiler/rustc_hir_typeck/src/_match.rs +++ b/compiler/rustc_hir_typeck/src/_match.rs @@ -374,7 +374,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - pub fn maybe_get_coercion_reason( + pub(crate) fn maybe_get_coercion_reason( &self, hir_id: hir::HirId, sp: Span, @@ -584,7 +584,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // (e.g. we're in the tail of a function body) // // Returns the `LocalDefId` of the RPIT, which is always identity-substituted. - pub fn return_position_impl_trait_from_match_expectation( + pub(crate) fn return_position_impl_trait_from_match_expectation( &self, expectation: Expectation<'tcx>, ) -> Option<LocalDefId> { diff --git a/compiler/rustc_hir_typeck/src/autoderef.rs b/compiler/rustc_hir_typeck/src/autoderef.rs index 69c4889d7a4..d2d6da8f32b 100644 --- a/compiler/rustc_hir_typeck/src/autoderef.rs +++ b/compiler/rustc_hir_typeck/src/autoderef.rs @@ -13,11 +13,11 @@ use super::method::MethodCallee; use super::{FnCtxt, PlaceOp}; impl<'a, 'tcx> FnCtxt<'a, 'tcx> { - pub fn autoderef(&'a self, span: Span, base_ty: Ty<'tcx>) -> Autoderef<'a, 'tcx> { + pub(crate) fn autoderef(&'a self, span: Span, base_ty: Ty<'tcx>) -> Autoderef<'a, 'tcx> { Autoderef::new(self, self.param_env, self.body_id, span, base_ty) } - pub fn try_overloaded_deref( + pub(crate) fn try_overloaded_deref( &self, span: Span, base_ty: Ty<'tcx>, @@ -26,11 +26,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } /// Returns the adjustment steps. - pub fn adjust_steps(&self, autoderef: &Autoderef<'a, 'tcx>) -> Vec<Adjustment<'tcx>> { + pub(crate) fn adjust_steps(&self, autoderef: &Autoderef<'a, 'tcx>) -> Vec<Adjustment<'tcx>> { self.register_infer_ok_obligations(self.adjust_steps_as_infer_ok(autoderef)) } - pub fn adjust_steps_as_infer_ok( + pub(crate) fn adjust_steps_as_infer_ok( &self, autoderef: &Autoderef<'a, 'tcx>, ) -> InferOk<'tcx, Vec<Adjustment<'tcx>>> { diff --git a/compiler/rustc_hir_typeck/src/callee.rs b/compiler/rustc_hir_typeck/src/callee.rs index 44cb08e44eb..fc08b872efc 100644 --- a/compiler/rustc_hir_typeck/src/callee.rs +++ b/compiler/rustc_hir_typeck/src/callee.rs @@ -29,7 +29,7 @@ use crate::errors; /// Checks that it is legal to call methods of the trait corresponding /// to `trait_id` (this only cares about the trait, not the specific /// method that is called). -pub fn check_legal_trait_for_method_call( +pub(crate) fn check_legal_trait_for_method_call( tcx: TyCtxt<'_>, span: Span, receiver: Option<Span>, @@ -62,7 +62,7 @@ enum CallStep<'tcx> { } impl<'a, 'tcx> FnCtxt<'a, 'tcx> { - pub fn check_call( + pub(crate) fn check_call( &self, call_expr: &'tcx hir::Expr<'tcx>, callee_expr: &'tcx hir::Expr<'tcx>, @@ -940,7 +940,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } #[derive(Debug)] -pub struct DeferredCallResolution<'tcx> { +pub(crate) struct DeferredCallResolution<'tcx> { call_expr: &'tcx hir::Expr<'tcx>, callee_expr: &'tcx hir::Expr<'tcx>, closure_ty: Ty<'tcx>, @@ -949,7 +949,7 @@ pub struct DeferredCallResolution<'tcx> { } impl<'a, 'tcx> DeferredCallResolution<'tcx> { - pub fn resolve(self, fcx: &FnCtxt<'a, 'tcx>) { + pub(crate) fn resolve(self, fcx: &FnCtxt<'a, 'tcx>) { debug!("DeferredCallResolution::resolve() {:?}", self); // we should not be invoked until the closure kind has been diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index b47d8a97bce..54ddff98869 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -850,6 +850,8 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { } // Safe `#[target_feature]` functions are not assignable to safe fn pointers (RFC 2396). + // FIXME(struct_target_features): should this be true also for functions that inherit + // target features from structs? if b_hdr.safety == hir::Safety::Safe && !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty() @@ -976,7 +978,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// adjusted type of the expression, if successful. /// Adjustments are only recorded if the coercion succeeded. /// The expressions *must not* have any preexisting adjustments. - pub fn coerce( + pub(crate) fn coerce( &self, expr: &hir::Expr<'_>, expr_ty: Ty<'tcx>, @@ -1011,7 +1013,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// /// Returns false if the coercion creates any obligations that result in /// errors. - pub fn can_coerce(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> bool { + pub(crate) fn can_coerce(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> bool { // FIXME(-Znext-solver): We need to structurally resolve both types here. let source = self.resolve_vars_with_obligations(expr_ty); debug!("coercion::can_with_predicates({:?} -> {:?})", source, target); @@ -1032,7 +1034,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Given a type and a target type, this function will calculate and return /// how many dereference steps needed to achieve `expr_ty <: target`. If /// it's not possible, return `None`. - pub fn deref_steps(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> Option<usize> { + pub(crate) fn deref_steps(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> Option<usize> { let cause = self.cause(DUMMY_SP, ObligationCauseCode::ExprAssignable); // We don't ever need two-phase here since we throw out the result of the coercion let coerce = Coerce::new(self, cause, AllowTwoPhase::No); @@ -1047,7 +1049,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// This function is for diagnostics only, since it does not register /// trait or region sub-obligations. (presumably we could, but it's not /// particularly important for diagnostics...) - pub fn deref_once_mutably_for_diagnostic(&self, expr_ty: Ty<'tcx>) -> Option<Ty<'tcx>> { + pub(crate) fn deref_once_mutably_for_diagnostic(&self, expr_ty: Ty<'tcx>) -> Option<Ty<'tcx>> { self.autoderef(DUMMY_SP, expr_ty).nth(1).and_then(|(deref_ty, _)| { self.infcx .type_implements_trait( @@ -1341,7 +1343,7 @@ pub fn can_coerce<'tcx>( /// } /// let final_ty = coerce.complete(fcx); /// ``` -pub struct CoerceMany<'tcx, 'exprs, E: AsCoercionSite> { +pub(crate) struct CoerceMany<'tcx, 'exprs, E: AsCoercionSite> { expected_ty: Ty<'tcx>, final_ty: Option<Ty<'tcx>>, expressions: Expressions<'tcx, 'exprs, E>, @@ -1350,7 +1352,7 @@ pub struct CoerceMany<'tcx, 'exprs, E: AsCoercionSite> { /// The type of a `CoerceMany` that is storing up the expressions into /// a buffer. We use this in `check/mod.rs` for things like `break`. -pub type DynamicCoerceMany<'tcx> = CoerceMany<'tcx, 'tcx, &'tcx hir::Expr<'tcx>>; +pub(crate) type DynamicCoerceMany<'tcx> = CoerceMany<'tcx, 'tcx, &'tcx hir::Expr<'tcx>>; enum Expressions<'tcx, 'exprs, E: AsCoercionSite> { Dynamic(Vec<&'tcx hir::Expr<'tcx>>), @@ -1361,7 +1363,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { /// The usual case; collect the set of expressions dynamically. /// If the full set of coercion sites is known before hand, /// consider `with_coercion_sites()` instead to avoid allocation. - pub fn new(expected_ty: Ty<'tcx>) -> Self { + pub(crate) fn new(expected_ty: Ty<'tcx>) -> Self { Self::make(expected_ty, Expressions::Dynamic(vec![])) } @@ -1370,7 +1372,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { /// expected to pass each element in the slice to `coerce(...)` in /// order. This is used with arrays in particular to avoid /// needlessly cloning the slice. - pub fn with_coercion_sites(expected_ty: Ty<'tcx>, coercion_sites: &'exprs [E]) -> Self { + pub(crate) fn with_coercion_sites(expected_ty: Ty<'tcx>, coercion_sites: &'exprs [E]) -> Self { Self::make(expected_ty, Expressions::UpFront(coercion_sites)) } @@ -1386,7 +1388,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { /// Typically, this is used as the expected type when /// type-checking each of the alternative expressions whose types /// we are trying to merge. - pub fn expected_ty(&self) -> Ty<'tcx> { + pub(crate) fn expected_ty(&self) -> Ty<'tcx> { self.expected_ty } @@ -1394,7 +1396,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { /// at the LUB of the expressions we've seen so far (if any). This /// isn't *final* until you call `self.complete()`, which will return /// the merged type. - pub fn merged_ty(&self) -> Ty<'tcx> { + pub(crate) fn merged_ty(&self) -> Ty<'tcx> { self.final_ty.unwrap_or(self.expected_ty) } @@ -1403,7 +1405,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { /// could coerce from. This will record `expression`, and later /// calls to `coerce` may come back and add adjustments and things /// if necessary. - pub fn coerce<'a>( + pub(crate) fn coerce<'a>( &mut self, fcx: &FnCtxt<'a, 'tcx>, cause: &ObligationCause<'tcx>, @@ -1425,7 +1427,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { /// The `augment_error` gives you a chance to extend the error /// message, in case any results (e.g., we use this to suggest /// removing a `;`). - pub fn coerce_forced_unit<'a>( + pub(crate) fn coerce_forced_unit<'a>( &mut self, fcx: &FnCtxt<'a, 'tcx>, cause: &ObligationCause<'tcx>, @@ -1920,7 +1922,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { } } - pub fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> { + pub(crate) fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> { if let Some(final_ty) = self.final_ty { final_ty } else { @@ -1934,7 +1936,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { /// Something that can be converted into an expression to which we can /// apply a coercion. -pub trait AsCoercionSite { +pub(crate) trait AsCoercionSite { fn as_coercion_site(&self) -> &hir::Expr<'_>; } diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index 0a9fa5c64a5..89f27e80774 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -18,7 +18,7 @@ use super::method::probe; use crate::FnCtxt; impl<'a, 'tcx> FnCtxt<'a, 'tcx> { - pub fn emit_type_mismatch_suggestions( + pub(crate) fn emit_type_mismatch_suggestions( &self, err: &mut Diag<'_>, expr: &hir::Expr<'tcx>, @@ -70,7 +70,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - pub fn emit_coerce_suggestions( + pub(crate) fn emit_coerce_suggestions( &self, err: &mut Diag<'_>, expr: &hir::Expr<'tcx>, @@ -165,13 +165,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Requires that the two types unify, and prints an error message if /// they don't. - pub fn demand_suptype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) { + pub(crate) fn demand_suptype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) { if let Err(e) = self.demand_suptype_diag(sp, expected, actual) { e.emit(); } } - pub fn demand_suptype_diag( + pub(crate) fn demand_suptype_diag( &'a self, sp: Span, expected: Ty<'tcx>, @@ -193,13 +193,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .map_err(|e| self.err_ctxt().report_mismatched_types(cause, expected, actual, e)) } - pub fn demand_eqtype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) { + pub(crate) fn demand_eqtype(&self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>) { if let Err(err) = self.demand_eqtype_diag(sp, expected, actual) { err.emit(); } } - pub fn demand_eqtype_diag( + pub(crate) fn demand_eqtype_diag( &'a self, sp: Span, expected: Ty<'tcx>, @@ -208,7 +208,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.demand_eqtype_with_origin(&self.misc(sp), expected, actual) } - pub fn demand_eqtype_with_origin( + pub(crate) fn demand_eqtype_with_origin( &'a self, cause: &ObligationCause<'tcx>, expected: Ty<'tcx>, @@ -220,7 +220,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .map_err(|e| self.err_ctxt().report_mismatched_types(cause, expected, actual, e)) } - pub fn demand_coerce( + pub(crate) fn demand_coerce( &self, expr: &'tcx hir::Expr<'tcx>, checked_ty: Ty<'tcx>, @@ -279,7 +279,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Notes the point at which a variable is constrained to some type incompatible /// with some expectation given by `source`. - pub fn note_source_of_type_mismatch_constraint( + pub(crate) fn note_source_of_type_mismatch_constraint( &self, err: &mut Diag<'_>, expr: &hir::Expr<'_>, @@ -558,7 +558,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // When encountering a type error on the value of a `break`, try to point at the reason for the // expected type. - pub fn annotate_loop_expected_due_to_inference( + pub(crate) fn annotate_loop_expected_due_to_inference( &self, err: &mut Diag<'_>, expr: &hir::Expr<'_>, @@ -964,7 +964,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ); } - pub fn get_conversion_methods_for_diagnostic( + pub(crate) fn get_conversion_methods_for_diagnostic( &self, span: Span, expected: Ty<'tcx>, @@ -1186,7 +1186,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } -pub enum TypeMismatchSource<'tcx> { +pub(crate) enum TypeMismatchSource<'tcx> { /// Expected the binding to have the given type, but it was found to have /// a different type. Find out when that type first became incompatible. Ty(Ty<'tcx>), diff --git a/compiler/rustc_hir_typeck/src/diverges.rs b/compiler/rustc_hir_typeck/src/diverges.rs index aa30fb0f0af..3066561a31d 100644 --- a/compiler/rustc_hir_typeck/src/diverges.rs +++ b/compiler/rustc_hir_typeck/src/diverges.rs @@ -8,7 +8,7 @@ use rustc_span::{Span, DUMMY_SP}; /// as diverging), with some manual adjustments for control-flow /// primitives (approximating a CFG). #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] -pub enum Diverges { +pub(crate) enum Diverges { /// Potentially unknown, some cases converge, /// others require a CFG to determine them. Maybe, diff --git a/compiler/rustc_hir_typeck/src/errors.rs b/compiler/rustc_hir_typeck/src/errors.rs index c35f7a84c4f..4d2770d2e50 100644 --- a/compiler/rustc_hir_typeck/src/errors.rs +++ b/compiler/rustc_hir_typeck/src/errors.rs @@ -17,7 +17,7 @@ use crate::fluent_generated as fluent; #[derive(Diagnostic)] #[diag(hir_typeck_field_multiply_specified_in_initializer, code = E0062)] -pub struct FieldMultiplySpecifiedInInitializer { +pub(crate) struct FieldMultiplySpecifiedInInitializer { #[primary_span] #[label] pub span: Span, @@ -28,7 +28,7 @@ pub struct FieldMultiplySpecifiedInInitializer { #[derive(Diagnostic)] #[diag(hir_typeck_return_stmt_outside_of_fn_body, code = E0572)] -pub struct ReturnStmtOutsideOfFnBody { +pub(crate) struct ReturnStmtOutsideOfFnBody { #[primary_span] pub span: Span, #[label(hir_typeck_encl_body_label)] @@ -38,7 +38,7 @@ pub struct ReturnStmtOutsideOfFnBody { pub statement_kind: ReturnLikeStatementKind, } -pub enum ReturnLikeStatementKind { +pub(crate) enum ReturnLikeStatementKind { Return, Become, } @@ -57,21 +57,21 @@ impl IntoDiagArg for ReturnLikeStatementKind { #[derive(Diagnostic)] #[diag(hir_typeck_rustcall_incorrect_args)] -pub struct RustCallIncorrectArgs { +pub(crate) struct RustCallIncorrectArgs { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(hir_typeck_yield_expr_outside_of_coroutine, code = E0627)] -pub struct YieldExprOutsideOfCoroutine { +pub(crate) struct YieldExprOutsideOfCoroutine { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(hir_typeck_struct_expr_non_exhaustive, code = E0639)] -pub struct StructExprNonExhaustive { +pub(crate) struct StructExprNonExhaustive { #[primary_span] pub span: Span, pub what: &'static str, @@ -79,21 +79,21 @@ pub struct StructExprNonExhaustive { #[derive(Diagnostic)] #[diag(hir_typeck_functional_record_update_on_non_struct, code = E0436)] -pub struct FunctionalRecordUpdateOnNonStruct { +pub(crate) struct FunctionalRecordUpdateOnNonStruct { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(hir_typeck_address_of_temporary_taken, code = E0745)] -pub struct AddressOfTemporaryTaken { +pub(crate) struct AddressOfTemporaryTaken { #[primary_span] #[label] pub span: Span, } #[derive(Subdiagnostic)] -pub enum AddReturnTypeSuggestion { +pub(crate) enum AddReturnTypeSuggestion { #[suggestion( hir_typeck_add_return_type_add, code = " -> {found}", @@ -116,7 +116,7 @@ pub enum AddReturnTypeSuggestion { } #[derive(Subdiagnostic)] -pub enum ExpectedReturnTypeLabel<'tcx> { +pub(crate) enum ExpectedReturnTypeLabel<'tcx> { #[label(hir_typeck_expected_default_return_type)] Unit { #[primary_span] @@ -132,7 +132,7 @@ pub enum ExpectedReturnTypeLabel<'tcx> { #[derive(Diagnostic)] #[diag(hir_typeck_explicit_destructor, code = E0040)] -pub struct ExplicitDestructorCall { +pub(crate) struct ExplicitDestructorCall { #[primary_span] #[label] pub span: Span, @@ -141,7 +141,7 @@ pub struct ExplicitDestructorCall { } #[derive(Subdiagnostic)] -pub enum ExplicitDestructorCallSugg { +pub(crate) enum ExplicitDestructorCallSugg { #[suggestion(hir_typeck_suggestion, code = "drop", applicability = "maybe-incorrect")] Empty(#[primary_span] Span), #[multipart_suggestion(hir_typeck_suggestion, style = "short")] @@ -155,7 +155,7 @@ pub enum ExplicitDestructorCallSugg { #[derive(Diagnostic)] #[diag(hir_typeck_missing_parentheses_in_range, code = E0689)] -pub struct MissingParenthesesInRange { +pub(crate) struct MissingParenthesesInRange { #[primary_span] #[label(hir_typeck_missing_parentheses_in_range)] pub span: Span, @@ -166,7 +166,7 @@ pub struct MissingParenthesesInRange { } #[derive(LintDiagnostic)] -pub enum NeverTypeFallbackFlowingIntoUnsafe { +pub(crate) enum NeverTypeFallbackFlowingIntoUnsafe { #[help] #[diag(hir_typeck_never_type_fallback_flowing_into_unsafe_call)] Call, @@ -187,7 +187,7 @@ pub enum NeverTypeFallbackFlowingIntoUnsafe { #[derive(LintDiagnostic)] #[help] #[diag(hir_typeck_dependency_on_unit_never_type_fallback)] -pub struct DependencyOnUnitNeverTypeFallback<'tcx> { +pub(crate) struct DependencyOnUnitNeverTypeFallback<'tcx> { #[note] pub obligation_span: Span, pub obligation: ty::Predicate<'tcx>, @@ -199,7 +199,7 @@ pub struct DependencyOnUnitNeverTypeFallback<'tcx> { style = "verbose", applicability = "maybe-incorrect" )] -pub struct AddMissingParenthesesInRange { +pub(crate) struct AddMissingParenthesesInRange { pub func_name: String, #[suggestion_part(code = "(")] pub left: Span, @@ -207,7 +207,7 @@ pub struct AddMissingParenthesesInRange { pub right: Span, } -pub struct TypeMismatchFruTypo { +pub(crate) struct TypeMismatchFruTypo { /// Span of the LHS of the range pub expr_span: Span, /// Span of the `..RHS` part of the range @@ -246,7 +246,7 @@ impl Subdiagnostic for TypeMismatchFruTypo { #[derive(LintDiagnostic)] #[diag(hir_typeck_lossy_provenance_int2ptr)] #[help] -pub struct LossyProvenanceInt2Ptr<'tcx> { +pub(crate) struct LossyProvenanceInt2Ptr<'tcx> { pub expr_ty: Ty<'tcx>, pub cast_ty: Ty<'tcx>, #[subdiagnostic] @@ -255,14 +255,14 @@ pub struct LossyProvenanceInt2Ptr<'tcx> { #[derive(LintDiagnostic)] #[diag(hir_typeck_ptr_cast_add_auto_to_object)] -pub struct PtrCastAddAutoToObject { +pub(crate) struct PtrCastAddAutoToObject { pub traits_len: usize, pub traits: DiagSymbolList<String>, } #[derive(Subdiagnostic)] #[multipart_suggestion(hir_typeck_suggestion, applicability = "has-placeholders")] -pub struct LossyProvenanceInt2PtrSuggestion { +pub(crate) struct LossyProvenanceInt2PtrSuggestion { #[suggestion_part(code = "(...).with_addr(")] pub lo: Span, #[suggestion_part(code = ")")] @@ -272,7 +272,7 @@ pub struct LossyProvenanceInt2PtrSuggestion { #[derive(LintDiagnostic)] #[diag(hir_typeck_lossy_provenance_ptr2int)] #[help] -pub struct LossyProvenancePtr2Int<'tcx> { +pub(crate) struct LossyProvenancePtr2Int<'tcx> { pub expr_ty: Ty<'tcx>, pub cast_ty: Ty<'tcx>, #[subdiagnostic] @@ -280,7 +280,7 @@ pub struct LossyProvenancePtr2Int<'tcx> { } #[derive(Subdiagnostic)] -pub enum LossyProvenancePtr2IntSuggestion<'tcx> { +pub(crate) enum LossyProvenancePtr2IntSuggestion<'tcx> { #[multipart_suggestion(hir_typeck_suggestion, applicability = "maybe-incorrect")] NeedsParensCast { #[suggestion_part(code = "(")] @@ -314,7 +314,7 @@ pub enum LossyProvenancePtr2IntSuggestion<'tcx> { } #[derive(Subdiagnostic)] -pub enum HelpUseLatestEdition { +pub(crate) enum HelpUseLatestEdition { #[help(hir_typeck_help_set_edition_cargo)] #[note(hir_typeck_note_edition_guide)] Cargo { edition: Edition }, @@ -324,7 +324,7 @@ pub enum HelpUseLatestEdition { } impl HelpUseLatestEdition { - pub fn new() -> Self { + pub(crate) fn new() -> Self { let edition = LATEST_STABLE_EDITION; if rustc_session::utils::was_invoked_from_cargo() { Self::Cargo { edition } @@ -336,7 +336,7 @@ impl HelpUseLatestEdition { #[derive(Diagnostic)] #[diag(hir_typeck_invalid_callee, code = E0618)] -pub struct InvalidCallee { +pub(crate) struct InvalidCallee { #[primary_span] pub span: Span, pub ty: String, @@ -344,7 +344,7 @@ pub struct InvalidCallee { #[derive(Diagnostic)] #[diag(hir_typeck_int_to_fat, code = E0606)] -pub struct IntToWide<'tcx> { +pub(crate) struct IntToWide<'tcx> { #[primary_span] #[label(hir_typeck_int_to_fat_label)] pub span: Span, @@ -357,7 +357,7 @@ pub struct IntToWide<'tcx> { } #[derive(Subdiagnostic)] -pub enum OptionResultRefMismatch { +pub(crate) enum OptionResultRefMismatch { #[suggestion( hir_typeck_option_result_copied, code = ".copied()", @@ -396,7 +396,7 @@ pub enum OptionResultRefMismatch { // }, } -pub struct RemoveSemiForCoerce { +pub(crate) struct RemoveSemiForCoerce { pub expr: Span, pub ret: Span, pub semi: Span, @@ -426,7 +426,7 @@ impl Subdiagnostic for RemoveSemiForCoerce { #[derive(Diagnostic)] #[diag(hir_typeck_const_select_must_be_const)] #[help] -pub struct ConstSelectMustBeConst { +pub(crate) struct ConstSelectMustBeConst { #[primary_span] pub span: Span, } @@ -435,7 +435,7 @@ pub struct ConstSelectMustBeConst { #[diag(hir_typeck_const_select_must_be_fn)] #[note] #[help] -pub struct ConstSelectMustBeFn<'a> { +pub(crate) struct ConstSelectMustBeFn<'a> { #[primary_span] pub span: Span, pub ty: Ty<'a>, @@ -443,14 +443,14 @@ pub struct ConstSelectMustBeFn<'a> { #[derive(Diagnostic)] #[diag(hir_typeck_union_pat_multiple_fields)] -pub struct UnionPatMultipleFields { +pub(crate) struct UnionPatMultipleFields { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(hir_typeck_union_pat_dotdot)] -pub struct UnionPatDotDot { +pub(crate) struct UnionPatDotDot { #[primary_span] pub span: Span, } @@ -461,7 +461,7 @@ pub struct UnionPatDotDot { applicability = "maybe-incorrect", style = "verbose" )] -pub struct UseIsEmpty { +pub(crate) struct UseIsEmpty { #[suggestion_part(code = "!")] pub lo: Span, #[suggestion_part(code = ".is_empty()")] @@ -471,13 +471,13 @@ pub struct UseIsEmpty { #[derive(Diagnostic)] #[diag(hir_typeck_arg_mismatch_indeterminate)] -pub struct ArgMismatchIndeterminate { +pub(crate) struct ArgMismatchIndeterminate { #[primary_span] pub span: Span, } #[derive(Subdiagnostic)] -pub enum SuggestBoxing { +pub(crate) enum SuggestBoxing { #[note(hir_typeck_suggest_boxing_note)] #[multipart_suggestion( hir_typeck_suggest_boxing_when_appropriate, @@ -511,7 +511,7 @@ pub enum SuggestBoxing { style = "verbose", code = "core::ptr::null_mut()" )] -pub struct SuggestPtrNullMut { +pub(crate) struct SuggestPtrNullMut { #[primary_span] pub span: Span, } @@ -519,7 +519,7 @@ pub struct SuggestPtrNullMut { #[derive(LintDiagnostic)] #[diag(hir_typeck_trivial_cast)] #[help] -pub struct TrivialCast<'tcx> { +pub(crate) struct TrivialCast<'tcx> { pub numeric: bool, pub expr_ty: Ty<'tcx>, pub cast_ty: Ty<'tcx>, @@ -527,7 +527,7 @@ pub struct TrivialCast<'tcx> { #[derive(Diagnostic)] #[diag(hir_typeck_no_associated_item, code = E0599)] -pub struct NoAssociatedItem { +pub(crate) struct NoAssociatedItem { #[primary_span] pub span: Span, pub item_kind: &'static str, @@ -539,7 +539,7 @@ pub struct NoAssociatedItem { #[derive(Subdiagnostic)] #[note(hir_typeck_candidate_trait_note)] -pub struct CandidateTraitNote { +pub(crate) struct CandidateTraitNote { #[primary_span] pub span: Span, pub trait_name: String, @@ -549,7 +549,7 @@ pub struct CandidateTraitNote { #[derive(Diagnostic)] #[diag(hir_typeck_cannot_cast_to_bool, code = E0054)] -pub struct CannotCastToBool<'tcx> { +pub(crate) struct CannotCastToBool<'tcx> { #[primary_span] pub span: Span, pub expr_ty: Ty<'tcx>, @@ -559,14 +559,14 @@ pub struct CannotCastToBool<'tcx> { #[derive(LintDiagnostic)] #[diag(hir_typeck_cast_enum_drop)] -pub struct CastEnumDrop<'tcx> { +pub(crate) struct CastEnumDrop<'tcx> { pub expr_ty: Ty<'tcx>, pub cast_ty: Ty<'tcx>, } #[derive(Diagnostic)] #[diag(hir_typeck_cast_unknown_pointer, code = E0641)] -pub struct CastUnknownPointer { +pub(crate) struct CastUnknownPointer { #[primary_span] pub span: Span, pub to: bool, @@ -574,7 +574,7 @@ pub struct CastUnknownPointer { pub sub: CastUnknownPointerSub, } -pub enum CastUnknownPointerSub { +pub(crate) enum CastUnknownPointerSub { To(Span), From(Span), } @@ -601,7 +601,7 @@ impl rustc_errors::Subdiagnostic for CastUnknownPointerSub { } #[derive(Subdiagnostic)] -pub enum CannotCastToBoolHelp { +pub(crate) enum CannotCastToBoolHelp { #[suggestion( hir_typeck_suggestion, applicability = "machine-applicable", @@ -615,7 +615,7 @@ pub enum CannotCastToBoolHelp { #[derive(Diagnostic)] #[diag(hir_typeck_ctor_is_private, code = E0603)] -pub struct CtorIsPrivate { +pub(crate) struct CtorIsPrivate { #[primary_span] pub span: Span, pub def: String, @@ -623,7 +623,7 @@ pub struct CtorIsPrivate { #[derive(Subdiagnostic)] #[note(hir_typeck_deref_is_empty)] -pub struct DerefImplsIsEmpty { +pub(crate) struct DerefImplsIsEmpty { #[primary_span] pub span: Span, pub deref_ty: String, @@ -635,7 +635,7 @@ pub struct DerefImplsIsEmpty { applicability = "machine-applicable", style = "verbose" )] -pub struct SuggestConvertViaMethod<'tcx> { +pub(crate) struct SuggestConvertViaMethod<'tcx> { #[suggestion_part(code = "{sugg}")] pub span: Span, #[suggestion_part(code = "")] @@ -647,13 +647,13 @@ pub struct SuggestConvertViaMethod<'tcx> { #[derive(Subdiagnostic)] #[note(hir_typeck_note_caller_chooses_ty_for_ty_param)] -pub struct NoteCallerChoosesTyForTyParam<'tcx> { +pub(crate) struct NoteCallerChoosesTyForTyParam<'tcx> { pub ty_param_name: Symbol, pub found_ty: Ty<'tcx>, } #[derive(Subdiagnostic)] -pub enum SuggestBoxingForReturnImplTrait { +pub(crate) enum SuggestBoxingForReturnImplTrait { #[multipart_suggestion(hir_typeck_rpit_change_return_type, applicability = "maybe-incorrect")] ChangeReturnType { #[suggestion_part(code = "Box<dyn")] @@ -672,7 +672,7 @@ pub enum SuggestBoxingForReturnImplTrait { #[derive(Diagnostic)] #[diag(hir_typeck_self_ctor_from_outer_item, code = E0401)] -pub struct SelfCtorFromOuterItem { +pub(crate) struct SelfCtorFromOuterItem { #[primary_span] pub span: Span, #[label] @@ -683,7 +683,7 @@ pub struct SelfCtorFromOuterItem { #[derive(LintDiagnostic)] #[diag(hir_typeck_self_ctor_from_outer_item)] -pub struct SelfCtorFromOuterItemLint { +pub(crate) struct SelfCtorFromOuterItemLint { #[label] pub impl_span: Span, #[subdiagnostic] @@ -692,7 +692,7 @@ pub struct SelfCtorFromOuterItemLint { #[derive(Subdiagnostic)] #[suggestion(hir_typeck_suggestion, code = "{name}", applicability = "machine-applicable")] -pub struct ReplaceWithName { +pub(crate) struct ReplaceWithName { #[primary_span] pub span: Span, pub name: String, diff --git a/compiler/rustc_hir_typeck/src/expectation.rs b/compiler/rustc_hir_typeck/src/expectation.rs index 76ae41db5c5..67f4dbee3cb 100644 --- a/compiler/rustc_hir_typeck/src/expectation.rs +++ b/compiler/rustc_hir_typeck/src/expectation.rs @@ -7,7 +7,7 @@ use super::FnCtxt; /// When type-checking an expression, we propagate downward /// whatever type hint we are able in the form of an `Expectation`. #[derive(Copy, Clone, Debug)] -pub enum Expectation<'tcx> { +pub(crate) enum Expectation<'tcx> { /// We know nothing about what type this expression should have. NoExpectation, diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 91778a36668..dd33b947b0d 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -51,7 +51,7 @@ use crate::{ }; impl<'a, 'tcx> FnCtxt<'a, 'tcx> { - pub fn check_expr_has_type_or_error( + pub(crate) fn check_expr_has_type_or_error( &self, expr: &'tcx hir::Expr<'tcx>, expected_ty: Ty<'tcx>, @@ -977,7 +977,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } /// Check if the expression that could not be assigned to was a typoed expression that - pub fn check_for_missing_semi(&self, expr: &'tcx hir::Expr<'tcx>, err: &mut Diag<'_>) -> bool { + pub(crate) fn check_for_missing_semi( + &self, + expr: &'tcx hir::Expr<'tcx>, + err: &mut Diag<'_>, + ) -> bool { if let hir::ExprKind::Binary(binop, lhs, rhs) = expr.kind && let hir::BinOpKind::Mul = binop.node && self.tcx.sess.source_map().is_multiline(lhs.span.between(rhs.span)) diff --git a/compiler/rustc_hir_typeck/src/fallback.rs b/compiler/rustc_hir_typeck/src/fallback.rs index 6e1b7504626..b1dc19b3777 100644 --- a/compiler/rustc_hir_typeck/src/fallback.rs +++ b/compiler/rustc_hir_typeck/src/fallback.rs @@ -18,7 +18,7 @@ use rustc_trait_selection::traits::{ObligationCause, ObligationCtxt}; use crate::{errors, FnCtxt, TypeckRootCtxt}; #[derive(Copy, Clone)] -pub enum DivergingFallbackBehavior { +pub(crate) enum DivergingFallbackBehavior { /// Always fallback to `()` (aka "always spontaneous decay") ToUnit, /// Sometimes fallback to `!`, but mainly fallback to `()` so that most of the crates are not broken. diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs index 21e6ac9332c..2d205d1ede9 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs @@ -132,18 +132,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { deferred_call_resolutions.remove(&closure_def_id).unwrap_or_default() } - pub fn tag(&self) -> String { + fn tag(&self) -> String { format!("{self:p}") } - pub fn local_ty(&self, span: Span, nid: HirId) -> Ty<'tcx> { + pub(crate) fn local_ty(&self, span: Span, nid: HirId) -> Ty<'tcx> { self.locals.borrow().get(&nid).cloned().unwrap_or_else(|| { span_bug!(span, "no type for local variable {}", self.tcx.hir().node_to_string(nid)) }) } #[inline] - pub fn write_ty(&self, id: HirId, ty: Ty<'tcx>) { + pub(crate) fn write_ty(&self, id: HirId, ty: Ty<'tcx>) { debug!("write_ty({:?}, {:?}) in fcx {}", id, self.resolve_vars_if_possible(ty), self.tag()); let mut typeck = self.typeck_results.borrow_mut(); let mut node_ty = typeck.node_types_mut(); @@ -165,7 +165,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - pub fn write_field_index( + pub(crate) fn write_field_index( &self, hir_id: HirId, index: FieldIdx, @@ -198,7 +198,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.write_args(hir_id, method.args); } - pub fn write_args(&self, node_id: HirId, args: GenericArgsRef<'tcx>) { + fn write_args(&self, node_id: HirId, args: GenericArgsRef<'tcx>) { if !args.is_empty() { debug!("write_args({:?}, {:?}) in fcx {}", node_id, args, self.tag()); @@ -364,7 +364,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) } - pub fn require_type_meets( + pub(crate) fn require_type_meets( &self, ty: Ty<'tcx>, span: Span, @@ -374,7 +374,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.register_bound(ty, def_id, traits::ObligationCause::new(span, self.body_id, code)); } - pub fn require_type_is_sized( + pub(crate) fn require_type_is_sized( &self, ty: Ty<'tcx>, span: Span, @@ -386,7 +386,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - pub fn require_type_is_sized_deferred( + pub(crate) fn require_type_is_sized_deferred( &self, ty: Ty<'tcx>, span: Span, @@ -397,7 +397,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - pub fn require_type_has_static_alignment( + pub(crate) fn require_type_has_static_alignment( &self, ty: Ty<'tcx>, span: Span, @@ -426,7 +426,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - pub fn register_bound( + pub(crate) fn register_bound( &self, ty: Ty<'tcx>, def_id: DefId, @@ -443,7 +443,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - pub fn lower_ty(&self, hir_ty: &hir::Ty<'tcx>) -> LoweredTy<'tcx> { + pub(crate) fn lower_ty(&self, hir_ty: &hir::Ty<'tcx>) -> LoweredTy<'tcx> { let ty = self.lowerer().lower_ty(hir_ty); self.register_wf_obligation(ty.into(), hir_ty.span, ObligationCauseCode::WellFormed(None)); LoweredTy::from_raw(self, hir_ty.span, ty) @@ -474,7 +474,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - pub fn lower_array_length(&self, length: &hir::ArrayLen<'tcx>) -> ty::Const<'tcx> { + pub(crate) fn lower_array_length(&self, length: &hir::ArrayLen<'tcx>) -> ty::Const<'tcx> { match length { hir::ArrayLen::Infer(inf) => self.ct_infer(None, inf.span), hir::ArrayLen::Body(const_arg) => { @@ -486,7 +486,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - pub fn lower_const_arg( + pub(crate) fn lower_const_arg( &self, const_arg: &'tcx hir::ConstArg<'tcx>, param_def_id: DefId, @@ -515,7 +515,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { t.has_free_regions() || t.has_aliases() || t.has_infer_types() } - pub fn node_ty(&self, id: HirId) -> Ty<'tcx> { + pub(crate) fn node_ty(&self, id: HirId) -> Ty<'tcx> { match self.typeck_results.borrow().node_types().get(id) { Some(&t) => t, None if let Some(e) = self.tainted_by_errors() => Ty::new_error(self.tcx, e), @@ -529,7 +529,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - pub fn node_ty_opt(&self, id: HirId) -> Option<Ty<'tcx>> { + pub(crate) fn node_ty_opt(&self, id: HirId) -> Option<Ty<'tcx>> { match self.typeck_results.borrow().node_types().get(id) { Some(&t) => Some(t), None if let Some(e) = self.tainted_by_errors() => Some(Ty::new_error(self.tcx, e)), @@ -538,7 +538,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } /// Registers an obligation for checking later, during regionck, that `arg` is well-formed. - pub fn register_wf_obligation( + pub(crate) fn register_wf_obligation( &self, arg: ty::GenericArg<'tcx>, span: Span, @@ -555,7 +555,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } /// Registers obligations that all `args` are well-formed. - pub fn add_wf_bounds(&self, args: GenericArgsRef<'tcx>, expr: &hir::Expr<'_>) { + pub(crate) fn add_wf_bounds(&self, args: GenericArgsRef<'tcx>, expr: &hir::Expr<'_>) { for arg in args.iter().filter(|arg| { matches!(arg.unpack(), GenericArgKind::Type(..) | GenericArgKind::Const(..)) }) { @@ -566,7 +566,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // FIXME(arielb1): use this instead of field.ty everywhere // Only for fields! Returns <none> for methods> // Indifferent to privacy flags - pub fn field_ty( + pub(crate) fn field_ty( &self, span: Span, field: &'tcx ty::FieldDef, @@ -897,7 +897,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Given a `HirId`, return the `HirId` of the enclosing function, its `FnDecl`, and whether a /// suggestion can be made, `None` otherwise. - pub fn get_fn_decl( + pub(crate) fn get_fn_decl( &self, blk_id: HirId, ) -> Option<(LocalDefId, &'tcx hir::FnDecl<'tcx>, bool)> { @@ -1534,7 +1534,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// /// If no resolution is possible, then an error is reported. /// Numeric inference variables may be left unresolved. - pub fn structurally_resolve_type(&self, sp: Span, ty: Ty<'tcx>) -> Ty<'tcx> { + pub(crate) fn structurally_resolve_type(&self, sp: Span, ty: Ty<'tcx>) -> Ty<'tcx> { let ty = self.try_structurally_resolve_type(sp, ty); if !ty.is_ty_var() { diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs index 130fd130ec8..a8ba9f139cc 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs @@ -12,7 +12,7 @@ use rustc_trait_selection::traits; use crate::FnCtxt; impl<'a, 'tcx> FnCtxt<'a, 'tcx> { - pub fn adjust_fulfillment_error_for_expr_obligation( + pub(crate) fn adjust_fulfillment_error_for_expr_obligation( &self, error: &mut traits::FulfillmentError<'tcx>, ) -> bool { @@ -483,7 +483,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { * * This function only updates the error span. */ - pub fn blame_specific_expr_if_possible( + pub(crate) fn blame_specific_expr_if_possible( &self, error: &mut traits::FulfillmentError<'tcx>, expr: &'tcx hir::Expr<'tcx>, diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/arg_matrix.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/arg_matrix.rs index 78895689433..cb77d3f85d9 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/arg_matrix.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/arg_matrix.rs @@ -17,7 +17,7 @@ rustc_index::newtype_index! { } impl ExpectedIdx { - pub fn to_provided_idx(self) -> ProvidedIdx { + pub(crate) fn to_provided_idx(self) -> ProvidedIdx { ProvidedIdx::from_usize(self.as_usize()) } } diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs index aca29d47587..5333982c420 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs @@ -45,7 +45,7 @@ use crate::{ }; #[derive(Clone, Copy, Default)] -pub enum DivergingBlockBehavior { +pub(crate) enum DivergingBlockBehavior { /// This is the current stable behavior: /// /// ```rust @@ -1556,7 +1556,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - pub fn check_struct_path( + pub(crate) fn check_struct_path( &self, qpath: &QPath<'tcx>, hir_id: HirId, @@ -1622,7 +1622,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - pub fn check_decl_initializer( + fn check_decl_initializer( &self, hir_id: HirId, pat: &'tcx hir::Pat<'tcx>, @@ -1700,7 +1700,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } /// Type check a `let` statement. - pub fn check_decl_local(&self, local: &'tcx hir::LetStmt<'tcx>) { + fn check_decl_local(&self, local: &'tcx hir::LetStmt<'tcx>) { self.check_decl(local.into()); if local.pat.is_never_pattern() { self.diverges.set(Diverges::Always { @@ -1710,7 +1710,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - pub fn check_stmt(&self, stmt: &'tcx hir::Stmt<'tcx>) { + fn check_stmt(&self, stmt: &'tcx hir::Stmt<'tcx>) { // Don't do all the complex logic below for `DeclItem`. match stmt.kind { hir::StmtKind::Item(..) => return, @@ -1745,7 +1745,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.diverges.set(self.diverges.get() | old_diverges); } - pub fn check_block_no_value(&self, blk: &'tcx hir::Block<'tcx>) { + pub(crate) fn check_block_no_value(&self, blk: &'tcx hir::Block<'tcx>) { let unit = self.tcx.types.unit; let ty = self.check_block_with_expected(blk, ExpectHasType(unit)); diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs index 33f80dd3773..8e69a075030 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs @@ -117,7 +117,7 @@ pub(crate) struct FnCtxt<'a, 'tcx> { } impl<'a, 'tcx> FnCtxt<'a, 'tcx> { - pub fn new( + pub(crate) fn new( root_ctxt: &'a TypeckRootCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, body_id: LocalDefId, @@ -148,15 +148,19 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.root_ctxt.infcx.dcx() } - pub fn cause(&self, span: Span, code: ObligationCauseCode<'tcx>) -> ObligationCause<'tcx> { + pub(crate) fn cause( + &self, + span: Span, + code: ObligationCauseCode<'tcx>, + ) -> ObligationCause<'tcx> { ObligationCause::new(span, self.body_id, code) } - pub fn misc(&self, span: Span) -> ObligationCause<'tcx> { + pub(crate) fn misc(&self, span: Span) -> ObligationCause<'tcx> { self.cause(span, ObligationCauseCode::Misc) } - pub fn sess(&self) -> &Session { + pub(crate) fn sess(&self) -> &Session { self.tcx.sess } @@ -165,7 +169,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Use [`InferCtxtErrorExt::err_ctxt`] to start one without a `TypeckResults`. /// /// [`InferCtxtErrorExt::err_ctxt`]: rustc_trait_selection::error_reporting::InferCtxtErrorExt::err_ctxt - pub fn err_ctxt(&'a self) -> TypeErrCtxt<'a, 'tcx> { + pub(crate) fn err_ctxt(&'a self) -> TypeErrCtxt<'a, 'tcx> { let mut sub_relations = SubRelations::default(); sub_relations.add_constraints( self, @@ -365,7 +369,7 @@ impl<'tcx> HirTyLowerer<'tcx> for FnCtxt<'_, 'tcx> { /// This is a bridge between the interface of HIR ty lowering, which outputs a raw /// `Ty`, and the API in this module, which expect `Ty` to be fully normalized. #[derive(Clone, Copy, Debug)] -pub struct LoweredTy<'tcx> { +pub(crate) struct LoweredTy<'tcx> { /// The unnormalized type provided by the user. pub raw: Ty<'tcx>, @@ -374,7 +378,7 @@ pub struct LoweredTy<'tcx> { } impl<'tcx> LoweredTy<'tcx> { - pub fn from_raw(fcx: &FnCtxt<'_, 'tcx>, span: Span, raw: Ty<'tcx>) -> LoweredTy<'tcx> { + fn from_raw(fcx: &FnCtxt<'_, 'tcx>, span: Span, raw: Ty<'tcx>) -> LoweredTy<'tcx> { // FIXME(-Znext-solver): We're still figuring out how to best handle // normalization and this doesn't feel too great. We should look at this // code again before stabilizing it. diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs index 11c6e65a211..031aa6159d2 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs @@ -64,7 +64,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// - Points out the method's return type as the reason for the expected type. /// - Possible missing semicolon. /// - Possible missing return type if the return type is the default, and not `fn main()`. - pub fn suggest_mismatched_types_on_tail( + pub(crate) fn suggest_mismatched_types_on_tail( &self, err: &mut Diag<'_>, expr: &'tcx hir::Expr<'tcx>, @@ -177,7 +177,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.err_ctxt().extract_callable_info(self.body_id, self.param_env, ty) } - pub fn suggest_two_fn_call( + pub(crate) fn suggest_two_fn_call( &self, err: &mut Diag<'_>, lhs_expr: &'tcx hir::Expr<'tcx>, @@ -251,7 +251,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - pub fn suggest_remove_last_method_call( + pub(crate) fn suggest_remove_last_method_call( &self, err: &mut Diag<'_>, expr: &hir::Expr<'tcx>, @@ -280,7 +280,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { false } - pub fn suggest_deref_ref_or_into( + pub(crate) fn suggest_deref_ref_or_into( &self, err: &mut Diag<'_>, expr: &hir::Expr<'tcx>, @@ -747,7 +747,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// /// If the expression is the expression of a closure without block (`|| expr`), a /// block is needed to be added too (`|| { expr; }`). This is denoted by `needs_block`. - pub fn suggest_missing_semicolon( + pub(crate) fn suggest_missing_semicolon( &self, err: &mut Diag<'_>, expression: &'tcx hir::Expr<'tcx>, @@ -2077,7 +2077,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // If the expr is a while or for loop and is the tail expr of its // enclosing body suggest returning a value right after it - pub fn suggest_returning_value_after_loop( + pub(crate) fn suggest_returning_value_after_loop( &self, err: &mut Diag<'_>, expr: &hir::Expr<'tcx>, diff --git a/compiler/rustc_hir_typeck/src/intrinsicck.rs b/compiler/rustc_hir_typeck/src/intrinsicck.rs index a9c929e76d5..62aa29e673d 100644 --- a/compiler/rustc_hir_typeck/src/intrinsicck.rs +++ b/compiler/rustc_hir_typeck/src/intrinsicck.rs @@ -38,7 +38,7 @@ fn unpack_option_like<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { } impl<'a, 'tcx> FnCtxt<'a, 'tcx> { - pub fn check_transmute(&self, from: Ty<'tcx>, to: Ty<'tcx>, hir_id: HirId) { + pub(crate) fn check_transmute(&self, from: Ty<'tcx>, to: Ty<'tcx>, hir_id: HirId) { let tcx = self.tcx; let dl = &tcx.data_layout; let span = tcx.hir().span(hir_id); diff --git a/compiler/rustc_hir_typeck/src/lib.rs b/compiler/rustc_hir_typeck/src/lib.rs index 8ff4c11f24a..8e6484f1e29 100644 --- a/compiler/rustc_hir_typeck/src/lib.rs +++ b/compiler/rustc_hir_typeck/src/lib.rs @@ -8,6 +8,7 @@ #![feature(let_chains)] #![feature(never_type)] #![feature(try_blocks)] +#![warn(unreachable_pub)] // tidy-alphabetical-end #[macro_use] diff --git a/compiler/rustc_hir_typeck/src/method/confirm.rs b/compiler/rustc_hir_typeck/src/method/confirm.rs index e0c0adac076..2c3cfcf3cbd 100644 --- a/compiler/rustc_hir_typeck/src/method/confirm.rs +++ b/compiler/rustc_hir_typeck/src/method/confirm.rs @@ -42,13 +42,13 @@ impl<'a, 'tcx> Deref for ConfirmContext<'a, 'tcx> { } #[derive(Debug)] -pub struct ConfirmResult<'tcx> { +pub(crate) struct ConfirmResult<'tcx> { pub callee: MethodCallee<'tcx>, pub illegal_sized_bound: Option<Span>, } impl<'a, 'tcx> FnCtxt<'a, 'tcx> { - pub fn confirm_method( + pub(crate) fn confirm_method( &self, span: Span, self_expr: &'tcx hir::Expr<'tcx>, @@ -66,7 +66,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { confirm_cx.confirm(unadjusted_self_ty, pick, segment) } - pub fn confirm_method_for_diagnostic( + pub(crate) fn confirm_method_for_diagnostic( &self, span: Span, self_expr: &'tcx hir::Expr<'tcx>, diff --git a/compiler/rustc_hir_typeck/src/method/mod.rs b/compiler/rustc_hir_typeck/src/method/mod.rs index d6110ab94c1..39307a29dad 100644 --- a/compiler/rustc_hir_typeck/src/method/mod.rs +++ b/compiler/rustc_hir_typeck/src/method/mod.rs @@ -4,7 +4,7 @@ mod confirm; mod prelude_edition_lints; -pub mod probe; +pub(crate) mod probe; mod suggest; use rustc_errors::{Applicability, Diag, SubdiagMessage}; @@ -24,15 +24,15 @@ use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt; use rustc_trait_selection::traits::{self, NormalizeExt}; use self::probe::{IsSuggestion, ProbeScope}; -pub use self::MethodError::*; +pub(crate) use self::MethodError::*; use crate::FnCtxt; -pub fn provide(providers: &mut Providers) { +pub(crate) fn provide(providers: &mut Providers) { probe::provide(providers); } #[derive(Clone, Copy, Debug)] -pub struct MethodCallee<'tcx> { +pub(crate) struct MethodCallee<'tcx> { /// Impl method ID, for inherent methods, or trait method ID, otherwise. pub def_id: DefId, pub args: GenericArgsRef<'tcx>, @@ -44,7 +44,7 @@ pub struct MethodCallee<'tcx> { } #[derive(Debug)] -pub enum MethodError<'tcx> { +pub(crate) enum MethodError<'tcx> { // Did not find an applicable method, but we did find various near-misses that may work. NoMatch(NoMatchData<'tcx>), @@ -70,7 +70,7 @@ pub enum MethodError<'tcx> { // Contains a list of static methods that may apply, a list of unsatisfied trait predicates which // could lead to matches if satisfied, and a list of not-in-scope traits which may work. #[derive(Debug)] -pub struct NoMatchData<'tcx> { +pub(crate) struct NoMatchData<'tcx> { pub static_candidates: Vec<CandidateSource>, pub unsatisfied_predicates: Vec<(ty::Predicate<'tcx>, Option<ty::Predicate<'tcx>>, Option<ObligationCause<'tcx>>)>, @@ -82,7 +82,7 @@ pub struct NoMatchData<'tcx> { // A pared down enum describing just the places from which a method // candidate can arise. Used for error reporting only. #[derive(Copy, Clone, Debug, Eq, PartialEq)] -pub enum CandidateSource { +pub(crate) enum CandidateSource { Impl(DefId), Trait(DefId /* trait id */), } @@ -254,7 +254,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { Ok(result.callee) } - pub fn lookup_method_for_diagnostic( + pub(crate) fn lookup_method_for_diagnostic( &self, self_ty: Ty<'tcx>, segment: &hir::PathSegment<'tcx>, @@ -296,7 +296,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { Ok(pick) } - pub fn lookup_probe_for_diagnostic( + pub(crate) fn lookup_probe_for_diagnostic( &self, method_name: Ident, self_ty: Ty<'tcx>, @@ -569,7 +569,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Finds item with name `item_name` defined in impl/trait `def_id` /// and return it, or `None`, if no such item was defined there. - pub fn associated_value(&self, def_id: DefId, item_name: Ident) -> Option<ty::AssocItem> { + fn associated_value(&self, def_id: DefId, item_name: Ident) -> Option<ty::AssocItem> { self.tcx .associated_items(def_id) .find_by_name_and_namespace(self.tcx, item_name, Namespace::ValueNS, def_id) diff --git a/compiler/rustc_hir_typeck/src/method/probe.rs b/compiler/rustc_hir_typeck/src/method/probe.rs index 28f537c87c4..48e33c81b85 100644 --- a/compiler/rustc_hir_typeck/src/method/probe.rs +++ b/compiler/rustc_hir_typeck/src/method/probe.rs @@ -38,14 +38,14 @@ use rustc_trait_selection::traits::{self, ObligationCause, ObligationCtxt}; use smallvec::{smallvec, SmallVec}; use self::CandidateKind::*; -pub use self::PickKind::*; +pub(crate) use self::PickKind::*; use super::{suggest, CandidateSource, MethodError, NoMatchData}; use crate::FnCtxt; /// Boolean flag used to indicate if this search is for a suggestion /// or not. If true, we can allow ambiguity and so forth. #[derive(Clone, Copy, Debug)] -pub struct IsSuggestion(pub bool); +pub(crate) struct IsSuggestion(pub bool); pub(crate) struct ProbeContext<'a, 'tcx> { fcx: &'a FnCtxt<'a, 'tcx>, @@ -134,7 +134,7 @@ enum ProbeResult { /// (at most) one of these. Either the receiver has type `T` and we convert it to `&T` (or with /// `mut`), or it has type `*mut T` and we convert it to `*const T`. #[derive(Debug, PartialEq, Copy, Clone)] -pub enum AutorefOrPtrAdjustment { +pub(crate) enum AutorefOrPtrAdjustment { /// Receiver has type `T`, add `&` or `&mut` (it `T` is `mut`), and maybe also "unsize" it. /// Unsizing is used to convert a `[T; N]` to `[T]`, which only makes sense when autorefing. Autoref { @@ -158,7 +158,7 @@ impl AutorefOrPtrAdjustment { } #[derive(Debug, Clone)] -pub struct Pick<'tcx> { +pub(crate) struct Pick<'tcx> { pub item: ty::AssocItem, pub kind: PickKind<'tcx>, pub import_ids: SmallVec<[LocalDefId; 1]>, @@ -179,7 +179,7 @@ pub struct Pick<'tcx> { } #[derive(Clone, Debug, PartialEq, Eq)] -pub enum PickKind<'tcx> { +pub(crate) enum PickKind<'tcx> { InherentImplPick, ObjectPick, TraitPick, @@ -189,10 +189,10 @@ pub enum PickKind<'tcx> { ), } -pub type PickResult<'tcx> = Result<Pick<'tcx>, MethodError<'tcx>>; +pub(crate) type PickResult<'tcx> = Result<Pick<'tcx>, MethodError<'tcx>>; #[derive(PartialEq, Eq, Copy, Clone, Debug)] -pub enum Mode { +pub(crate) enum Mode { // An expression of the form `receiver.method_name(...)`. // Autoderefs are performed on `receiver`, lookup is done based on the // `self` argument of the method, and static methods aren't considered. @@ -204,7 +204,7 @@ pub enum Mode { } #[derive(PartialEq, Eq, Copy, Clone, Debug)] -pub enum ProbeScope { +pub(crate) enum ProbeScope { // Single candidate coming from pre-resolved delegation method. Single(DefId), @@ -507,7 +507,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } -pub fn provide(providers: &mut Providers) { +pub(crate) fn provide(providers: &mut Providers) { providers.method_autoderef_steps = method_autoderef_steps; } @@ -1288,7 +1288,7 @@ impl<'tcx> Pick<'tcx> { /// Checks whether two picks do not refer to the same trait item for the same `Self` type. /// Only useful for comparisons of picks in order to improve diagnostics. /// Do not use for type checking. - pub fn differs_from(&self, other: &Self) -> bool { + pub(crate) fn differs_from(&self, other: &Self) -> bool { let Self { item: AssocItem { @@ -1312,7 +1312,7 @@ impl<'tcx> Pick<'tcx> { } /// In case there were unstable name collisions, emit them as a lint. - pub fn maybe_emit_unstable_name_collision_hint( + pub(crate) fn maybe_emit_unstable_name_collision_hint( &self, tcx: TyCtxt<'tcx>, span: Span, diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index 8b8bb29dacd..b78bb8cb98d 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -415,7 +415,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { err } - pub fn suggest_use_shadowed_binding_with_method( + fn suggest_use_shadowed_binding_with_method( &self, self_source: SelfSource<'tcx>, method_name: Ident, @@ -4223,19 +4223,19 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } #[derive(Copy, Clone, Debug)] -pub enum SelfSource<'a> { +enum SelfSource<'a> { QPath(&'a hir::Ty<'a>), MethodCall(&'a hir::Expr<'a> /* rcvr */), } #[derive(Copy, Clone, PartialEq, Eq)] -pub struct TraitInfo { +pub(crate) struct TraitInfo { pub def_id: DefId, } /// Retrieves all traits in this crate and any dependent crates, /// and wraps them into `TraitInfo` for custom sorting. -pub fn all_traits(tcx: TyCtxt<'_>) -> Vec<TraitInfo> { +pub(crate) fn all_traits(tcx: TyCtxt<'_>) -> Vec<TraitInfo> { tcx.all_traits().map(|def_id| TraitInfo { def_id }).collect() } diff --git a/compiler/rustc_hir_typeck/src/op.rs b/compiler/rustc_hir_typeck/src/op.rs index c54f6cfd099..fb0d30d5b0e 100644 --- a/compiler/rustc_hir_typeck/src/op.rs +++ b/compiler/rustc_hir_typeck/src/op.rs @@ -25,7 +25,7 @@ use crate::Expectation; impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Checks a `a <op>= b` - pub fn check_binop_assign( + pub(crate) fn check_binop_assign( &self, expr: &'tcx hir::Expr<'tcx>, op: hir::BinOp, @@ -84,7 +84,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } /// Checks a potentially overloaded binary operator. - pub fn check_binop( + pub(crate) fn check_binop( &self, expr: &'tcx hir::Expr<'tcx>, op: hir::BinOp, @@ -770,7 +770,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - pub fn check_user_unop( + pub(crate) fn check_user_unop( &self, ex: &'tcx hir::Expr<'tcx>, operand_ty: Ty<'tcx>, diff --git a/compiler/rustc_hir_typeck/src/pat.rs b/compiler/rustc_hir_typeck/src/pat.rs index a8e5e09c8bb..206de455cd5 100644 --- a/compiler/rustc_hir_typeck/src/pat.rs +++ b/compiler/rustc_hir_typeck/src/pat.rs @@ -944,7 +944,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - pub fn check_dereferenceable( + fn check_dereferenceable( &self, span: Span, expected: Ty<'tcx>, diff --git a/compiler/rustc_hir_typeck/src/place_op.rs b/compiler/rustc_hir_typeck/src/place_op.rs index ad04b6b8b1d..bb227272584 100644 --- a/compiler/rustc_hir_typeck/src/place_op.rs +++ b/compiler/rustc_hir_typeck/src/place_op.rs @@ -246,7 +246,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// always know whether a place needs to be mutable or not in the first pass. /// This happens whether there is an implicit mutable reborrow, e.g. when the type /// is used as the receiver of a method call. - pub fn convert_place_derefs_to_mutable(&self, expr: &hir::Expr<'_>) { + pub(crate) fn convert_place_derefs_to_mutable(&self, expr: &hir::Expr<'_>) { // Gather up expressions we want to munge. let mut exprs = vec![expr]; diff --git a/compiler/rustc_hir_typeck/src/rvalue_scopes.rs b/compiler/rustc_hir_typeck/src/rvalue_scopes.rs index f22a13d292e..fb0fe23be65 100644 --- a/compiler/rustc_hir_typeck/src/rvalue_scopes.rs +++ b/compiler/rustc_hir_typeck/src/rvalue_scopes.rs @@ -65,7 +65,7 @@ fn record_rvalue_scope( } } -pub fn resolve_rvalue_scopes<'a, 'tcx>( +pub(crate) fn resolve_rvalue_scopes<'a, 'tcx>( fcx: &'a FnCtxt<'a, 'tcx>, scope_tree: &'a ScopeTree, def_id: DefId, diff --git a/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs b/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs index a43164589b5..e6b8da3e5d6 100644 --- a/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs +++ b/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs @@ -77,7 +77,7 @@ impl<'tcx> Deref for TypeckRootCtxt<'tcx> { } impl<'tcx> TypeckRootCtxt<'tcx> { - pub fn new(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Self { + pub(crate) fn new(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Self { let hir_owner = tcx.local_def_id_to_hir_id(def_id).owner; let infcx = tcx.infer_ctxt().ignoring_regions().with_opaque_type_inference(def_id).build(); @@ -124,7 +124,7 @@ impl<'tcx> TypeckRootCtxt<'tcx> { infer_ok.value } - pub fn update_infer_var_info(&self, obligation: &PredicateObligation<'tcx>) { + fn update_infer_var_info(&self, obligation: &PredicateObligation<'tcx>) { let infer_var_info = &mut self.infer_var_info.borrow_mut(); // (*) binder skipped diff --git a/compiler/rustc_hir_typeck/src/upvar.rs b/compiler/rustc_hir_typeck/src/upvar.rs index 55f002291f0..5350affb3bc 100644 --- a/compiler/rustc_hir_typeck/src/upvar.rs +++ b/compiler/rustc_hir_typeck/src/upvar.rs @@ -74,7 +74,7 @@ enum PlaceAncestryRelation { type InferredCaptureInformation<'tcx> = Vec<(Place<'tcx>, ty::CaptureInfo)>; impl<'a, 'tcx> FnCtxt<'a, 'tcx> { - pub fn closure_analyze(&self, body: &'tcx hir::Body<'tcx>) { + pub(crate) fn closure_analyze(&self, body: &'tcx hir::Body<'tcx>) { InferBorrowKindVisitor { fcx: self }.visit_body(body); // it's our job to process these. diff --git a/compiler/rustc_hir_typeck/src/writeback.rs b/compiler/rustc_hir_typeck/src/writeback.rs index 0327a3097ec..0853ed9b05b 100644 --- a/compiler/rustc_hir_typeck/src/writeback.rs +++ b/compiler/rustc_hir_typeck/src/writeback.rs @@ -35,7 +35,7 @@ use crate::FnCtxt; // resolve_type_vars_in_body, which creates a new TypeTables which // doesn't contain any inference types. impl<'a, 'tcx> FnCtxt<'a, 'tcx> { - pub fn resolve_type_vars_in_body( + pub(crate) fn resolve_type_vars_in_body( &self, body: &'tcx hir::Body<'tcx>, ) -> &'tcx ty::TypeckResults<'tcx> { diff --git a/compiler/rustc_incremental/src/assert_dep_graph.rs b/compiler/rustc_incremental/src/assert_dep_graph.rs index b29ba59c9f3..46f30526d2a 100644 --- a/compiler/rustc_incremental/src/assert_dep_graph.rs +++ b/compiler/rustc_incremental/src/assert_dep_graph.rs @@ -55,7 +55,7 @@ use {rustc_ast as ast, rustc_graphviz as dot, rustc_hir as hir}; use crate::errors; #[allow(missing_docs)] -pub fn assert_dep_graph(tcx: TyCtxt<'_>) { +pub(crate) fn assert_dep_graph(tcx: TyCtxt<'_>) { tcx.dep_graph.with_ignore(|| { if tcx.sess.opts.unstable_opts.dump_dep_graph { tcx.dep_graph.with_query(dump_graph); @@ -261,7 +261,7 @@ fn dump_graph(query: &DepGraphQuery) { } #[allow(missing_docs)] -pub struct GraphvizDepGraph(FxIndexSet<DepKind>, Vec<(DepKind, DepKind)>); +struct GraphvizDepGraph(FxIndexSet<DepKind>, Vec<(DepKind, DepKind)>); impl<'a> dot::GraphWalk<'a> for GraphvizDepGraph { type Node = DepKind; diff --git a/compiler/rustc_incremental/src/errors.rs b/compiler/rustc_incremental/src/errors.rs index c6f8b99bcd6..cb21f975878 100644 --- a/compiler/rustc_incremental/src/errors.rs +++ b/compiler/rustc_incremental/src/errors.rs @@ -6,7 +6,7 @@ use rustc_span::{Span, Symbol}; #[derive(Diagnostic)] #[diag(incremental_unrecognized_depnode)] -pub struct UnrecognizedDepNode { +pub(crate) struct UnrecognizedDepNode { #[primary_span] pub span: Span, pub name: Symbol, @@ -14,28 +14,28 @@ pub struct UnrecognizedDepNode { #[derive(Diagnostic)] #[diag(incremental_missing_depnode)] -pub struct MissingDepNode { +pub(crate) struct MissingDepNode { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(incremental_missing_if_this_changed)] -pub struct MissingIfThisChanged { +pub(crate) struct MissingIfThisChanged { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(incremental_ok)] -pub struct Ok { +pub(crate) struct Ok { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(incremental_no_path)] -pub struct NoPath { +pub(crate) struct NoPath { #[primary_span] pub span: Span, pub target: Symbol, @@ -44,7 +44,7 @@ pub struct NoPath { #[derive(Diagnostic)] #[diag(incremental_assertion_auto)] -pub struct AssertionAuto<'a> { +pub(crate) struct AssertionAuto<'a> { #[primary_span] pub span: Span, pub name: &'a str, @@ -53,7 +53,7 @@ pub struct AssertionAuto<'a> { #[derive(Diagnostic)] #[diag(incremental_undefined_clean_dirty_assertions_item)] -pub struct UndefinedCleanDirtyItem { +pub(crate) struct UndefinedCleanDirtyItem { #[primary_span] pub span: Span, pub kind: String, @@ -61,7 +61,7 @@ pub struct UndefinedCleanDirtyItem { #[derive(Diagnostic)] #[diag(incremental_undefined_clean_dirty_assertions)] -pub struct UndefinedCleanDirty { +pub(crate) struct UndefinedCleanDirty { #[primary_span] pub span: Span, pub kind: String, @@ -69,7 +69,7 @@ pub struct UndefinedCleanDirty { #[derive(Diagnostic)] #[diag(incremental_repeated_depnode_label)] -pub struct RepeatedDepNodeLabel<'a> { +pub(crate) struct RepeatedDepNodeLabel<'a> { #[primary_span] pub span: Span, pub label: &'a str, @@ -77,7 +77,7 @@ pub struct RepeatedDepNodeLabel<'a> { #[derive(Diagnostic)] #[diag(incremental_unrecognized_depnode_label)] -pub struct UnrecognizedDepNodeLabel<'a> { +pub(crate) struct UnrecognizedDepNodeLabel<'a> { #[primary_span] pub span: Span, pub label: &'a str, @@ -85,7 +85,7 @@ pub struct UnrecognizedDepNodeLabel<'a> { #[derive(Diagnostic)] #[diag(incremental_not_dirty)] -pub struct NotDirty<'a> { +pub(crate) struct NotDirty<'a> { #[primary_span] pub span: Span, pub dep_node_str: &'a str, @@ -93,7 +93,7 @@ pub struct NotDirty<'a> { #[derive(Diagnostic)] #[diag(incremental_not_clean)] -pub struct NotClean<'a> { +pub(crate) struct NotClean<'a> { #[primary_span] pub span: Span, pub dep_node_str: &'a str, @@ -101,7 +101,7 @@ pub struct NotClean<'a> { #[derive(Diagnostic)] #[diag(incremental_not_loaded)] -pub struct NotLoaded<'a> { +pub(crate) struct NotLoaded<'a> { #[primary_span] pub span: Span, pub dep_node_str: &'a str, @@ -109,7 +109,7 @@ pub struct NotLoaded<'a> { #[derive(Diagnostic)] #[diag(incremental_unknown_item)] -pub struct UnknownItem { +pub(crate) struct UnknownItem { #[primary_span] pub span: Span, pub name: Symbol, @@ -117,14 +117,14 @@ pub struct UnknownItem { #[derive(Diagnostic)] #[diag(incremental_no_cfg)] -pub struct NoCfg { +pub(crate) struct NoCfg { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(incremental_associated_value_expected_for)] -pub struct AssociatedValueExpectedFor { +pub(crate) struct AssociatedValueExpectedFor { #[primary_span] pub span: Span, pub ident: Ident, @@ -132,21 +132,21 @@ pub struct AssociatedValueExpectedFor { #[derive(Diagnostic)] #[diag(incremental_associated_value_expected)] -pub struct AssociatedValueExpected { +pub(crate) struct AssociatedValueExpected { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(incremental_unchecked_clean)] -pub struct UncheckedClean { +pub(crate) struct UncheckedClean { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(incremental_delete_old)] -pub struct DeleteOld<'a> { +pub(crate) struct DeleteOld<'a> { pub name: &'a str, pub path: PathBuf, pub err: std::io::Error, @@ -154,7 +154,7 @@ pub struct DeleteOld<'a> { #[derive(Diagnostic)] #[diag(incremental_create_new)] -pub struct CreateNew<'a> { +pub(crate) struct CreateNew<'a> { pub name: &'a str, pub path: PathBuf, pub err: std::io::Error, @@ -162,7 +162,7 @@ pub struct CreateNew<'a> { #[derive(Diagnostic)] #[diag(incremental_write_new)] -pub struct WriteNew<'a> { +pub(crate) struct WriteNew<'a> { pub name: &'a str, pub path: PathBuf, pub err: std::io::Error, @@ -170,14 +170,14 @@ pub struct WriteNew<'a> { #[derive(Diagnostic)] #[diag(incremental_canonicalize_path)] -pub struct CanonicalizePath { +pub(crate) struct CanonicalizePath { pub path: PathBuf, pub err: std::io::Error, } #[derive(Diagnostic)] #[diag(incremental_create_incr_comp_dir)] -pub struct CreateIncrCompDir<'a> { +pub(crate) struct CreateIncrCompDir<'a> { pub tag: &'a str, pub path: &'a Path, pub err: std::io::Error, @@ -185,7 +185,7 @@ pub struct CreateIncrCompDir<'a> { #[derive(Diagnostic)] #[diag(incremental_create_lock)] -pub struct CreateLock<'a> { +pub(crate) struct CreateLock<'a> { pub lock_err: std::io::Error, pub session_dir: &'a Path, #[note(incremental_lock_unsupported)] @@ -197,84 +197,84 @@ pub struct CreateLock<'a> { #[derive(Diagnostic)] #[diag(incremental_delete_lock)] -pub struct DeleteLock<'a> { +pub(crate) struct DeleteLock<'a> { pub path: &'a Path, pub err: std::io::Error, } #[derive(Diagnostic)] #[diag(incremental_hard_link_failed)] -pub struct HardLinkFailed<'a> { +pub(crate) struct HardLinkFailed<'a> { pub path: &'a Path, } #[derive(Diagnostic)] #[diag(incremental_delete_partial)] -pub struct DeletePartial<'a> { +pub(crate) struct DeletePartial<'a> { pub path: &'a Path, pub err: std::io::Error, } #[derive(Diagnostic)] #[diag(incremental_delete_full)] -pub struct DeleteFull<'a> { +pub(crate) struct DeleteFull<'a> { pub path: &'a Path, pub err: std::io::Error, } #[derive(Diagnostic)] #[diag(incremental_finalize)] -pub struct Finalize<'a> { +pub(crate) struct Finalize<'a> { pub path: &'a Path, pub err: std::io::Error, } #[derive(Diagnostic)] #[diag(incremental_invalid_gc_failed)] -pub struct InvalidGcFailed<'a> { +pub(crate) struct InvalidGcFailed<'a> { pub path: &'a Path, pub err: std::io::Error, } #[derive(Diagnostic)] #[diag(incremental_finalized_gc_failed)] -pub struct FinalizedGcFailed<'a> { +pub(crate) struct FinalizedGcFailed<'a> { pub path: &'a Path, pub err: std::io::Error, } #[derive(Diagnostic)] #[diag(incremental_session_gc_failed)] -pub struct SessionGcFailed<'a> { +pub(crate) struct SessionGcFailed<'a> { pub path: &'a Path, pub err: std::io::Error, } #[derive(Diagnostic)] #[diag(incremental_assert_not_loaded)] -pub struct AssertNotLoaded; +pub(crate) struct AssertNotLoaded; #[derive(Diagnostic)] #[diag(incremental_assert_loaded)] -pub struct AssertLoaded; +pub(crate) struct AssertLoaded; #[derive(Diagnostic)] #[diag(incremental_delete_incompatible)] -pub struct DeleteIncompatible { +pub(crate) struct DeleteIncompatible { pub path: PathBuf, pub err: std::io::Error, } #[derive(Diagnostic)] #[diag(incremental_load_dep_graph)] -pub struct LoadDepGraph { +pub(crate) struct LoadDepGraph { pub path: PathBuf, pub err: std::io::Error, } #[derive(Diagnostic)] #[diag(incremental_move_dep_graph)] -pub struct MoveDepGraph<'a> { +pub(crate) struct MoveDepGraph<'a> { pub from: &'a Path, pub to: &'a Path, pub err: std::io::Error, @@ -282,14 +282,14 @@ pub struct MoveDepGraph<'a> { #[derive(Diagnostic)] #[diag(incremental_create_dep_graph)] -pub struct CreateDepGraph<'a> { +pub(crate) struct CreateDepGraph<'a> { pub path: &'a Path, pub err: std::io::Error, } #[derive(Diagnostic)] #[diag(incremental_copy_workproduct_to_cache)] -pub struct CopyWorkProductToCache<'a> { +pub(crate) struct CopyWorkProductToCache<'a> { pub from: &'a Path, pub to: &'a Path, pub err: std::io::Error, @@ -297,13 +297,13 @@ pub struct CopyWorkProductToCache<'a> { #[derive(Diagnostic)] #[diag(incremental_delete_workproduct)] -pub struct DeleteWorkProduct<'a> { +pub(crate) struct DeleteWorkProduct<'a> { pub path: &'a Path, pub err: std::io::Error, } #[derive(Diagnostic)] #[diag(incremental_corrupt_file)] -pub struct CorruptFile<'a> { +pub(crate) struct CorruptFile<'a> { pub path: &'a Path, } diff --git a/compiler/rustc_incremental/src/lib.rs b/compiler/rustc_incremental/src/lib.rs index fcdcb08eed6..c79d108183c 100644 --- a/compiler/rustc_incremental/src/lib.rs +++ b/compiler/rustc_incremental/src/lib.rs @@ -6,6 +6,7 @@ #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] #![doc(rust_logo)] #![feature(rustdoc_internals)] +#![warn(unreachable_pub)] // tidy-alphabetical-end mod assert_dep_graph; diff --git a/compiler/rustc_incremental/src/persist/data.rs b/compiler/rustc_incremental/src/persist/data.rs index 81e5410978d..d962dc866f4 100644 --- a/compiler/rustc_incremental/src/persist/data.rs +++ b/compiler/rustc_incremental/src/persist/data.rs @@ -4,7 +4,7 @@ use rustc_macros::{Decodable, Encodable}; use rustc_middle::dep_graph::{WorkProduct, WorkProductId}; #[derive(Debug, Encodable, Decodable)] -pub struct SerializedWorkProduct { +pub(crate) struct SerializedWorkProduct { /// node that produced the work-product pub id: WorkProductId, diff --git a/compiler/rustc_incremental/src/persist/dirty_clean.rs b/compiler/rustc_incremental/src/persist/dirty_clean.rs index 1e02324f404..88cb82f0f37 100644 --- a/compiler/rustc_incremental/src/persist/dirty_clean.rs +++ b/compiler/rustc_incremental/src/persist/dirty_clean.rs @@ -133,7 +133,7 @@ struct Assertion { loaded_from_disk: Labels, } -pub fn check_dirty_clean_annotations(tcx: TyCtxt<'_>) { +pub(crate) fn check_dirty_clean_annotations(tcx: TyCtxt<'_>) { if !tcx.sess.opts.unstable_opts.query_dep_graph { return; } @@ -174,7 +174,7 @@ pub fn check_dirty_clean_annotations(tcx: TyCtxt<'_>) { }) } -pub struct DirtyCleanVisitor<'tcx> { +struct DirtyCleanVisitor<'tcx> { tcx: TyCtxt<'tcx>, checked_attrs: FxHashSet<ast::AttrId>, } @@ -429,7 +429,7 @@ fn expect_associated_value(tcx: TyCtxt<'_>, item: &NestedMetaItem) -> Symbol { /// A visitor that collects all `#[rustc_clean]` attributes from /// the HIR. It is used to verify that we really ran checks for all annotated /// nodes. -pub struct FindAllAttrs<'tcx> { +struct FindAllAttrs<'tcx> { tcx: TyCtxt<'tcx>, found_attrs: Vec<&'tcx Attribute>, } diff --git a/compiler/rustc_incremental/src/persist/file_format.rs b/compiler/rustc_incremental/src/persist/file_format.rs index 174414d0c85..f834c48cbf8 100644 --- a/compiler/rustc_incremental/src/persist/file_format.rs +++ b/compiler/rustc_incremental/src/persist/file_format.rs @@ -89,7 +89,7 @@ where /// incompatible version of the compiler. /// - Returns `Err(..)` if some kind of IO error occurred while reading the /// file. -pub fn read_file( +pub(crate) fn read_file( path: &Path, report_incremental_info: bool, is_nightly_build: bool, diff --git a/compiler/rustc_incremental/src/persist/fs.rs b/compiler/rustc_incremental/src/persist/fs.rs index 0e87bc1e692..feb25a9a89d 100644 --- a/compiler/rustc_incremental/src/persist/fs.rs +++ b/compiler/rustc_incremental/src/persist/fs.rs @@ -157,7 +157,7 @@ pub(crate) fn work_products_path(sess: &Session) -> PathBuf { } /// Returns the path to a session's query cache. -pub fn query_cache_path(sess: &Session) -> PathBuf { +pub(crate) fn query_cache_path(sess: &Session) -> PathBuf { in_incr_comp_dir_sess(sess, QUERY_CACHE_FILENAME) } diff --git a/compiler/rustc_index/src/lib.rs b/compiler/rustc_index/src/lib.rs index b9d2a43206b..f773b5b46ad 100644 --- a/compiler/rustc_index/src/lib.rs +++ b/compiler/rustc_index/src/lib.rs @@ -1,8 +1,9 @@ // tidy-alphabetical-start #![cfg_attr(all(feature = "nightly", test), feature(stmt_expr_attributes))] #![cfg_attr(feature = "nightly", allow(internal_features))] -#![cfg_attr(feature = "nightly", feature(extend_one, new_uninit, step_trait, test))] +#![cfg_attr(feature = "nightly", feature(extend_one, step_trait, test))] #![cfg_attr(feature = "nightly", feature(new_zeroed_alloc))] +#![warn(unreachable_pub)] // tidy-alphabetical-end pub mod bit_set; diff --git a/compiler/rustc_infer/src/errors/mod.rs b/compiler/rustc_infer/src/errors/mod.rs index 1a5c0137219..76ea9c3433d 100644 --- a/compiler/rustc_infer/src/errors/mod.rs +++ b/compiler/rustc_infer/src/errors/mod.rs @@ -3,7 +3,7 @@ use rustc_span::Span; #[derive(Diagnostic)] #[diag(infer_opaque_hidden_type)] -pub struct OpaqueHiddenTypeDiag { +pub(crate) struct OpaqueHiddenTypeDiag { #[primary_span] #[label] pub span: Span, diff --git a/compiler/rustc_infer/src/infer/free_regions.rs b/compiler/rustc_infer/src/infer/free_regions.rs index 0dde3082d48..9a5674369da 100644 --- a/compiler/rustc_infer/src/infer/free_regions.rs +++ b/compiler/rustc_infer/src/infer/free_regions.rs @@ -18,11 +18,11 @@ pub(crate) struct RegionRelations<'a, 'tcx> { } impl<'a, 'tcx> RegionRelations<'a, 'tcx> { - pub fn new(tcx: TyCtxt<'tcx>, free_regions: &'a FreeRegionMap<'tcx>) -> Self { + pub(crate) fn new(tcx: TyCtxt<'tcx>, free_regions: &'a FreeRegionMap<'tcx>) -> Self { Self { tcx, free_regions } } - pub fn lub_param_regions(&self, r_a: Region<'tcx>, r_b: Region<'tcx>) -> Region<'tcx> { + pub(crate) fn lub_param_regions(&self, r_a: Region<'tcx>, r_b: Region<'tcx>) -> Region<'tcx> { self.free_regions.lub_param_regions(self.tcx, r_a, r_b) } } @@ -80,7 +80,7 @@ impl<'tcx> FreeRegionMap<'tcx> { /// cases, this is more conservative than necessary, in order to /// avoid making arbitrary choices. See /// `TransitiveRelation::postdom_upper_bound` for more details. - pub fn lub_param_regions( + pub(crate) fn lub_param_regions( &self, tcx: TyCtxt<'tcx>, r_a: Region<'tcx>, diff --git a/compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs b/compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs index c2c0c7a41fe..e5533213400 100644 --- a/compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs +++ b/compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs @@ -43,7 +43,7 @@ pub(crate) fn resolve<'tcx>( /// Contains the result of lexical region resolution. Offers methods /// to lookup up the final value of a region variable. #[derive(Clone)] -pub struct LexicalRegionResolutions<'tcx> { +pub(crate) struct LexicalRegionResolutions<'tcx> { pub(crate) values: IndexVec<RegionVid, VarValue<'tcx>>, } diff --git a/compiler/rustc_infer/src/infer/relate/generalize.rs b/compiler/rustc_infer/src/infer/relate/generalize.rs index 542104fa10b..6fa10a95313 100644 --- a/compiler/rustc_infer/src/infer/relate/generalize.rs +++ b/compiler/rustc_infer/src/infer/relate/generalize.rs @@ -705,7 +705,7 @@ impl<'tcx> TypeRelation<TyCtxt<'tcx>> for Generalizer<'_, 'tcx> { /// not only the generalized type, but also a bool flag /// indicating whether further WF checks are needed. #[derive(Debug)] -pub struct Generalization<T> { +struct Generalization<T> { /// When generalizing `<?0 as Trait>::Assoc` or /// `<T as Bar<<?0 as Foo>::Assoc>>::Assoc` /// for `?0` generalization returns an inference diff --git a/compiler/rustc_infer/src/infer/relate/lattice.rs b/compiler/rustc_infer/src/infer/relate/lattice.rs index f555fedbb5b..1eafbb9acb3 100644 --- a/compiler/rustc_infer/src/infer/relate/lattice.rs +++ b/compiler/rustc_infer/src/infer/relate/lattice.rs @@ -29,7 +29,7 @@ use crate::traits::ObligationCause; /// /// GLB moves "down" the lattice (to smaller values); LUB moves /// "up" the lattice (to bigger values). -pub trait LatticeDir<'f, 'tcx>: PredicateEmittingRelation<InferCtxt<'tcx>> { +pub(crate) trait LatticeDir<'f, 'tcx>: PredicateEmittingRelation<InferCtxt<'tcx>> { fn infcx(&self) -> &'f InferCtxt<'tcx>; fn cause(&self) -> &ObligationCause<'tcx>; diff --git a/compiler/rustc_infer/src/infer/snapshot/fudge.rs b/compiler/rustc_infer/src/infer/snapshot/fudge.rs index bc954054ea2..fdf55447f79 100644 --- a/compiler/rustc_infer/src/infer/snapshot/fudge.rs +++ b/compiler/rustc_infer/src/infer/snapshot/fudge.rs @@ -170,7 +170,7 @@ impl<'tcx> InferCtxt<'tcx> { } } -pub struct InferenceFudger<'a, 'tcx> { +struct InferenceFudger<'a, 'tcx> { infcx: &'a InferCtxt<'tcx>, type_vars: (Range<TyVid>, Vec<TypeVariableOrigin>), int_vars: Range<IntVid>, diff --git a/compiler/rustc_infer/src/infer/snapshot/undo_log.rs b/compiler/rustc_infer/src/infer/snapshot/undo_log.rs index 50a0d3bf214..366af913ddc 100644 --- a/compiler/rustc_infer/src/infer/snapshot/undo_log.rs +++ b/compiler/rustc_infer/src/infer/snapshot/undo_log.rs @@ -158,7 +158,7 @@ impl<'tcx> InferCtxtInner<'tcx> { } impl<'tcx> InferCtxtUndoLogs<'tcx> { - pub fn start_snapshot(&mut self) -> Snapshot<'tcx> { + pub(crate) fn start_snapshot(&mut self) -> Snapshot<'tcx> { self.num_open_snapshots += 1; Snapshot { undo_len: self.logs.len(), _marker: PhantomData } } diff --git a/compiler/rustc_infer/src/lib.rs b/compiler/rustc_infer/src/lib.rs index 30dc666128c..94aa2ddd92f 100644 --- a/compiler/rustc_infer/src/lib.rs +++ b/compiler/rustc_infer/src/lib.rs @@ -28,6 +28,7 @@ #![feature(let_chains)] #![feature(rustdoc_internals)] #![recursion_limit = "512"] // For rustdoc +#![warn(unreachable_pub)] // tidy-alphabetical-end #[macro_use] diff --git a/compiler/rustc_infer/src/traits/mod.rs b/compiler/rustc_infer/src/traits/mod.rs index 4f34c139545..3a05b576a97 100644 --- a/compiler/rustc_infer/src/traits/mod.rs +++ b/compiler/rustc_infer/src/traits/mod.rs @@ -22,7 +22,7 @@ pub use self::engine::{FromSolverError, ScrubbedTraitError, TraitEngine}; pub(crate) use self::project::UndoLog; pub use self::project::{ MismatchedProjectionTypes, Normalized, NormalizedTerm, ProjectionCache, ProjectionCacheEntry, - ProjectionCacheKey, ProjectionCacheStorage, Reveal, + ProjectionCacheKey, ProjectionCacheStorage, }; pub use self::ImplSource::*; pub use self::SelectionError::*; diff --git a/compiler/rustc_infer/src/traits/project.rs b/compiler/rustc_infer/src/traits/project.rs index 9ed557ec40b..3d4ec9e51db 100644 --- a/compiler/rustc_infer/src/traits/project.rs +++ b/compiler/rustc_infer/src/traits/project.rs @@ -2,7 +2,7 @@ use rustc_data_structures::snapshot_map::{self, SnapshotMapRef, SnapshotMapStorage}; use rustc_data_structures::undo_log::Rollback; -pub use rustc_middle::traits::{EvaluationResult, Reveal}; +use rustc_middle::traits::EvaluationResult; use rustc_middle::ty; use super::PredicateObligation; diff --git a/compiler/rustc_interface/src/callbacks.rs b/compiler/rustc_interface/src/callbacks.rs index 786e2bb511f..f66b9eb3a28 100644 --- a/compiler/rustc_interface/src/callbacks.rs +++ b/compiler/rustc_interface/src/callbacks.rs @@ -18,11 +18,19 @@ use rustc_query_system::dep_graph::dep_node::default_dep_kind_debug; use rustc_query_system::dep_graph::{DepContext, DepKind, DepNode}; fn track_span_parent(def_id: rustc_span::def_id::LocalDefId) { - tls::with_opt(|tcx| { - if let Some(tcx) = tcx { - let _span = tcx.source_span(def_id); - // Sanity check: relative span's parent must be an absolute span. - debug_assert_eq!(_span.data_untracked().parent, None); + tls::with_context_opt(|icx| { + if let Some(icx) = icx { + // `track_span_parent` gets called a lot from HIR lowering code. + // Skip doing anything if we aren't tracking dependencies. + let tracks_deps = match icx.task_deps { + TaskDepsRef::Allow(..) => true, + TaskDepsRef::EvalAlways | TaskDepsRef::Ignore | TaskDepsRef::Forbid => false, + }; + if tracks_deps { + let _span = icx.tcx.source_span(def_id); + // Sanity check: relative span's parent must be an absolute span. + debug_assert_eq!(_span.data_untracked().parent, None); + } } }) } diff --git a/compiler/rustc_interface/src/lib.rs b/compiler/rustc_interface/src/lib.rs index 3492df69b8d..3b6c2acaf30 100644 --- a/compiler/rustc_interface/src/lib.rs +++ b/compiler/rustc_interface/src/lib.rs @@ -2,6 +2,7 @@ #![feature(decl_macro)] #![feature(let_chains)] #![feature(try_blocks)] +#![warn(unreachable_pub)] // tidy-alphabetical-end mod callbacks; diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index 96a6f52d60b..779b98d073d 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -784,7 +784,20 @@ fn run_required_analyses(tcx: TyCtxt<'_>) { } ); }); + rustc_hir_analysis::check_crate(tcx); + sess.time("MIR_coroutine_by_move_body", || { + tcx.hir().par_body_owners(|def_id| { + if tcx.needs_coroutine_by_move_body_def_id(def_id) { + tcx.ensure_with_value().coroutine_by_move_body_def_id(def_id); + } + }); + }); + // Freeze definitions as we don't add new ones at this point. + // We need to wait until now since we synthesize a by-move body + // This improves performance by allowing lock-free access to them. + tcx.untracked().definitions.freeze(); + sess.time("MIR_borrow_checking", || { tcx.hir().par_body_owners(|def_id| { // Run unsafety check because it's responsible for stealing and @@ -816,6 +829,7 @@ fn run_required_analyses(tcx: TyCtxt<'_>) { ); } }); + sess.time("layout_testing", || layout_test::test_layout(tcx)); sess.time("abi_testing", || abi_test::test_abi(tcx)); diff --git a/compiler/rustc_interface/src/tests.rs b/compiler/rustc_interface/src/tests.rs index 486136a2bcc..844d8ef02e0 100644 --- a/compiler/rustc_interface/src/tests.rs +++ b/compiler/rustc_interface/src/tests.rs @@ -10,11 +10,11 @@ use rustc_errors::{registry, ColorConfig}; use rustc_session::config::{ build_configuration, build_session_options, rustc_optgroups, BranchProtection, CFGuard, Cfg, CollapseMacroDebuginfo, CoverageLevel, CoverageOptions, DebugInfo, DumpMonoStatsFormat, - ErrorOutputType, ExternEntry, ExternLocation, Externs, FunctionReturn, InliningThreshold, - Input, InstrumentCoverage, InstrumentXRay, LinkSelfContained, LinkerPluginLto, LocationDetail, - LtoCli, NextSolverConfig, OomStrategy, Options, OutFileName, OutputType, OutputTypes, PAuthKey, - PacRet, Passes, PatchableFunctionEntry, Polonius, ProcMacroExecutionStrategy, Strip, - SwitchWithOptPath, SymbolManglingVersion, WasiExecModel, + ErrorOutputType, ExternEntry, ExternLocation, Externs, FmtDebug, FunctionReturn, + InliningThreshold, Input, InstrumentCoverage, InstrumentXRay, LinkSelfContained, + LinkerPluginLto, LocationDetail, LtoCli, NextSolverConfig, OomStrategy, Options, OutFileName, + OutputType, OutputTypes, PAuthKey, PacRet, Passes, PatchableFunctionEntry, Polonius, + ProcMacroExecutionStrategy, Strip, SwitchWithOptPath, SymbolManglingVersion, WasiExecModel, }; use rustc_session::lint::Level; use rustc_session::search_paths::SearchPath; @@ -780,6 +780,7 @@ fn test_unstable_options_tracking_hash() { tracked!(fewer_names, Some(true)); tracked!(fixed_x18, true); tracked!(flatten_format_args, false); + tracked!(fmt_debug, FmtDebug::Shallow); tracked!(force_unstable_if_unmarked, true); tracked!(fuel, Some(("abc".to_string(), 99))); tracked!(function_return, FunctionReturn::ThunkExtern); @@ -794,6 +795,7 @@ fn test_unstable_options_tracking_hash() { tracked!(instrument_xray, Some(InstrumentXRay::default())); tracked!(link_directives, false); tracked!(link_only, true); + tracked!(lint_llvm_ir, true); tracked!(llvm_module_flag, vec![("bar".to_string(), 123, "max".to_string())]); tracked!(llvm_plugins, vec![String::from("plugin_name")]); tracked!(location_detail, LocationDetail { file: true, line: false, column: false }); diff --git a/compiler/rustc_lexer/src/lib.rs b/compiler/rustc_lexer/src/lib.rs index 2116ba6c079..31fdd2d7cec 100644 --- a/compiler/rustc_lexer/src/lib.rs +++ b/compiler/rustc_lexer/src/lib.rs @@ -23,6 +23,7 @@ // We want to be able to build this crate with a stable compiler, // so no `#![feature]` attributes should be added. #![deny(unstable_features)] +#![warn(unreachable_pub)] // tidy-alphabetical-end mod cursor; diff --git a/compiler/rustc_lint/src/early.rs b/compiler/rustc_lint/src/early.rs index 6fb0a624644..0ee9dda1fef 100644 --- a/compiler/rustc_lint/src/early.rs +++ b/compiler/rustc_lint/src/early.rs @@ -413,7 +413,7 @@ pub fn check_ast_node<'a>( } } -pub fn check_ast_node_inner<'a, T: EarlyLintPass>( +fn check_ast_node_inner<'a, T: EarlyLintPass>( sess: &Session, check_node: impl EarlyCheckNode<'a>, context: EarlyContext<'_>, diff --git a/compiler/rustc_lint/src/errors.rs b/compiler/rustc_lint/src/errors.rs index 85ee18aba8f..d109a5c9030 100644 --- a/compiler/rustc_lint/src/errors.rs +++ b/compiler/rustc_lint/src/errors.rs @@ -8,7 +8,7 @@ use crate::fluent_generated as fluent; #[derive(Diagnostic)] #[diag(lint_overruled_attribute, code = E0453)] -pub struct OverruledAttribute<'a> { +pub(crate) struct OverruledAttribute<'a> { #[primary_span] pub span: Span, #[label] @@ -19,7 +19,7 @@ pub struct OverruledAttribute<'a> { pub sub: OverruledAttributeSub, } -pub enum OverruledAttributeSub { +pub(crate) enum OverruledAttributeSub { DefaultSource { id: String }, NodeSource { span: Span, reason: Option<Symbol> }, CommandLineSource, @@ -52,7 +52,7 @@ impl Subdiagnostic for OverruledAttributeSub { #[derive(Diagnostic)] #[diag(lint_malformed_attribute, code = E0452)] -pub struct MalformedAttribute { +pub(crate) struct MalformedAttribute { #[primary_span] pub span: Span, #[subdiagnostic] @@ -60,7 +60,7 @@ pub struct MalformedAttribute { } #[derive(Subdiagnostic)] -pub enum MalformedAttributeSub { +pub(crate) enum MalformedAttributeSub { #[label(lint_bad_attribute_argument)] BadAttributeArgument(#[primary_span] Span), #[label(lint_reason_must_be_string_literal)] @@ -71,7 +71,7 @@ pub enum MalformedAttributeSub { #[derive(Diagnostic)] #[diag(lint_unknown_tool_in_scoped_lint, code = E0710)] -pub struct UnknownToolInScopedLint { +pub(crate) struct UnknownToolInScopedLint { #[primary_span] pub span: Option<Span>, pub tool_name: Symbol, @@ -82,7 +82,7 @@ pub struct UnknownToolInScopedLint { #[derive(Diagnostic)] #[diag(lint_builtin_ellipsis_inclusive_range_patterns, code = E0783)] -pub struct BuiltinEllipsisInclusiveRangePatterns { +pub(crate) struct BuiltinEllipsisInclusiveRangePatterns { #[primary_span] pub span: Span, #[suggestion(style = "short", code = "{replace}", applicability = "machine-applicable")] @@ -92,20 +92,20 @@ pub struct BuiltinEllipsisInclusiveRangePatterns { #[derive(Subdiagnostic)] #[note(lint_requested_level)] -pub struct RequestedLevel<'a> { +pub(crate) struct RequestedLevel<'a> { pub level: Level, pub lint_name: &'a str, } #[derive(Diagnostic)] #[diag(lint_unsupported_group, code = E0602)] -pub struct UnsupportedGroup { +pub(crate) struct UnsupportedGroup { pub lint_group: String, } #[derive(Diagnostic)] #[diag(lint_check_name_unknown_tool, code = E0602)] -pub struct CheckNameUnknownTool<'a> { +pub(crate) struct CheckNameUnknownTool<'a> { pub tool_name: Symbol, #[subdiagnostic] pub sub: RequestedLevel<'a>, diff --git a/compiler/rustc_lint/src/late.rs b/compiler/rustc_lint/src/late.rs index 638b623510e..cb369d99a84 100644 --- a/compiler/rustc_lint/src/late.rs +++ b/compiler/rustc_lint/src/late.rs @@ -47,7 +47,7 @@ macro_rules! lint_callback { ($cx:expr, $f:ident, $($args:expr),*) => ({ /// Implements the AST traversal for late lint passes. `T` provides the /// `check_*` methods. -pub struct LateContextAndPass<'tcx, T: LateLintPass<'tcx>> { +struct LateContextAndPass<'tcx, T: LateLintPass<'tcx>> { context: LateContext<'tcx>, pass: T, } diff --git a/compiler/rustc_lint/src/levels.rs b/compiler/rustc_lint/src/levels.rs index 91d4f95df80..07ac63ec96c 100644 --- a/compiler/rustc_lint/src/levels.rs +++ b/compiler/rustc_lint/src/levels.rs @@ -1103,7 +1103,7 @@ pub(crate) fn provide(providers: &mut Providers) { *providers = Providers { shallow_lint_levels_on, lint_expectations, ..*providers }; } -pub fn parse_lint_and_tool_name(lint_name: &str) -> (Option<Symbol>, &str) { +pub(crate) fn parse_lint_and_tool_name(lint_name: &str) -> (Option<Symbol>, &str) { match lint_name.split_once("::") { Some((tool_name, lint_name)) => { let tool_name = Symbol::intern(tool_name); diff --git a/compiler/rustc_lint/src/lib.rs b/compiler/rustc_lint/src/lib.rs index a6e7d288f08..c5a5c5b30af 100644 --- a/compiler/rustc_lint/src/lib.rs +++ b/compiler/rustc_lint/src/lib.rs @@ -39,6 +39,7 @@ #![feature(rustc_attrs)] #![feature(rustdoc_internals)] #![feature(trait_upcasting)] +#![warn(unreachable_pub)] // tidy-alphabetical-end mod async_closures; diff --git a/compiler/rustc_lint/src/lints.rs b/compiler/rustc_lint/src/lints.rs index c12c5427997..c6bcb1f3e83 100644 --- a/compiler/rustc_lint/src/lints.rs +++ b/compiler/rustc_lint/src/lints.rs @@ -26,7 +26,7 @@ use crate::{fluent_generated as fluent, LateContext}; // array_into_iter.rs #[derive(LintDiagnostic)] #[diag(lint_shadowed_into_iter)] -pub struct ShadowedIntoIterDiag { +pub(crate) struct ShadowedIntoIterDiag { pub target: &'static str, pub edition: &'static str, #[suggestion(lint_use_iter_suggestion, code = "iter", applicability = "machine-applicable")] @@ -36,7 +36,7 @@ pub struct ShadowedIntoIterDiag { } #[derive(Subdiagnostic)] -pub enum ShadowedIntoIterDiagSub { +pub(crate) enum ShadowedIntoIterDiagSub { #[suggestion(lint_remove_into_iter_suggestion, code = "", applicability = "maybe-incorrect")] RemoveIntoIter { #[primary_span] @@ -57,7 +57,7 @@ pub enum ShadowedIntoIterDiagSub { // builtin.rs #[derive(LintDiagnostic)] #[diag(lint_builtin_while_true)] -pub struct BuiltinWhileTrue { +pub(crate) struct BuiltinWhileTrue { #[suggestion(style = "short", code = "{replace}", applicability = "machine-applicable")] pub suggestion: Span, pub replace: String, @@ -65,7 +65,7 @@ pub struct BuiltinWhileTrue { #[derive(LintDiagnostic)] #[diag(lint_builtin_non_shorthand_field_patterns)] -pub struct BuiltinNonShorthandFieldPatterns { +pub(crate) struct BuiltinNonShorthandFieldPatterns { pub ident: Ident, #[suggestion(code = "{prefix}{ident}", applicability = "machine-applicable")] pub suggestion: Span, @@ -73,7 +73,7 @@ pub struct BuiltinNonShorthandFieldPatterns { } #[derive(LintDiagnostic)] -pub enum BuiltinUnsafe { +pub(crate) enum BuiltinUnsafe { #[diag(lint_builtin_allow_internal_unsafe)] AllowInternalUnsafe, #[diag(lint_builtin_unsafe_block)] @@ -121,16 +121,16 @@ pub enum BuiltinUnsafe { #[derive(LintDiagnostic)] #[diag(lint_builtin_missing_doc)] -pub struct BuiltinMissingDoc<'a> { +pub(crate) struct BuiltinMissingDoc<'a> { pub article: &'a str, pub desc: &'a str, } #[derive(LintDiagnostic)] #[diag(lint_builtin_missing_copy_impl)] -pub struct BuiltinMissingCopyImpl; +pub(crate) struct BuiltinMissingCopyImpl; -pub struct BuiltinMissingDebugImpl<'a> { +pub(crate) struct BuiltinMissingDebugImpl<'a> { pub tcx: TyCtxt<'a>, pub def_id: DefId, } @@ -145,7 +145,7 @@ impl<'a> LintDiagnostic<'a, ()> for BuiltinMissingDebugImpl<'_> { #[derive(LintDiagnostic)] #[diag(lint_builtin_anonymous_params)] -pub struct BuiltinAnonymousParams<'a> { +pub(crate) struct BuiltinAnonymousParams<'a> { #[suggestion(code = "_: {ty_snip}")] pub suggestion: (Span, Applicability), pub ty_snip: &'a str, @@ -154,7 +154,7 @@ pub struct BuiltinAnonymousParams<'a> { // FIXME(davidtwco) translatable deprecated attr #[derive(LintDiagnostic)] #[diag(lint_builtin_deprecated_attr_link)] -pub struct BuiltinDeprecatedAttrLink<'a> { +pub(crate) struct BuiltinDeprecatedAttrLink<'a> { pub name: Symbol, pub reason: &'a str, pub link: &'a str, @@ -163,7 +163,7 @@ pub struct BuiltinDeprecatedAttrLink<'a> { } #[derive(Subdiagnostic)] -pub enum BuiltinDeprecatedAttrLinkSuggestion<'a> { +pub(crate) enum BuiltinDeprecatedAttrLinkSuggestion<'a> { #[suggestion(lint_msg_suggestion, code = "", applicability = "machine-applicable")] Msg { #[primary_span] @@ -179,7 +179,7 @@ pub enum BuiltinDeprecatedAttrLinkSuggestion<'a> { #[derive(LintDiagnostic)] #[diag(lint_builtin_deprecated_attr_used)] -pub struct BuiltinDeprecatedAttrUsed { +pub(crate) struct BuiltinDeprecatedAttrUsed { pub name: String, #[suggestion( lint_builtin_deprecated_attr_default_suggestion, @@ -192,7 +192,7 @@ pub struct BuiltinDeprecatedAttrUsed { #[derive(LintDiagnostic)] #[diag(lint_builtin_unused_doc_comment)] -pub struct BuiltinUnusedDocComment<'a> { +pub(crate) struct BuiltinUnusedDocComment<'a> { pub kind: &'a str, #[label] pub label: Span, @@ -201,7 +201,7 @@ pub struct BuiltinUnusedDocComment<'a> { } #[derive(Subdiagnostic)] -pub enum BuiltinUnusedDocCommentSub { +pub(crate) enum BuiltinUnusedDocCommentSub { #[help(lint_plain_help)] PlainHelp, #[help(lint_block_help)] @@ -210,7 +210,7 @@ pub enum BuiltinUnusedDocCommentSub { #[derive(LintDiagnostic)] #[diag(lint_builtin_no_mangle_generic)] -pub struct BuiltinNoMangleGeneric { +pub(crate) struct BuiltinNoMangleGeneric { // Use of `#[no_mangle]` suggests FFI intent; correct // fix may be to monomorphize source by hand #[suggestion(style = "short", code = "", applicability = "maybe-incorrect")] @@ -219,21 +219,21 @@ pub struct BuiltinNoMangleGeneric { #[derive(LintDiagnostic)] #[diag(lint_builtin_const_no_mangle)] -pub struct BuiltinConstNoMangle { +pub(crate) struct BuiltinConstNoMangle { #[suggestion(code = "pub static", applicability = "machine-applicable")] pub suggestion: Span, } #[derive(LintDiagnostic)] #[diag(lint_builtin_mutable_transmutes)] -pub struct BuiltinMutablesTransmutes; +pub(crate) struct BuiltinMutablesTransmutes; #[derive(LintDiagnostic)] #[diag(lint_builtin_unstable_features)] -pub struct BuiltinUnstableFeatures; +pub(crate) struct BuiltinUnstableFeatures; // lint_ungated_async_fn_track_caller -pub struct BuiltinUngatedAsyncFnTrackCaller<'a> { +pub(crate) struct BuiltinUngatedAsyncFnTrackCaller<'a> { pub label: Span, pub session: &'a Session, } @@ -252,7 +252,7 @@ impl<'a> LintDiagnostic<'a, ()> for BuiltinUngatedAsyncFnTrackCaller<'_> { #[derive(LintDiagnostic)] #[diag(lint_builtin_unreachable_pub)] -pub struct BuiltinUnreachablePub<'a> { +pub(crate) struct BuiltinUnreachablePub<'a> { pub what: &'a str, #[suggestion(code = "pub(crate)")] pub suggestion: (Span, Applicability), @@ -262,12 +262,12 @@ pub struct BuiltinUnreachablePub<'a> { #[derive(LintDiagnostic)] #[diag(lint_macro_expr_fragment_specifier_2024_migration)] -pub struct MacroExprFragment2024 { +pub(crate) struct MacroExprFragment2024 { #[suggestion(code = "expr_2021", applicability = "machine-applicable")] pub suggestion: Span, } -pub struct BuiltinTypeAliasBounds<'a, 'hir> { +pub(crate) struct BuiltinTypeAliasBounds<'a, 'hir> { pub in_where_clause: bool, pub label: Span, pub enable_feat_help: bool, @@ -338,13 +338,13 @@ impl<'a> LintDiagnostic<'a, ()> for BuiltinTypeAliasBounds<'_, '_> { #[derive(LintDiagnostic)] #[diag(lint_builtin_trivial_bounds)] -pub struct BuiltinTrivialBounds<'a> { +pub(crate) struct BuiltinTrivialBounds<'a> { pub predicate_kind_name: &'a str, pub predicate: Clause<'a>, } #[derive(LintDiagnostic)] -pub enum BuiltinEllipsisInclusiveRangePatternsLint { +pub(crate) enum BuiltinEllipsisInclusiveRangePatternsLint { #[diag(lint_builtin_ellipsis_inclusive_range_patterns)] Parenthesise { #[suggestion(code = "{replace}", applicability = "machine-applicable")] @@ -360,7 +360,7 @@ pub enum BuiltinEllipsisInclusiveRangePatternsLint { #[derive(LintDiagnostic)] #[diag(lint_builtin_keyword_idents)] -pub struct BuiltinKeywordIdents { +pub(crate) struct BuiltinKeywordIdents { pub kw: Ident, pub next: Edition, #[suggestion(code = "r#{kw}", applicability = "machine-applicable")] @@ -369,7 +369,7 @@ pub struct BuiltinKeywordIdents { #[derive(LintDiagnostic)] #[diag(lint_builtin_explicit_outlives)] -pub struct BuiltinExplicitOutlives { +pub(crate) struct BuiltinExplicitOutlives { pub count: usize, #[subdiagnostic] pub suggestion: BuiltinExplicitOutlivesSuggestion, @@ -377,7 +377,7 @@ pub struct BuiltinExplicitOutlives { #[derive(Subdiagnostic)] #[multipart_suggestion(lint_suggestion)] -pub struct BuiltinExplicitOutlivesSuggestion { +pub(crate) struct BuiltinExplicitOutlivesSuggestion { #[suggestion_part(code = "")] pub spans: Vec<Span>, #[applicability] @@ -386,7 +386,7 @@ pub struct BuiltinExplicitOutlivesSuggestion { #[derive(LintDiagnostic)] #[diag(lint_builtin_incomplete_features)] -pub struct BuiltinIncompleteFeatures { +pub(crate) struct BuiltinIncompleteFeatures { pub name: Symbol, #[subdiagnostic] pub note: Option<BuiltinFeatureIssueNote>, @@ -397,21 +397,21 @@ pub struct BuiltinIncompleteFeatures { #[derive(LintDiagnostic)] #[diag(lint_builtin_internal_features)] #[note] -pub struct BuiltinInternalFeatures { +pub(crate) struct BuiltinInternalFeatures { pub name: Symbol, } #[derive(Subdiagnostic)] #[help(lint_help)] -pub struct BuiltinIncompleteFeaturesHelp; +pub(crate) struct BuiltinIncompleteFeaturesHelp; #[derive(Subdiagnostic)] #[note(lint_note)] -pub struct BuiltinFeatureIssueNote { +pub(crate) struct BuiltinFeatureIssueNote { pub n: NonZero<u32>, } -pub struct BuiltinUnpermittedTypeInit<'a> { +pub(crate) struct BuiltinUnpermittedTypeInit<'a> { pub msg: DiagMessage, pub ty: Ty<'a>, pub label: Span, @@ -436,7 +436,7 @@ impl<'a> LintDiagnostic<'a, ()> for BuiltinUnpermittedTypeInit<'_> { } // FIXME(davidtwco): make translatable -pub struct BuiltinUnpermittedTypeInitSub { +pub(crate) struct BuiltinUnpermittedTypeInitSub { pub err: InitError, } @@ -463,7 +463,7 @@ impl Subdiagnostic for BuiltinUnpermittedTypeInitSub { } #[derive(LintDiagnostic)] -pub enum BuiltinClashingExtern<'a> { +pub(crate) enum BuiltinClashingExtern<'a> { #[diag(lint_builtin_clashing_extern_same_name)] SameName { this: Symbol, @@ -489,7 +489,7 @@ pub enum BuiltinClashingExtern<'a> { } // FIXME(davidtwco): translatable expected/found -pub struct BuiltinClashingExternSub<'a> { +pub(crate) struct BuiltinClashingExternSub<'a> { pub tcx: TyCtxt<'a>, pub expected: Ty<'a>, pub found: Ty<'a>, @@ -511,7 +511,7 @@ impl Subdiagnostic for BuiltinClashingExternSub<'_> { #[derive(LintDiagnostic)] #[diag(lint_builtin_deref_nullptr)] -pub struct BuiltinDerefNullptr { +pub(crate) struct BuiltinDerefNullptr { #[label] pub label: Span, } @@ -519,7 +519,7 @@ pub struct BuiltinDerefNullptr { // FIXME: migrate fluent::lint::builtin_asm_labels #[derive(LintDiagnostic)] -pub enum BuiltinSpecialModuleNameUsed { +pub(crate) enum BuiltinSpecialModuleNameUsed { #[diag(lint_builtin_special_module_name_used_lib)] #[note] #[help] @@ -532,7 +532,7 @@ pub enum BuiltinSpecialModuleNameUsed { // deref_into_dyn_supertrait.rs #[derive(LintDiagnostic)] #[diag(lint_supertrait_as_deref_target)] -pub struct SupertraitAsDerefTarget<'a> { +pub(crate) struct SupertraitAsDerefTarget<'a> { pub self_ty: Ty<'a>, pub supertrait_principal: PolyExistentialTraitRef<'a>, pub target_principal: PolyExistentialTraitRef<'a>, @@ -544,7 +544,7 @@ pub struct SupertraitAsDerefTarget<'a> { #[derive(Subdiagnostic)] #[label(lint_label2)] -pub struct SupertraitAsDerefTargetLabel { +pub(crate) struct SupertraitAsDerefTargetLabel { #[primary_span] pub label: Span, } @@ -552,7 +552,7 @@ pub struct SupertraitAsDerefTargetLabel { // enum_intrinsics_non_enums.rs #[derive(LintDiagnostic)] #[diag(lint_enum_intrinsics_mem_discriminant)] -pub struct EnumIntrinsicsMemDiscriminate<'a> { +pub(crate) struct EnumIntrinsicsMemDiscriminate<'a> { pub ty_param: Ty<'a>, #[note] pub note: Span, @@ -561,14 +561,14 @@ pub struct EnumIntrinsicsMemDiscriminate<'a> { #[derive(LintDiagnostic)] #[diag(lint_enum_intrinsics_mem_variant)] #[note] -pub struct EnumIntrinsicsMemVariant<'a> { +pub(crate) struct EnumIntrinsicsMemVariant<'a> { pub ty_param: Ty<'a>, } // expect.rs #[derive(LintDiagnostic)] #[diag(lint_expectation)] -pub struct Expectation { +pub(crate) struct Expectation { #[subdiagnostic] pub rationale: Option<ExpectationNote>, #[note] @@ -577,13 +577,13 @@ pub struct Expectation { #[derive(Subdiagnostic)] #[note(lint_rationale)] -pub struct ExpectationNote { +pub(crate) struct ExpectationNote { pub rationale: Symbol, } // ptr_nulls.rs #[derive(LintDiagnostic)] -pub enum PtrNullChecksDiag<'a> { +pub(crate) enum PtrNullChecksDiag<'a> { #[diag(lint_ptr_null_checks_fn_ptr)] #[help(lint_help)] FnPtr { @@ -604,7 +604,7 @@ pub enum PtrNullChecksDiag<'a> { // for_loops_over_fallibles.rs #[derive(LintDiagnostic)] #[diag(lint_for_loops_over_fallibles)] -pub struct ForLoopsOverFalliblesDiag<'a> { +pub(crate) struct ForLoopsOverFalliblesDiag<'a> { pub article: &'static str, pub ref_prefix: &'static str, pub ty: &'static str, @@ -617,7 +617,7 @@ pub struct ForLoopsOverFalliblesDiag<'a> { } #[derive(Subdiagnostic)] -pub enum ForLoopsOverFalliblesLoopSub<'a> { +pub(crate) enum ForLoopsOverFalliblesLoopSub<'a> { #[suggestion(lint_remove_next, code = ".by_ref()", applicability = "maybe-incorrect")] RemoveNext { #[primary_span] @@ -636,14 +636,14 @@ pub enum ForLoopsOverFalliblesLoopSub<'a> { #[derive(Subdiagnostic)] #[suggestion(lint_use_question_mark, code = "?", applicability = "maybe-incorrect")] -pub struct ForLoopsOverFalliblesQuestionMark { +pub(crate) struct ForLoopsOverFalliblesQuestionMark { #[primary_span] pub suggestion: Span, } #[derive(Subdiagnostic)] #[multipart_suggestion(lint_suggestion, applicability = "maybe-incorrect")] -pub struct ForLoopsOverFalliblesSuggestion<'a> { +pub(crate) struct ForLoopsOverFalliblesSuggestion<'a> { pub var: &'a str, #[suggestion_part(code = "if let {var}(")] pub start_span: Span, @@ -652,7 +652,7 @@ pub struct ForLoopsOverFalliblesSuggestion<'a> { } #[derive(Subdiagnostic)] -pub enum UseLetUnderscoreIgnoreSuggestion { +pub(crate) enum UseLetUnderscoreIgnoreSuggestion { #[note(lint_use_let_underscore_ignore_suggestion)] Note, #[multipart_suggestion( @@ -671,7 +671,7 @@ pub enum UseLetUnderscoreIgnoreSuggestion { // drop_forget_useless.rs #[derive(LintDiagnostic)] #[diag(lint_dropping_references)] -pub struct DropRefDiag<'a> { +pub(crate) struct DropRefDiag<'a> { pub arg_ty: Ty<'a>, #[label] pub label: Span, @@ -681,7 +681,7 @@ pub struct DropRefDiag<'a> { #[derive(LintDiagnostic)] #[diag(lint_dropping_copy_types)] -pub struct DropCopyDiag<'a> { +pub(crate) struct DropCopyDiag<'a> { pub arg_ty: Ty<'a>, #[label] pub label: Span, @@ -691,7 +691,7 @@ pub struct DropCopyDiag<'a> { #[derive(LintDiagnostic)] #[diag(lint_forgetting_references)] -pub struct ForgetRefDiag<'a> { +pub(crate) struct ForgetRefDiag<'a> { pub arg_ty: Ty<'a>, #[label] pub label: Span, @@ -701,7 +701,7 @@ pub struct ForgetRefDiag<'a> { #[derive(LintDiagnostic)] #[diag(lint_forgetting_copy_types)] -pub struct ForgetCopyDiag<'a> { +pub(crate) struct ForgetCopyDiag<'a> { pub arg_ty: Ty<'a>, #[label] pub label: Span, @@ -711,7 +711,7 @@ pub struct ForgetCopyDiag<'a> { #[derive(LintDiagnostic)] #[diag(lint_undropped_manually_drops)] -pub struct UndroppedManuallyDropsDiag<'a> { +pub(crate) struct UndroppedManuallyDropsDiag<'a> { pub arg_ty: Ty<'a>, #[label] pub label: Span, @@ -721,7 +721,7 @@ pub struct UndroppedManuallyDropsDiag<'a> { #[derive(Subdiagnostic)] #[multipart_suggestion(lint_suggestion, applicability = "machine-applicable")] -pub struct UndroppedManuallyDropsSuggestion { +pub(crate) struct UndroppedManuallyDropsSuggestion { #[suggestion_part(code = "std::mem::ManuallyDrop::into_inner(")] pub start_span: Span, #[suggestion_part(code = ")")] @@ -730,7 +730,7 @@ pub struct UndroppedManuallyDropsSuggestion { // invalid_from_utf8.rs #[derive(LintDiagnostic)] -pub enum InvalidFromUtf8Diag { +pub(crate) enum InvalidFromUtf8Diag { #[diag(lint_invalid_from_utf8_unchecked)] Unchecked { method: String, @@ -749,7 +749,7 @@ pub enum InvalidFromUtf8Diag { // reference_casting.rs #[derive(LintDiagnostic)] -pub enum InvalidReferenceCastingDiag<'tcx> { +pub(crate) enum InvalidReferenceCastingDiag<'tcx> { #[diag(lint_invalid_reference_casting_borrow_as_mut)] #[note(lint_invalid_reference_casting_note_book)] BorrowAsMut { @@ -784,7 +784,7 @@ pub enum InvalidReferenceCastingDiag<'tcx> { #[derive(LintDiagnostic)] #[diag(lint_hidden_unicode_codepoints)] #[note] -pub struct HiddenUnicodeCodepointsDiag<'a> { +pub(crate) struct HiddenUnicodeCodepointsDiag<'a> { pub label: &'a str, pub count: usize, #[label] @@ -795,7 +795,7 @@ pub struct HiddenUnicodeCodepointsDiag<'a> { pub sub: HiddenUnicodeCodepointsDiagSub, } -pub struct HiddenUnicodeCodepointsDiagLabels { +pub(crate) struct HiddenUnicodeCodepointsDiagLabels { pub spans: Vec<(char, Span)>, } @@ -811,7 +811,7 @@ impl Subdiagnostic for HiddenUnicodeCodepointsDiagLabels { } } -pub enum HiddenUnicodeCodepointsDiagSub { +pub(crate) enum HiddenUnicodeCodepointsDiagSub { Escape { spans: Vec<(char, Span)> }, NoEscape { spans: Vec<(char, Span)> }, } @@ -866,7 +866,7 @@ impl Subdiagnostic for HiddenUnicodeCodepointsDiagSub { #[derive(LintDiagnostic)] #[diag(lint_map_unit_fn)] #[note] -pub struct MappingToUnit { +pub(crate) struct MappingToUnit { #[label(lint_function_label)] pub function_label: Span, #[label(lint_argument_label)] @@ -882,7 +882,7 @@ pub struct MappingToUnit { #[derive(LintDiagnostic)] #[diag(lint_default_hash_types)] #[note] -pub struct DefaultHashTypesDiag<'a> { +pub(crate) struct DefaultHashTypesDiag<'a> { pub preferred: &'a str, pub used: Symbol, } @@ -890,17 +890,17 @@ pub struct DefaultHashTypesDiag<'a> { #[derive(LintDiagnostic)] #[diag(lint_query_instability)] #[note] -pub struct QueryInstability { +pub(crate) struct QueryInstability { pub query: Symbol, } #[derive(LintDiagnostic)] #[diag(lint_span_use_eq_ctxt)] -pub struct SpanUseEqCtxtDiag; +pub(crate) struct SpanUseEqCtxtDiag; #[derive(LintDiagnostic)] #[diag(lint_tykind_kind)] -pub struct TykindKind { +pub(crate) struct TykindKind { #[suggestion(code = "ty", applicability = "maybe-incorrect")] pub suggestion: Span, } @@ -908,11 +908,11 @@ pub struct TykindKind { #[derive(LintDiagnostic)] #[diag(lint_tykind)] #[help] -pub struct TykindDiag; +pub(crate) struct TykindDiag; #[derive(LintDiagnostic)] #[diag(lint_ty_qualified)] -pub struct TyQualified { +pub(crate) struct TyQualified { pub ty: String, #[suggestion(code = "{ty}", applicability = "maybe-incorrect")] pub suggestion: Span, @@ -920,7 +920,7 @@ pub struct TyQualified { #[derive(LintDiagnostic)] #[diag(lint_non_glob_import_type_ir_inherent)] -pub struct NonGlobImportTypeIrInherent { +pub(crate) struct NonGlobImportTypeIrInherent { #[suggestion(code = "{snippet}", applicability = "maybe-incorrect")] pub suggestion: Option<Span>, pub snippet: &'static str, @@ -929,32 +929,32 @@ pub struct NonGlobImportTypeIrInherent { #[derive(LintDiagnostic)] #[diag(lint_lintpass_by_hand)] #[help] -pub struct LintPassByHand; +pub(crate) struct LintPassByHand; #[derive(LintDiagnostic)] #[diag(lint_non_existent_doc_keyword)] #[help] -pub struct NonExistentDocKeyword { +pub(crate) struct NonExistentDocKeyword { pub keyword: Symbol, } #[derive(LintDiagnostic)] #[diag(lint_diag_out_of_impl)] -pub struct DiagOutOfImpl; +pub(crate) struct DiagOutOfImpl; #[derive(LintDiagnostic)] #[diag(lint_untranslatable_diag)] -pub struct UntranslatableDiag; +pub(crate) struct UntranslatableDiag; #[derive(LintDiagnostic)] #[diag(lint_bad_opt_access)] -pub struct BadOptAccessDiag<'a> { +pub(crate) struct BadOptAccessDiag<'a> { pub msg: &'a str, } // let_underscore.rs #[derive(LintDiagnostic)] -pub enum NonBindingLet { +pub(crate) enum NonBindingLet { #[diag(lint_non_binding_let_on_sync_lock)] SyncLock { #[label] @@ -969,7 +969,7 @@ pub enum NonBindingLet { }, } -pub struct NonBindingLetSub { +pub(crate) struct NonBindingLetSub { pub suggestion: Span, pub drop_fn_start_end: Option<(Span, Span)>, pub is_assign_desugar: bool, @@ -1012,7 +1012,7 @@ impl Subdiagnostic for NonBindingLetSub { // levels.rs #[derive(LintDiagnostic)] #[diag(lint_overruled_attribute)] -pub struct OverruledAttributeLint<'a> { +pub(crate) struct OverruledAttributeLint<'a> { #[label] pub overruled: Span, pub lint_level: &'a str, @@ -1023,7 +1023,7 @@ pub struct OverruledAttributeLint<'a> { #[derive(LintDiagnostic)] #[diag(lint_deprecated_lint_name)] -pub struct DeprecatedLintName<'a> { +pub(crate) struct DeprecatedLintName<'a> { pub name: String, #[suggestion(code = "{replace}", applicability = "machine-applicable")] pub suggestion: Span, @@ -1033,7 +1033,7 @@ pub struct DeprecatedLintName<'a> { #[derive(LintDiagnostic)] #[diag(lint_deprecated_lint_name)] #[help] -pub struct DeprecatedLintNameFromCommandLine<'a> { +pub(crate) struct DeprecatedLintNameFromCommandLine<'a> { pub name: String, pub replace: &'a str, #[subdiagnostic] @@ -1042,14 +1042,14 @@ pub struct DeprecatedLintNameFromCommandLine<'a> { #[derive(LintDiagnostic)] #[diag(lint_renamed_lint)] -pub struct RenamedLint<'a> { +pub(crate) struct RenamedLint<'a> { pub name: &'a str, #[subdiagnostic] pub suggestion: RenamedLintSuggestion<'a>, } #[derive(Subdiagnostic)] -pub enum RenamedLintSuggestion<'a> { +pub(crate) enum RenamedLintSuggestion<'a> { #[suggestion(lint_suggestion, code = "{replace}", applicability = "machine-applicable")] WithSpan { #[primary_span] @@ -1062,7 +1062,7 @@ pub enum RenamedLintSuggestion<'a> { #[derive(LintDiagnostic)] #[diag(lint_renamed_lint)] -pub struct RenamedLintFromCommandLine<'a> { +pub(crate) struct RenamedLintFromCommandLine<'a> { pub name: &'a str, #[subdiagnostic] pub suggestion: RenamedLintSuggestion<'a>, @@ -1072,14 +1072,14 @@ pub struct RenamedLintFromCommandLine<'a> { #[derive(LintDiagnostic)] #[diag(lint_removed_lint)] -pub struct RemovedLint<'a> { +pub(crate) struct RemovedLint<'a> { pub name: &'a str, pub reason: &'a str, } #[derive(LintDiagnostic)] #[diag(lint_removed_lint)] -pub struct RemovedLintFromCommandLine<'a> { +pub(crate) struct RemovedLintFromCommandLine<'a> { pub name: &'a str, pub reason: &'a str, #[subdiagnostic] @@ -1088,14 +1088,14 @@ pub struct RemovedLintFromCommandLine<'a> { #[derive(LintDiagnostic)] #[diag(lint_unknown_lint)] -pub struct UnknownLint { +pub(crate) struct UnknownLint { pub name: String, #[subdiagnostic] pub suggestion: Option<UnknownLintSuggestion>, } #[derive(Subdiagnostic)] -pub enum UnknownLintSuggestion { +pub(crate) enum UnknownLintSuggestion { #[suggestion(lint_suggestion, code = "{replace}", applicability = "maybe-incorrect")] WithSpan { #[primary_span] @@ -1109,7 +1109,7 @@ pub enum UnknownLintSuggestion { #[derive(LintDiagnostic)] #[diag(lint_unknown_lint, code = E0602)] -pub struct UnknownLintFromCommandLine<'a> { +pub(crate) struct UnknownLintFromCommandLine<'a> { pub name: String, #[subdiagnostic] pub suggestion: Option<UnknownLintSuggestion>, @@ -1119,7 +1119,7 @@ pub struct UnknownLintFromCommandLine<'a> { #[derive(LintDiagnostic)] #[diag(lint_ignored_unless_crate_specified)] -pub struct IgnoredUnlessCrateSpecified<'a> { +pub(crate) struct IgnoredUnlessCrateSpecified<'a> { pub level: &'a str, pub name: Symbol, } @@ -1129,7 +1129,7 @@ pub struct IgnoredUnlessCrateSpecified<'a> { #[diag(lint_cstring_ptr)] #[note] #[help] -pub struct CStringPtr { +pub(crate) struct CStringPtr { #[label(lint_as_ptr_label)] pub as_ptr: Span, #[label(lint_unwrap_label)] @@ -1139,19 +1139,19 @@ pub struct CStringPtr { // multiple_supertrait_upcastable.rs #[derive(LintDiagnostic)] #[diag(lint_multiple_supertrait_upcastable)] -pub struct MultipleSupertraitUpcastable { +pub(crate) struct MultipleSupertraitUpcastable { pub ident: Ident, } // non_ascii_idents.rs #[derive(LintDiagnostic)] #[diag(lint_identifier_non_ascii_char)] -pub struct IdentifierNonAsciiChar; +pub(crate) struct IdentifierNonAsciiChar; #[derive(LintDiagnostic)] #[diag(lint_identifier_uncommon_codepoints)] #[note] -pub struct IdentifierUncommonCodepoints { +pub(crate) struct IdentifierUncommonCodepoints { pub codepoints: Vec<char>, pub codepoints_len: usize, pub identifier_type: &'static str, @@ -1159,7 +1159,7 @@ pub struct IdentifierUncommonCodepoints { #[derive(LintDiagnostic)] #[diag(lint_confusable_identifier_pair)] -pub struct ConfusableIdentifierPair { +pub(crate) struct ConfusableIdentifierPair { pub existing_sym: Symbol, pub sym: Symbol, #[label(lint_other_use)] @@ -1172,13 +1172,13 @@ pub struct ConfusableIdentifierPair { #[diag(lint_mixed_script_confusables)] #[note(lint_includes_note)] #[note] -pub struct MixedScriptConfusables { +pub(crate) struct MixedScriptConfusables { pub set: String, pub includes: String, } // non_fmt_panic.rs -pub struct NonFmtPanicUnused { +pub(crate) struct NonFmtPanicUnused { pub count: usize, pub suggestion: Option<Span>, } @@ -1209,7 +1209,7 @@ impl<'a> LintDiagnostic<'a, ()> for NonFmtPanicUnused { #[derive(LintDiagnostic)] #[diag(lint_non_fmt_panic_braces)] #[note] -pub struct NonFmtPanicBraces { +pub(crate) struct NonFmtPanicBraces { pub count: usize, #[suggestion(code = "\"{{}}\", ", applicability = "machine-applicable")] pub suggestion: Option<Span>, @@ -1218,7 +1218,7 @@ pub struct NonFmtPanicBraces { // nonstandard_style.rs #[derive(LintDiagnostic)] #[diag(lint_non_camel_case_type)] -pub struct NonCamelCaseType<'a> { +pub(crate) struct NonCamelCaseType<'a> { pub sort: &'a str, pub name: &'a str, #[subdiagnostic] @@ -1226,7 +1226,7 @@ pub struct NonCamelCaseType<'a> { } #[derive(Subdiagnostic)] -pub enum NonCamelCaseTypeSub { +pub(crate) enum NonCamelCaseTypeSub { #[label(lint_label)] Label { #[primary_span] @@ -1242,7 +1242,7 @@ pub enum NonCamelCaseTypeSub { #[derive(LintDiagnostic)] #[diag(lint_non_snake_case)] -pub struct NonSnakeCaseDiag<'a> { +pub(crate) struct NonSnakeCaseDiag<'a> { pub sort: &'a str, pub name: &'a str, pub sc: String, @@ -1250,7 +1250,7 @@ pub struct NonSnakeCaseDiag<'a> { pub sub: NonSnakeCaseDiagSub, } -pub enum NonSnakeCaseDiagSub { +pub(crate) enum NonSnakeCaseDiagSub { Label { span: Span }, Help, RenameOrConvertSuggestion { span: Span, suggestion: Ident }, @@ -1302,7 +1302,7 @@ impl Subdiagnostic for NonSnakeCaseDiagSub { #[derive(LintDiagnostic)] #[diag(lint_non_upper_case_global)] -pub struct NonUpperCaseGlobal<'a> { +pub(crate) struct NonUpperCaseGlobal<'a> { pub sort: &'a str, pub name: &'a str, #[subdiagnostic] @@ -1310,7 +1310,7 @@ pub struct NonUpperCaseGlobal<'a> { } #[derive(Subdiagnostic)] -pub enum NonUpperCaseGlobalSub { +pub(crate) enum NonUpperCaseGlobalSub { #[label(lint_label)] Label { #[primary_span] @@ -1328,7 +1328,7 @@ pub enum NonUpperCaseGlobalSub { #[derive(LintDiagnostic)] #[diag(lint_noop_method_call)] #[note] -pub struct NoopMethodCallDiag<'a> { +pub(crate) struct NoopMethodCallDiag<'a> { pub method: Symbol, pub orig_ty: Ty<'a>, pub trait_: Symbol, @@ -1344,18 +1344,18 @@ pub struct NoopMethodCallDiag<'a> { #[derive(LintDiagnostic)] #[diag(lint_suspicious_double_ref_deref)] -pub struct SuspiciousDoubleRefDerefDiag<'a> { +pub(crate) struct SuspiciousDoubleRefDerefDiag<'a> { pub ty: Ty<'a>, } #[derive(LintDiagnostic)] #[diag(lint_suspicious_double_ref_clone)] -pub struct SuspiciousDoubleRefCloneDiag<'a> { +pub(crate) struct SuspiciousDoubleRefCloneDiag<'a> { pub ty: Ty<'a>, } // non_local_defs.rs -pub enum NonLocalDefinitionsDiag { +pub(crate) enum NonLocalDefinitionsDiag { Impl { depth: u32, body_kind_descr: &'static str, @@ -1487,7 +1487,7 @@ impl<'a> LintDiagnostic<'a, ()> for NonLocalDefinitionsDiag { #[derive(Subdiagnostic)] #[note(lint_non_local_definitions_cargo_update)] -pub struct NonLocalDefinitionsCargoUpdateNote { +pub(crate) struct NonLocalDefinitionsCargoUpdateNote { pub macro_kind: &'static str, pub macro_name: Symbol, pub crate_name: Symbol, @@ -1497,7 +1497,7 @@ pub struct NonLocalDefinitionsCargoUpdateNote { #[derive(LintDiagnostic)] #[diag(lint_ambiguous_negative_literals)] #[note(lint_example)] -pub struct AmbiguousNegativeLiteralsDiag { +pub(crate) struct AmbiguousNegativeLiteralsDiag { #[subdiagnostic] pub negative_literal: AmbiguousNegativeLiteralsNegativeLiteralSuggestion, #[subdiagnostic] @@ -1506,7 +1506,7 @@ pub struct AmbiguousNegativeLiteralsDiag { #[derive(Subdiagnostic)] #[multipart_suggestion(lint_negative_literal, applicability = "maybe-incorrect")] -pub struct AmbiguousNegativeLiteralsNegativeLiteralSuggestion { +pub(crate) struct AmbiguousNegativeLiteralsNegativeLiteralSuggestion { #[suggestion_part(code = "(")] pub start_span: Span, #[suggestion_part(code = ")")] @@ -1515,7 +1515,7 @@ pub struct AmbiguousNegativeLiteralsNegativeLiteralSuggestion { #[derive(Subdiagnostic)] #[multipart_suggestion(lint_current_behavior, applicability = "maybe-incorrect")] -pub struct AmbiguousNegativeLiteralsCurrentBehaviorSuggestion { +pub(crate) struct AmbiguousNegativeLiteralsCurrentBehaviorSuggestion { #[suggestion_part(code = "(")] pub start_span: Span, #[suggestion_part(code = ")")] @@ -1525,7 +1525,7 @@ pub struct AmbiguousNegativeLiteralsCurrentBehaviorSuggestion { // pass_by_value.rs #[derive(LintDiagnostic)] #[diag(lint_pass_by_value)] -pub struct PassByValueDiag { +pub(crate) struct PassByValueDiag { pub ty: String, #[suggestion(code = "{ty}", applicability = "maybe-incorrect")] pub suggestion: Span, @@ -1534,14 +1534,14 @@ pub struct PassByValueDiag { // redundant_semicolon.rs #[derive(LintDiagnostic)] #[diag(lint_redundant_semicolons)] -pub struct RedundantSemicolonsDiag { +pub(crate) struct RedundantSemicolonsDiag { pub multiple: bool, #[suggestion(code = "", applicability = "maybe-incorrect")] pub suggestion: Span, } // traits.rs -pub struct DropTraitConstraintsDiag<'a> { +pub(crate) struct DropTraitConstraintsDiag<'a> { pub predicate: Clause<'a>, pub tcx: TyCtxt<'a>, pub def_id: DefId, @@ -1556,7 +1556,7 @@ impl<'a> LintDiagnostic<'a, ()> for DropTraitConstraintsDiag<'_> { } } -pub struct DropGlue<'a> { +pub(crate) struct DropGlue<'a> { pub tcx: TyCtxt<'a>, pub def_id: DefId, } @@ -1572,14 +1572,14 @@ impl<'a> LintDiagnostic<'a, ()> for DropGlue<'_> { // types.rs #[derive(LintDiagnostic)] #[diag(lint_range_endpoint_out_of_range)] -pub struct RangeEndpointOutOfRange<'a> { +pub(crate) struct RangeEndpointOutOfRange<'a> { pub ty: &'a str, #[subdiagnostic] pub sub: UseInclusiveRange<'a>, } #[derive(Subdiagnostic)] -pub enum UseInclusiveRange<'a> { +pub(crate) enum UseInclusiveRange<'a> { #[suggestion( lint_range_use_inclusive_range, code = "{start}..={literal}{suffix}", @@ -1605,7 +1605,7 @@ pub enum UseInclusiveRange<'a> { #[derive(LintDiagnostic)] #[diag(lint_overflowing_bin_hex)] -pub struct OverflowingBinHex<'a> { +pub(crate) struct OverflowingBinHex<'a> { pub ty: &'a str, pub lit: String, pub dec: u128, @@ -1618,7 +1618,7 @@ pub struct OverflowingBinHex<'a> { pub sign_bit_sub: Option<OverflowingBinHexSignBitSub<'a>>, } -pub enum OverflowingBinHexSign { +pub(crate) enum OverflowingBinHexSign { Positive, Negative, } @@ -1642,7 +1642,7 @@ impl Subdiagnostic for OverflowingBinHexSign { } #[derive(Subdiagnostic)] -pub enum OverflowingBinHexSub<'a> { +pub(crate) enum OverflowingBinHexSub<'a> { #[suggestion( lint_suggestion, code = "{sans_suffix}{suggestion_ty}", @@ -1664,7 +1664,7 @@ pub enum OverflowingBinHexSub<'a> { code = "{lit_no_suffix}{uint_ty} as {int_ty}", applicability = "maybe-incorrect" )] -pub struct OverflowingBinHexSignBitSub<'a> { +pub(crate) struct OverflowingBinHexSignBitSub<'a> { #[primary_span] pub span: Span, pub lit_no_suffix: &'a str, @@ -1676,7 +1676,7 @@ pub struct OverflowingBinHexSignBitSub<'a> { #[derive(LintDiagnostic)] #[diag(lint_overflowing_int)] #[note] -pub struct OverflowingInt<'a> { +pub(crate) struct OverflowingInt<'a> { pub ty: &'a str, pub lit: String, pub min: i128, @@ -1687,13 +1687,13 @@ pub struct OverflowingInt<'a> { #[derive(Subdiagnostic)] #[help(lint_help)] -pub struct OverflowingIntHelp<'a> { +pub(crate) struct OverflowingIntHelp<'a> { pub suggestion_ty: &'a str, } #[derive(LintDiagnostic)] #[diag(lint_only_cast_u8_to_char)] -pub struct OnlyCastu8ToChar { +pub(crate) struct OnlyCastu8ToChar { #[suggestion(code = "'\\u{{{literal:X}}}'", applicability = "machine-applicable")] pub span: Span, pub literal: u128, @@ -1702,7 +1702,7 @@ pub struct OnlyCastu8ToChar { #[derive(LintDiagnostic)] #[diag(lint_overflowing_uint)] #[note] -pub struct OverflowingUInt<'a> { +pub(crate) struct OverflowingUInt<'a> { pub ty: &'a str, pub lit: String, pub min: u128, @@ -1712,17 +1712,17 @@ pub struct OverflowingUInt<'a> { #[derive(LintDiagnostic)] #[diag(lint_overflowing_literal)] #[note] -pub struct OverflowingLiteral<'a> { +pub(crate) struct OverflowingLiteral<'a> { pub ty: &'a str, pub lit: String, } #[derive(LintDiagnostic)] #[diag(lint_unused_comparisons)] -pub struct UnusedComparisons; +pub(crate) struct UnusedComparisons; #[derive(LintDiagnostic)] -pub enum InvalidNanComparisons { +pub(crate) enum InvalidNanComparisons { #[diag(lint_invalid_nan_comparisons_eq_ne)] EqNe { #[subdiagnostic] @@ -1733,7 +1733,7 @@ pub enum InvalidNanComparisons { } #[derive(Subdiagnostic)] -pub enum InvalidNanComparisonsSuggestion { +pub(crate) enum InvalidNanComparisonsSuggestion { #[multipart_suggestion( lint_suggestion, style = "verbose", @@ -1752,7 +1752,7 @@ pub enum InvalidNanComparisonsSuggestion { } #[derive(LintDiagnostic)] -pub enum AmbiguousWidePointerComparisons<'a> { +pub(crate) enum AmbiguousWidePointerComparisons<'a> { #[diag(lint_ambiguous_wide_pointer_comparisons)] Spanful { #[subdiagnostic] @@ -1773,7 +1773,7 @@ pub enum AmbiguousWidePointerComparisons<'a> { // FIXME(#53934): make machine-applicable again applicability = "maybe-incorrect" )] -pub struct AmbiguousWidePointerComparisonsAddrMetadataSuggestion<'a> { +pub(crate) struct AmbiguousWidePointerComparisonsAddrMetadataSuggestion<'a> { pub ne: &'a str, pub deref_left: &'a str, pub deref_right: &'a str, @@ -1788,7 +1788,7 @@ pub struct AmbiguousWidePointerComparisonsAddrMetadataSuggestion<'a> { } #[derive(Subdiagnostic)] -pub enum AmbiguousWidePointerComparisonsAddrSuggestion<'a> { +pub(crate) enum AmbiguousWidePointerComparisonsAddrSuggestion<'a> { #[multipart_suggestion( lint_addr_suggestion, style = "verbose", @@ -1832,7 +1832,7 @@ pub enum AmbiguousWidePointerComparisonsAddrSuggestion<'a> { }, } -pub struct ImproperCTypes<'a> { +pub(crate) struct ImproperCTypes<'a> { pub ty: Ty<'a>, pub desc: &'a str, pub label: Span, @@ -1860,29 +1860,29 @@ impl<'a> LintDiagnostic<'a, ()> for ImproperCTypes<'_> { #[derive(LintDiagnostic)] #[diag(lint_variant_size_differences)] -pub struct VariantSizeDifferencesDiag { +pub(crate) struct VariantSizeDifferencesDiag { pub largest: u64, } #[derive(LintDiagnostic)] #[diag(lint_atomic_ordering_load)] #[help] -pub struct AtomicOrderingLoad; +pub(crate) struct AtomicOrderingLoad; #[derive(LintDiagnostic)] #[diag(lint_atomic_ordering_store)] #[help] -pub struct AtomicOrderingStore; +pub(crate) struct AtomicOrderingStore; #[derive(LintDiagnostic)] #[diag(lint_atomic_ordering_fence)] #[help] -pub struct AtomicOrderingFence; +pub(crate) struct AtomicOrderingFence; #[derive(LintDiagnostic)] #[diag(lint_atomic_ordering_invalid)] #[help] -pub struct InvalidAtomicOrderingDiag { +pub(crate) struct InvalidAtomicOrderingDiag { pub method: Symbol, #[label] pub fail_order_arg_span: Span, @@ -1891,7 +1891,7 @@ pub struct InvalidAtomicOrderingDiag { // unused.rs #[derive(LintDiagnostic)] #[diag(lint_unused_op)] -pub struct UnusedOp<'a> { +pub(crate) struct UnusedOp<'a> { pub op: &'a str, #[label] pub label: Span, @@ -1900,7 +1900,7 @@ pub struct UnusedOp<'a> { } #[derive(Subdiagnostic)] -pub enum UnusedOpSuggestion { +pub(crate) enum UnusedOpSuggestion { #[suggestion( lint_suggestion, style = "verbose", @@ -1922,7 +1922,7 @@ pub enum UnusedOpSuggestion { #[derive(LintDiagnostic)] #[diag(lint_unused_result)] -pub struct UnusedResult<'a> { +pub(crate) struct UnusedResult<'a> { pub ty: Ty<'a>, } @@ -1931,7 +1931,7 @@ pub struct UnusedResult<'a> { #[derive(LintDiagnostic)] #[diag(lint_unused_closure)] #[note] -pub struct UnusedClosure<'a> { +pub(crate) struct UnusedClosure<'a> { pub count: usize, pub pre: &'a str, pub post: &'a str, @@ -1942,7 +1942,7 @@ pub struct UnusedClosure<'a> { #[derive(LintDiagnostic)] #[diag(lint_unused_coroutine)] #[note] -pub struct UnusedCoroutine<'a> { +pub(crate) struct UnusedCoroutine<'a> { pub count: usize, pub pre: &'a str, pub post: &'a str, @@ -1950,7 +1950,7 @@ pub struct UnusedCoroutine<'a> { // FIXME(davidtwco): this isn't properly translatable because of the pre/post // strings -pub struct UnusedDef<'a, 'b> { +pub(crate) struct UnusedDef<'a, 'b> { pub pre: &'a str, pub post: &'a str, pub cx: &'a LateContext<'b>, @@ -1961,7 +1961,7 @@ pub struct UnusedDef<'a, 'b> { #[derive(Subdiagnostic)] -pub enum UnusedDefSuggestion { +pub(crate) enum UnusedDefSuggestion { #[suggestion( lint_suggestion, style = "verbose", @@ -2000,13 +2000,13 @@ impl<'a> LintDiagnostic<'a, ()> for UnusedDef<'_, '_> { #[derive(LintDiagnostic)] #[diag(lint_path_statement_drop)] -pub struct PathStatementDrop { +pub(crate) struct PathStatementDrop { #[subdiagnostic] pub sub: PathStatementDropSub, } #[derive(Subdiagnostic)] -pub enum PathStatementDropSub { +pub(crate) enum PathStatementDropSub { #[suggestion(lint_suggestion, code = "drop({snippet});", applicability = "machine-applicable")] Suggestion { #[primary_span] @@ -2022,11 +2022,11 @@ pub enum PathStatementDropSub { #[derive(LintDiagnostic)] #[diag(lint_path_statement_no_effect)] -pub struct PathStatementNoEffect; +pub(crate) struct PathStatementNoEffect; #[derive(LintDiagnostic)] #[diag(lint_unused_delim)] -pub struct UnusedDelim<'a> { +pub(crate) struct UnusedDelim<'a> { pub delim: &'static str, pub item: &'a str, #[subdiagnostic] @@ -2035,7 +2035,7 @@ pub struct UnusedDelim<'a> { #[derive(Subdiagnostic)] #[multipart_suggestion(lint_suggestion, applicability = "machine-applicable")] -pub struct UnusedDelimSuggestion { +pub(crate) struct UnusedDelimSuggestion { #[suggestion_part(code = "{start_replace}")] pub start_span: Span, pub start_replace: &'static str, @@ -2046,19 +2046,19 @@ pub struct UnusedDelimSuggestion { #[derive(LintDiagnostic)] #[diag(lint_unused_import_braces)] -pub struct UnusedImportBracesDiag { +pub(crate) struct UnusedImportBracesDiag { pub node: Symbol, } #[derive(LintDiagnostic)] #[diag(lint_unused_allocation)] -pub struct UnusedAllocationDiag; +pub(crate) struct UnusedAllocationDiag; #[derive(LintDiagnostic)] #[diag(lint_unused_allocation_mut)] -pub struct UnusedAllocationMutDiag; +pub(crate) struct UnusedAllocationMutDiag; -pub struct AsyncFnInTraitDiag { +pub(crate) struct AsyncFnInTraitDiag { pub sugg: Option<Vec<(Span, String)>>, } @@ -2074,13 +2074,13 @@ impl<'a> LintDiagnostic<'a, ()> for AsyncFnInTraitDiag { #[derive(LintDiagnostic)] #[diag(lint_unit_bindings)] -pub struct UnitBindingsDiag { +pub(crate) struct UnitBindingsDiag { #[label] pub label: Span, } #[derive(LintDiagnostic)] -pub enum InvalidAsmLabel { +pub(crate) enum InvalidAsmLabel { #[diag(lint_invalid_asm_label_named)] #[help] #[note] @@ -2110,7 +2110,7 @@ pub enum InvalidAsmLabel { } #[derive(Subdiagnostic)] -pub enum UnexpectedCfgCargoHelp { +pub(crate) enum UnexpectedCfgCargoHelp { #[help(lint_unexpected_cfg_add_cargo_feature)] #[help(lint_unexpected_cfg_add_cargo_toml_lint_cfg)] LintCfg { cargo_toml_lint_cfg: String }, @@ -2127,13 +2127,13 @@ impl UnexpectedCfgCargoHelp { ) } - pub fn lint_cfg(unescaped: &str) -> Self { + pub(crate) fn lint_cfg(unescaped: &str) -> Self { UnexpectedCfgCargoHelp::LintCfg { cargo_toml_lint_cfg: Self::cargo_toml_lint_cfg(unescaped), } } - pub fn lint_cfg_and_build_rs(unescaped: &str, escaped: &str) -> Self { + pub(crate) fn lint_cfg_and_build_rs(unescaped: &str, escaped: &str) -> Self { UnexpectedCfgCargoHelp::LintCfgAndBuildRs { cargo_toml_lint_cfg: Self::cargo_toml_lint_cfg(unescaped), build_rs_println: format!("println!(\"cargo::rustc-check-cfg={escaped}\");"), @@ -2143,19 +2143,19 @@ impl UnexpectedCfgCargoHelp { #[derive(Subdiagnostic)] #[help(lint_unexpected_cfg_add_cmdline_arg)] -pub struct UnexpectedCfgRustcHelp { +pub(crate) struct UnexpectedCfgRustcHelp { pub cmdline_arg: String, } impl UnexpectedCfgRustcHelp { - pub fn new(unescaped: &str) -> Self { + pub(crate) fn new(unescaped: &str) -> Self { Self { cmdline_arg: format!("--check-cfg={unescaped}") } } } #[derive(LintDiagnostic)] #[diag(lint_unexpected_cfg_name)] -pub struct UnexpectedCfgName { +pub(crate) struct UnexpectedCfgName { #[subdiagnostic] pub code_sugg: unexpected_cfg_name::CodeSuggestion, #[subdiagnostic] @@ -2164,13 +2164,13 @@ pub struct UnexpectedCfgName { pub name: Symbol, } -pub mod unexpected_cfg_name { +pub(crate) mod unexpected_cfg_name { use rustc_errors::DiagSymbolList; use rustc_macros::Subdiagnostic; use rustc_span::{Span, Symbol}; #[derive(Subdiagnostic)] - pub enum CodeSuggestion { + pub(crate) enum CodeSuggestion { #[help(lint_unexpected_cfg_define_features)] DefineFeatures, #[suggestion( @@ -2227,7 +2227,7 @@ pub mod unexpected_cfg_name { #[derive(Subdiagnostic)] #[help(lint_unexpected_cfg_name_expected_values)] - pub struct ExpectedValues { + pub(crate) struct ExpectedValues { pub best_match: Symbol, pub possibilities: DiagSymbolList, } @@ -2238,7 +2238,7 @@ pub mod unexpected_cfg_name { applicability = "maybe-incorrect", code = "{code}" )] - pub struct FoundWithSimilarValue { + pub(crate) struct FoundWithSimilarValue { #[primary_span] pub span: Span, pub code: String, @@ -2246,13 +2246,13 @@ pub mod unexpected_cfg_name { #[derive(Subdiagnostic)] #[help_once(lint_unexpected_cfg_name_expected_names)] - pub struct ExpectedNames { + pub(crate) struct ExpectedNames { pub possibilities: DiagSymbolList, pub and_more: usize, } #[derive(Subdiagnostic)] - pub enum InvocationHelp { + pub(crate) enum InvocationHelp { #[note(lint_unexpected_cfg_doc_cargo)] Cargo { #[subdiagnostic] @@ -2265,7 +2265,7 @@ pub mod unexpected_cfg_name { #[derive(LintDiagnostic)] #[diag(lint_unexpected_cfg_value)] -pub struct UnexpectedCfgValue { +pub(crate) struct UnexpectedCfgValue { #[subdiagnostic] pub code_sugg: unexpected_cfg_value::CodeSuggestion, #[subdiagnostic] @@ -2275,13 +2275,13 @@ pub struct UnexpectedCfgValue { pub value: String, } -pub mod unexpected_cfg_value { +pub(crate) mod unexpected_cfg_value { use rustc_errors::DiagSymbolList; use rustc_macros::Subdiagnostic; use rustc_span::{Span, Symbol}; #[derive(Subdiagnostic)] - pub enum CodeSuggestion { + pub(crate) enum CodeSuggestion { ChangeValue { #[subdiagnostic] expected_values: ExpectedValues, @@ -2305,7 +2305,7 @@ pub mod unexpected_cfg_value { } #[derive(Subdiagnostic)] - pub enum ChangeValueSuggestion { + pub(crate) enum ChangeValueSuggestion { #[suggestion( lint_unexpected_cfg_value_similar_name, code = r#""{best_match}""#, @@ -2334,7 +2334,7 @@ pub mod unexpected_cfg_value { code = "", applicability = "maybe-incorrect" )] - pub struct RemoveValueSuggestion { + pub(crate) struct RemoveValueSuggestion { #[primary_span] pub span: Span, } @@ -2345,14 +2345,14 @@ pub mod unexpected_cfg_value { code = "", applicability = "maybe-incorrect" )] - pub struct RemoveConditionSuggestion { + pub(crate) struct RemoveConditionSuggestion { #[primary_span] pub span: Span, } #[derive(Subdiagnostic)] #[note(lint_unexpected_cfg_value_expected_values)] - pub struct ExpectedValues { + pub(crate) struct ExpectedValues { pub name: Symbol, pub have_none_possibility: bool, pub possibilities: DiagSymbolList, @@ -2360,7 +2360,7 @@ pub mod unexpected_cfg_value { } #[derive(Subdiagnostic)] - pub enum InvocationHelp { + pub(crate) enum InvocationHelp { #[note(lint_unexpected_cfg_doc_cargo)] Cargo(#[subdiagnostic] Option<CargoHelp>), #[note(lint_unexpected_cfg_doc_rustc)] @@ -2368,7 +2368,7 @@ pub mod unexpected_cfg_value { } #[derive(Subdiagnostic)] - pub enum CargoHelp { + pub(crate) enum CargoHelp { #[help(lint_unexpected_cfg_value_add_feature)] AddFeature { value: Symbol, @@ -2383,7 +2383,7 @@ pub mod unexpected_cfg_value { #[diag(lint_unexpected_builtin_cfg)] #[note(lint_controlled_by)] #[note(lint_incoherent)] -pub struct UnexpectedBuiltinCfg { +pub(crate) struct UnexpectedBuiltinCfg { pub(crate) cfg: String, pub(crate) cfg_name: Symbol, pub(crate) controlled_by: &'static str, @@ -2392,15 +2392,15 @@ pub struct UnexpectedBuiltinCfg { #[derive(LintDiagnostic)] #[diag(lint_macro_use_deprecated)] #[help] -pub struct MacroUseDeprecated; +pub(crate) struct MacroUseDeprecated; #[derive(LintDiagnostic)] #[diag(lint_unused_macro_use)] -pub struct UnusedMacroUse; +pub(crate) struct UnusedMacroUse; #[derive(LintDiagnostic)] #[diag(lint_private_extern_crate_reexport, code = E0365)] -pub struct PrivateExternCrateReexport { +pub(crate) struct PrivateExternCrateReexport { pub ident: Ident, #[suggestion(code = "pub ", style = "verbose", applicability = "maybe-incorrect")] pub sugg: Span, @@ -2408,28 +2408,28 @@ pub struct PrivateExternCrateReexport { #[derive(LintDiagnostic)] #[diag(lint_unused_label)] -pub struct UnusedLabel; +pub(crate) struct UnusedLabel; #[derive(LintDiagnostic)] #[diag(lint_macro_is_private)] -pub struct MacroIsPrivate { +pub(crate) struct MacroIsPrivate { pub ident: Ident, } #[derive(LintDiagnostic)] #[diag(lint_unused_macro_definition)] -pub struct UnusedMacroDefinition { +pub(crate) struct UnusedMacroDefinition { pub name: Symbol, } #[derive(LintDiagnostic)] #[diag(lint_macro_rule_never_used)] -pub struct MacroRuleNeverUsed { +pub(crate) struct MacroRuleNeverUsed { pub n: usize, pub name: Symbol, } -pub struct UnstableFeature { +pub(crate) struct UnstableFeature { pub msg: DiagMessage, } @@ -2441,81 +2441,81 @@ impl<'a> LintDiagnostic<'a, ()> for UnstableFeature { #[derive(LintDiagnostic)] #[diag(lint_avoid_intel_syntax)] -pub struct AvoidIntelSyntax; +pub(crate) struct AvoidIntelSyntax; #[derive(LintDiagnostic)] #[diag(lint_avoid_att_syntax)] -pub struct AvoidAttSyntax; +pub(crate) struct AvoidAttSyntax; #[derive(LintDiagnostic)] #[diag(lint_incomplete_include)] -pub struct IncompleteInclude; +pub(crate) struct IncompleteInclude; #[derive(LintDiagnostic)] #[diag(lint_unnameable_test_items)] -pub struct UnnameableTestItems; +pub(crate) struct UnnameableTestItems; #[derive(LintDiagnostic)] #[diag(lint_duplicate_macro_attribute)] -pub struct DuplicateMacroAttribute; +pub(crate) struct DuplicateMacroAttribute; #[derive(LintDiagnostic)] #[diag(lint_cfg_attr_no_attributes)] -pub struct CfgAttrNoAttributes; +pub(crate) struct CfgAttrNoAttributes; #[derive(LintDiagnostic)] #[diag(lint_crate_type_in_cfg_attr_deprecated)] -pub struct CrateTypeInCfgAttr; +pub(crate) struct CrateTypeInCfgAttr; #[derive(LintDiagnostic)] #[diag(lint_crate_name_in_cfg_attr_deprecated)] -pub struct CrateNameInCfgAttr; +pub(crate) struct CrateNameInCfgAttr; #[derive(LintDiagnostic)] #[diag(lint_missing_fragment_specifier)] -pub struct MissingFragmentSpecifier; +pub(crate) struct MissingFragmentSpecifier; #[derive(LintDiagnostic)] #[diag(lint_metavariable_still_repeating)] -pub struct MetaVariableStillRepeating { +pub(crate) struct MetaVariableStillRepeating { pub name: MacroRulesNormalizedIdent, } #[derive(LintDiagnostic)] #[diag(lint_metavariable_wrong_operator)] -pub struct MetaVariableWrongOperator; +pub(crate) struct MetaVariableWrongOperator; #[derive(LintDiagnostic)] #[diag(lint_duplicate_matcher_binding)] -pub struct DuplicateMatcherBinding; +pub(crate) struct DuplicateMatcherBinding; #[derive(LintDiagnostic)] #[diag(lint_unknown_macro_variable)] -pub struct UnknownMacroVariable { +pub(crate) struct UnknownMacroVariable { pub name: MacroRulesNormalizedIdent, } #[derive(LintDiagnostic)] #[diag(lint_unused_crate_dependency)] #[help] -pub struct UnusedCrateDependency { +pub(crate) struct UnusedCrateDependency { pub extern_crate: Symbol, pub local_crate: Symbol, } #[derive(LintDiagnostic)] #[diag(lint_wasm_c_abi)] -pub struct WasmCAbi; +pub(crate) struct WasmCAbi; #[derive(LintDiagnostic)] #[diag(lint_ill_formed_attribute_input)] -pub struct IllFormedAttributeInput { +pub(crate) struct IllFormedAttributeInput { pub num_suggestions: usize, pub suggestions: DiagArgValue, } #[derive(LintDiagnostic)] -pub enum InnerAttributeUnstable { +pub(crate) enum InnerAttributeUnstable { #[diag(lint_inner_macro_attribute_unstable)] InnerMacroAttribute, #[diag(lint_custom_inner_attribute_unstable)] @@ -2524,7 +2524,7 @@ pub enum InnerAttributeUnstable { #[derive(LintDiagnostic)] #[diag(lint_unknown_diagnostic_attribute)] -pub struct UnknownDiagnosticAttribute { +pub(crate) struct UnknownDiagnosticAttribute { #[subdiagnostic] pub typo: Option<UnknownDiagnosticAttributeTypoSugg>, } @@ -2536,7 +2536,7 @@ pub struct UnknownDiagnosticAttribute { code = "{typo_name}", applicability = "machine-applicable" )] -pub struct UnknownDiagnosticAttributeTypoSugg { +pub(crate) struct UnknownDiagnosticAttributeTypoSugg { #[primary_span] pub span: Span, pub typo_name: Symbol, @@ -2545,7 +2545,7 @@ pub struct UnknownDiagnosticAttributeTypoSugg { #[derive(LintDiagnostic)] #[diag(lint_unicode_text_flow)] #[note] -pub struct UnicodeTextFlow { +pub(crate) struct UnicodeTextFlow { #[label] pub comment_span: Span, #[subdiagnostic] @@ -2558,7 +2558,7 @@ pub struct UnicodeTextFlow { #[derive(Subdiagnostic)] #[label(lint_label_comment_char)] -pub struct UnicodeCharNoteSub { +pub(crate) struct UnicodeCharNoteSub { #[primary_span] pub span: Span, pub c_debug: String, @@ -2566,21 +2566,21 @@ pub struct UnicodeCharNoteSub { #[derive(Subdiagnostic)] #[multipart_suggestion(lint_suggestion, applicability = "machine-applicable", style = "hidden")] -pub struct UnicodeTextFlowSuggestion { +pub(crate) struct UnicodeTextFlowSuggestion { #[suggestion_part(code = "")] pub spans: Vec<Span>, } #[derive(LintDiagnostic)] #[diag(lint_abs_path_with_module)] -pub struct AbsPathWithModule { +pub(crate) struct AbsPathWithModule { #[subdiagnostic] pub sugg: AbsPathWithModuleSugg, } #[derive(Subdiagnostic)] #[suggestion(lint_suggestion, code = "{replacement}")] -pub struct AbsPathWithModuleSugg { +pub(crate) struct AbsPathWithModuleSugg { #[primary_span] pub span: Span, #[applicability] @@ -2590,7 +2590,7 @@ pub struct AbsPathWithModuleSugg { #[derive(LintDiagnostic)] #[diag(lint_proc_macro_derive_resolution_fallback)] -pub struct ProcMacroDeriveResolutionFallback { +pub(crate) struct ProcMacroDeriveResolutionFallback { #[label] pub span: Span, pub ns: Namespace, @@ -2599,28 +2599,28 @@ pub struct ProcMacroDeriveResolutionFallback { #[derive(LintDiagnostic)] #[diag(lint_macro_expanded_macro_exports_accessed_by_absolute_paths)] -pub struct MacroExpandedMacroExportsAccessedByAbsolutePaths { +pub(crate) struct MacroExpandedMacroExportsAccessedByAbsolutePaths { #[note] pub definition: Span, } #[derive(LintDiagnostic)] #[diag(lint_hidden_lifetime_parameters)] -pub struct ElidedLifetimesInPaths { +pub(crate) struct ElidedLifetimesInPaths { #[subdiagnostic] pub subdiag: ElidedLifetimeInPathSubdiag, } #[derive(LintDiagnostic)] #[diag(lint_invalid_crate_type_value)] -pub struct UnknownCrateTypes { +pub(crate) struct UnknownCrateTypes { #[subdiagnostic] pub sugg: Option<UnknownCrateTypesSub>, } #[derive(Subdiagnostic)] #[suggestion(lint_suggestion, code = r#""{candidate}""#, applicability = "maybe-incorrect")] -pub struct UnknownCrateTypesSub { +pub(crate) struct UnknownCrateTypesSub { #[primary_span] pub span: Span, pub candidate: Symbol, @@ -2628,7 +2628,7 @@ pub struct UnknownCrateTypesSub { #[derive(LintDiagnostic)] #[diag(lint_unused_imports)] -pub struct UnusedImports { +pub(crate) struct UnusedImports { #[subdiagnostic] pub sugg: UnusedImportsSugg, #[help] @@ -2639,7 +2639,7 @@ pub struct UnusedImports { } #[derive(Subdiagnostic)] -pub enum UnusedImportsSugg { +pub(crate) enum UnusedImportsSugg { #[suggestion( lint_suggestion_remove_whole_use, applicability = "machine-applicable", @@ -2664,7 +2664,7 @@ pub enum UnusedImportsSugg { #[derive(LintDiagnostic)] #[diag(lint_redundant_import)] -pub struct RedundantImport { +pub(crate) struct RedundantImport { #[subdiagnostic] pub subs: Vec<RedundantImportSub>, @@ -2672,7 +2672,7 @@ pub struct RedundantImport { } #[derive(Subdiagnostic)] -pub enum RedundantImportSub { +pub(crate) enum RedundantImportSub { #[label(lint_label_imported_here)] ImportedHere(#[primary_span] Span), #[label(lint_label_defined_here)] @@ -2686,13 +2686,13 @@ pub enum RedundantImportSub { #[derive(LintDiagnostic)] #[diag(lint_unused_doc_comment)] #[help] -pub struct UnusedDocComment { +pub(crate) struct UnusedDocComment { #[label] pub span: Span, } #[derive(LintDiagnostic)] -pub enum PatternsInFnsWithoutBody { +pub(crate) enum PatternsInFnsWithoutBody { #[diag(lint_pattern_in_foreign)] Foreign { #[subdiagnostic] @@ -2707,7 +2707,7 @@ pub enum PatternsInFnsWithoutBody { #[derive(Subdiagnostic)] #[suggestion(lint_remove_mut_from_pattern, code = "{ident}", applicability = "machine-applicable")] -pub struct PatternsInFnsWithoutBodySub { +pub(crate) struct PatternsInFnsWithoutBodySub { #[primary_span] pub span: Span, @@ -2717,7 +2717,7 @@ pub struct PatternsInFnsWithoutBodySub { #[derive(LintDiagnostic)] #[diag(lint_extern_without_abi)] #[help] -pub struct MissingAbi { +pub(crate) struct MissingAbi { #[label] pub span: Span, @@ -2726,14 +2726,14 @@ pub struct MissingAbi { #[derive(LintDiagnostic)] #[diag(lint_legacy_derive_helpers)] -pub struct LegacyDeriveHelpers { +pub(crate) struct LegacyDeriveHelpers { #[label] pub span: Span, } #[derive(LintDiagnostic)] #[diag(lint_or_patterns_back_compat)] -pub struct OrPatternsBackCompat { +pub(crate) struct OrPatternsBackCompat { #[suggestion(code = "{suggestion}", applicability = "machine-applicable")] pub span: Span, pub suggestion: String, @@ -2741,7 +2741,7 @@ pub struct OrPatternsBackCompat { #[derive(LintDiagnostic)] #[diag(lint_reserved_prefix)] -pub struct ReservedPrefix { +pub(crate) struct ReservedPrefix { #[label] pub label: Span, #[suggestion(code = " ", applicability = "machine-applicable")] @@ -2752,7 +2752,7 @@ pub struct ReservedPrefix { #[derive(LintDiagnostic)] #[diag(lint_unused_builtin_attribute)] -pub struct UnusedBuiltinAttribute { +pub(crate) struct UnusedBuiltinAttribute { #[note] pub invoc_span: Span, @@ -2762,7 +2762,7 @@ pub struct UnusedBuiltinAttribute { #[derive(LintDiagnostic)] #[diag(lint_trailing_semi_macro)] -pub struct TrailingMacro { +pub(crate) struct TrailingMacro { #[note(lint_note1)] #[note(lint_note2)] pub is_trailing: bool, @@ -2772,14 +2772,14 @@ pub struct TrailingMacro { #[derive(LintDiagnostic)] #[diag(lint_break_with_label_and_loop)] -pub struct BreakWithLabelAndLoop { +pub(crate) struct BreakWithLabelAndLoop { #[subdiagnostic] pub sub: BreakWithLabelAndLoopSub, } #[derive(Subdiagnostic)] #[multipart_suggestion(lint_suggestion, applicability = "machine-applicable")] -pub struct BreakWithLabelAndLoopSub { +pub(crate) struct BreakWithLabelAndLoopSub { #[suggestion_part(code = "(")] pub left: Span, #[suggestion_part(code = ")")] @@ -2789,13 +2789,13 @@ pub struct BreakWithLabelAndLoopSub { #[derive(LintDiagnostic)] #[diag(lint_deprecated_where_clause_location)] #[note] -pub struct DeprecatedWhereClauseLocation { +pub(crate) struct DeprecatedWhereClauseLocation { #[subdiagnostic] pub suggestion: DeprecatedWhereClauseLocationSugg, } #[derive(Subdiagnostic)] -pub enum DeprecatedWhereClauseLocationSugg { +pub(crate) enum DeprecatedWhereClauseLocationSugg { #[multipart_suggestion(lint_suggestion_move_to_end, applicability = "machine-applicable")] MoveToEnd { #[suggestion_part(code = "")] @@ -2814,14 +2814,14 @@ pub enum DeprecatedWhereClauseLocationSugg { #[derive(LintDiagnostic)] #[diag(lint_missing_unsafe_on_extern)] -pub struct MissingUnsafeOnExtern { +pub(crate) struct MissingUnsafeOnExtern { #[suggestion(code = "unsafe ", applicability = "machine-applicable")] pub suggestion: Span, } #[derive(LintDiagnostic)] #[diag(lint_single_use_lifetime)] -pub struct SingleUseLifetime { +pub(crate) struct SingleUseLifetime { #[label(lint_label_param)] pub param_span: Span, #[label(lint_label_use)] @@ -2834,7 +2834,7 @@ pub struct SingleUseLifetime { #[derive(Subdiagnostic)] #[multipart_suggestion(lint_suggestion, applicability = "machine-applicable")] -pub struct SingleUseLifetimeSugg { +pub(crate) struct SingleUseLifetimeSugg { #[suggestion_part(code = "")] pub deletion_span: Option<Span>, #[suggestion_part(code = "{replace_lt}")] @@ -2845,7 +2845,7 @@ pub struct SingleUseLifetimeSugg { #[derive(LintDiagnostic)] #[diag(lint_unused_lifetime)] -pub struct UnusedLifetime { +pub(crate) struct UnusedLifetime { #[suggestion(code = "", applicability = "machine-applicable")] pub deletion_span: Option<Span>, @@ -2854,7 +2854,7 @@ pub struct UnusedLifetime { #[derive(LintDiagnostic)] #[diag(lint_named_argument_used_positionally)] -pub struct NamedArgumentUsedPositionally { +pub(crate) struct NamedArgumentUsedPositionally { #[label(lint_label_named_arg)] pub named_arg_sp: Span, #[label(lint_label_position_arg)] @@ -2869,21 +2869,21 @@ pub struct NamedArgumentUsedPositionally { #[derive(LintDiagnostic)] #[diag(lint_byte_slice_in_packed_struct_with_derive)] #[help] -pub struct ByteSliceInPackedStructWithDerive { +pub(crate) struct ByteSliceInPackedStructWithDerive { // FIXME: make this translatable pub ty: String, } #[derive(LintDiagnostic)] #[diag(lint_unused_extern_crate)] -pub struct UnusedExternCrate { +pub(crate) struct UnusedExternCrate { #[suggestion(code = "", applicability = "machine-applicable")] pub removal_span: Span, } #[derive(LintDiagnostic)] #[diag(lint_extern_crate_not_idiomatic)] -pub struct ExternCrateNotIdiomatic { +pub(crate) struct ExternCrateNotIdiomatic { #[suggestion(style = "verbose", code = "{code}", applicability = "machine-applicable")] pub span: Span, @@ -2891,7 +2891,7 @@ pub struct ExternCrateNotIdiomatic { } // FIXME: make this translatable -pub struct AmbiguousGlobImports { +pub(crate) struct AmbiguousGlobImports { pub ambiguity: AmbiguityErrorDiag, } @@ -2904,7 +2904,7 @@ impl<'a, G: EmissionGuarantee> LintDiagnostic<'a, G> for AmbiguousGlobImports { #[derive(LintDiagnostic)] #[diag(lint_ambiguous_glob_reexport)] -pub struct AmbiguousGlobReexports { +pub(crate) struct AmbiguousGlobReexports { #[label(lint_label_first_reexport)] pub first_reexport: Span, #[label(lint_label_duplicate_reexport)] @@ -2917,7 +2917,7 @@ pub struct AmbiguousGlobReexports { #[derive(LintDiagnostic)] #[diag(lint_hidden_glob_reexport)] -pub struct HiddenGlobReexports { +pub(crate) struct HiddenGlobReexports { #[note(lint_note_glob_reexport)] pub glob_reexport: Span, #[note(lint_note_private_item)] @@ -2930,14 +2930,14 @@ pub struct HiddenGlobReexports { #[derive(LintDiagnostic)] #[diag(lint_unnecessary_qualification)] -pub struct UnusedQualifications { +pub(crate) struct UnusedQualifications { #[suggestion(style = "verbose", code = "", applicability = "machine-applicable")] pub removal_span: Span, } #[derive(LintDiagnostic)] #[diag(lint_associated_const_elided_lifetime)] -pub struct AssociatedConstElidedLifetime { +pub(crate) struct AssociatedConstElidedLifetime { #[suggestion(style = "verbose", code = "{code}", applicability = "machine-applicable")] pub span: Span, @@ -2949,7 +2949,7 @@ pub struct AssociatedConstElidedLifetime { #[derive(LintDiagnostic)] #[diag(lint_redundant_import_visibility)] -pub struct RedundantImportVisibility { +pub(crate) struct RedundantImportVisibility { #[note] pub span: Span, #[help] @@ -2961,7 +2961,7 @@ pub struct RedundantImportVisibility { #[derive(LintDiagnostic)] #[diag(lint_unsafe_attr_outside_unsafe)] -pub struct UnsafeAttrOutsideUnsafe { +pub(crate) struct UnsafeAttrOutsideUnsafe { #[label] pub span: Span, #[subdiagnostic] @@ -2973,7 +2973,7 @@ pub struct UnsafeAttrOutsideUnsafe { lint_unsafe_attr_outside_unsafe_suggestion, applicability = "machine-applicable" )] -pub struct UnsafeAttrOutsideUnsafeSuggestion { +pub(crate) struct UnsafeAttrOutsideUnsafeSuggestion { #[suggestion_part(code = "unsafe(")] pub left: Span, #[suggestion_part(code = ")")] @@ -2983,6 +2983,6 @@ pub struct UnsafeAttrOutsideUnsafeSuggestion { #[derive(LintDiagnostic)] #[diag(lint_out_of_scope_macro_calls)] #[help] -pub struct OutOfScopeMacroCalls { +pub(crate) struct OutOfScopeMacroCalls { pub path: String, } diff --git a/compiler/rustc_lint/src/non_local_def.rs b/compiler/rustc_lint/src/non_local_def.rs index 5ad677995da..13a3c741fe3 100644 --- a/compiler/rustc_lint/src/non_local_def.rs +++ b/compiler/rustc_lint/src/non_local_def.rs @@ -55,7 +55,7 @@ declare_lint! { } #[derive(Default)] -pub struct NonLocalDefinitions { +pub(crate) struct NonLocalDefinitions { body_depth: u32, } diff --git a/compiler/rustc_lint/src/nonstandard_style.rs b/compiler/rustc_lint/src/nonstandard_style.rs index d7fd41c0ad7..d81052b5e24 100644 --- a/compiler/rustc_lint/src/nonstandard_style.rs +++ b/compiler/rustc_lint/src/nonstandard_style.rs @@ -17,13 +17,13 @@ use crate::lints::{ use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext}; #[derive(PartialEq)] -pub enum MethodLateContext { +pub(crate) enum MethodLateContext { TraitAutoImpl, TraitImpl, PlainImpl, } -pub fn method_context(cx: &LateContext<'_>, id: LocalDefId) -> MethodLateContext { +pub(crate) fn method_context(cx: &LateContext<'_>, id: LocalDefId) -> MethodLateContext { let item = cx.tcx.associated_item(id); match item.container { ty::TraitContainer => MethodLateContext::TraitAutoImpl, diff --git a/compiler/rustc_lint/src/shadowed_into_iter.rs b/compiler/rustc_lint/src/shadowed_into_iter.rs index 4fe35a6a0a3..bb9c7d85c2e 100644 --- a/compiler/rustc_lint/src/shadowed_into_iter.rs +++ b/compiler/rustc_lint/src/shadowed_into_iter.rs @@ -65,7 +65,7 @@ declare_lint! { } #[derive(Copy, Clone)] -pub struct ShadowedIntoIter; +pub(crate) struct ShadowedIntoIter; impl_lint_pass!(ShadowedIntoIter => [ARRAY_INTO_ITER, BOXED_SLICE_INTO_ITER]); diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index f1da14bb1f3..f2f7c0eaa4d 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -165,7 +165,7 @@ declare_lint! { } #[derive(Copy, Clone)] -pub struct TypeLimits { +pub(crate) struct TypeLimits { /// Id of the last visited negated expression negated_expr_id: Option<hir::HirId>, /// Span of the last visited negated expression @@ -180,7 +180,7 @@ impl_lint_pass!(TypeLimits => [ ]); impl TypeLimits { - pub fn new() -> TypeLimits { + pub(crate) fn new() -> TypeLimits { TypeLimits { negated_expr_id: None, negated_expr_span: None } } } @@ -1008,7 +1008,7 @@ pub(crate) fn nonnull_optimization_guaranteed<'tcx>( /// `repr(transparent)` structs can have a single non-1-ZST field, this function returns that /// field. -pub fn transparent_newtype_field<'a, 'tcx>( +pub(crate) fn transparent_newtype_field<'a, 'tcx>( tcx: TyCtxt<'tcx>, variant: &'a ty::VariantDef, ) -> Option<&'a ty::FieldDef> { diff --git a/compiler/rustc_lint/src/unused.rs b/compiler/rustc_lint/src/unused.rs index 553d9db12c5..c3b80e01c36 100644 --- a/compiler/rustc_lint/src/unused.rs +++ b/compiler/rustc_lint/src/unused.rs @@ -1019,7 +1019,7 @@ declare_lint! { "`if`, `match`, `while` and `return` do not need parentheses" } -pub struct UnusedParens { +pub(crate) struct UnusedParens { with_self_ty_parens: bool, /// `1 as (i32) < 2` parses to ExprKind::Lt /// `1 as i32 < 2` parses to i32::<2[missing angle bracket] @@ -1027,7 +1027,7 @@ pub struct UnusedParens { } impl UnusedParens { - pub fn new() -> Self { + pub(crate) fn new() -> Self { Self { with_self_ty_parens: false, parens_in_cast_in_lt: Vec::new() } } } diff --git a/compiler/rustc_lint_defs/src/lib.rs b/compiler/rustc_lint_defs/src/lib.rs index 0f07de43e80..c17b85db3b0 100644 --- a/compiler/rustc_lint_defs/src/lib.rs +++ b/compiler/rustc_lint_defs/src/lib.rs @@ -1,3 +1,7 @@ +// tidy-alphabetical-start +#![warn(unreachable_pub)] +// tidy-alphabetical-end + use rustc_ast::node_id::NodeId; use rustc_ast::{AttrId, Attribute}; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; diff --git a/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp b/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp index 9884ed15b8a..c7306b0516f 100644 --- a/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp +++ b/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp @@ -713,7 +713,7 @@ extern "C" LLVMRustResult LLVMRustOptimize( LLVMModuleRef ModuleRef, LLVMTargetMachineRef TMRef, LLVMRustPassBuilderOptLevel OptLevelRust, LLVMRustOptStage OptStage, bool IsLinkerPluginLTO, bool NoPrepopulatePasses, bool VerifyIR, - bool UseThinLTOBuffers, bool MergeFunctions, bool UnrollLoops, + bool LintIR, bool UseThinLTOBuffers, bool MergeFunctions, bool UnrollLoops, bool SLPVectorize, bool LoopVectorize, bool DisableSimplifyLibCalls, bool EmitLifetimeMarkers, LLVMRustSanitizerOptions *SanitizerOptions, const char *PGOGenPath, const char *PGOUsePath, bool InstrumentCoverage, @@ -842,6 +842,13 @@ extern "C" LLVMRustResult LLVMRustOptimize( }); } + if (LintIR) { + PipelineStartEPCallbacks.push_back( + [](ModulePassManager &MPM, OptimizationLevel Level) { + MPM.addPass(createModuleToFunctionPassAdaptor(LintPass())); + }); + } + if (InstrumentGCOV) { PipelineStartEPCallbacks.push_back( [](ModulePassManager &MPM, OptimizationLevel Level) { diff --git a/compiler/rustc_llvm/src/lib.rs b/compiler/rustc_llvm/src/lib.rs index 939e5e4dbd4..3532d50c64e 100644 --- a/compiler/rustc_llvm/src/lib.rs +++ b/compiler/rustc_llvm/src/lib.rs @@ -1,8 +1,10 @@ // tidy-alphabetical-start #![allow(internal_features)] +#![cfg_attr(bootstrap, feature(unsafe_attributes, unsafe_extern_blocks))] #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] #![doc(rust_logo)] #![feature(rustdoc_internals)] +#![warn(unreachable_pub)] // tidy-alphabetical-end // NOTE: This crate only exists to allow linking on mingw targets. @@ -28,7 +30,7 @@ impl RustString { } /// Appending to a Rust string -- used by RawRustStringOstream. -#[no_mangle] +#[unsafe(no_mangle)] pub unsafe extern "C" fn LLVMRustStringWriteImpl( sr: &RustString, ptr: *const c_char, @@ -46,7 +48,7 @@ pub fn initialize_available_targets() { ($cfg:meta, $($method:ident),*) => { { #[cfg($cfg)] fn init() { - extern "C" { + unsafe extern "C" { $(fn $method();)* } unsafe { diff --git a/compiler/rustc_macros/src/diagnostics/mod.rs b/compiler/rustc_macros/src/diagnostics/mod.rs index 134045d0644..0f7b8921509 100644 --- a/compiler/rustc_macros/src/diagnostics/mod.rs +++ b/compiler/rustc_macros/src/diagnostics/mod.rs @@ -55,7 +55,7 @@ use synstructure::Structure; /// /// See rustc dev guide for more examples on using the `#[derive(Diagnostic)]`: /// <https://rustc-dev-guide.rust-lang.org/diagnostics/diagnostic-structs.html> -pub fn diagnostic_derive(mut s: Structure<'_>) -> TokenStream { +pub(super) fn diagnostic_derive(mut s: Structure<'_>) -> TokenStream { s.underscore_const(true); DiagnosticDerive::new(s).into_tokens() } @@ -102,7 +102,7 @@ pub fn diagnostic_derive(mut s: Structure<'_>) -> TokenStream { /// /// See rustc dev guide for more examples on using the `#[derive(LintDiagnostic)]`: /// <https://rustc-dev-guide.rust-lang.org/diagnostics/diagnostic-structs.html#reference> -pub fn lint_diagnostic_derive(mut s: Structure<'_>) -> TokenStream { +pub(super) fn lint_diagnostic_derive(mut s: Structure<'_>) -> TokenStream { s.underscore_const(true); LintDiagnosticDerive::new(s).into_tokens() } @@ -153,7 +153,7 @@ pub fn lint_diagnostic_derive(mut s: Structure<'_>) -> TokenStream { /// /// diag.subdiagnostic(RawIdentifierSuggestion { span, applicability, ident }); /// ``` -pub fn subdiagnostic_derive(mut s: Structure<'_>) -> TokenStream { +pub(super) fn subdiagnostic_derive(mut s: Structure<'_>) -> TokenStream { s.underscore_const(true); SubdiagnosticDerive::new().into_tokens(s) } diff --git a/compiler/rustc_macros/src/lib.rs b/compiler/rustc_macros/src/lib.rs index 929bc2df6f6..f46c795b956 100644 --- a/compiler/rustc_macros/src/lib.rs +++ b/compiler/rustc_macros/src/lib.rs @@ -6,6 +6,7 @@ #![feature(proc_macro_diagnostic)] #![feature(proc_macro_span)] #![feature(proc_macro_tracked_env)] +#![warn(unreachable_pub)] // tidy-alphabetical-end use proc_macro::TokenStream; diff --git a/compiler/rustc_macros/src/lift.rs b/compiler/rustc_macros/src/lift.rs index 627f4088d5f..bf4a7665ceb 100644 --- a/compiler/rustc_macros/src/lift.rs +++ b/compiler/rustc_macros/src/lift.rs @@ -1,7 +1,7 @@ use quote::quote; use syn::parse_quote; -pub fn lift_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::TokenStream { +pub(super) fn lift_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::TokenStream { s.add_bounds(synstructure::AddBounds::Generics); s.bind_with(|_| synstructure::BindStyle::Move); s.underscore_const(true); diff --git a/compiler/rustc_macros/src/query.rs b/compiler/rustc_macros/src/query.rs index ceff1da9763..886a38c8ff2 100644 --- a/compiler/rustc_macros/src/query.rs +++ b/compiler/rustc_macros/src/query.rs @@ -307,7 +307,7 @@ fn add_query_desc_cached_impl( }); } -pub fn rustc_queries(input: TokenStream) -> TokenStream { +pub(super) fn rustc_queries(input: TokenStream) -> TokenStream { let queries = parse_macro_input!(input as List<Query>); let mut query_stream = quote! {}; diff --git a/compiler/rustc_macros/src/serialize.rs b/compiler/rustc_macros/src/serialize.rs index 7b5dd1601c1..2c33a0ac0aa 100644 --- a/compiler/rustc_macros/src/serialize.rs +++ b/compiler/rustc_macros/src/serialize.rs @@ -3,7 +3,9 @@ use quote::{quote, quote_spanned}; use syn::parse_quote; use syn::spanned::Spanned; -pub fn type_decodable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::TokenStream { +pub(super) fn type_decodable_derive( + mut s: synstructure::Structure<'_>, +) -> proc_macro2::TokenStream { let decoder_ty = quote! { __D }; let bound = if s.ast().generics.lifetimes().any(|lt| lt.lifetime.ident == "tcx") { quote! { <I = ::rustc_middle::ty::TyCtxt<'tcx>> } @@ -20,7 +22,9 @@ pub fn type_decodable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2: decodable_body(s, decoder_ty) } -pub fn meta_decodable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::TokenStream { +pub(super) fn meta_decodable_derive( + mut s: synstructure::Structure<'_>, +) -> proc_macro2::TokenStream { if !s.ast().generics.lifetimes().any(|lt| lt.lifetime.ident == "tcx") { s.add_impl_generic(parse_quote! { 'tcx }); } @@ -32,7 +36,7 @@ pub fn meta_decodable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2: decodable_body(s, decoder_ty) } -pub fn decodable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::TokenStream { +pub(super) fn decodable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::TokenStream { let decoder_ty = quote! { __D }; s.add_impl_generic(parse_quote! { #decoder_ty: ::rustc_span::SpanDecoder }); s.add_bounds(synstructure::AddBounds::Generics); @@ -41,7 +45,9 @@ pub fn decodable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::Toke decodable_body(s, decoder_ty) } -pub fn decodable_generic_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::TokenStream { +pub(super) fn decodable_generic_derive( + mut s: synstructure::Structure<'_>, +) -> proc_macro2::TokenStream { let decoder_ty = quote! { __D }; s.add_impl_generic(parse_quote! { #decoder_ty: ::rustc_serialize::Decoder }); s.add_bounds(synstructure::AddBounds::Generics); @@ -123,7 +129,9 @@ fn decode_field(field: &syn::Field) -> proc_macro2::TokenStream { quote_spanned! { field_span=> #decode_inner_method(#__decoder) } } -pub fn type_encodable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::TokenStream { +pub(super) fn type_encodable_derive( + mut s: synstructure::Structure<'_>, +) -> proc_macro2::TokenStream { let bound = if s.ast().generics.lifetimes().any(|lt| lt.lifetime.ident == "tcx") { quote! { <I = ::rustc_middle::ty::TyCtxt<'tcx>> } } else if s.ast().generics.type_params().any(|ty| ty.ident == "I") { @@ -140,7 +148,9 @@ pub fn type_encodable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2: encodable_body(s, encoder_ty, false) } -pub fn meta_encodable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::TokenStream { +pub(super) fn meta_encodable_derive( + mut s: synstructure::Structure<'_>, +) -> proc_macro2::TokenStream { if !s.ast().generics.lifetimes().any(|lt| lt.lifetime.ident == "tcx") { s.add_impl_generic(parse_quote! { 'tcx }); } @@ -152,7 +162,7 @@ pub fn meta_encodable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2: encodable_body(s, encoder_ty, true) } -pub fn encodable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::TokenStream { +pub(super) fn encodable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::TokenStream { let encoder_ty = quote! { __E }; s.add_impl_generic(parse_quote! { #encoder_ty: ::rustc_span::SpanEncoder }); s.add_bounds(synstructure::AddBounds::Generics); @@ -161,7 +171,9 @@ pub fn encodable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::Toke encodable_body(s, encoder_ty, false) } -pub fn encodable_generic_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::TokenStream { +pub(super) fn encodable_generic_derive( + mut s: synstructure::Structure<'_>, +) -> proc_macro2::TokenStream { let encoder_ty = quote! { __E }; s.add_impl_generic(parse_quote! { #encoder_ty: ::rustc_serialize::Encoder }); s.add_bounds(synstructure::AddBounds::Generics); diff --git a/compiler/rustc_macros/src/symbols.rs b/compiler/rustc_macros/src/symbols.rs index 6074c93d59c..341186ac1ca 100644 --- a/compiler/rustc_macros/src/symbols.rs +++ b/compiler/rustc_macros/src/symbols.rs @@ -131,7 +131,7 @@ impl Errors { } } -pub fn symbols(input: TokenStream) -> TokenStream { +pub(super) fn symbols(input: TokenStream) -> TokenStream { let (mut output, errors) = symbols_with_errors(input); // If we generated any errors, then report them as compiler_error!() macro calls. diff --git a/compiler/rustc_macros/src/type_foldable.rs b/compiler/rustc_macros/src/type_foldable.rs index 5617c53b119..8ddfa96e095 100644 --- a/compiler/rustc_macros/src/type_foldable.rs +++ b/compiler/rustc_macros/src/type_foldable.rs @@ -1,7 +1,7 @@ use quote::{quote, ToTokens}; use syn::parse_quote; -pub fn type_foldable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::TokenStream { +pub(super) fn type_foldable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::TokenStream { if let syn::Data::Union(_) = s.ast().data { panic!("cannot derive on union") } diff --git a/compiler/rustc_macros/src/type_visitable.rs b/compiler/rustc_macros/src/type_visitable.rs index 94e86e0e246..527ca26c0eb 100644 --- a/compiler/rustc_macros/src/type_visitable.rs +++ b/compiler/rustc_macros/src/type_visitable.rs @@ -1,7 +1,9 @@ use quote::quote; use syn::parse_quote; -pub fn type_visitable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::TokenStream { +pub(super) fn type_visitable_derive( + mut s: synstructure::Structure<'_>, +) -> proc_macro2::TokenStream { if let syn::Data::Union(_) = s.ast().data { panic!("cannot derive on union") } diff --git a/compiler/rustc_metadata/src/lib.rs b/compiler/rustc_metadata/src/lib.rs index acaf9fb0fc3..c798ca00bcc 100644 --- a/compiler/rustc_metadata/src/lib.rs +++ b/compiler/rustc_metadata/src/lib.rs @@ -16,6 +16,7 @@ #![feature(proc_macro_internals)] #![feature(rustdoc_internals)] #![feature(trusted_len)] +#![warn(unreachable_pub)] // tidy-alphabetical-end extern crate proc_macro; diff --git a/compiler/rustc_metadata/src/rmeta/decoder.rs b/compiler/rustc_metadata/src/rmeta/decoder.rs index a13eac08c9f..09aea233718 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder.rs @@ -56,13 +56,13 @@ impl std::ops::Deref for MetadataBlob { impl MetadataBlob { /// Runs the [`MemDecoder`] validation and if it passes, constructs a new [`MetadataBlob`]. - pub fn new(slice: OwnedSlice) -> Result<Self, ()> { + pub(crate) fn new(slice: OwnedSlice) -> Result<Self, ()> { if MemDecoder::new(&slice, 0).is_ok() { Ok(Self(slice)) } else { Err(()) } } /// Since this has passed the validation of [`MetadataBlob::new`], this returns bytes which are /// known to pass the [`MemDecoder`] validation. - pub fn bytes(&self) -> &OwnedSlice { + pub(crate) fn bytes(&self) -> &OwnedSlice { &self.0 } } @@ -332,12 +332,12 @@ impl<'a, 'tcx> DecodeContext<'a, 'tcx> { } #[inline] - pub fn blob(&self) -> &'a MetadataBlob { + pub(crate) fn blob(&self) -> &'a MetadataBlob { self.blob } #[inline] - pub fn cdata(&self) -> CrateMetadataRef<'a> { + fn cdata(&self) -> CrateMetadataRef<'a> { debug_assert!(self.cdata.is_some(), "missing CrateMetadata in DecodeContext"); self.cdata.unwrap() } @@ -377,7 +377,7 @@ impl<'a, 'tcx> DecodeContext<'a, 'tcx> { } #[inline] - pub fn read_raw_bytes(&mut self, len: usize) -> &[u8] { + fn read_raw_bytes(&mut self, len: usize) -> &[u8] { self.opaque.read_raw_bytes(len) } } @@ -962,7 +962,7 @@ impl CrateRoot { } } -impl<'a, 'tcx> CrateMetadataRef<'a> { +impl<'a> CrateMetadataRef<'a> { fn missing(self, descr: &str, id: DefIndex) -> ! { bug!("missing `{descr}` for {:?}", self.local_def_id(id)) } @@ -1036,7 +1036,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { .decode((self, sess)) } - fn load_proc_macro(self, id: DefIndex, tcx: TyCtxt<'tcx>) -> SyntaxExtension { + fn load_proc_macro<'tcx>(self, id: DefIndex, tcx: TyCtxt<'tcx>) -> SyntaxExtension { let (name, kind, helper_attrs) = match *self.raw_proc_macro(id) { ProcMacro::CustomDerive { trait_name, attributes, client } => { let helper_attrs = @@ -1070,7 +1070,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { ) } - fn get_explicit_item_bounds( + fn get_explicit_item_bounds<'tcx>( self, index: DefIndex, tcx: TyCtxt<'tcx>, @@ -1084,7 +1084,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { ty::EarlyBinder::bind(&*output) } - fn get_explicit_item_super_predicates( + fn get_explicit_item_super_predicates<'tcx>( self, index: DefIndex, tcx: TyCtxt<'tcx>, @@ -1141,7 +1141,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { ) } - fn get_adt_def(self, item_id: DefIndex, tcx: TyCtxt<'tcx>) -> ty::AdtDef<'tcx> { + fn get_adt_def<'tcx>(self, item_id: DefIndex, tcx: TyCtxt<'tcx>) -> ty::AdtDef<'tcx> { let kind = self.def_kind(item_id); let did = self.local_def_id(item_id); @@ -1225,12 +1225,12 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { /// Iterates over the stability implications in the given crate (when a `#[unstable]` attribute /// has an `implied_by` meta item, then the mapping from the implied feature to the actual /// feature is a stability implication). - fn get_stability_implications(self, tcx: TyCtxt<'tcx>) -> &'tcx [(Symbol, Symbol)] { + fn get_stability_implications<'tcx>(self, tcx: TyCtxt<'tcx>) -> &'tcx [(Symbol, Symbol)] { tcx.arena.alloc_from_iter(self.root.stability_implications.decode(self)) } /// Iterates over the lang items in the given crate. - fn get_lang_items(self, tcx: TyCtxt<'tcx>) -> &'tcx [(DefId, LangItem)] { + fn get_lang_items<'tcx>(self, tcx: TyCtxt<'tcx>) -> &'tcx [(DefId, LangItem)] { tcx.arena.alloc_from_iter( self.root .lang_items @@ -1239,7 +1239,11 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { ) } - fn get_stripped_cfg_items(self, cnum: CrateNum, tcx: TyCtxt<'tcx>) -> &'tcx [StrippedCfgItem] { + fn get_stripped_cfg_items<'tcx>( + self, + cnum: CrateNum, + tcx: TyCtxt<'tcx>, + ) -> &'tcx [StrippedCfgItem] { let item_names = self .root .stripped_cfg_items @@ -1412,7 +1416,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { .decode((self, sess)) } - fn get_inherent_implementations_for_type( + fn get_inherent_implementations_for_type<'tcx>( self, tcx: TyCtxt<'tcx>, id: DefIndex, @@ -1439,7 +1443,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { }) } - fn get_incoherent_impls(self, tcx: TyCtxt<'tcx>, simp: SimplifiedType) -> &'tcx [DefId] { + fn get_incoherent_impls<'tcx>(self, tcx: TyCtxt<'tcx>, simp: SimplifiedType) -> &'tcx [DefId] { if let Some(impls) = self.cdata.incoherent_impls.get(&simp) { tcx.arena.alloc_from_iter(impls.decode(self).map(|idx| self.local_def_id(idx))) } else { @@ -1447,7 +1451,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { } } - fn get_implementations_of_trait( + fn get_implementations_of_trait<'tcx>( self, tcx: TyCtxt<'tcx>, trait_def_id: DefId, @@ -1491,7 +1495,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { self.root.foreign_modules.decode((self, sess)) } - fn get_dylib_dependency_formats( + fn get_dylib_dependency_formats<'tcx>( self, tcx: TyCtxt<'tcx>, ) -> &'tcx [(CrateNum, LinkagePreference)] { @@ -1503,11 +1507,11 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { ) } - fn get_missing_lang_items(self, tcx: TyCtxt<'tcx>) -> &'tcx [LangItem] { + fn get_missing_lang_items<'tcx>(self, tcx: TyCtxt<'tcx>) -> &'tcx [LangItem] { tcx.arena.alloc_from_iter(self.root.lang_items_missing.decode(self)) } - fn exported_symbols( + fn exported_symbols<'tcx>( self, tcx: TyCtxt<'tcx>, ) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportInfo)] { diff --git a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs index 46039f6e5f6..27625f79108 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs @@ -224,6 +224,7 @@ provide! { tcx, def_id, other, cdata, variances_of => { table } fn_sig => { table } codegen_fn_attrs => { table } + struct_target_features => { table } impl_trait_header => { table } const_param_default => { table } object_lifetime_default => { table } diff --git a/compiler/rustc_metadata/src/rmeta/def_path_hash_map.rs b/compiler/rustc_metadata/src/rmeta/def_path_hash_map.rs index 01fbf37788f..19369425f81 100644 --- a/compiler/rustc_metadata/src/rmeta/def_path_hash_map.rs +++ b/compiler/rustc_metadata/src/rmeta/def_path_hash_map.rs @@ -17,7 +17,7 @@ parameterized_over_tcx! { impl DefPathHashMapRef<'_> { #[inline] - pub fn def_path_hash_to_def_index(&self, def_path_hash: &DefPathHash) -> DefIndex { + pub(crate) fn def_path_hash_to_def_index(&self, def_path_hash: &DefPathHash) -> DefIndex { match *self { DefPathHashMapRef::OwnedFromMetadata(ref map) => { map.get(&def_path_hash.local_hash()).unwrap() diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 0d83f8c6c5c..d9a844ad837 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -872,7 +872,8 @@ fn should_encode_span(def_kind: DefKind) -> bool { | DefKind::OpaqueTy | DefKind::Field | DefKind::Impl { .. } - | DefKind::Closure => true, + | DefKind::Closure + | DefKind::SyntheticCoroutineBody => true, DefKind::ForeignMod | DefKind::GlobalAsm => false, } } @@ -902,6 +903,7 @@ fn should_encode_attrs(def_kind: DefKind) -> bool { // https://github.com/model-checking/kani and is not a performance // or maintenance issue for us. DefKind::Closure => true, + DefKind::SyntheticCoroutineBody => false, DefKind::TyParam | DefKind::ConstParam | DefKind::Ctor(..) @@ -948,7 +950,8 @@ fn should_encode_expn_that_defined(def_kind: DefKind) -> bool { | DefKind::Field | DefKind::LifetimeParam | DefKind::GlobalAsm - | DefKind::Closure => false, + | DefKind::Closure + | DefKind::SyntheticCoroutineBody => false, } } @@ -984,7 +987,8 @@ fn should_encode_visibility(def_kind: DefKind) -> bool { | DefKind::GlobalAsm | DefKind::Impl { .. } | DefKind::Closure - | DefKind::ExternCrate => false, + | DefKind::ExternCrate + | DefKind::SyntheticCoroutineBody => false, } } @@ -1019,7 +1023,8 @@ fn should_encode_stability(def_kind: DefKind) -> bool { | DefKind::InlineConst | DefKind::GlobalAsm | DefKind::Closure - | DefKind::ExternCrate => false, + | DefKind::ExternCrate + | DefKind::SyntheticCoroutineBody => false, } } @@ -1061,6 +1066,7 @@ fn should_encode_mir( } // Coroutines require optimized MIR to compute layout. DefKind::Closure if tcx.is_coroutine(def_id.to_def_id()) => (false, true), + DefKind::SyntheticCoroutineBody => (false, true), // Full-fledged functions + closures DefKind::AssocFn | DefKind::Fn | DefKind::Closure => { let generics = tcx.generics_of(def_id); @@ -1109,7 +1115,8 @@ fn should_encode_variances<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, def_kind: Def | DefKind::InlineConst | DefKind::GlobalAsm | DefKind::Closure - | DefKind::ExternCrate => false, + | DefKind::ExternCrate + | DefKind::SyntheticCoroutineBody => false, DefKind::TyAlias => tcx.type_alias_is_lazy(def_id), } } @@ -1137,7 +1144,8 @@ fn should_encode_generics(def_kind: DefKind) -> bool { | DefKind::Impl { .. } | DefKind::Field | DefKind::TyParam - | DefKind::Closure => true, + | DefKind::Closure + | DefKind::SyntheticCoroutineBody => true, DefKind::Mod | DefKind::ForeignMod | DefKind::ConstParam @@ -1168,7 +1176,8 @@ fn should_encode_type(tcx: TyCtxt<'_>, def_id: LocalDefId, def_kind: DefKind) -> | DefKind::Closure | DefKind::ConstParam | DefKind::AnonConst - | DefKind::InlineConst => true, + | DefKind::InlineConst + | DefKind::SyntheticCoroutineBody => true, DefKind::OpaqueTy => { let origin = tcx.opaque_type_origin(def_id); @@ -1240,7 +1249,8 @@ fn should_encode_fn_sig(def_kind: DefKind) -> bool { | DefKind::Use | DefKind::LifetimeParam | DefKind::GlobalAsm - | DefKind::ExternCrate => false, + | DefKind::ExternCrate + | DefKind::SyntheticCoroutineBody => false, } } @@ -1277,7 +1287,8 @@ fn should_encode_constness(def_kind: DefKind) -> bool { | DefKind::Use | DefKind::LifetimeParam | DefKind::GlobalAsm - | DefKind::ExternCrate => false, + | DefKind::ExternCrate + | DefKind::SyntheticCoroutineBody => false, } } @@ -1310,7 +1321,8 @@ fn should_encode_const(def_kind: DefKind) -> bool { | DefKind::Use | DefKind::LifetimeParam | DefKind::GlobalAsm - | DefKind::ExternCrate => false, + | DefKind::ExternCrate + | DefKind::SyntheticCoroutineBody => false, } } @@ -1380,6 +1392,9 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { if def_kind.has_codegen_attrs() { record!(self.tables.codegen_fn_attrs[def_id] <- self.tcx.codegen_fn_attrs(def_id)); } + if def_kind.has_struct_target_features() { + record_array!(self.tables.struct_target_features[def_id] <- self.tcx.struct_target_features(def_id)); + } if should_encode_visibility(def_kind) { let vis = self.tcx.local_visibility(local_id).map_id(|def_id| def_id.local_def_index); @@ -1458,7 +1473,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { record!(self.tables.associated_type_for_effects[def_id] <- assoc_def_id); } } - if def_kind == DefKind::Closure + if let DefKind::Closure | DefKind::SyntheticCoroutineBody = def_kind && let Some(coroutine_kind) = self.tcx.coroutine_kind(def_id) { self.tables.coroutine_kind.set(def_id.index, Some(coroutine_kind)) @@ -2294,7 +2309,7 @@ fn encode_root_position(mut file: &File, pos: usize) -> Result<(), std::io::Erro Ok(()) } -pub fn provide(providers: &mut Providers) { +pub(crate) fn provide(providers: &mut Providers) { *providers = Providers { doc_link_resolutions: |tcx, def_id| { tcx.resolutions(()) diff --git a/compiler/rustc_metadata/src/rmeta/mod.rs b/compiler/rustc_metadata/src/rmeta/mod.rs index c1b77172983..aec728d4262 100644 --- a/compiler/rustc_metadata/src/rmeta/mod.rs +++ b/compiler/rustc_metadata/src/rmeta/mod.rs @@ -19,7 +19,7 @@ use rustc_macros::{ Decodable, Encodable, MetadataDecodable, MetadataEncodable, TyDecodable, TyEncodable, }; use rustc_middle::metadata::ModChild; -use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs; +use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrs, TargetFeature}; use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile; use rustc_middle::middle::exported_symbols::{ExportedSymbol, SymbolExportInfo}; use rustc_middle::middle::lib_features::FeatureStability; @@ -427,6 +427,7 @@ define_tables! { variances_of: Table<DefIndex, LazyArray<ty::Variance>>, fn_sig: Table<DefIndex, LazyValue<ty::EarlyBinder<'static, ty::PolyFnSig<'static>>>>, codegen_fn_attrs: Table<DefIndex, LazyValue<CodegenFnAttrs>>, + struct_target_features: Table<DefIndex, LazyArray<TargetFeature>>, impl_trait_header: Table<DefIndex, LazyValue<ty::ImplTraitHeader<'static>>>, const_param_default: Table<DefIndex, LazyValue<ty::EarlyBinder<'static, rustc_middle::ty::Const<'static>>>>, object_lifetime_default: Table<DefIndex, LazyValue<ObjectLifetimeDefault>>, diff --git a/compiler/rustc_metadata/src/rmeta/table.rs b/compiler/rustc_metadata/src/rmeta/table.rs index 617372a97b5..3a6f3543317 100644 --- a/compiler/rustc_metadata/src/rmeta/table.rs +++ b/compiler/rustc_metadata/src/rmeta/table.rs @@ -171,6 +171,7 @@ fixed_size_enum! { ( Macro(MacroKind::Bang) ) ( Macro(MacroKind::Attr) ) ( Macro(MacroKind::Derive) ) + ( SyntheticCoroutineBody ) } } diff --git a/compiler/rustc_middle/src/arena.rs b/compiler/rustc_middle/src/arena.rs index 37c10b14054..7050a06b8dc 100644 --- a/compiler/rustc_middle/src/arena.rs +++ b/compiler/rustc_middle/src/arena.rs @@ -35,7 +35,6 @@ macro_rules! arena_types { )>, [] crate_for_resolver: rustc_data_structures::steal::Steal<(rustc_ast::Crate, rustc_ast::AttrVec)>, [] resolutions: rustc_middle::ty::ResolverGlobalCtxt, - [decode] code_region: rustc_middle::mir::coverage::CodeRegion, [] const_allocs: rustc_middle::mir::interpret::Allocation, [] region_scope_tree: rustc_middle::middle::region::ScopeTree, // Required for the incremental on-disk cache diff --git a/compiler/rustc_middle/src/dep_graph/dep_node.rs b/compiler/rustc_middle/src/dep_graph/dep_node.rs index 9ebe4a57b02..2d47d1d19af 100644 --- a/compiler/rustc_middle/src/dep_graph/dep_node.rs +++ b/compiler/rustc_middle/src/dep_graph/dep_node.rs @@ -61,8 +61,9 @@ use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LocalModDefId, ModDefId, LO use rustc_hir::definitions::DefPathHash; use rustc_hir::{HirId, ItemLocalId, OwnerId}; pub use rustc_query_system::dep_graph::dep_node::DepKind; +pub use rustc_query_system::dep_graph::DepNode; use rustc_query_system::dep_graph::FingerprintStyle; -pub use rustc_query_system::dep_graph::{DepContext, DepNode, DepNodeParams}; +pub(crate) use rustc_query_system::dep_graph::{DepContext, DepNodeParams}; use rustc_span::symbol::Symbol; use crate::mir::mono::MonoItem; @@ -101,7 +102,7 @@ macro_rules! define_dep_nodes { // This checks that the discriminants of the variants have been assigned consecutively // from 0 so that they can be used as a dense index. - pub const DEP_KIND_VARIANTS: u16 = { + pub(crate) const DEP_KIND_VARIANTS: u16 = { let deps = &[$(dep_kinds::$variant,)*]; let mut i = 0; while i < deps.len() { diff --git a/compiler/rustc_middle/src/hir/map/mod.rs b/compiler/rustc_middle/src/hir/map/mod.rs index 0f85998204c..3d346b9cc5d 100644 --- a/compiler/rustc_middle/src/hir/map/mod.rs +++ b/compiler/rustc_middle/src/hir/map/mod.rs @@ -307,7 +307,7 @@ impl<'hir> Map<'hir> { } DefKind::InlineConst => BodyOwnerKind::Const { inline: true }, DefKind::Ctor(..) | DefKind::Fn | DefKind::AssocFn => BodyOwnerKind::Fn, - DefKind::Closure => BodyOwnerKind::Closure, + DefKind::Closure | DefKind::SyntheticCoroutineBody => BodyOwnerKind::Closure, DefKind::Static { safety: _, mutability, nested: false } => { BodyOwnerKind::Static(mutability) } diff --git a/compiler/rustc_middle/src/lib.rs b/compiler/rustc_middle/src/lib.rs index 6886562d9b7..2a85f85a9f4 100644 --- a/compiler/rustc_middle/src/lib.rs +++ b/compiler/rustc_middle/src/lib.rs @@ -28,7 +28,7 @@ #![allow(rustc::diagnostic_outside_of_impl)] #![allow(rustc::potential_query_instability)] #![allow(rustc::untranslatable_diagnostic)] -#![cfg_attr(bootstrap, feature(min_exhaustive_patterns))] +#![cfg_attr(bootstrap, feature(min_exhaustive_patterns, unsafe_extern_blocks))] #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] #![doc(rust_logo)] #![feature(allocator_api)] @@ -53,7 +53,6 @@ #![feature(min_specialization)] #![feature(negative_impls)] #![feature(never_type)] -#![feature(new_uninit)] #![feature(ptr_alignment_type)] #![feature(rustc_attrs)] #![feature(rustdoc_internals)] @@ -63,6 +62,7 @@ #![feature(try_blocks)] #![feature(type_alias_impl_trait)] #![feature(yeet_expr)] +#![warn(unreachable_pub)] // tidy-alphabetical-end #[cfg(test)] diff --git a/compiler/rustc_middle/src/middle/codegen_fn_attrs.rs b/compiler/rustc_middle/src/middle/codegen_fn_attrs.rs index b7d290e58d2..c098a739592 100644 --- a/compiler/rustc_middle/src/middle/codegen_fn_attrs.rs +++ b/compiler/rustc_middle/src/middle/codegen_fn_attrs.rs @@ -26,8 +26,8 @@ pub struct CodegenFnAttrs { /// be set when `link_name` is set. This is for foreign items with the /// "raw-dylib" kind. pub link_ordinal: Option<u16>, - /// The `#[target_feature(enable = "...")]` attribute and the enabled - /// features (only enabled features are supported right now). + /// All the target features that are enabled for this function. Some features might be enabled + /// implicitly. pub target_features: Vec<TargetFeature>, /// The `#[linkage = "..."]` attribute on Rust-defined items and the value we found. pub linkage: Option<Linkage>, @@ -55,8 +55,8 @@ pub struct CodegenFnAttrs { pub struct TargetFeature { /// The name of the target feature (e.g. "avx") pub name: Symbol, - /// The feature is implied by another feature, rather than explicitly added by the - /// `#[target_feature]` attribute + /// The feature is implied by another feature or by an argument, rather than explicitly + /// added by the `#[target_feature]` attribute pub implied: bool, } diff --git a/compiler/rustc_middle/src/mir/basic_blocks.rs b/compiler/rustc_middle/src/mir/basic_blocks.rs index c08bfc1fa95..183b898253e 100644 --- a/compiler/rustc_middle/src/mir/basic_blocks.rs +++ b/compiler/rustc_middle/src/mir/basic_blocks.rs @@ -18,9 +18,9 @@ pub struct BasicBlocks<'tcx> { } // Typically 95%+ of basic blocks have 4 or fewer predecessors. -pub type Predecessors = IndexVec<BasicBlock, SmallVec<[BasicBlock; 4]>>; +type Predecessors = IndexVec<BasicBlock, SmallVec<[BasicBlock; 4]>>; -pub type SwitchSources = FxHashMap<(BasicBlock, BasicBlock), SmallVec<[Option<u128>; 1]>>; +type SwitchSources = FxHashMap<(BasicBlock, BasicBlock), SmallVec<[Option<u128>; 1]>>; #[derive(Clone, Default, Debug)] struct Cache { diff --git a/compiler/rustc_middle/src/mir/coverage.rs b/compiler/rustc_middle/src/mir/coverage.rs index b11c523cfe9..bfe2a2c2cb3 100644 --- a/compiler/rustc_middle/src/mir/coverage.rs +++ b/compiler/rustc_middle/src/mir/coverage.rs @@ -163,7 +163,7 @@ impl Debug for CoverageKind { #[derive(Clone, TyEncodable, TyDecodable, Hash, HashStable, PartialEq, Eq, PartialOrd, Ord)] #[derive(TypeFoldable, TypeVisitable)] -pub struct CodeRegion { +pub struct SourceRegion { pub file_name: Symbol, pub start_line: u32, pub start_col: u32, @@ -171,7 +171,7 @@ pub struct CodeRegion { pub end_col: u32, } -impl Debug for CodeRegion { +impl Debug for SourceRegion { fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result { write!( fmt, @@ -242,7 +242,7 @@ impl MappingKind { #[derive(TyEncodable, TyDecodable, Hash, HashStable, TypeFoldable, TypeVisitable)] pub struct Mapping { pub kind: MappingKind, - pub code_region: CodeRegion, + pub source_region: SourceRegion, } /// Stores per-function coverage information attached to a `mir::Body`, diff --git a/compiler/rustc_middle/src/mir/generic_graph.rs b/compiler/rustc_middle/src/mir/generic_graph.rs index 51e26ab7984..a52ec58a1ee 100644 --- a/compiler/rustc_middle/src/mir/generic_graph.rs +++ b/compiler/rustc_middle/src/mir/generic_graph.rs @@ -2,7 +2,7 @@ use gsgdt::{Edge, Graph, Node, NodeStyle}; use rustc_middle::mir::*; /// Convert an MIR function into a gsgdt Graph -pub fn mir_fn_to_generic_graph<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'_>) -> Graph { +pub(crate) fn mir_fn_to_generic_graph<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'_>) -> Graph { let def_id = body.source.def_id(); let def_name = graphviz_safe_def_name(def_id); let graph_name = format!("Mir_{def_name}"); diff --git a/compiler/rustc_middle/src/mir/interpret/allocation/init_mask.rs b/compiler/rustc_middle/src/mir/interpret/allocation/init_mask.rs index 1d2a82c575a..dfaf96e14f6 100644 --- a/compiler/rustc_middle/src/mir/interpret/allocation/init_mask.rs +++ b/compiler/rustc_middle/src/mir/interpret/allocation/init_mask.rs @@ -243,7 +243,7 @@ impl hash::Hash for InitMaskMaterialized { } impl InitMaskMaterialized { - pub const BLOCK_SIZE: u64 = 64; + const BLOCK_SIZE: u64 = 64; fn new(size: Size, state: bool) -> Self { let mut m = InitMaskMaterialized { blocks: vec![] }; diff --git a/compiler/rustc_middle/src/mir/mod.rs b/compiler/rustc_middle/src/mir/mod.rs index 5b2aac781eb..7b901915037 100644 --- a/compiler/rustc_middle/src/mir/mod.rs +++ b/compiler/rustc_middle/src/mir/mod.rs @@ -267,18 +267,6 @@ pub struct CoroutineInfo<'tcx> { /// Coroutine drop glue. This field is populated after the state transform pass. pub coroutine_drop: Option<Body<'tcx>>, - /// The body of the coroutine, modified to take its upvars by move rather than by ref. - /// - /// This is used by coroutine-closures, which must return a different flavor of coroutine - /// when called using `AsyncFnOnce::call_once`. It is produced by the `ByMoveBody` pass which - /// is run right after building the initial MIR, and will only be populated for coroutines - /// which come out of the async closure desugaring. - /// - /// This body should be processed in lockstep with the containing body -- any optimization - /// passes, etc, should be applied to this body as well. This is done automatically if - /// using `run_passes`. - pub by_move_body: Option<Body<'tcx>>, - /// The layout of a coroutine. This field is populated after the state transform pass. pub coroutine_layout: Option<CoroutineLayout<'tcx>>, @@ -298,7 +286,6 @@ impl<'tcx> CoroutineInfo<'tcx> { coroutine_kind, yield_ty: Some(yield_ty), resume_ty: Some(resume_ty), - by_move_body: None, coroutine_drop: None, coroutine_layout: None, } @@ -665,10 +652,6 @@ impl<'tcx> Body<'tcx> { self.coroutine.as_ref().and_then(|coroutine| coroutine.coroutine_drop.as_ref()) } - pub fn coroutine_by_move_body(&self) -> Option<&Body<'tcx>> { - self.coroutine.as_ref()?.by_move_body.as_ref() - } - #[inline] pub fn coroutine_kind(&self) -> Option<CoroutineKind> { self.coroutine.as_ref().map(|coroutine| coroutine.coroutine_kind) diff --git a/compiler/rustc_middle/src/mir/mono.rs b/compiler/rustc_middle/src/mir/mono.rs index 336a9388a56..69b5e0a79c7 100644 --- a/compiler/rustc_middle/src/mir/mono.rs +++ b/compiler/rustc_middle/src/mir/mono.rs @@ -396,7 +396,7 @@ impl<'tcx> CodegenUnit<'tcx> { // The codegen tests rely on items being process in the same order as // they appear in the file, so for local items, we sort by node_id first #[derive(PartialEq, Eq, PartialOrd, Ord)] - pub struct ItemSortKey<'tcx>(Option<usize>, SymbolName<'tcx>); + struct ItemSortKey<'tcx>(Option<usize>, SymbolName<'tcx>); fn item_sort_key<'tcx>(tcx: TyCtxt<'tcx>, item: MonoItem<'tcx>) -> ItemSortKey<'tcx> { ItemSortKey( @@ -415,7 +415,6 @@ impl<'tcx> CodegenUnit<'tcx> { | InstanceKind::Virtual(..) | InstanceKind::ClosureOnceShim { .. } | InstanceKind::ConstructCoroutineInClosureShim { .. } - | InstanceKind::CoroutineKindShim { .. } | InstanceKind::DropGlue(..) | InstanceKind::CloneShim(..) | InstanceKind::ThreadLocalShim(..) diff --git a/compiler/rustc_middle/src/mir/pretty.rs b/compiler/rustc_middle/src/mir/pretty.rs index efdc0c710ba..6785805c27d 100644 --- a/compiler/rustc_middle/src/mir/pretty.rs +++ b/compiler/rustc_middle/src/mir/pretty.rs @@ -547,8 +547,8 @@ fn write_function_coverage_info( for (id, expression) in expressions.iter_enumerated() { writeln!(w, "{INDENT}coverage {id:?} => {expression:?};")?; } - for coverage::Mapping { kind, code_region } in mappings { - writeln!(w, "{INDENT}coverage {kind:?} => {code_region:?};")?; + for coverage::Mapping { kind, source_region } in mappings { + writeln!(w, "{INDENT}coverage {kind:?} => {source_region:?};")?; } writeln!(w)?; diff --git a/compiler/rustc_middle/src/mir/visit.rs b/compiler/rustc_middle/src/mir/visit.rs index bfb129495ce..64898a8495e 100644 --- a/compiler/rustc_middle/src/mir/visit.rs +++ b/compiler/rustc_middle/src/mir/visit.rs @@ -349,7 +349,6 @@ macro_rules! make_mir_visitor { coroutine_closure_def_id: _def_id, receiver_by_ref: _, } | - ty::InstanceKind::CoroutineKindShim { coroutine_def_id: _def_id } | ty::InstanceKind::AsyncDropGlueCtorShim(_def_id, None) | ty::InstanceKind::DropGlue(_def_id, None) => {} diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index 75166624f95..6434bd0d7bf 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -47,7 +47,7 @@ use {rustc_ast as ast, rustc_attr as attr, rustc_hir as hir}; use crate::infer::canonical::{self, Canonical}; use crate::lint::LintExpectation; use crate::metadata::ModChild; -use crate::middle::codegen_fn_attrs::CodegenFnAttrs; +use crate::middle::codegen_fn_attrs::{CodegenFnAttrs, TargetFeature}; use crate::middle::debugger_visualizer::DebuggerVisualizerFile; use crate::middle::exported_symbols::{ExportedSymbol, SymbolExportInfo}; use crate::middle::lib_features::LibFeatures; @@ -312,20 +312,10 @@ rustc_queries! { /// predicates (where-clauses) that must be proven true in order /// to reference it. This is almost always the "predicates query" /// that you want. - /// - /// `predicates_of` builds on `predicates_defined_on` -- in fact, - /// it is almost always the same as that query, except for the - /// case of traits. For traits, `predicates_of` contains - /// an additional `Self: Trait<...>` predicate that users don't - /// actually write. This reflects the fact that to invoke the - /// trait (e.g., via `Default::default`) you must supply types - /// that actually implement the trait. (However, this extra - /// predicate gets in the way of some checks, which are intended - /// to operate over only the actual where-clauses written by the - /// user.) query predicates_of(key: DefId) -> ty::GenericPredicates<'tcx> { desc { |tcx| "computing predicates of `{}`", tcx.def_path_str(key) } cache_on_disk_if { key.is_local() } + feedable } query opaque_types_defined_by( @@ -498,6 +488,7 @@ rustc_queries! { /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/mir/construction.html query mir_built(key: LocalDefId) -> &'tcx Steal<mir::Body<'tcx>> { desc { |tcx| "building MIR for `{}`", tcx.def_path_str(key) } + feedable } /// Try to build an abstract representation of the given constant. @@ -617,14 +608,6 @@ rustc_queries! { desc { "getting wasm import module map" } } - /// Maps from the `DefId` of an item (trait/struct/enum/fn) to the - /// predicates (where-clauses) directly defined on it. This is - /// equal to the `explicit_predicates_of` predicates plus the - /// `inferred_outlives_of` predicates. - query predicates_defined_on(key: DefId) -> ty::GenericPredicates<'tcx> { - desc { |tcx| "computing predicates of `{}`", tcx.def_path_str(key) } - } - /// Returns everything that looks like a predicate written explicitly /// by the user on a trait item. /// @@ -742,6 +725,7 @@ rustc_queries! { query constness(key: DefId) -> hir::Constness { desc { |tcx| "checking if item is const: `{}`", tcx.def_path_str(key) } separate_provide_extern + feedable } query asyncness(key: DefId) -> ty::Asyncness { @@ -760,10 +744,22 @@ rustc_queries! { desc { |tcx| "checking if item is promotable: `{}`", tcx.def_path_str(key) } } + /// The body of the coroutine, modified to take its upvars by move rather than by ref. + /// + /// This is used by coroutine-closures, which must return a different flavor of coroutine + /// when called using `AsyncFnOnce::call_once`. It is produced by the `ByMoveBody` pass which + /// is run right after building the initial MIR, and will only be populated for coroutines + /// which come out of the async closure desugaring. + query coroutine_by_move_body_def_id(def_id: DefId) -> DefId { + desc { |tcx| "looking up the coroutine by-move body for `{}`", tcx.def_path_str(def_id) } + separate_provide_extern + } + /// Returns `Some(coroutine_kind)` if the node pointed to by `def_id` is a coroutine. query coroutine_kind(def_id: DefId) -> Option<hir::CoroutineKind> { desc { |tcx| "looking up coroutine kind of `{}`", tcx.def_path_str(def_id) } separate_provide_extern + feedable } query coroutine_for_closure(def_id: DefId) -> DefId { @@ -1249,6 +1245,11 @@ rustc_queries! { feedable } + query struct_target_features(def_id: DefId) -> &'tcx [TargetFeature] { + separate_provide_extern + desc { |tcx| "computing target features for struct `{}`", tcx.def_path_str(def_id) } + } + query asm_target_features(def_id: DefId) -> &'tcx FxIndexSet<Symbol> { desc { |tcx| "computing target features for inline asm of `{}`", tcx.def_path_str(def_id) } } diff --git a/compiler/rustc_middle/src/ty/codec.rs b/compiler/rustc_middle/src/ty/codec.rs index 401f6da6526..46203ee150f 100644 --- a/compiler/rustc_middle/src/ty/codec.rs +++ b/compiler/rustc_middle/src/ty/codec.rs @@ -462,7 +462,6 @@ impl_decodable_via_ref! { &'tcx traits::ImplSource<'tcx, ()>, &'tcx mir::Body<'tcx>, &'tcx mir::BorrowCheckResult<'tcx>, - &'tcx mir::coverage::CodeRegion, &'tcx ty::List<ty::BoundVariableKind>, &'tcx ty::ListWithCachedTypeInfo<ty::Clause<'tcx>>, &'tcx ty::List<FieldIdx>, diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index cad3515f068..70df205d893 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -1579,6 +1579,12 @@ impl<'tcx> TyCtxt<'tcx> { ) } + // Whether the body owner is synthetic, which in this case means it does not correspond to + // meaningful HIR. This is currently used to skip over MIR borrowck. + pub fn is_synthetic_mir(self, def_id: impl Into<DefId>) -> bool { + matches!(self.def_kind(def_id.into()), DefKind::SyntheticCoroutineBody) + } + /// Returns `true` if the node pointed to by `def_id` is a general coroutine that implements `Coroutine`. /// This means it is neither an `async` or `gen` construct. pub fn is_general_coroutine(self, def_id: DefId) -> bool { @@ -2184,7 +2190,7 @@ macro_rules! sty_debug_print { all_infer: usize, } - pub fn go(fmt: &mut std::fmt::Formatter<'_>, tcx: TyCtxt<'_>) -> std::fmt::Result { + pub(crate) fn go(fmt: &mut std::fmt::Formatter<'_>, tcx: TyCtxt<'_>) -> std::fmt::Result { let mut total = DebugStat { total: 0, lt_infer: 0, @@ -3168,6 +3174,18 @@ impl<'tcx> TyCtxt<'tcx> { self.impl_trait_header(def_id).map_or(ty::ImplPolarity::Positive, |h| h.polarity) } + pub fn needs_coroutine_by_move_body_def_id(self, def_id: LocalDefId) -> bool { + if let Some(hir::CoroutineKind::Desugared(_, hir::CoroutineSource::Closure)) = + self.coroutine_kind(def_id) + && let ty::Coroutine(_, args) = self.type_of(def_id).instantiate_identity().kind() + && args.as_coroutine().kind_ty().to_opt_closure_kind() != Some(ty::ClosureKind::FnOnce) + { + true + } else { + false + } + } + /// Whether this is a trait implementation that has `#[diagnostic::do_not_recommend]` pub fn do_not_recommend_impl(self, def_id: DefId) -> bool { matches!(self.def_kind(def_id), DefKind::Impl { of_trait: true }) diff --git a/compiler/rustc_middle/src/ty/instance.rs b/compiler/rustc_middle/src/ty/instance.rs index ecb3943e788..7d5f0f1e9c4 100644 --- a/compiler/rustc_middle/src/ty/instance.rs +++ b/compiler/rustc_middle/src/ty/instance.rs @@ -141,14 +141,6 @@ pub enum InstanceKind<'tcx> { receiver_by_ref: bool, }, - /// `<[coroutine] as Future>::poll`, but for coroutines produced when `AsyncFnOnce` - /// is called on a coroutine-closure whose closure kind greater than `FnOnce`, or - /// similarly for `AsyncFnMut`. - /// - /// This will select the body that is produced by the `ByMoveBody` transform, and thus - /// take and use all of its upvars by-move rather than by-ref. - CoroutineKindShim { coroutine_def_id: DefId }, - /// Compiler-generated accessor for thread locals which returns a reference to the thread local /// the `DefId` defines. This is used to export thread locals from dylibs on platforms lacking /// native support. @@ -248,7 +240,6 @@ impl<'tcx> InstanceKind<'tcx> { coroutine_closure_def_id: def_id, receiver_by_ref: _, } - | ty::InstanceKind::CoroutineKindShim { coroutine_def_id: def_id } | InstanceKind::DropGlue(def_id, _) | InstanceKind::CloneShim(def_id, _) | InstanceKind::FnPtrAddrShim(def_id, _) @@ -270,7 +261,6 @@ impl<'tcx> InstanceKind<'tcx> { | InstanceKind::Intrinsic(..) | InstanceKind::ClosureOnceShim { .. } | ty::InstanceKind::ConstructCoroutineInClosureShim { .. } - | ty::InstanceKind::CoroutineKindShim { .. } | InstanceKind::DropGlue(..) | InstanceKind::AsyncDropGlueCtorShim(..) | InstanceKind::CloneShim(..) @@ -377,7 +367,6 @@ impl<'tcx> InstanceKind<'tcx> { | InstanceKind::AsyncDropGlueCtorShim(_, Some(_)) => false, InstanceKind::ClosureOnceShim { .. } | InstanceKind::ConstructCoroutineInClosureShim { .. } - | InstanceKind::CoroutineKindShim { .. } | InstanceKind::DropGlue(..) | InstanceKind::AsyncDropGlueCtorShim(..) | InstanceKind::Item(_) @@ -452,7 +441,6 @@ pub fn fmt_instance( InstanceKind::FnPtrShim(_, ty) => write!(f, " - shim({ty})"), InstanceKind::ClosureOnceShim { .. } => write!(f, " - shim"), InstanceKind::ConstructCoroutineInClosureShim { .. } => write!(f, " - shim"), - InstanceKind::CoroutineKindShim { .. } => write!(f, " - shim"), InstanceKind::DropGlue(_, None) => write!(f, " - shim(None)"), InstanceKind::DropGlue(_, Some(ty)) => write!(f, " - shim(Some({ty}))"), InstanceKind::CloneShim(_, ty) => write!(f, " - shim({ty})"), @@ -850,7 +838,9 @@ impl<'tcx> Instance<'tcx> { Some(Instance { def: ty::InstanceKind::Item(coroutine_def_id), args }) } else { Some(Instance { - def: ty::InstanceKind::CoroutineKindShim { coroutine_def_id }, + def: ty::InstanceKind::Item( + tcx.coroutine_by_move_body_def_id(coroutine_def_id), + ), args, }) } diff --git a/compiler/rustc_middle/src/ty/list.rs b/compiler/rustc_middle/src/ty/list.rs index 1a1acf36d77..af76d5b7d92 100644 --- a/compiler/rustc_middle/src/ty/list.rs +++ b/compiler/rustc_middle/src/ty/list.rs @@ -58,7 +58,7 @@ impl<T> Default for &List<T> { } } -extern "C" { +unsafe extern "C" { /// A dummy type used to force `List` to be unsized while not requiring /// references to it be wide pointers. type OpaqueListContents; diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index 1e3b5800cba..e41ea7507ef 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -1756,7 +1756,6 @@ impl<'tcx> TyCtxt<'tcx> { | ty::InstanceKind::Virtual(..) | ty::InstanceKind::ClosureOnceShim { .. } | ty::InstanceKind::ConstructCoroutineInClosureShim { .. } - | ty::InstanceKind::CoroutineKindShim { .. } | ty::InstanceKind::DropGlue(..) | ty::InstanceKind::CloneShim(..) | ty::InstanceKind::ThreadLocalShim(..) @@ -1874,7 +1873,8 @@ impl<'tcx> TyCtxt<'tcx> { identity_kind_ty.to_opt_closure_kind(), Some(ClosureKind::Fn | ClosureKind::FnMut) ); - mir.coroutine_by_move_body().unwrap().coroutine_layout_raw() + self.optimized_mir(self.coroutine_by_move_body_def_id(def_id)) + .coroutine_layout_raw() } } } diff --git a/compiler/rustc_middle/src/ty/parameterized.rs b/compiler/rustc_middle/src/ty/parameterized.rs index 7e1255f606c..be611e19b49 100644 --- a/compiler/rustc_middle/src/ty/parameterized.rs +++ b/compiler/rustc_middle/src/ty/parameterized.rs @@ -59,6 +59,7 @@ trivially_parameterized_over_tcx! { std::string::String, crate::metadata::ModChild, crate::middle::codegen_fn_attrs::CodegenFnAttrs, + crate::middle::codegen_fn_attrs::TargetFeature, crate::middle::debugger_visualizer::DebuggerVisualizerFile, crate::middle::exported_symbols::SymbolExportInfo, crate::middle::lib_features::FeatureStability, diff --git a/compiler/rustc_mir_build/messages.ftl b/compiler/rustc_mir_build/messages.ftl index 7a10e627ccd..a42e8ff0168 100644 --- a/compiler/rustc_mir_build/messages.ftl +++ b/compiler/rustc_mir_build/messages.ftl @@ -125,6 +125,17 @@ mir_build_initializing_type_with_requires_unsafe_unsafe_op_in_unsafe_fn_allowed .note = initializing a layout restricted type's field with a value outside the valid range is undefined behavior .label = initializing type with `rustc_layout_scalar_valid_range` attr +mir_build_initializing_type_with_target_feature_requires_unsafe = + initializing type with `target_feature` attr is unsafe and requires unsafe block + .note = this struct can only be constructed if the corresponding `target_feature`s are available + .label = initializing type with `target_feature` attr + +mir_build_initializing_type_with_target_feature_requires_unsafe_unsafe_op_in_unsafe_fn_allowed = + initializing type with `target_feature` attr is unsafe and requires unsafe function or block + .note = this struct can only be constructed if the corresponding `target_feature`s are available + .label = initializing type with `target_feature` attr + + mir_build_inline_assembly_requires_unsafe = use of inline assembly is unsafe and requires unsafe block .note = inline assembly is entirely unchecked and can cause undefined behavior @@ -387,6 +398,11 @@ mir_build_unsafe_op_in_unsafe_fn_initializing_type_with_requires_unsafe = .note = initializing a layout restricted type's field with a value outside the valid range is undefined behavior .label = initializing type with `rustc_layout_scalar_valid_range` attr +mir_build_unsafe_op_in_unsafe_fn_initializing_type_with_target_feature_requires_unsafe = + initializing type with `target_feature` attr is unsafe and requires unsafe block + .note = this struct can only be constructed if the corresponding `target_feature`s are available + .label = initializing type with `target_feature` attr + mir_build_unsafe_op_in_unsafe_fn_inline_assembly_requires_unsafe = use of inline assembly is unsafe and requires unsafe block .note = inline assembly is entirely unchecked and can cause undefined behavior diff --git a/compiler/rustc_mir_build/src/check_unsafety.rs b/compiler/rustc_mir_build/src/check_unsafety.rs index b6cf7a40ecd..4ce796cea7a 100644 --- a/compiler/rustc_mir_build/src/check_unsafety.rs +++ b/compiler/rustc_mir_build/src/check_unsafety.rs @@ -461,14 +461,18 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> { }; self.requires_unsafe(expr.span, CallToUnsafeFunction(func_id)); } else if let &ty::FnDef(func_did, _) = self.thir[fun].ty.kind() { - // If the called function has target features the calling function hasn't, + // If the called function has explicit target features the calling function hasn't, // the call requires `unsafe`. Don't check this on wasm // targets, though. For more information on wasm see the // is_like_wasm check in hir_analysis/src/collect.rs + // Implicit target features are OK because they are either a consequence of some + // explicit target feature (which is checked to be present in the caller) or + // come from a witness argument. let callee_features = &self.tcx.codegen_fn_attrs(func_did).target_features; if !self.tcx.sess.target.options.is_like_wasm && !callee_features.iter().all(|feature| { - self.body_target_features.iter().any(|f| f.name == feature.name) + feature.implied + || self.body_target_features.iter().any(|f| f.name == feature.name) }) { let missing: Vec<_> = callee_features @@ -542,10 +546,16 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> { user_ty: _, fields: _, base: _, - }) => match self.tcx.layout_scalar_valid_range(adt_def.did()) { - (Bound::Unbounded, Bound::Unbounded) => {} - _ => self.requires_unsafe(expr.span, InitializingTypeWith), - }, + }) => { + match self.tcx.layout_scalar_valid_range(adt_def.did()) { + (Bound::Unbounded, Bound::Unbounded) => {} + _ => self.requires_unsafe(expr.span, InitializingTypeWith), + } + if !self.tcx.struct_target_features(adt_def.did()).is_empty() { + self.requires_unsafe(expr.span, ConstructingTargetFeaturesType) + } + } + ExprKind::Closure(box ClosureExpr { closure_id, args: _, @@ -647,6 +657,7 @@ enum UnsafeOpKind { CallToUnsafeFunction(Option<DefId>), UseOfInlineAssembly, InitializingTypeWith, + ConstructingTargetFeaturesType, UseOfMutableStatic, UseOfExternStatic, DerefOfRawPointer, @@ -728,6 +739,15 @@ impl UnsafeOpKind { unsafe_not_inherited_note, }, ), + ConstructingTargetFeaturesType => tcx.emit_node_span_lint( + UNSAFE_OP_IN_UNSAFE_FN, + hir_id, + span, + UnsafeOpInUnsafeFnInitializingTypeWithTargetFeatureRequiresUnsafe { + span, + unsafe_not_inherited_note, + }, + ), UseOfMutableStatic => tcx.emit_node_span_lint( UNSAFE_OP_IN_UNSAFE_FN, hir_id, @@ -885,6 +905,20 @@ impl UnsafeOpKind { unsafe_not_inherited_note, }); } + ConstructingTargetFeaturesType if unsafe_op_in_unsafe_fn_allowed => { + dcx.emit_err( + InitializingTypeWithTargetFeatureRequiresUnsafeUnsafeOpInUnsafeFnAllowed { + span, + unsafe_not_inherited_note, + }, + ); + } + ConstructingTargetFeaturesType => { + dcx.emit_err(InitializingTypeWithTargetFeatureRequiresUnsafe { + span, + unsafe_not_inherited_note, + }); + } UseOfMutableStatic if unsafe_op_in_unsafe_fn_allowed => { dcx.emit_err(UseOfMutableStaticRequiresUnsafeUnsafeOpInUnsafeFnAllowed { span, @@ -993,7 +1027,7 @@ impl UnsafeOpKind { } } -pub fn check_unsafety(tcx: TyCtxt<'_>, def: LocalDefId) { +pub(crate) fn check_unsafety(tcx: TyCtxt<'_>, def: LocalDefId) { // Closures and inline consts are handled by their owner, if it has a body // Also, don't safety check custom MIR if tcx.is_typeck_child(def.to_def_id()) || tcx.has_attr(def, sym::custom_mir) { diff --git a/compiler/rustc_mir_build/src/errors.rs b/compiler/rustc_mir_build/src/errors.rs index 7f9eefd1d52..e7d6239aa9b 100644 --- a/compiler/rustc_mir_build/src/errors.rs +++ b/compiler/rustc_mir_build/src/errors.rs @@ -87,6 +87,16 @@ pub(crate) struct UnsafeOpInUnsafeFnInitializingTypeWithRequiresUnsafe { } #[derive(LintDiagnostic)] +#[diag(mir_build_unsafe_op_in_unsafe_fn_initializing_type_with_target_feature_requires_unsafe, code = E0133)] +#[note] +pub(crate) struct UnsafeOpInUnsafeFnInitializingTypeWithTargetFeatureRequiresUnsafe { + #[label] + pub(crate) span: Span, + #[subdiagnostic] + pub(crate) unsafe_not_inherited_note: Option<UnsafeNotInheritedLintNote>, +} + +#[derive(LintDiagnostic)] #[diag(mir_build_unsafe_op_in_unsafe_fn_mutable_static_requires_unsafe, code = E0133)] #[note] pub(crate) struct UnsafeOpInUnsafeFnUseOfMutableStaticRequiresUnsafe { @@ -251,6 +261,17 @@ pub(crate) struct InitializingTypeWithRequiresUnsafe { } #[derive(Diagnostic)] +#[diag(mir_build_initializing_type_with_target_feature_requires_unsafe, code = E0133)] +#[note] +pub(crate) struct InitializingTypeWithTargetFeatureRequiresUnsafe { + #[primary_span] + #[label] + pub(crate) span: Span, + #[subdiagnostic] + pub(crate) unsafe_not_inherited_note: Option<UnsafeNotInheritedNote>, +} + +#[derive(Diagnostic)] #[diag( mir_build_initializing_type_with_requires_unsafe_unsafe_op_in_unsafe_fn_allowed, code = E0133 @@ -265,6 +286,20 @@ pub(crate) struct InitializingTypeWithRequiresUnsafeUnsafeOpInUnsafeFnAllowed { } #[derive(Diagnostic)] +#[diag( + mir_build_initializing_type_with_target_feature_requires_unsafe_unsafe_op_in_unsafe_fn_allowed, + code = E0133 +)] +#[note] +pub(crate) struct InitializingTypeWithTargetFeatureRequiresUnsafeUnsafeOpInUnsafeFnAllowed { + #[primary_span] + #[label] + pub(crate) span: Span, + #[subdiagnostic] + pub(crate) unsafe_not_inherited_note: Option<UnsafeNotInheritedNote>, +} + +#[derive(Diagnostic)] #[diag(mir_build_mutable_static_requires_unsafe, code = E0133)] #[note] pub(crate) struct UseOfMutableStaticRequiresUnsafe { diff --git a/compiler/rustc_mir_build/src/lib.rs b/compiler/rustc_mir_build/src/lib.rs index 66004179b10..3dbb552cdbb 100644 --- a/compiler/rustc_mir_build/src/lib.rs +++ b/compiler/rustc_mir_build/src/lib.rs @@ -8,6 +8,7 @@ #![feature(if_let_guard)] #![feature(let_chains)] #![feature(try_blocks)] +#![warn(unreachable_pub)] // tidy-alphabetical-end mod build; diff --git a/compiler/rustc_mir_dataflow/src/framework/engine.rs b/compiler/rustc_mir_dataflow/src/framework/engine.rs index 364a416480f..0bab03b0271 100644 --- a/compiler/rustc_mir_dataflow/src/framework/engine.rs +++ b/compiler/rustc_mir_dataflow/src/framework/engine.rs @@ -24,7 +24,7 @@ use crate::errors::{ }; use crate::framework::BitSetExt; -pub type EntrySets<'tcx, A> = IndexVec<BasicBlock, <A as AnalysisDomain<'tcx>>::Domain>; +type EntrySets<'tcx, A> = IndexVec<BasicBlock, <A as AnalysisDomain<'tcx>>::Domain>; /// A dataflow analysis that has converged to fixpoint. #[derive(Clone)] diff --git a/compiler/rustc_mir_dataflow/src/framework/mod.rs b/compiler/rustc_mir_dataflow/src/framework/mod.rs index 6eaed0f7753..6da3a20dc02 100644 --- a/compiler/rustc_mir_dataflow/src/framework/mod.rs +++ b/compiler/rustc_mir_dataflow/src/framework/mod.rs @@ -510,7 +510,7 @@ impl<T: Idx> GenKill<T> for lattice::Dual<BitSet<T>> { // NOTE: DO NOT CHANGE VARIANT ORDER. The derived `Ord` impls rely on the current order. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] -pub enum Effect { +enum Effect { /// The "before" effect (e.g., `apply_before_statement_effect`) for a statement (or /// terminator). Before, @@ -520,7 +520,7 @@ pub enum Effect { } impl Effect { - pub const fn at_index(self, statement_index: usize) -> EffectIndex { + const fn at_index(self, statement_index: usize) -> EffectIndex { EffectIndex { effect: self, statement_index } } } diff --git a/compiler/rustc_mir_dataflow/src/lib.rs b/compiler/rustc_mir_dataflow/src/lib.rs index 8708bebeeb0..9385b52103f 100644 --- a/compiler/rustc_mir_dataflow/src/lib.rs +++ b/compiler/rustc_mir_dataflow/src/lib.rs @@ -5,6 +5,7 @@ #![feature(exact_size_is_empty)] #![feature(let_chains)] #![feature(try_blocks)] +#![warn(unreachable_pub)] // tidy-alphabetical-end use rustc_middle::ty; diff --git a/compiler/rustc_mir_dataflow/src/move_paths/abs_domain.rs b/compiler/rustc_mir_dataflow/src/move_paths/abs_domain.rs index 2a7f23ef6d2..df4c0593246 100644 --- a/compiler/rustc_mir_dataflow/src/move_paths/abs_domain.rs +++ b/compiler/rustc_mir_dataflow/src/move_paths/abs_domain.rs @@ -15,12 +15,12 @@ use rustc_middle::mir::{Local, Operand, PlaceElem, ProjectionElem}; use rustc_middle::ty::Ty; #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] -pub struct AbstractOperand; +pub(crate) struct AbstractOperand; #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] -pub struct AbstractType; -pub type AbstractElem = ProjectionElem<AbstractOperand, AbstractType>; +pub(crate) struct AbstractType; +pub(crate) type AbstractElem = ProjectionElem<AbstractOperand, AbstractType>; -pub trait Lift { +pub(crate) trait Lift { type Abstract; fn lift(&self) -> Self::Abstract; } diff --git a/compiler/rustc_mir_transform/src/coroutine.rs b/compiler/rustc_mir_transform/src/coroutine.rs index 703339bf5bc..d9d2abc554a 100644 --- a/compiler/rustc_mir_transform/src/coroutine.rs +++ b/compiler/rustc_mir_transform/src/coroutine.rs @@ -53,7 +53,7 @@ mod by_move_body; use std::{iter, ops}; -pub use by_move_body::ByMoveBody; +pub use by_move_body::coroutine_by_move_body_def_id; use rustc_data_structures::fx::FxHashSet; use rustc_errors::pluralize; use rustc_hir as hir; diff --git a/compiler/rustc_mir_transform/src/coroutine/by_move_body.rs b/compiler/rustc_mir_transform/src/coroutine/by_move_body.rs index 7ea36f08232..ebe8d2eff4f 100644 --- a/compiler/rustc_mir_transform/src/coroutine/by_move_body.rs +++ b/compiler/rustc_mir_transform/src/coroutine/by_move_body.rs @@ -69,161 +69,167 @@ //! in case precise captures (edition 2021 closure capture rules) caused the inner coroutine //! to split one field capture into two. +use rustc_data_structures::steal::Steal; use rustc_data_structures::unord::UnordMap; use rustc_hir as hir; +use rustc_hir::def::DefKind; +use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_middle::bug; use rustc_middle::hir::place::{Projection, ProjectionKind}; use rustc_middle::mir::visit::MutVisitor; -use rustc_middle::mir::{self, dump_mir, MirPass}; +use rustc_middle::mir::{self, dump_mir}; use rustc_middle::ty::{self, InstanceKind, Ty, TyCtxt, TypeVisitableExt}; +use rustc_span::symbol::kw; use rustc_target::abi::{FieldIdx, VariantIdx}; -use crate::pass_manager::validate_body; - -pub struct ByMoveBody; +pub fn coroutine_by_move_body_def_id<'tcx>( + tcx: TyCtxt<'tcx>, + coroutine_def_id: LocalDefId, +) -> DefId { + let body = tcx.mir_built(coroutine_def_id).borrow(); -impl<'tcx> MirPass<'tcx> for ByMoveBody { - fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut mir::Body<'tcx>) { - // We only need to generate by-move coroutine bodies for coroutines that come - // from coroutine-closures. - let Some(coroutine_def_id) = body.source.def_id().as_local() else { - return; - }; - let Some(hir::CoroutineKind::Desugared(_, hir::CoroutineSource::Closure)) = - tcx.coroutine_kind(coroutine_def_id) - else { - return; - }; + let Some(hir::CoroutineKind::Desugared(_, hir::CoroutineSource::Closure)) = + tcx.coroutine_kind(coroutine_def_id) + else { + bug!("should only be invoked on coroutine-closures"); + }; - // Also, let's skip processing any bodies with errors, since there's no guarantee - // the MIR body will be constructed well. - let coroutine_ty = body.local_decls[ty::CAPTURE_STRUCT_LOCAL].ty; - if coroutine_ty.references_error() { - return; - } + // Also, let's skip processing any bodies with errors, since there's no guarantee + // the MIR body will be constructed well. + let coroutine_ty = body.local_decls[ty::CAPTURE_STRUCT_LOCAL].ty; - // We don't need to generate a by-move coroutine if the coroutine body was - // produced by the `CoroutineKindShim`, since it's already by-move. - if matches!(body.source.instance, ty::InstanceKind::CoroutineKindShim { .. }) { - return; - } + let ty::Coroutine(_, args) = *coroutine_ty.kind() else { bug!("{body:#?}") }; + let args = args.as_coroutine(); - let ty::Coroutine(_, args) = *coroutine_ty.kind() else { bug!("{body:#?}") }; - let args = args.as_coroutine(); + let coroutine_kind = args.kind_ty().to_opt_closure_kind().unwrap(); - let coroutine_kind = args.kind_ty().to_opt_closure_kind().unwrap(); + let parent_def_id = tcx.local_parent(coroutine_def_id); + let ty::CoroutineClosure(_, parent_args) = + *tcx.type_of(parent_def_id).instantiate_identity().kind() + else { + bug!(); + }; + if parent_args.references_error() { + return coroutine_def_id.to_def_id(); + } - let parent_def_id = tcx.local_parent(coroutine_def_id); - let ty::CoroutineClosure(_, parent_args) = - *tcx.type_of(parent_def_id).instantiate_identity().kind() - else { - bug!(); - }; - let parent_closure_args = parent_args.as_coroutine_closure(); - let num_args = parent_closure_args - .coroutine_closure_sig() - .skip_binder() - .tupled_inputs_ty - .tuple_fields() - .len(); + let parent_closure_args = parent_args.as_coroutine_closure(); + let num_args = parent_closure_args + .coroutine_closure_sig() + .skip_binder() + .tupled_inputs_ty + .tuple_fields() + .len(); - let field_remapping: UnordMap<_, _> = ty::analyze_coroutine_closure_captures( - tcx.closure_captures(parent_def_id).iter().copied(), - tcx.closure_captures(coroutine_def_id).iter().skip(num_args).copied(), - |(parent_field_idx, parent_capture), (child_field_idx, child_capture)| { - // Store this set of additional projections (fields and derefs). - // We need to re-apply them later. - let mut child_precise_captures = child_capture.place.projections - [parent_capture.place.projections.len()..] - .to_vec(); + let field_remapping: UnordMap<_, _> = ty::analyze_coroutine_closure_captures( + tcx.closure_captures(parent_def_id).iter().copied(), + tcx.closure_captures(coroutine_def_id).iter().skip(num_args).copied(), + |(parent_field_idx, parent_capture), (child_field_idx, child_capture)| { + // Store this set of additional projections (fields and derefs). + // We need to re-apply them later. + let mut child_precise_captures = + child_capture.place.projections[parent_capture.place.projections.len()..].to_vec(); - // If the parent capture is by-ref, then we need to apply an additional - // deref before applying any further projections to this place. - if parent_capture.is_by_ref() { - child_precise_captures.insert( - 0, - Projection { ty: parent_capture.place.ty(), kind: ProjectionKind::Deref }, - ); - } - // If the child capture is by-ref, then we need to apply a "ref" - // projection (i.e. `&`) at the end. But wait! We don't have that - // as a projection kind. So instead, we can apply its dual and - // *peel* a deref off of the place when it shows up in the MIR body. - // Luckily, by construction this is always possible. - let peel_deref = if child_capture.is_by_ref() { - assert!( - parent_capture.is_by_ref() || coroutine_kind != ty::ClosureKind::FnOnce, - "`FnOnce` coroutine-closures return coroutines that capture from \ + // If the parent capture is by-ref, then we need to apply an additional + // deref before applying any further projections to this place. + if parent_capture.is_by_ref() { + child_precise_captures.insert( + 0, + Projection { ty: parent_capture.place.ty(), kind: ProjectionKind::Deref }, + ); + } + // If the child capture is by-ref, then we need to apply a "ref" + // projection (i.e. `&`) at the end. But wait! We don't have that + // as a projection kind. So instead, we can apply its dual and + // *peel* a deref off of the place when it shows up in the MIR body. + // Luckily, by construction this is always possible. + let peel_deref = if child_capture.is_by_ref() { + assert!( + parent_capture.is_by_ref() || coroutine_kind != ty::ClosureKind::FnOnce, + "`FnOnce` coroutine-closures return coroutines that capture from \ their body; it will always result in a borrowck error!" - ); - true - } else { - false - }; + ); + true + } else { + false + }; - // Regarding the behavior above, you may think that it's redundant to both - // insert a deref and then peel a deref if the parent and child are both - // captured by-ref. This would be correct, except for the case where we have - // precise capturing projections, since the inserted deref is to the *beginning* - // and the peeled deref is at the *end*. I cannot seem to actually find a - // case where this happens, though, but let's keep this code flexible. + // Regarding the behavior above, you may think that it's redundant to both + // insert a deref and then peel a deref if the parent and child are both + // captured by-ref. This would be correct, except for the case where we have + // precise capturing projections, since the inserted deref is to the *beginning* + // and the peeled deref is at the *end*. I cannot seem to actually find a + // case where this happens, though, but let's keep this code flexible. - // Finally, store the type of the parent's captured place. We need - // this when building the field projection in the MIR body later on. - let mut parent_capture_ty = parent_capture.place.ty(); - parent_capture_ty = match parent_capture.info.capture_kind { - ty::UpvarCapture::ByValue => parent_capture_ty, - ty::UpvarCapture::ByRef(kind) => Ty::new_ref( - tcx, - tcx.lifetimes.re_erased, - parent_capture_ty, - kind.to_mutbl_lossy(), - ), - }; + // Finally, store the type of the parent's captured place. We need + // this when building the field projection in the MIR body later on. + let mut parent_capture_ty = parent_capture.place.ty(); + parent_capture_ty = match parent_capture.info.capture_kind { + ty::UpvarCapture::ByValue => parent_capture_ty, + ty::UpvarCapture::ByRef(kind) => Ty::new_ref( + tcx, + tcx.lifetimes.re_erased, + parent_capture_ty, + kind.to_mutbl_lossy(), + ), + }; + ( + FieldIdx::from_usize(child_field_idx + num_args), ( - FieldIdx::from_usize(child_field_idx + num_args), - ( - FieldIdx::from_usize(parent_field_idx + num_args), - parent_capture_ty, - peel_deref, - child_precise_captures, - ), - ) - }, - ) - .collect(); + FieldIdx::from_usize(parent_field_idx + num_args), + parent_capture_ty, + peel_deref, + child_precise_captures, + ), + ) + }, + ) + .collect(); - if coroutine_kind == ty::ClosureKind::FnOnce { - assert_eq!(field_remapping.len(), tcx.closure_captures(parent_def_id).len()); - return; - } + if coroutine_kind == ty::ClosureKind::FnOnce { + assert_eq!(field_remapping.len(), tcx.closure_captures(parent_def_id).len()); + // The by-move body is just the body :) + return coroutine_def_id.to_def_id(); + } - let by_move_coroutine_ty = tcx - .instantiate_bound_regions_with_erased(parent_closure_args.coroutine_closure_sig()) - .to_coroutine_given_kind_and_upvars( - tcx, - parent_closure_args.parent_args(), - coroutine_def_id.to_def_id(), - ty::ClosureKind::FnOnce, - tcx.lifetimes.re_erased, - parent_closure_args.tupled_upvars_ty(), - parent_closure_args.coroutine_captures_by_ref_ty(), - ); + let by_move_coroutine_ty = tcx + .instantiate_bound_regions_with_erased(parent_closure_args.coroutine_closure_sig()) + .to_coroutine_given_kind_and_upvars( + tcx, + parent_closure_args.parent_args(), + coroutine_def_id.to_def_id(), + ty::ClosureKind::FnOnce, + tcx.lifetimes.re_erased, + parent_closure_args.tupled_upvars_ty(), + parent_closure_args.coroutine_captures_by_ref_ty(), + ); - let mut by_move_body = body.clone(); - MakeByMoveBody { tcx, field_remapping, by_move_coroutine_ty }.visit_body(&mut by_move_body); - dump_mir(tcx, false, "coroutine_by_move", &0, &by_move_body, |_, _| Ok(())); + let mut by_move_body = body.clone(); + MakeByMoveBody { tcx, field_remapping, by_move_coroutine_ty }.visit_body(&mut by_move_body); + dump_mir(tcx, false, "coroutine_by_move", &0, &by_move_body, |_, _| Ok(())); - // Let's just always validate this body. - validate_body(tcx, &mut by_move_body, "Initial coroutine_by_move body".to_string()); + let body_def = tcx.create_def(coroutine_def_id, kw::Empty, DefKind::SyntheticCoroutineBody); + by_move_body.source = + mir::MirSource::from_instance(InstanceKind::Item(body_def.def_id().to_def_id())); - // FIXME: use query feeding to generate the body right here and then only store the `DefId` of the new body. - by_move_body.source = mir::MirSource::from_instance(InstanceKind::CoroutineKindShim { - coroutine_def_id: coroutine_def_id.to_def_id(), - }); - body.coroutine.as_mut().unwrap().by_move_body = Some(by_move_body); - } + // Inherited from the by-ref coroutine. + body_def.codegen_fn_attrs(tcx.codegen_fn_attrs(coroutine_def_id).clone()); + body_def.constness(tcx.constness(coroutine_def_id).clone()); + body_def.coroutine_kind(tcx.coroutine_kind(coroutine_def_id).clone()); + body_def.def_ident_span(tcx.def_ident_span(coroutine_def_id)); + body_def.def_span(tcx.def_span(coroutine_def_id)); + body_def.explicit_predicates_of(tcx.explicit_predicates_of(coroutine_def_id).clone()); + body_def.generics_of(tcx.generics_of(coroutine_def_id).clone()); + body_def.param_env(tcx.param_env(coroutine_def_id).clone()); + body_def.predicates_of(tcx.predicates_of(coroutine_def_id).clone()); + + // The type of the coroutine is the `by_move_coroutine_ty`. + body_def.type_of(ty::EarlyBinder::bind(by_move_coroutine_ty)); + + body_def.mir_built(tcx.arena.alloc(Steal::new(by_move_body))); + + body_def.def_id().to_def_id() } struct MakeByMoveBody<'tcx> { diff --git a/compiler/rustc_mir_transform/src/coverage/mod.rs b/compiler/rustc_mir_transform/src/coverage/mod.rs index 96ca3b43d5c..af0f1e38a75 100644 --- a/compiler/rustc_mir_transform/src/coverage/mod.rs +++ b/compiler/rustc_mir_transform/src/coverage/mod.rs @@ -13,7 +13,7 @@ use rustc_hir::intravisit::{walk_expr, Visitor}; use rustc_middle::hir::map::Map; use rustc_middle::hir::nested_filter; use rustc_middle::mir::coverage::{ - CodeRegion, CoverageKind, DecisionInfo, FunctionCoverageInfo, Mapping, MappingKind, + CoverageKind, DecisionInfo, FunctionCoverageInfo, Mapping, MappingKind, SourceRegion, }; use rustc_middle::mir::{ self, BasicBlock, BasicBlockData, SourceInfo, Statement, StatementKind, Terminator, @@ -159,7 +159,7 @@ fn create_mappings<'tcx>( .expect("all BCBs with spans were given counters") .as_term() }; - let region_for_span = |span: Span| make_code_region(source_map, file_name, span, body_span); + let region_for_span = |span: Span| make_source_region(source_map, file_name, span, body_span); // Fully destructure the mappings struct to make sure we don't miss any kinds. let ExtractedMappings { @@ -175,9 +175,9 @@ fn create_mappings<'tcx>( mappings.extend(code_mappings.iter().filter_map( // Ordinary code mappings are the simplest kind. |&mappings::CodeMapping { span, bcb }| { - let code_region = region_for_span(span)?; + let source_region = region_for_span(span)?; let kind = MappingKind::Code(term_for_bcb(bcb)); - Some(Mapping { kind, code_region }) + Some(Mapping { kind, source_region }) }, )); @@ -186,29 +186,29 @@ fn create_mappings<'tcx>( let true_term = term_for_bcb(true_bcb); let false_term = term_for_bcb(false_bcb); let kind = MappingKind::Branch { true_term, false_term }; - let code_region = region_for_span(span)?; - Some(Mapping { kind, code_region }) + let source_region = region_for_span(span)?; + Some(Mapping { kind, source_region }) }, )); mappings.extend(mcdc_branches.iter().filter_map( |&mappings::MCDCBranch { span, true_bcb, false_bcb, condition_info, decision_depth: _ }| { - let code_region = region_for_span(span)?; + let source_region = region_for_span(span)?; let true_term = term_for_bcb(true_bcb); let false_term = term_for_bcb(false_bcb); let kind = match condition_info { Some(mcdc_params) => MappingKind::MCDCBranch { true_term, false_term, mcdc_params }, None => MappingKind::Branch { true_term, false_term }, }; - Some(Mapping { kind, code_region }) + Some(Mapping { kind, source_region }) }, )); mappings.extend(mcdc_decisions.iter().filter_map( |&mappings::MCDCDecision { span, bitmap_idx, num_conditions, .. }| { - let code_region = region_for_span(span)?; + let source_region = region_for_span(span)?; let kind = MappingKind::MCDCDecision(DecisionInfo { bitmap_idx, num_conditions }); - Some(Mapping { kind, code_region }) + Some(Mapping { kind, source_region }) }, )); @@ -362,19 +362,13 @@ fn inject_statement(mir_body: &mut mir::Body<'_>, counter_kind: CoverageKind, bb /// but it's hard to rule out entirely (especially in the presence of complex macros /// or other expansions), and if it does happen then skipping a span or function is /// better than an ICE or `llvm-cov` failure that the user might have no way to avoid. -fn make_code_region( +#[instrument(level = "debug", skip(source_map))] +fn make_source_region( source_map: &SourceMap, file_name: Symbol, span: Span, body_span: Span, -) -> Option<CodeRegion> { - debug!( - "Called make_code_region(file_name={}, span={}, body_span={})", - file_name, - source_map.span_to_diagnostic_string(span), - source_map.span_to_diagnostic_string(body_span) - ); - +) -> Option<SourceRegion> { let lo = span.lo(); let hi = span.hi(); @@ -424,7 +418,7 @@ fn make_code_region( start_line = source_map.doctest_offset_line(&file.name, start_line); end_line = source_map.doctest_offset_line(&file.name, end_line); - check_code_region(CodeRegion { + check_source_region(SourceRegion { file_name, start_line: start_line as u32, start_col: start_col as u32, @@ -433,12 +427,12 @@ fn make_code_region( }) } -/// If `llvm-cov` sees a code region that is improperly ordered (end < start), +/// If `llvm-cov` sees a source region that is improperly ordered (end < start), /// it will immediately exit with a fatal error. To prevent that from happening, /// discard regions that are improperly ordered, or might be interpreted in a /// way that makes them improperly ordered. -fn check_code_region(code_region: CodeRegion) -> Option<CodeRegion> { - let CodeRegion { file_name: _, start_line, start_col, end_line, end_col } = code_region; +fn check_source_region(source_region: SourceRegion) -> Option<SourceRegion> { + let SourceRegion { file_name: _, start_line, start_col, end_line, end_col } = source_region; // Line/column coordinates are supposed to be 1-based. If we ever emit // coordinates of 0, `llvm-cov` might misinterpret them. @@ -451,17 +445,17 @@ fn check_code_region(code_region: CodeRegion) -> Option<CodeRegion> { let is_ordered = (start_line, start_col) <= (end_line, end_col); if all_nonzero && end_col_has_high_bit_unset && is_ordered { - Some(code_region) + Some(source_region) } else { debug!( - ?code_region, + ?source_region, ?all_nonzero, ?end_col_has_high_bit_unset, ?is_ordered, - "Skipping code region that would be misinterpreted or rejected by LLVM" + "Skipping source region that would be misinterpreted or rejected by LLVM" ); // If this happens in a debug build, ICE to make it easier to notice. - debug_assert!(false, "Improper code region: {code_region:?}"); + debug_assert!(false, "Improper source region: {source_region:?}"); None } } diff --git a/compiler/rustc_mir_transform/src/inline.rs b/compiler/rustc_mir_transform/src/inline.rs index 61fc5fc8816..2d6950be55d 100644 --- a/compiler/rustc_mir_transform/src/inline.rs +++ b/compiler/rustc_mir_transform/src/inline.rs @@ -341,7 +341,6 @@ impl<'tcx> Inliner<'tcx> { | InstanceKind::FnPtrShim(..) | InstanceKind::ClosureOnceShim { .. } | InstanceKind::ConstructCoroutineInClosureShim { .. } - | InstanceKind::CoroutineKindShim { .. } | InstanceKind::DropGlue(..) | InstanceKind::CloneShim(..) | InstanceKind::ThreadLocalShim(..) diff --git a/compiler/rustc_mir_transform/src/inline/cycle.rs b/compiler/rustc_mir_transform/src/inline/cycle.rs index f5274c664cf..c65cc993b19 100644 --- a/compiler/rustc_mir_transform/src/inline/cycle.rs +++ b/compiler/rustc_mir_transform/src/inline/cycle.rs @@ -88,7 +88,6 @@ pub(crate) fn mir_callgraph_reachable<'tcx>( | InstanceKind::FnPtrShim(..) | InstanceKind::ClosureOnceShim { .. } | InstanceKind::ConstructCoroutineInClosureShim { .. } - | InstanceKind::CoroutineKindShim { .. } | InstanceKind::ThreadLocalShim { .. } | InstanceKind::CloneShim(..) => {} @@ -136,6 +135,14 @@ pub(crate) fn mir_callgraph_reachable<'tcx>( } false } + // FIXME(-Znext-solver): Remove this hack when trait solver overflow can return an error. + // In code like that pointed out in #128887, the type complexity we ask the solver to deal with + // grows as we recurse into the call graph. If we use the same recursion limit here and in the + // solver, the solver hits the limit first and emits a fatal error. But if we use a reduced + // limit, we will hit the limit first and give up on looking for inlining. And in any case, + // the default recursion limits are quite generous for us. If we need to recurse 64 times + // into the call graph, we're probably not going to find any useful MIR inlining. + let recursion_limit = tcx.recursion_limit() / 2; process( tcx, param_env, @@ -144,7 +151,7 @@ pub(crate) fn mir_callgraph_reachable<'tcx>( &mut Vec::new(), &mut FxHashSet::default(), &mut FxHashMap::default(), - tcx.recursion_limit(), + recursion_limit, ) } diff --git a/compiler/rustc_mir_transform/src/lib.rs b/compiler/rustc_mir_transform/src/lib.rs index 1f214bc42cb..88094b44edf 100644 --- a/compiler/rustc_mir_transform/src/lib.rs +++ b/compiler/rustc_mir_transform/src/lib.rs @@ -135,6 +135,7 @@ pub fn provide(providers: &mut Providers) { mir_inliner_callees: inline::cycle::mir_inliner_callees, promoted_mir, deduced_param_attrs: deduce_param_attrs::deduced_param_attrs, + coroutine_by_move_body_def_id: coroutine::coroutine_by_move_body_def_id, ..providers.queries }; } @@ -293,10 +294,6 @@ fn mir_built(tcx: TyCtxt<'_>, def: LocalDefId) -> &Steal<Body<'_>> { &Lint(check_packed_ref::CheckPackedRef), &Lint(check_const_item_mutation::CheckConstItemMutation), &Lint(function_item_references::FunctionItemReferences), - // If this is an async closure's output coroutine, generate - // by-move and by-mut bodies if needed. We do this first so - // they can be optimized in lockstep with their parent bodies. - &coroutine::ByMoveBody, // What we need to do constant evaluation. &simplify::SimplifyCfg::Initial, &rustc_peek::SanityCheck, // Just a lint @@ -329,8 +326,15 @@ fn mir_promoted( | DefKind::AnonConst => tcx.mir_const_qualif(def), _ => ConstQualifs::default(), }; - // has_ffi_unwind_calls query uses the raw mir, so make sure it is run. + + // the `has_ffi_unwind_calls` query uses the raw mir, so make sure it is run. tcx.ensure_with_value().has_ffi_unwind_calls(def); + + // the `by_move_body` query uses the raw mir, so make sure it is run. + if tcx.needs_coroutine_by_move_body_def_id(def) { + tcx.ensure_with_value().coroutine_by_move_body_def_id(def); + } + let mut body = tcx.mir_built(def).steal(); if let Some(error_reported) = const_qualifs.tainted_by_errors { body.tainted_by_errors = Some(error_reported); @@ -339,14 +343,6 @@ fn mir_promoted( // Collect `required_consts` *before* promotion, so if there are any consts being promoted // we still add them to the list in the outer MIR body. RequiredConstsVisitor::compute_required_consts(&mut body); - // If this has an associated by-move async closure body, that doesn't get run through these - // passes itself, it gets "tagged along" by the pass manager. `RequiredConstsVisitor` is not - // a regular pass so we have to also apply it manually to the other body. - if let Some(coroutine) = body.coroutine.as_mut() { - if let Some(by_move_body) = coroutine.by_move_body.as_mut() { - RequiredConstsVisitor::compute_required_consts(by_move_body); - } - } // What we need to run borrowck etc. let promote_pass = promote_consts::PromoteTemps::default(); @@ -398,7 +394,10 @@ fn mir_drops_elaborated_and_const_checked(tcx: TyCtxt<'_>, def: LocalDefId) -> & if tcx.is_coroutine(def.to_def_id()) { tcx.ensure_with_value().mir_coroutine_witnesses(def); } - let mir_borrowck = tcx.mir_borrowck(def); + + // We only need to borrowck non-synthetic MIR. + let tainted_by_errors = + if !tcx.is_synthetic_mir(def) { tcx.mir_borrowck(def).tainted_by_errors } else { None }; let is_fn_like = tcx.def_kind(def).is_fn_like(); if is_fn_like { @@ -410,7 +409,8 @@ fn mir_drops_elaborated_and_const_checked(tcx: TyCtxt<'_>, def: LocalDefId) -> & let (body, _) = tcx.mir_promoted(def); let mut body = body.steal(); - if let Some(error_reported) = mir_borrowck.tainted_by_errors { + + if let Some(error_reported) = tainted_by_errors { body.tainted_by_errors = Some(error_reported); } @@ -660,14 +660,6 @@ fn inner_optimized_mir(tcx: TyCtxt<'_>, did: LocalDefId) -> Body<'_> { // visited does not depend on the optimization level. // We do not use `run_passes` for this as that might skip the pass if `injection_phase` is set. mentioned_items::MentionedItems.run_pass(tcx, &mut body); - // If this has an associated by-move async closure body, that doesn't get run through these - // passes itself, it gets "tagged along" by the pass manager. Since we're not using the pass - // manager we have to do this by hand. - if let Some(coroutine) = body.coroutine.as_mut() { - if let Some(by_move_body) = coroutine.by_move_body.as_mut() { - mentioned_items::MentionedItems.run_pass(tcx, by_move_body); - } - } // If `mir_drops_elaborated_and_const_checked` found that the current body has unsatisfiable // predicates, it will shrink the MIR to a single `unreachable` terminator. @@ -690,7 +682,9 @@ fn promoted_mir(tcx: TyCtxt<'_>, def: LocalDefId) -> &IndexVec<Promoted, Body<'_ return tcx.arena.alloc(IndexVec::new()); } - tcx.ensure_with_value().mir_borrowck(def); + if !tcx.is_synthetic_mir(def) { + tcx.ensure_with_value().mir_borrowck(def); + } let mut promoted = tcx.mir_promoted(def).1.steal(); for body in &mut promoted { diff --git a/compiler/rustc_mir_transform/src/pass_manager.rs b/compiler/rustc_mir_transform/src/pass_manager.rs index 824a4b2f2df..d092477e340 100644 --- a/compiler/rustc_mir_transform/src/pass_manager.rs +++ b/compiler/rustc_mir_transform/src/pass_manager.rs @@ -182,12 +182,6 @@ fn run_passes_inner<'tcx>( body.pass_count = 1; } - - if let Some(coroutine) = body.coroutine.as_mut() { - if let Some(by_move_body) = coroutine.by_move_body.as_mut() { - run_passes_inner(tcx, by_move_body, passes, phase_change, validate_each); - } - } } pub fn validate_body<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>, when: String) { diff --git a/compiler/rustc_mir_transform/src/shim.rs b/compiler/rustc_mir_transform/src/shim.rs index 09b4e5e0711..86eada0183f 100644 --- a/compiler/rustc_mir_transform/src/shim.rs +++ b/compiler/rustc_mir_transform/src/shim.rs @@ -78,15 +78,11 @@ fn make_shim<'tcx>(tcx: TyCtxt<'tcx>, instance: ty::InstanceKind<'tcx>) -> Body< receiver_by_ref, } => build_construct_coroutine_by_move_shim(tcx, coroutine_closure_def_id, receiver_by_ref), - ty::InstanceKind::CoroutineKindShim { coroutine_def_id } => { - return tcx.optimized_mir(coroutine_def_id).coroutine_by_move_body().unwrap().clone(); - } - ty::InstanceKind::DropGlue(def_id, ty) => { // FIXME(#91576): Drop shims for coroutines aren't subject to the MIR passes at the end // of this function. Is this intentional? - if let Some(ty::Coroutine(coroutine_def_id, args)) = ty.map(Ty::kind) { - let coroutine_body = tcx.optimized_mir(*coroutine_def_id); + if let Some(&ty::Coroutine(coroutine_def_id, args)) = ty.map(Ty::kind) { + let coroutine_body = tcx.optimized_mir(coroutine_def_id); let ty::Coroutine(_, id_args) = *tcx.type_of(coroutine_def_id).skip_binder().kind() else { @@ -105,7 +101,9 @@ fn make_shim<'tcx>(tcx: TyCtxt<'tcx>, instance: ty::InstanceKind<'tcx>) -> Body< args.as_coroutine().kind_ty().to_opt_closure_kind().unwrap(), ty::ClosureKind::FnOnce ); - coroutine_body.coroutine_by_move_body().unwrap().coroutine_drop().unwrap() + tcx.optimized_mir(tcx.coroutine_by_move_body_def_id(coroutine_def_id)) + .coroutine_drop() + .unwrap() }; let mut body = EarlyBinder::bind(body.clone()).instantiate(tcx, args); diff --git a/compiler/rustc_mir_transform/src/validate.rs b/compiler/rustc_mir_transform/src/validate.rs index 36908036796..99e06f59dd0 100644 --- a/compiler/rustc_mir_transform/src/validate.rs +++ b/compiler/rustc_mir_transform/src/validate.rs @@ -102,25 +102,6 @@ impl<'tcx> MirPass<'tcx> for Validator { } } } - - // Enforce that coroutine-closure layouts are identical. - if let Some(layout) = body.coroutine_layout_raw() - && let Some(by_move_body) = body.coroutine_by_move_body() - && let Some(by_move_layout) = by_move_body.coroutine_layout_raw() - { - // FIXME(async_closures): We could do other validation here? - if layout.variant_fields.len() != by_move_layout.variant_fields.len() { - cfg_checker.fail( - Location::START, - format!( - "Coroutine layout has different number of variant fields from \ - by-move coroutine layout:\n\ - layout: {layout:#?}\n\ - by_move_layout: {by_move_layout:#?}", - ), - ); - } - } } } diff --git a/compiler/rustc_monomorphize/src/collector.rs b/compiler/rustc_monomorphize/src/collector.rs index ff4207fbefd..9c820b888d9 100644 --- a/compiler/rustc_monomorphize/src/collector.rs +++ b/compiler/rustc_monomorphize/src/collector.rs @@ -242,12 +242,12 @@ use tracing::{debug, instrument, trace}; use crate::errors::{self, EncounteredErrorWhileInstantiating, NoOptimizedMir, RecursionLimit}; #[derive(PartialEq)] -pub enum MonoItemCollectionStrategy { +pub(crate) enum MonoItemCollectionStrategy { Eager, Lazy, } -pub struct UsageMap<'tcx> { +pub(crate) struct UsageMap<'tcx> { // Maps every mono item to the mono items used by it. used_map: UnordMap<MonoItem<'tcx>, Vec<MonoItem<'tcx>>>, @@ -306,13 +306,17 @@ impl<'tcx> UsageMap<'tcx> { assert!(self.used_map.insert(user_item, used_items).is_none()); } - pub fn get_user_items(&self, item: MonoItem<'tcx>) -> &[MonoItem<'tcx>] { + pub(crate) fn get_user_items(&self, item: MonoItem<'tcx>) -> &[MonoItem<'tcx>] { self.user_map.get(&item).map(|items| items.as_slice()).unwrap_or(&[]) } /// Internally iterate over all inlined items used by `item`. - pub fn for_each_inlined_used_item<F>(&self, tcx: TyCtxt<'tcx>, item: MonoItem<'tcx>, mut f: F) - where + pub(crate) fn for_each_inlined_used_item<F>( + &self, + tcx: TyCtxt<'tcx>, + item: MonoItem<'tcx>, + mut f: F, + ) where F: FnMut(MonoItem<'tcx>), { let used_items = self.used_map.get(&item).unwrap(); @@ -920,7 +924,6 @@ fn visit_instance_use<'tcx>( | ty::InstanceKind::ReifyShim(..) | ty::InstanceKind::ClosureOnceShim { .. } | ty::InstanceKind::ConstructCoroutineInClosureShim { .. } - | ty::InstanceKind::CoroutineKindShim { .. } | ty::InstanceKind::Item(..) | ty::InstanceKind::FnPtrShim(..) | ty::InstanceKind::CloneShim(..) @@ -1616,6 +1619,6 @@ pub(crate) fn collect_crate_mono_items<'tcx>( (mono_items, state.usage_map.into_inner()) } -pub fn provide(providers: &mut Providers) { +pub(crate) fn provide(providers: &mut Providers) { providers.hooks.should_codegen_locally = should_codegen_locally; } diff --git a/compiler/rustc_monomorphize/src/errors.rs b/compiler/rustc_monomorphize/src/errors.rs index c97e07ee3ba..d5fae6e23cb 100644 --- a/compiler/rustc_monomorphize/src/errors.rs +++ b/compiler/rustc_monomorphize/src/errors.rs @@ -8,7 +8,7 @@ use crate::fluent_generated as fluent; #[derive(Diagnostic)] #[diag(monomorphize_recursion_limit)] -pub struct RecursionLimit { +pub(crate) struct RecursionLimit { #[primary_span] pub span: Span, pub shrunk: String, @@ -22,13 +22,13 @@ pub struct RecursionLimit { #[derive(Diagnostic)] #[diag(monomorphize_no_optimized_mir)] -pub struct NoOptimizedMir { +pub(crate) struct NoOptimizedMir { #[note] pub span: Span, pub crate_name: Symbol, } -pub struct UnusedGenericParamsHint { +pub(crate) struct UnusedGenericParamsHint { pub span: Span, pub param_spans: Vec<Span>, pub param_names: Vec<String>, @@ -53,7 +53,7 @@ impl<G: EmissionGuarantee> Diagnostic<'_, G> for UnusedGenericParamsHint { #[derive(LintDiagnostic)] #[diag(monomorphize_large_assignments)] #[note] -pub struct LargeAssignmentsLint { +pub(crate) struct LargeAssignmentsLint { #[label] pub span: Span, pub size: u64, @@ -62,7 +62,7 @@ pub struct LargeAssignmentsLint { #[derive(Diagnostic)] #[diag(monomorphize_symbol_already_defined)] -pub struct SymbolAlreadyDefined { +pub(crate) struct SymbolAlreadyDefined { #[primary_span] pub span: Option<Span>, pub symbol: String, @@ -70,13 +70,13 @@ pub struct SymbolAlreadyDefined { #[derive(Diagnostic)] #[diag(monomorphize_couldnt_dump_mono_stats)] -pub struct CouldntDumpMonoStats { +pub(crate) struct CouldntDumpMonoStats { pub error: String, } #[derive(Diagnostic)] #[diag(monomorphize_encountered_error_while_instantiating)] -pub struct EncounteredErrorWhileInstantiating { +pub(crate) struct EncounteredErrorWhileInstantiating { #[primary_span] pub span: Span, pub formatted_item: String, @@ -85,10 +85,10 @@ pub struct EncounteredErrorWhileInstantiating { #[derive(Diagnostic)] #[diag(monomorphize_start_not_found)] #[help] -pub struct StartNotFound; +pub(crate) struct StartNotFound; #[derive(Diagnostic)] #[diag(monomorphize_unknown_cgu_collection_mode)] -pub struct UnknownCguCollectionMode<'a> { +pub(crate) struct UnknownCguCollectionMode<'a> { pub mode: &'a str, } diff --git a/compiler/rustc_monomorphize/src/lib.rs b/compiler/rustc_monomorphize/src/lib.rs index d6b0f9c4d28..b22e8e30465 100644 --- a/compiler/rustc_monomorphize/src/lib.rs +++ b/compiler/rustc_monomorphize/src/lib.rs @@ -1,5 +1,6 @@ // tidy-alphabetical-start #![feature(array_windows)] +#![warn(unreachable_pub)] // tidy-alphabetical-end use rustc_hir::lang_items::LangItem; diff --git a/compiler/rustc_monomorphize/src/partitioning.rs b/compiler/rustc_monomorphize/src/partitioning.rs index 610ad41ce52..0d295b8f280 100644 --- a/compiler/rustc_monomorphize/src/partitioning.rs +++ b/compiler/rustc_monomorphize/src/partitioning.rs @@ -626,7 +626,6 @@ fn characteristic_def_id_of_mono_item<'tcx>( | ty::InstanceKind::FnPtrShim(..) | ty::InstanceKind::ClosureOnceShim { .. } | ty::InstanceKind::ConstructCoroutineInClosureShim { .. } - | ty::InstanceKind::CoroutineKindShim { .. } | ty::InstanceKind::Intrinsic(..) | ty::InstanceKind::DropGlue(..) | ty::InstanceKind::Virtual(..) @@ -796,7 +795,6 @@ fn mono_item_visibility<'tcx>( | InstanceKind::Intrinsic(..) | InstanceKind::ClosureOnceShim { .. } | InstanceKind::ConstructCoroutineInClosureShim { .. } - | InstanceKind::CoroutineKindShim { .. } | InstanceKind::DropGlue(..) | InstanceKind::AsyncDropGlueCtorShim(..) | InstanceKind::CloneShim(..) @@ -1302,7 +1300,7 @@ fn dump_mono_items_stats<'tcx>( Ok(()) } -pub fn provide(providers: &mut Providers) { +pub(crate) fn provide(providers: &mut Providers) { providers.collect_and_partition_mono_items = collect_and_partition_mono_items; providers.is_codegened_item = |tcx, def_id| { diff --git a/compiler/rustc_monomorphize/src/polymorphize.rs b/compiler/rustc_monomorphize/src/polymorphize.rs index 5a24202db65..c65ad9fa67e 100644 --- a/compiler/rustc_monomorphize/src/polymorphize.rs +++ b/compiler/rustc_monomorphize/src/polymorphize.rs @@ -19,7 +19,7 @@ use tracing::{debug, instrument}; use crate::errors::UnusedGenericParamsHint; /// Provide implementations of queries relating to polymorphization analysis. -pub fn provide(providers: &mut Providers) { +pub(crate) fn provide(providers: &mut Providers) { providers.unused_generic_params = unused_generic_params; } @@ -127,7 +127,7 @@ fn mark_used_by_default_parameters<'tcx>( unused_parameters: &mut UnusedGenericParams, ) { match tcx.def_kind(def_id) { - DefKind::Closure => { + DefKind::Closure | DefKind::SyntheticCoroutineBody => { for param in &generics.own_params { debug!(?param, "(closure/gen)"); unused_parameters.mark_used(param.index); diff --git a/compiler/rustc_next_trait_solver/src/lib.rs b/compiler/rustc_next_trait_solver/src/lib.rs index 0a5b4278058..ea244b5107a 100644 --- a/compiler/rustc_next_trait_solver/src/lib.rs +++ b/compiler/rustc_next_trait_solver/src/lib.rs @@ -4,6 +4,10 @@ //! but were uplifted in the process of making the new trait solver generic. //! So if you got to this crate from the old solver, it's totally normal. +// tidy-alphabetical-start +#![warn(unreachable_pub)] +// tidy-alphabetical-end + pub mod canonicalizer; pub mod coherence; pub mod delegate; diff --git a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs index e328284c001..3f2f34d3255 100644 --- a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs @@ -92,7 +92,7 @@ where #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] #[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] // FIXME: This can be made crate-private once `EvalCtxt` also lives in this crate. -pub struct NestedGoals<I: Interner> { +struct NestedGoals<I: Interner> { /// These normalizes-to goals are treated specially during the evaluation /// loop. In each iteration we take the RHS of the projection, replace it with /// a fresh inference variable, and only after evaluating that goal do we @@ -109,11 +109,11 @@ pub struct NestedGoals<I: Interner> { } impl<I: Interner> NestedGoals<I> { - pub fn new() -> Self { + fn new() -> Self { Self { normalizes_to_goals: Vec::new(), goals: Vec::new() } } - pub fn is_empty(&self) -> bool { + fn is_empty(&self) -> bool { self.normalizes_to_goals.is_empty() && self.goals.is_empty() } } diff --git a/compiler/rustc_next_trait_solver/src/solve/inspect/build.rs b/compiler/rustc_next_trait_solver/src/solve/inspect/build.rs index 86fb036cd3d..742d45de7d3 100644 --- a/compiler/rustc_next_trait_solver/src/solve/inspect/build.rs +++ b/compiler/rustc_next_trait_solver/src/solve/inspect/build.rs @@ -222,13 +222,13 @@ impl<D: SolverDelegate<Interner = I>, I: Interner> ProofTreeBuilder<D> { self.state.as_deref_mut() } - pub fn take_and_enter_probe(&mut self) -> ProofTreeBuilder<D> { + pub(crate) fn take_and_enter_probe(&mut self) -> ProofTreeBuilder<D> { let mut nested = ProofTreeBuilder { state: self.state.take(), _infcx: PhantomData }; nested.enter_probe(); nested } - pub fn finalize(self) -> Option<inspect::GoalEvaluation<I>> { + pub(crate) fn finalize(self) -> Option<inspect::GoalEvaluation<I>> { match *self.state? { DebugSolver::GoalEvaluation(wip_goal_evaluation) => { Some(wip_goal_evaluation.finalize()) @@ -237,22 +237,22 @@ impl<D: SolverDelegate<Interner = I>, I: Interner> ProofTreeBuilder<D> { } } - pub fn new_maybe_root(generate_proof_tree: GenerateProofTree) -> ProofTreeBuilder<D> { + pub(crate) fn new_maybe_root(generate_proof_tree: GenerateProofTree) -> ProofTreeBuilder<D> { match generate_proof_tree { GenerateProofTree::No => ProofTreeBuilder::new_noop(), GenerateProofTree::Yes => ProofTreeBuilder::new_root(), } } - pub fn new_root() -> ProofTreeBuilder<D> { + fn new_root() -> ProofTreeBuilder<D> { ProofTreeBuilder::new(DebugSolver::Root) } - pub fn new_noop() -> ProofTreeBuilder<D> { + fn new_noop() -> ProofTreeBuilder<D> { ProofTreeBuilder { state: None, _infcx: PhantomData } } - pub fn is_noop(&self) -> bool { + pub(crate) fn is_noop(&self) -> bool { self.state.is_none() } @@ -272,7 +272,7 @@ impl<D: SolverDelegate<Interner = I>, I: Interner> ProofTreeBuilder<D> { }) } - pub fn new_canonical_goal_evaluation( + pub(crate) fn new_canonical_goal_evaluation( &mut self, goal: CanonicalInput<I>, ) -> ProofTreeBuilder<D> { @@ -284,7 +284,10 @@ impl<D: SolverDelegate<Interner = I>, I: Interner> ProofTreeBuilder<D> { }) } - pub fn canonical_goal_evaluation(&mut self, canonical_goal_evaluation: ProofTreeBuilder<D>) { + pub(crate) fn canonical_goal_evaluation( + &mut self, + canonical_goal_evaluation: ProofTreeBuilder<D>, + ) { if let Some(this) = self.as_mut() { match (this, *canonical_goal_evaluation.state.unwrap()) { ( @@ -299,7 +302,7 @@ impl<D: SolverDelegate<Interner = I>, I: Interner> ProofTreeBuilder<D> { } } - pub fn canonical_goal_evaluation_overflow(&mut self) { + pub(crate) fn canonical_goal_evaluation_overflow(&mut self) { if let Some(this) = self.as_mut() { match this { DebugSolver::CanonicalGoalEvaluation(canonical_goal_evaluation) => { @@ -310,7 +313,7 @@ impl<D: SolverDelegate<Interner = I>, I: Interner> ProofTreeBuilder<D> { } } - pub fn goal_evaluation(&mut self, goal_evaluation: ProofTreeBuilder<D>) { + pub(crate) fn goal_evaluation(&mut self, goal_evaluation: ProofTreeBuilder<D>) { if let Some(this) = self.as_mut() { match this { DebugSolver::Root => *this = *goal_evaluation.state.unwrap(), @@ -322,7 +325,7 @@ impl<D: SolverDelegate<Interner = I>, I: Interner> ProofTreeBuilder<D> { } } - pub fn new_goal_evaluation_step( + pub(crate) fn new_goal_evaluation_step( &mut self, var_values: ty::CanonicalVarValues<I>, instantiated_goal: QueryInput<I, I::Predicate>, @@ -340,7 +343,7 @@ impl<D: SolverDelegate<Interner = I>, I: Interner> ProofTreeBuilder<D> { }) } - pub fn goal_evaluation_step(&mut self, goal_evaluation_step: ProofTreeBuilder<D>) { + pub(crate) fn goal_evaluation_step(&mut self, goal_evaluation_step: ProofTreeBuilder<D>) { if let Some(this) = self.as_mut() { match (this, *goal_evaluation_step.state.unwrap()) { ( @@ -354,7 +357,7 @@ impl<D: SolverDelegate<Interner = I>, I: Interner> ProofTreeBuilder<D> { } } - pub fn add_var_value<T: Into<I::GenericArg>>(&mut self, arg: T) { + pub(crate) fn add_var_value<T: Into<I::GenericArg>>(&mut self, arg: T) { match self.as_mut() { None => {} Some(DebugSolver::CanonicalGoalEvaluationStep(state)) => { @@ -364,7 +367,7 @@ impl<D: SolverDelegate<Interner = I>, I: Interner> ProofTreeBuilder<D> { } } - pub fn enter_probe(&mut self) { + fn enter_probe(&mut self) { match self.as_mut() { None => {} Some(DebugSolver::CanonicalGoalEvaluationStep(state)) => { @@ -381,7 +384,7 @@ impl<D: SolverDelegate<Interner = I>, I: Interner> ProofTreeBuilder<D> { } } - pub fn probe_kind(&mut self, probe_kind: inspect::ProbeKind<I>) { + pub(crate) fn probe_kind(&mut self, probe_kind: inspect::ProbeKind<I>) { match self.as_mut() { None => {} Some(DebugSolver::CanonicalGoalEvaluationStep(state)) => { @@ -392,7 +395,11 @@ impl<D: SolverDelegate<Interner = I>, I: Interner> ProofTreeBuilder<D> { } } - pub fn probe_final_state(&mut self, delegate: &D, max_input_universe: ty::UniverseIndex) { + pub(crate) fn probe_final_state( + &mut self, + delegate: &D, + max_input_universe: ty::UniverseIndex, + ) { match self.as_mut() { None => {} Some(DebugSolver::CanonicalGoalEvaluationStep(state)) => { @@ -409,7 +416,7 @@ impl<D: SolverDelegate<Interner = I>, I: Interner> ProofTreeBuilder<D> { } } - pub fn add_normalizes_to_goal( + pub(crate) fn add_normalizes_to_goal( &mut self, delegate: &D, max_input_universe: ty::UniverseIndex, @@ -423,7 +430,7 @@ impl<D: SolverDelegate<Interner = I>, I: Interner> ProofTreeBuilder<D> { ); } - pub fn add_goal( + pub(crate) fn add_goal( &mut self, delegate: &D, max_input_universe: ty::UniverseIndex, @@ -469,7 +476,7 @@ impl<D: SolverDelegate<Interner = I>, I: Interner> ProofTreeBuilder<D> { } } - pub fn make_canonical_response(&mut self, shallow_certainty: Certainty) { + pub(crate) fn make_canonical_response(&mut self, shallow_certainty: Certainty) { match self.as_mut() { Some(DebugSolver::CanonicalGoalEvaluationStep(state)) => { state @@ -482,7 +489,7 @@ impl<D: SolverDelegate<Interner = I>, I: Interner> ProofTreeBuilder<D> { } } - pub fn finish_probe(mut self) -> ProofTreeBuilder<D> { + pub(crate) fn finish_probe(mut self) -> ProofTreeBuilder<D> { match self.as_mut() { None => {} Some(DebugSolver::CanonicalGoalEvaluationStep(state)) => { @@ -497,7 +504,7 @@ impl<D: SolverDelegate<Interner = I>, I: Interner> ProofTreeBuilder<D> { self } - pub fn query_result(&mut self, result: QueryResult<I>) { + pub(crate) fn query_result(&mut self, result: QueryResult<I>) { if let Some(this) = self.as_mut() { match this { DebugSolver::CanonicalGoalEvaluation(canonical_goal_evaluation) => { diff --git a/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs b/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs index 5738173c7a8..c7a9846cd97 100644 --- a/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs @@ -862,7 +862,7 @@ where _ecx: &mut EvalCtxt<'_, D>, goal: Goal<I, Self>, ) -> Result<Candidate<I>, NoSolution> { - panic!("`BikeshedIntrinsicFrom` does not have an associated type: {:?}", goal) + panic!("`TransmuteFrom` does not have an associated type: {:?}", goal) } fn consider_builtin_effects_intersection_candidate( diff --git a/compiler/rustc_next_trait_solver/src/solve/normalizes_to/opaque_types.rs b/compiler/rustc_next_trait_solver/src/solve/normalizes_to/opaque_types.rs index 120f96d24bd..6a0703c5313 100644 --- a/compiler/rustc_next_trait_solver/src/solve/normalizes_to/opaque_types.rs +++ b/compiler/rustc_next_trait_solver/src/solve/normalizes_to/opaque_types.rs @@ -97,7 +97,7 @@ where /// Checks whether each generic argument is simply a unique generic placeholder. /// /// FIXME: Interner argument is needed to constrain the `I` parameter. -pub fn uses_unique_placeholders_ignoring_regions<I: Interner>( +fn uses_unique_placeholders_ignoring_regions<I: Interner>( _cx: I, args: I::GenericArgs, ) -> Result<(), NotUniqueParam<I>> { @@ -130,7 +130,7 @@ pub fn uses_unique_placeholders_ignoring_regions<I: Interner>( } // FIXME: This should check for dupes and non-params first, then infer vars. -pub enum NotUniqueParam<I: Interner> { +enum NotUniqueParam<I: Interner> { DuplicateParam(I::GenericArg), NotParam(I::GenericArg), } diff --git a/compiler/rustc_parse/src/errors.rs b/compiler/rustc_parse/src/errors.rs index abaff7d9c19..da1103a4fe5 100644 --- a/compiler/rustc_parse/src/errors.rs +++ b/compiler/rustc_parse/src/errors.rs @@ -260,7 +260,7 @@ pub(crate) struct NotAsNegationOperator { } #[derive(Subdiagnostic)] -pub enum NotAsNegationOperatorSub { +pub(crate) enum NotAsNegationOperatorSub { #[suggestion( parse_unexpected_token_after_not_default, style = "verbose", @@ -424,7 +424,7 @@ pub(crate) enum IfExpressionMissingThenBlockSub { #[derive(Diagnostic)] #[diag(parse_ternary_operator)] #[help] -pub struct TernaryOperator { +pub(crate) struct TernaryOperator { #[primary_span] pub span: Span, } @@ -1088,7 +1088,7 @@ pub(crate) enum ExpectedIdentifierFound { } impl ExpectedIdentifierFound { - pub fn new(token_descr: Option<TokenDescription>, span: Span) -> Self { + pub(crate) fn new(token_descr: Option<TokenDescription>, span: Span) -> Self { (match token_descr { Some(TokenDescription::ReservedIdentifier) => { ExpectedIdentifierFound::ReservedIdentifier @@ -1659,7 +1659,7 @@ pub(crate) struct SelfArgumentPointer { #[derive(Diagnostic)] #[diag(parse_unexpected_token_after_dot)] -pub struct UnexpectedTokenAfterDot<'a> { +pub(crate) struct UnexpectedTokenAfterDot<'a> { #[primary_span] pub span: Span, pub actual: Cow<'a, str>, @@ -1928,7 +1928,7 @@ pub(crate) enum UnexpectedTokenAfterStructName { } impl UnexpectedTokenAfterStructName { - pub fn new(span: Span, token: Token) -> Self { + pub(crate) fn new(span: Span, token: Token) -> Self { match TokenDescription::from_token(&token) { Some(TokenDescription::ReservedIdentifier) => Self::ReservedIdentifier { span, token }, Some(TokenDescription::Keyword) => Self::Keyword { span, token }, @@ -2006,7 +2006,7 @@ pub(crate) enum TopLevelOrPatternNotAllowed { #[derive(Diagnostic)] #[diag(parse_cannot_be_raw_ident)] -pub struct CannotBeRawIdent { +pub(crate) struct CannotBeRawIdent { #[primary_span] pub span: Span, pub ident: Symbol, @@ -2014,14 +2014,14 @@ pub struct CannotBeRawIdent { #[derive(Diagnostic)] #[diag(parse_keyword_lifetime)] -pub struct KeywordLifetime { +pub(crate) struct KeywordLifetime { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(parse_invalid_label)] -pub struct InvalidLabel { +pub(crate) struct InvalidLabel { #[primary_span] pub span: Span, pub name: Symbol, @@ -2029,7 +2029,7 @@ pub struct InvalidLabel { #[derive(Diagnostic)] #[diag(parse_cr_doc_comment)] -pub struct CrDocComment { +pub(crate) struct CrDocComment { #[primary_span] pub span: Span, pub block: bool, @@ -2037,14 +2037,14 @@ pub struct CrDocComment { #[derive(Diagnostic)] #[diag(parse_no_digits_literal, code = E0768)] -pub struct NoDigitsLiteral { +pub(crate) struct NoDigitsLiteral { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(parse_invalid_digit_literal)] -pub struct InvalidDigitLiteral { +pub(crate) struct InvalidDigitLiteral { #[primary_span] pub span: Span, pub base: u32, @@ -2052,14 +2052,14 @@ pub struct InvalidDigitLiteral { #[derive(Diagnostic)] #[diag(parse_empty_exponent_float)] -pub struct EmptyExponentFloat { +pub(crate) struct EmptyExponentFloat { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(parse_float_literal_unsupported_base)] -pub struct FloatLiteralUnsupportedBase { +pub(crate) struct FloatLiteralUnsupportedBase { #[primary_span] pub span: Span, pub base: &'static str, @@ -2068,7 +2068,7 @@ pub struct FloatLiteralUnsupportedBase { #[derive(Diagnostic)] #[diag(parse_unknown_prefix)] #[note] -pub struct UnknownPrefix<'a> { +pub(crate) struct UnknownPrefix<'a> { #[primary_span] #[label] pub span: Span, @@ -2079,12 +2079,12 @@ pub struct UnknownPrefix<'a> { #[derive(Subdiagnostic)] #[note(parse_macro_expands_to_adt_field)] -pub struct MacroExpandsToAdtField<'a> { +pub(crate) struct MacroExpandsToAdtField<'a> { pub adt_ty: &'a str, } #[derive(Subdiagnostic)] -pub enum UnknownPrefixSugg { +pub(crate) enum UnknownPrefixSugg { #[suggestion( parse_suggestion_br, code = "br", @@ -2114,7 +2114,7 @@ pub enum UnknownPrefixSugg { #[derive(Diagnostic)] #[diag(parse_too_many_hashes)] -pub struct TooManyHashes { +pub(crate) struct TooManyHashes { #[primary_span] pub span: Span, pub num: u32, @@ -2122,7 +2122,7 @@ pub struct TooManyHashes { #[derive(Diagnostic)] #[diag(parse_unknown_start_of_token)] -pub struct UnknownTokenStart { +pub(crate) struct UnknownTokenStart { #[primary_span] pub span: Span, pub escaped: String, @@ -2135,7 +2135,7 @@ pub struct UnknownTokenStart { } #[derive(Subdiagnostic)] -pub enum TokenSubstitution { +pub(crate) enum TokenSubstitution { #[suggestion( parse_sugg_quotes, code = "{suggestion}", @@ -2168,16 +2168,16 @@ pub enum TokenSubstitution { #[derive(Subdiagnostic)] #[note(parse_note_repeats)] -pub struct UnknownTokenRepeat { +pub(crate) struct UnknownTokenRepeat { pub repeats: usize, } #[derive(Subdiagnostic)] #[help(parse_help_null)] -pub struct UnknownTokenNull; +pub(crate) struct UnknownTokenNull; #[derive(Diagnostic)] -pub enum UnescapeError { +pub(crate) enum UnescapeError { #[diag(parse_invalid_unicode_escape)] #[help] InvalidUnicodeEscape { @@ -2322,7 +2322,7 @@ pub enum UnescapeError { } #[derive(Subdiagnostic)] -pub enum MoreThanOneCharSugg { +pub(crate) enum MoreThanOneCharSugg { #[suggestion( parse_consider_normalized, code = "{normalized}", @@ -2370,7 +2370,7 @@ pub enum MoreThanOneCharSugg { } #[derive(Subdiagnostic)] -pub enum MoreThanOneCharNote { +pub(crate) enum MoreThanOneCharNote { #[note(parse_followed_by)] AllCombining { #[primary_span] @@ -2388,7 +2388,7 @@ pub enum MoreThanOneCharNote { } #[derive(Subdiagnostic)] -pub enum NoBraceUnicodeSub { +pub(crate) enum NoBraceUnicodeSub { #[suggestion( parse_use_braces, code = "{suggestion}", @@ -2703,7 +2703,7 @@ pub(crate) struct InvalidDynKeyword { } #[derive(Subdiagnostic)] -pub enum HelpUseLatestEdition { +pub(crate) enum HelpUseLatestEdition { #[help(parse_help_set_edition_cargo)] #[note(parse_note_edition_guide)] Cargo { edition: Edition }, @@ -2713,7 +2713,7 @@ pub enum HelpUseLatestEdition { } impl HelpUseLatestEdition { - pub fn new() -> Self { + pub(crate) fn new() -> Self { let edition = LATEST_STABLE_EDITION; if rustc_session::utils::was_invoked_from_cargo() { Self::Cargo { edition } @@ -2725,7 +2725,7 @@ impl HelpUseLatestEdition { #[derive(Diagnostic)] #[diag(parse_box_syntax_removed)] -pub struct BoxSyntaxRemoved { +pub(crate) struct BoxSyntaxRemoved { #[primary_span] pub span: Span, #[subdiagnostic] @@ -2738,7 +2738,7 @@ pub struct BoxSyntaxRemoved { applicability = "machine-applicable", style = "verbose" )] -pub struct AddBoxNew { +pub(crate) struct AddBoxNew { #[suggestion_part(code = "Box::new(")] pub box_kw_and_lo: Span, #[suggestion_part(code = ")")] @@ -3190,7 +3190,7 @@ pub(crate) struct DotDotRangeAttribute { #[derive(Diagnostic)] #[diag(parse_invalid_attr_unsafe)] #[note] -pub struct InvalidAttrUnsafe { +pub(crate) struct InvalidAttrUnsafe { #[primary_span] #[label] pub span: Span, @@ -3199,7 +3199,7 @@ pub struct InvalidAttrUnsafe { #[derive(Diagnostic)] #[diag(parse_unsafe_attr_outside_unsafe)] -pub struct UnsafeAttrOutsideUnsafe { +pub(crate) struct UnsafeAttrOutsideUnsafe { #[primary_span] #[label] pub span: Span, @@ -3212,7 +3212,7 @@ pub struct UnsafeAttrOutsideUnsafe { parse_unsafe_attr_outside_unsafe_suggestion, applicability = "machine-applicable" )] -pub struct UnsafeAttrOutsideUnsafeSuggestion { +pub(crate) struct UnsafeAttrOutsideUnsafeSuggestion { #[suggestion_part(code = "unsafe(")] pub left: Span, #[suggestion_part(code = ")")] @@ -3221,7 +3221,7 @@ pub struct UnsafeAttrOutsideUnsafeSuggestion { #[derive(Diagnostic)] #[diag(parse_binder_before_modifiers)] -pub struct BinderBeforeModifiers { +pub(crate) struct BinderBeforeModifiers { #[primary_span] pub binder_span: Span, #[label] @@ -3230,7 +3230,7 @@ pub struct BinderBeforeModifiers { #[derive(Diagnostic)] #[diag(parse_binder_and_polarity)] -pub struct BinderAndPolarity { +pub(crate) struct BinderAndPolarity { #[primary_span] pub polarity_span: Span, #[label] @@ -3240,7 +3240,7 @@ pub struct BinderAndPolarity { #[derive(Diagnostic)] #[diag(parse_modifiers_and_polarity)] -pub struct PolarityAndModifiers { +pub(crate) struct PolarityAndModifiers { #[primary_span] pub polarity_span: Span, #[label] diff --git a/compiler/rustc_parse/src/lib.rs b/compiler/rustc_parse/src/lib.rs index 37079271493..788bb732ef7 100644 --- a/compiler/rustc_parse/src/lib.rs +++ b/compiler/rustc_parse/src/lib.rs @@ -11,6 +11,7 @@ #![feature(if_let_guard)] #![feature(iter_intersperse)] #![feature(let_chains)] +#![warn(unreachable_pub)] // tidy-alphabetical-end use std::path::Path; diff --git a/compiler/rustc_parse/src/parser/item.rs b/compiler/rustc_parse/src/parser/item.rs index 14da6c331f1..c6a5e1908f7 100644 --- a/compiler/rustc_parse/src/parser/item.rs +++ b/compiler/rustc_parse/src/parser/item.rs @@ -51,7 +51,9 @@ impl<'a> Parser<'a> { } /// Parses the contents of a module (inner attributes followed by module items). - /// We exit once we hit `term` + /// We exit once we hit `term` which can be either + /// - EOF (for files) + /// - `}` for mod items pub fn parse_mod( &mut self, term: &TokenKind, diff --git a/compiler/rustc_parse_format/src/lib.rs b/compiler/rustc_parse_format/src/lib.rs index cb758150789..51084ef4441 100644 --- a/compiler/rustc_parse_format/src/lib.rs +++ b/compiler/rustc_parse_format/src/lib.rs @@ -13,6 +13,7 @@ html_playground_url = "https://play.rust-lang.org/", test(attr(deny(warnings))) )] +#![warn(unreachable_pub)] // tidy-alphabetical-end use std::{iter, str, string}; diff --git a/compiler/rustc_passes/messages.ftl b/compiler/rustc_passes/messages.ftl index e7f208d5ad5..38450fc288a 100644 --- a/compiler/rustc_passes/messages.ftl +++ b/compiler/rustc_passes/messages.ftl @@ -672,6 +672,10 @@ passes_should_be_applied_to_fn = *[false] not a function definition } +passes_should_be_applied_to_fn_or_unit_struct = + attribute should be applied to a function definition or unit struct + .label = not a function definition or a unit struct + passes_should_be_applied_to_static = attribute should be applied to a static .label = not a static diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index d1dac9ca6da..5dbb3854c8f 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -517,6 +517,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { sym::no_mangle, sym::naked, sym::instruction_set, + sym::repr, // code generation sym::cold, sym::target_feature, @@ -746,12 +747,35 @@ impl<'tcx> CheckAttrVisitor<'tcx> { Target::Field | Target::Arm | Target::MacroDef => { self.inline_attr_str_error_with_macro_def(hir_id, attr, "target_feature"); } + Target::Struct if self.tcx.features().struct_target_features => { + let ty = self.tcx.hir_node(hir_id).expect_item(); + match ty.kind { + ItemKind::Struct(data, _) => { + if data.fields().len() != 0 { + self.dcx().emit_err(errors::AttrShouldBeAppliedToFnOrUnitStruct { + attr_span: attr.span, + defn_span: span, + }); + } + } + _ => { + panic!("Target::Struct for a non-struct"); + } + } + } _ => { - self.dcx().emit_err(errors::AttrShouldBeAppliedToFn { - attr_span: attr.span, - defn_span: span, - on_crate: hir_id == CRATE_HIR_ID, - }); + if self.tcx.features().struct_target_features { + self.dcx().emit_err(errors::AttrShouldBeAppliedToFnOrUnitStruct { + attr_span: attr.span, + defn_span: span, + }); + } else { + self.dcx().emit_err(errors::AttrShouldBeAppliedToFn { + attr_span: attr.span, + defn_span: span, + on_crate: hir_id == CRATE_HIR_ID, + }); + } } } } diff --git a/compiler/rustc_passes/src/debugger_visualizer.rs b/compiler/rustc_passes/src/debugger_visualizer.rs index 5d871bacb1d..fec149c8c43 100644 --- a/compiler/rustc_passes/src/debugger_visualizer.rs +++ b/compiler/rustc_passes/src/debugger_visualizer.rs @@ -95,6 +95,6 @@ fn debugger_visualizers(tcx: TyCtxt<'_>, _: LocalCrate) -> Vec<DebuggerVisualize visitor.visualizers } -pub fn provide(providers: &mut Providers) { +pub(crate) fn provide(providers: &mut Providers) { providers.debugger_visualizers = debugger_visualizers; } diff --git a/compiler/rustc_passes/src/diagnostic_items.rs b/compiler/rustc_passes/src/diagnostic_items.rs index 624ebb2f9f2..425e203f2b0 100644 --- a/compiler/rustc_passes/src/diagnostic_items.rs +++ b/compiler/rustc_passes/src/diagnostic_items.rs @@ -90,7 +90,7 @@ fn all_diagnostic_items(tcx: TyCtxt<'_>, (): ()) -> DiagnosticItems { items } -pub fn provide(providers: &mut Providers) { +pub(crate) fn provide(providers: &mut Providers) { providers.diagnostic_items = diagnostic_items; providers.all_diagnostic_items = all_diagnostic_items; } diff --git a/compiler/rustc_passes/src/errors.rs b/compiler/rustc_passes/src/errors.rs index 1202351bdcd..1e9ab7af9be 100644 --- a/compiler/rustc_passes/src/errors.rs +++ b/compiler/rustc_passes/src/errors.rs @@ -18,41 +18,41 @@ use crate::lang_items::Duplicate; #[derive(LintDiagnostic)] #[diag(passes_incorrect_do_not_recommend_location)] -pub struct IncorrectDoNotRecommendLocation; +pub(crate) struct IncorrectDoNotRecommendLocation; #[derive(LintDiagnostic)] #[diag(passes_outer_crate_level_attr)] -pub struct OuterCrateLevelAttr; +pub(crate) struct OuterCrateLevelAttr; #[derive(LintDiagnostic)] #[diag(passes_inner_crate_level_attr)] -pub struct InnerCrateLevelAttr; +pub(crate) struct InnerCrateLevelAttr; #[derive(LintDiagnostic)] #[diag(passes_ignored_attr_with_macro)] -pub struct IgnoredAttrWithMacro<'a> { +pub(crate) struct IgnoredAttrWithMacro<'a> { pub sym: &'a str, } #[derive(LintDiagnostic)] #[diag(passes_ignored_attr)] -pub struct IgnoredAttr<'a> { +pub(crate) struct IgnoredAttr<'a> { pub sym: &'a str, } #[derive(LintDiagnostic)] #[diag(passes_inline_ignored_function_prototype)] -pub struct IgnoredInlineAttrFnProto; +pub(crate) struct IgnoredInlineAttrFnProto; #[derive(LintDiagnostic)] #[diag(passes_inline_ignored_constants)] #[warning] #[note] -pub struct IgnoredInlineAttrConstants; +pub(crate) struct IgnoredInlineAttrConstants; #[derive(Diagnostic)] #[diag(passes_inline_not_fn_or_closure, code = E0518)] -pub struct InlineNotFnOrClosure { +pub(crate) struct InlineNotFnOrClosure { #[primary_span] pub attr_span: Span, #[label] @@ -61,7 +61,7 @@ pub struct InlineNotFnOrClosure { #[derive(Diagnostic)] #[diag(passes_coverage_not_fn_or_closure, code = E0788)] -pub struct CoverageNotFnOrClosure { +pub(crate) struct CoverageNotFnOrClosure { #[primary_span] pub attr_span: Span, #[label] @@ -70,11 +70,11 @@ pub struct CoverageNotFnOrClosure { #[derive(LintDiagnostic)] #[diag(passes_optimize_not_fn_or_closure)] -pub struct OptimizeNotFnOrClosure; +pub(crate) struct OptimizeNotFnOrClosure; #[derive(Diagnostic)] #[diag(passes_should_be_applied_to_fn)] -pub struct AttrShouldBeAppliedToFn { +pub(crate) struct AttrShouldBeAppliedToFn { #[primary_span] pub attr_span: Span, #[label] @@ -83,8 +83,17 @@ pub struct AttrShouldBeAppliedToFn { } #[derive(Diagnostic)] +#[diag(passes_should_be_applied_to_fn_or_unit_struct)] +pub(crate) struct AttrShouldBeAppliedToFnOrUnitStruct { + #[primary_span] + pub attr_span: Span, + #[label] + pub defn_span: Span, +} + +#[derive(Diagnostic)] #[diag(passes_should_be_applied_to_fn, code = E0739)] -pub struct TrackedCallerWrongLocation { +pub(crate) struct TrackedCallerWrongLocation { #[primary_span] pub attr_span: Span, #[label] @@ -94,7 +103,7 @@ pub struct TrackedCallerWrongLocation { #[derive(Diagnostic)] #[diag(passes_should_be_applied_to_struct_enum, code = E0701)] -pub struct NonExhaustiveWrongLocation { +pub(crate) struct NonExhaustiveWrongLocation { #[primary_span] pub attr_span: Span, #[label] @@ -103,7 +112,7 @@ pub struct NonExhaustiveWrongLocation { #[derive(Diagnostic)] #[diag(passes_should_be_applied_to_trait)] -pub struct AttrShouldBeAppliedToTrait { +pub(crate) struct AttrShouldBeAppliedToTrait { #[primary_span] pub attr_span: Span, #[label] @@ -112,11 +121,11 @@ pub struct AttrShouldBeAppliedToTrait { #[derive(LintDiagnostic)] #[diag(passes_target_feature_on_statement)] -pub struct TargetFeatureOnStatement; +pub(crate) struct TargetFeatureOnStatement; #[derive(Diagnostic)] #[diag(passes_should_be_applied_to_static)] -pub struct AttrShouldBeAppliedToStatic { +pub(crate) struct AttrShouldBeAppliedToStatic { #[primary_span] pub attr_span: Span, #[label] @@ -125,7 +134,7 @@ pub struct AttrShouldBeAppliedToStatic { #[derive(Diagnostic)] #[diag(passes_doc_expect_str)] -pub struct DocExpectStr<'a> { +pub(crate) struct DocExpectStr<'a> { #[primary_span] pub attr_span: Span, pub attr_name: &'a str, @@ -133,7 +142,7 @@ pub struct DocExpectStr<'a> { #[derive(Diagnostic)] #[diag(passes_doc_alias_empty)] -pub struct DocAliasEmpty<'a> { +pub(crate) struct DocAliasEmpty<'a> { #[primary_span] pub span: Span, pub attr_str: &'a str, @@ -141,7 +150,7 @@ pub struct DocAliasEmpty<'a> { #[derive(Diagnostic)] #[diag(passes_doc_alias_bad_char)] -pub struct DocAliasBadChar<'a> { +pub(crate) struct DocAliasBadChar<'a> { #[primary_span] pub span: Span, pub attr_str: &'a str, @@ -150,7 +159,7 @@ pub struct DocAliasBadChar<'a> { #[derive(Diagnostic)] #[diag(passes_doc_alias_start_end)] -pub struct DocAliasStartEnd<'a> { +pub(crate) struct DocAliasStartEnd<'a> { #[primary_span] pub span: Span, pub attr_str: &'a str, @@ -158,7 +167,7 @@ pub struct DocAliasStartEnd<'a> { #[derive(Diagnostic)] #[diag(passes_doc_alias_bad_location)] -pub struct DocAliasBadLocation<'a> { +pub(crate) struct DocAliasBadLocation<'a> { #[primary_span] pub span: Span, pub attr_str: &'a str, @@ -167,7 +176,7 @@ pub struct DocAliasBadLocation<'a> { #[derive(Diagnostic)] #[diag(passes_doc_alias_not_an_alias)] -pub struct DocAliasNotAnAlias<'a> { +pub(crate) struct DocAliasNotAnAlias<'a> { #[primary_span] pub span: Span, pub attr_str: &'a str, @@ -175,42 +184,42 @@ pub struct DocAliasNotAnAlias<'a> { #[derive(LintDiagnostic)] #[diag(passes_doc_alias_duplicated)] -pub struct DocAliasDuplicated { +pub(crate) struct DocAliasDuplicated { #[label] pub first_defn: Span, } #[derive(Diagnostic)] #[diag(passes_doc_alias_not_string_literal)] -pub struct DocAliasNotStringLiteral { +pub(crate) struct DocAliasNotStringLiteral { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(passes_doc_alias_malformed)] -pub struct DocAliasMalformed { +pub(crate) struct DocAliasMalformed { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(passes_doc_keyword_empty_mod)] -pub struct DocKeywordEmptyMod { +pub(crate) struct DocKeywordEmptyMod { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(passes_doc_keyword_not_mod)] -pub struct DocKeywordNotMod { +pub(crate) struct DocKeywordNotMod { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(passes_doc_keyword_invalid_ident)] -pub struct DocKeywordInvalidIdent { +pub(crate) struct DocKeywordInvalidIdent { #[primary_span] pub span: Span, pub doc_keyword: Symbol, @@ -218,14 +227,14 @@ pub struct DocKeywordInvalidIdent { #[derive(Diagnostic)] #[diag(passes_doc_fake_variadic_not_valid)] -pub struct DocFakeVariadicNotValid { +pub(crate) struct DocFakeVariadicNotValid { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(passes_doc_keyword_only_impl)] -pub struct DocKeywordOnlyImpl { +pub(crate) struct DocKeywordOnlyImpl { #[primary_span] pub span: Span, } @@ -233,7 +242,7 @@ pub struct DocKeywordOnlyImpl { #[derive(Diagnostic)] #[diag(passes_doc_inline_conflict)] #[help] -pub struct DocKeywordConflict { +pub(crate) struct DocKeywordConflict { #[primary_span] pub spans: MultiSpan, } @@ -241,7 +250,7 @@ pub struct DocKeywordConflict { #[derive(LintDiagnostic)] #[diag(passes_doc_inline_only_use)] #[note] -pub struct DocInlineOnlyUse { +pub(crate) struct DocInlineOnlyUse { #[label] pub attr_span: Span, #[label(passes_not_a_use_item_label)] @@ -251,7 +260,7 @@ pub struct DocInlineOnlyUse { #[derive(LintDiagnostic)] #[diag(passes_doc_masked_only_extern_crate)] #[note] -pub struct DocMaskedOnlyExternCrate { +pub(crate) struct DocMaskedOnlyExternCrate { #[label] pub attr_span: Span, #[label(passes_not_an_extern_crate_label)] @@ -260,7 +269,7 @@ pub struct DocMaskedOnlyExternCrate { #[derive(LintDiagnostic)] #[diag(passes_doc_masked_not_extern_crate_self)] -pub struct DocMaskedNotExternCrateSelf { +pub(crate) struct DocMaskedNotExternCrateSelf { #[label] pub attr_span: Span, #[label(passes_extern_crate_self_label)] @@ -269,7 +278,7 @@ pub struct DocMaskedNotExternCrateSelf { #[derive(Diagnostic)] #[diag(passes_doc_attr_not_crate_level)] -pub struct DocAttrNotCrateLevel<'a> { +pub(crate) struct DocAttrNotCrateLevel<'a> { #[primary_span] pub span: Span, pub attr_name: &'a str, @@ -277,25 +286,25 @@ pub struct DocAttrNotCrateLevel<'a> { #[derive(LintDiagnostic)] #[diag(passes_doc_test_unknown)] -pub struct DocTestUnknown { +pub(crate) struct DocTestUnknown { pub path: String, } #[derive(LintDiagnostic)] #[diag(passes_doc_test_literal)] -pub struct DocTestLiteral; +pub(crate) struct DocTestLiteral; #[derive(LintDiagnostic)] #[diag(passes_doc_test_takes_list)] -pub struct DocTestTakesList; +pub(crate) struct DocTestTakesList; #[derive(LintDiagnostic)] #[diag(passes_doc_cfg_hide_takes_list)] -pub struct DocCfgHideTakesList; +pub(crate) struct DocCfgHideTakesList; #[derive(LintDiagnostic)] #[diag(passes_doc_test_unknown_any)] -pub struct DocTestUnknownAny { +pub(crate) struct DocTestUnknownAny { pub path: String, } @@ -303,7 +312,7 @@ pub struct DocTestUnknownAny { #[diag(passes_doc_test_unknown_spotlight)] #[note] #[note(passes_no_op_note)] -pub struct DocTestUnknownSpotlight { +pub(crate) struct DocTestUnknownSpotlight { pub path: String, #[suggestion(style = "short", applicability = "machine-applicable", code = "notable_trait")] pub span: Span, @@ -311,7 +320,7 @@ pub struct DocTestUnknownSpotlight { #[derive(LintDiagnostic)] #[diag(passes_doc_test_unknown_include)] -pub struct DocTestUnknownInclude { +pub(crate) struct DocTestUnknownInclude { pub path: String, pub value: String, pub inner: &'static str, @@ -321,11 +330,11 @@ pub struct DocTestUnknownInclude { #[derive(LintDiagnostic)] #[diag(passes_doc_invalid)] -pub struct DocInvalid; +pub(crate) struct DocInvalid; #[derive(Diagnostic)] #[diag(passes_pass_by_value)] -pub struct PassByValue { +pub(crate) struct PassByValue { #[primary_span] pub attr_span: Span, #[label] @@ -334,7 +343,7 @@ pub struct PassByValue { #[derive(Diagnostic)] #[diag(passes_allow_incoherent_impl)] -pub struct AllowIncoherentImpl { +pub(crate) struct AllowIncoherentImpl { #[primary_span] pub attr_span: Span, #[label] @@ -343,7 +352,7 @@ pub struct AllowIncoherentImpl { #[derive(Diagnostic)] #[diag(passes_has_incoherent_inherent_impl)] -pub struct HasIncoherentInherentImpl { +pub(crate) struct HasIncoherentInherentImpl { #[primary_span] pub attr_span: Span, #[label] @@ -352,35 +361,35 @@ pub struct HasIncoherentInherentImpl { #[derive(Diagnostic)] #[diag(passes_both_ffi_const_and_pure, code = E0757)] -pub struct BothFfiConstAndPure { +pub(crate) struct BothFfiConstAndPure { #[primary_span] pub attr_span: Span, } #[derive(Diagnostic)] #[diag(passes_ffi_pure_invalid_target, code = E0755)] -pub struct FfiPureInvalidTarget { +pub(crate) struct FfiPureInvalidTarget { #[primary_span] pub attr_span: Span, } #[derive(Diagnostic)] #[diag(passes_ffi_const_invalid_target, code = E0756)] -pub struct FfiConstInvalidTarget { +pub(crate) struct FfiConstInvalidTarget { #[primary_span] pub attr_span: Span, } #[derive(LintDiagnostic)] #[diag(passes_must_use_no_effect)] -pub struct MustUseNoEffect { +pub(crate) struct MustUseNoEffect { pub article: &'static str, pub target: rustc_hir::Target, } #[derive(Diagnostic)] #[diag(passes_must_not_suspend)] -pub struct MustNotSuspend { +pub(crate) struct MustNotSuspend { #[primary_span] pub attr_span: Span, #[label] @@ -390,7 +399,7 @@ pub struct MustNotSuspend { #[derive(LintDiagnostic)] #[diag(passes_cold)] #[warning] -pub struct Cold { +pub(crate) struct Cold { #[label] pub span: Span, pub on_crate: bool, @@ -399,7 +408,7 @@ pub struct Cold { #[derive(LintDiagnostic)] #[diag(passes_link)] #[warning] -pub struct Link { +pub(crate) struct Link { #[label] pub span: Option<Span>, } @@ -407,7 +416,7 @@ pub struct Link { #[derive(LintDiagnostic)] #[diag(passes_link_name)] #[warning] -pub struct LinkName<'a> { +pub(crate) struct LinkName<'a> { #[help] pub attr_span: Option<Span>, #[label] @@ -417,7 +426,7 @@ pub struct LinkName<'a> { #[derive(Diagnostic)] #[diag(passes_no_link)] -pub struct NoLink { +pub(crate) struct NoLink { #[primary_span] pub attr_span: Span, #[label] @@ -426,7 +435,7 @@ pub struct NoLink { #[derive(Diagnostic)] #[diag(passes_export_name)] -pub struct ExportName { +pub(crate) struct ExportName { #[primary_span] pub attr_span: Span, #[label] @@ -435,7 +444,7 @@ pub struct ExportName { #[derive(Diagnostic)] #[diag(passes_rustc_layout_scalar_valid_range_not_struct)] -pub struct RustcLayoutScalarValidRangeNotStruct { +pub(crate) struct RustcLayoutScalarValidRangeNotStruct { #[primary_span] pub attr_span: Span, #[label] @@ -444,14 +453,14 @@ pub struct RustcLayoutScalarValidRangeNotStruct { #[derive(Diagnostic)] #[diag(passes_rustc_layout_scalar_valid_range_arg)] -pub struct RustcLayoutScalarValidRangeArg { +pub(crate) struct RustcLayoutScalarValidRangeArg { #[primary_span] pub attr_span: Span, } #[derive(Diagnostic)] #[diag(passes_rustc_legacy_const_generics_only)] -pub struct RustcLegacyConstGenericsOnly { +pub(crate) struct RustcLegacyConstGenericsOnly { #[primary_span] pub attr_span: Span, #[label] @@ -460,7 +469,7 @@ pub struct RustcLegacyConstGenericsOnly { #[derive(Diagnostic)] #[diag(passes_rustc_legacy_const_generics_index)] -pub struct RustcLegacyConstGenericsIndex { +pub(crate) struct RustcLegacyConstGenericsIndex { #[primary_span] pub attr_span: Span, #[label] @@ -469,7 +478,7 @@ pub struct RustcLegacyConstGenericsIndex { #[derive(Diagnostic)] #[diag(passes_rustc_legacy_const_generics_index_exceed)] -pub struct RustcLegacyConstGenericsIndexExceed { +pub(crate) struct RustcLegacyConstGenericsIndexExceed { #[primary_span] #[label] pub span: Span, @@ -478,14 +487,14 @@ pub struct RustcLegacyConstGenericsIndexExceed { #[derive(Diagnostic)] #[diag(passes_rustc_legacy_const_generics_index_negative)] -pub struct RustcLegacyConstGenericsIndexNegative { +pub(crate) struct RustcLegacyConstGenericsIndexNegative { #[primary_span] pub invalid_args: Vec<Span>, } #[derive(Diagnostic)] #[diag(passes_rustc_dirty_clean)] -pub struct RustcDirtyClean { +pub(crate) struct RustcDirtyClean { #[primary_span] pub span: Span, } @@ -493,7 +502,7 @@ pub struct RustcDirtyClean { #[derive(LintDiagnostic)] #[diag(passes_link_section)] #[warning] -pub struct LinkSection { +pub(crate) struct LinkSection { #[label] pub span: Span, } @@ -502,7 +511,7 @@ pub struct LinkSection { #[diag(passes_no_mangle_foreign)] #[warning] #[note] -pub struct NoMangleForeign { +pub(crate) struct NoMangleForeign { #[label] pub span: Span, #[suggestion(code = "", applicability = "machine-applicable")] @@ -513,32 +522,32 @@ pub struct NoMangleForeign { #[derive(LintDiagnostic)] #[diag(passes_no_mangle)] #[warning] -pub struct NoMangle { +pub(crate) struct NoMangle { #[label] pub span: Span, } #[derive(Diagnostic)] #[diag(passes_repr_ident, code = E0565)] -pub struct ReprIdent { +pub(crate) struct ReprIdent { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(passes_repr_conflicting, code = E0566)] -pub struct ReprConflicting { +pub(crate) struct ReprConflicting { #[primary_span] pub hint_spans: Vec<Span>, } #[derive(LintDiagnostic)] #[diag(passes_repr_conflicting, code = E0566)] -pub struct ReprConflictingLint; +pub(crate) struct ReprConflictingLint; #[derive(Diagnostic)] #[diag(passes_used_static)] -pub struct UsedStatic { +pub(crate) struct UsedStatic { #[primary_span] pub attr_span: Span, #[label] @@ -548,14 +557,14 @@ pub struct UsedStatic { #[derive(Diagnostic)] #[diag(passes_used_compiler_linker)] -pub struct UsedCompilerLinker { +pub(crate) struct UsedCompilerLinker { #[primary_span] pub spans: Vec<Span>, } #[derive(Diagnostic)] #[diag(passes_allow_internal_unstable)] -pub struct AllowInternalUnstable { +pub(crate) struct AllowInternalUnstable { #[primary_span] pub attr_span: Span, #[label] @@ -564,7 +573,7 @@ pub struct AllowInternalUnstable { #[derive(Diagnostic)] #[diag(passes_debug_visualizer_placement)] -pub struct DebugVisualizerPlacement { +pub(crate) struct DebugVisualizerPlacement { #[primary_span] pub span: Span, } @@ -574,14 +583,14 @@ pub struct DebugVisualizerPlacement { #[note(passes_note_1)] #[note(passes_note_2)] #[note(passes_note_3)] -pub struct DebugVisualizerInvalid { +pub(crate) struct DebugVisualizerInvalid { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(passes_debug_visualizer_unreadable)] -pub struct DebugVisualizerUnreadable<'a> { +pub(crate) struct DebugVisualizerUnreadable<'a> { #[primary_span] pub span: Span, pub file: &'a Path, @@ -590,7 +599,7 @@ pub struct DebugVisualizerUnreadable<'a> { #[derive(Diagnostic)] #[diag(passes_rustc_allow_const_fn_unstable)] -pub struct RustcAllowConstFnUnstable { +pub(crate) struct RustcAllowConstFnUnstable { #[primary_span] pub attr_span: Span, #[label] @@ -599,7 +608,7 @@ pub struct RustcAllowConstFnUnstable { #[derive(Diagnostic)] #[diag(passes_rustc_safe_intrinsic)] -pub struct RustcSafeIntrinsic { +pub(crate) struct RustcSafeIntrinsic { #[primary_span] pub attr_span: Span, #[label] @@ -608,7 +617,7 @@ pub struct RustcSafeIntrinsic { #[derive(Diagnostic)] #[diag(passes_rustc_std_internal_symbol)] -pub struct RustcStdInternalSymbol { +pub(crate) struct RustcStdInternalSymbol { #[primary_span] pub attr_span: Span, #[label] @@ -617,7 +626,7 @@ pub struct RustcStdInternalSymbol { #[derive(Diagnostic)] #[diag(passes_rustc_pub_transparent)] -pub struct RustcPubTransparent { +pub(crate) struct RustcPubTransparent { #[primary_span] pub attr_span: Span, #[label] @@ -626,28 +635,28 @@ pub struct RustcPubTransparent { #[derive(Diagnostic)] #[diag(passes_link_ordinal)] -pub struct LinkOrdinal { +pub(crate) struct LinkOrdinal { #[primary_span] pub attr_span: Span, } #[derive(Diagnostic)] #[diag(passes_confusables)] -pub struct Confusables { +pub(crate) struct Confusables { #[primary_span] pub attr_span: Span, } #[derive(Diagnostic)] #[diag(passes_coroutine_on_non_closure)] -pub struct CoroutineOnNonClosure { +pub(crate) struct CoroutineOnNonClosure { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(passes_linkage)] -pub struct Linkage { +pub(crate) struct Linkage { #[primary_span] pub attr_span: Span, #[label] @@ -681,23 +690,23 @@ pub(crate) struct IncorrectMetaItemSuggestion { #[derive(Diagnostic)] #[diag(passes_stability_promotable)] -pub struct StabilityPromotable { +pub(crate) struct StabilityPromotable { #[primary_span] pub attr_span: Span, } #[derive(LintDiagnostic)] #[diag(passes_deprecated)] -pub struct Deprecated; +pub(crate) struct Deprecated; #[derive(LintDiagnostic)] #[diag(passes_macro_use)] -pub struct MacroUse { +pub(crate) struct MacroUse { pub name: Symbol, } #[derive(LintDiagnostic)] -pub enum MacroExport { +pub(crate) enum MacroExport { #[diag(passes_macro_export)] Normal, @@ -713,7 +722,7 @@ pub enum MacroExport { } #[derive(Subdiagnostic)] -pub enum UnusedNote { +pub(crate) enum UnusedNote { #[note(passes_unused_empty_lints_note)] EmptyList { name: Symbol }, #[note(passes_unused_no_lints_note)] @@ -724,7 +733,7 @@ pub enum UnusedNote { #[derive(LintDiagnostic)] #[diag(passes_unused)] -pub struct Unused { +pub(crate) struct Unused { #[suggestion(code = "", applicability = "machine-applicable")] pub attr_span: Span, #[subdiagnostic] @@ -733,7 +742,7 @@ pub struct Unused { #[derive(Diagnostic)] #[diag(passes_non_exported_macro_invalid_attrs, code = E0518)] -pub struct NonExportedMacroInvalidAttrs { +pub(crate) struct NonExportedMacroInvalidAttrs { #[primary_span] #[label] pub attr_span: Span, @@ -741,14 +750,14 @@ pub struct NonExportedMacroInvalidAttrs { #[derive(Diagnostic)] #[diag(passes_may_dangle)] -pub struct InvalidMayDangle { +pub(crate) struct InvalidMayDangle { #[primary_span] pub attr_span: Span, } #[derive(LintDiagnostic)] #[diag(passes_unused_duplicate)] -pub struct UnusedDuplicate { +pub(crate) struct UnusedDuplicate { #[suggestion(code = "", applicability = "machine-applicable")] pub this: Span, #[note] @@ -759,7 +768,7 @@ pub struct UnusedDuplicate { #[derive(Diagnostic)] #[diag(passes_unused_multiple)] -pub struct UnusedMultiple { +pub(crate) struct UnusedMultiple { #[primary_span] #[suggestion(code = "", applicability = "machine-applicable")] pub this: Span, @@ -770,7 +779,7 @@ pub struct UnusedMultiple { #[derive(Diagnostic)] #[diag(passes_rustc_lint_opt_ty)] -pub struct RustcLintOptTy { +pub(crate) struct RustcLintOptTy { #[primary_span] pub attr_span: Span, #[label] @@ -779,7 +788,7 @@ pub struct RustcLintOptTy { #[derive(Diagnostic)] #[diag(passes_rustc_lint_opt_deny_field_access)] -pub struct RustcLintOptDenyFieldAccess { +pub(crate) struct RustcLintOptDenyFieldAccess { #[primary_span] pub attr_span: Span, #[label] @@ -788,7 +797,7 @@ pub struct RustcLintOptDenyFieldAccess { #[derive(Diagnostic)] #[diag(passes_collapse_debuginfo)] -pub struct CollapseDebuginfo { +pub(crate) struct CollapseDebuginfo { #[primary_span] pub attr_span: Span, #[label] @@ -797,14 +806,14 @@ pub struct CollapseDebuginfo { #[derive(LintDiagnostic)] #[diag(passes_deprecated_annotation_has_no_effect)] -pub struct DeprecatedAnnotationHasNoEffect { +pub(crate) struct DeprecatedAnnotationHasNoEffect { #[suggestion(applicability = "machine-applicable", code = "")] pub span: Span, } #[derive(Diagnostic)] #[diag(passes_unknown_external_lang_item, code = E0264)] -pub struct UnknownExternLangItem { +pub(crate) struct UnknownExternLangItem { #[primary_span] pub span: Span, pub lang_item: Symbol, @@ -812,25 +821,25 @@ pub struct UnknownExternLangItem { #[derive(Diagnostic)] #[diag(passes_missing_panic_handler)] -pub struct MissingPanicHandler; +pub(crate) struct MissingPanicHandler; #[derive(Diagnostic)] #[diag(passes_panic_unwind_without_std)] #[help] #[note] -pub struct PanicUnwindWithoutStd; +pub(crate) struct PanicUnwindWithoutStd; #[derive(Diagnostic)] #[diag(passes_missing_lang_item)] #[note] #[help] -pub struct MissingLangItem { +pub(crate) struct MissingLangItem { pub name: Symbol, } #[derive(Diagnostic)] #[diag(passes_lang_item_fn_with_track_caller)] -pub struct LangItemWithTrackCaller { +pub(crate) struct LangItemWithTrackCaller { #[primary_span] pub attr_span: Span, pub name: Symbol, @@ -840,7 +849,7 @@ pub struct LangItemWithTrackCaller { #[derive(Diagnostic)] #[diag(passes_lang_item_fn_with_target_feature)] -pub struct LangItemWithTargetFeature { +pub(crate) struct LangItemWithTargetFeature { #[primary_span] pub attr_span: Span, pub name: Symbol, @@ -850,7 +859,7 @@ pub struct LangItemWithTargetFeature { #[derive(Diagnostic)] #[diag(passes_lang_item_on_incorrect_target, code = E0718)] -pub struct LangItemOnIncorrectTarget { +pub(crate) struct LangItemOnIncorrectTarget { #[primary_span] #[label] pub span: Span, @@ -861,14 +870,14 @@ pub struct LangItemOnIncorrectTarget { #[derive(Diagnostic)] #[diag(passes_unknown_lang_item, code = E0522)] -pub struct UnknownLangItem { +pub(crate) struct UnknownLangItem { #[primary_span] #[label] pub span: Span, pub name: Symbol, } -pub struct InvalidAttrAtCrateLevel { +pub(crate) struct InvalidAttrAtCrateLevel { pub span: Span, pub sugg_span: Option<Span>, pub name: Symbol, @@ -876,7 +885,7 @@ pub struct InvalidAttrAtCrateLevel { } #[derive(Clone, Copy)] -pub struct ItemFollowingInnerAttr { +pub(crate) struct ItemFollowingInnerAttr { pub span: Span, pub kind: &'static str, } @@ -907,7 +916,7 @@ impl<G: EmissionGuarantee> Diagnostic<'_, G> for InvalidAttrAtCrateLevel { #[derive(Diagnostic)] #[diag(passes_duplicate_diagnostic_item_in_crate)] -pub struct DuplicateDiagnosticItemInCrate { +pub(crate) struct DuplicateDiagnosticItemInCrate { #[primary_span] pub duplicate_span: Option<Span>, #[note(passes_diagnostic_item_first_defined)] @@ -921,7 +930,7 @@ pub struct DuplicateDiagnosticItemInCrate { #[derive(Diagnostic)] #[diag(passes_layout_abi)] -pub struct LayoutAbi { +pub(crate) struct LayoutAbi { #[primary_span] pub span: Span, pub abi: String, @@ -929,7 +938,7 @@ pub struct LayoutAbi { #[derive(Diagnostic)] #[diag(passes_layout_align)] -pub struct LayoutAlign { +pub(crate) struct LayoutAlign { #[primary_span] pub span: Span, pub align: String, @@ -937,7 +946,7 @@ pub struct LayoutAlign { #[derive(Diagnostic)] #[diag(passes_layout_size)] -pub struct LayoutSize { +pub(crate) struct LayoutSize { #[primary_span] pub span: Span, pub size: String, @@ -945,7 +954,7 @@ pub struct LayoutSize { #[derive(Diagnostic)] #[diag(passes_layout_homogeneous_aggregate)] -pub struct LayoutHomogeneousAggregate { +pub(crate) struct LayoutHomogeneousAggregate { #[primary_span] pub span: Span, pub homogeneous_aggregate: String, @@ -953,7 +962,7 @@ pub struct LayoutHomogeneousAggregate { #[derive(Diagnostic)] #[diag(passes_layout_of)] -pub struct LayoutOf { +pub(crate) struct LayoutOf { #[primary_span] pub span: Span, pub normalized_ty: String, @@ -962,14 +971,14 @@ pub struct LayoutOf { #[derive(Diagnostic)] #[diag(passes_layout_invalid_attribute)] -pub struct LayoutInvalidAttribute { +pub(crate) struct LayoutInvalidAttribute { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(passes_abi_of)] -pub struct AbiOf { +pub(crate) struct AbiOf { #[primary_span] pub span: Span, pub fn_name: Symbol, @@ -978,7 +987,7 @@ pub struct AbiOf { #[derive(Diagnostic)] #[diag(passes_abi_ne)] -pub struct AbiNe { +pub(crate) struct AbiNe { #[primary_span] pub span: Span, pub left: String, @@ -987,14 +996,14 @@ pub struct AbiNe { #[derive(Diagnostic)] #[diag(passes_abi_invalid_attribute)] -pub struct AbiInvalidAttribute { +pub(crate) struct AbiInvalidAttribute { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(passes_unrecognized_field)] -pub struct UnrecognizedField { +pub(crate) struct UnrecognizedField { #[primary_span] pub span: Span, pub name: Symbol, @@ -1002,7 +1011,7 @@ pub struct UnrecognizedField { #[derive(Diagnostic)] #[diag(passes_feature_stable_twice, code = E0711)] -pub struct FeatureStableTwice { +pub(crate) struct FeatureStableTwice { #[primary_span] pub span: Span, pub feature: Symbol, @@ -1012,7 +1021,7 @@ pub struct FeatureStableTwice { #[derive(Diagnostic)] #[diag(passes_feature_previously_declared, code = E0711)] -pub struct FeaturePreviouslyDeclared<'a, 'b> { +pub(crate) struct FeaturePreviouslyDeclared<'a, 'b> { #[primary_span] pub span: Span, pub feature: Symbol, @@ -1020,7 +1029,7 @@ pub struct FeaturePreviouslyDeclared<'a, 'b> { pub prev_declared: &'b str, } -pub struct BreakNonLoop<'a> { +pub(crate) struct BreakNonLoop<'a> { pub span: Span, pub head: Option<Span>, pub kind: &'a str, @@ -1075,7 +1084,7 @@ impl<'a, G: EmissionGuarantee> Diagnostic<'_, G> for BreakNonLoop<'a> { #[derive(Diagnostic)] #[diag(passes_continue_labeled_block, code = E0696)] -pub struct ContinueLabeledBlock { +pub(crate) struct ContinueLabeledBlock { #[primary_span] #[label] pub span: Span, @@ -1085,7 +1094,7 @@ pub struct ContinueLabeledBlock { #[derive(Diagnostic)] #[diag(passes_break_inside_closure, code = E0267)] -pub struct BreakInsideClosure<'a> { +pub(crate) struct BreakInsideClosure<'a> { #[primary_span] #[label] pub span: Span, @@ -1096,7 +1105,7 @@ pub struct BreakInsideClosure<'a> { #[derive(Diagnostic)] #[diag(passes_break_inside_coroutine, code = E0267)] -pub struct BreakInsideCoroutine<'a> { +pub(crate) struct BreakInsideCoroutine<'a> { #[primary_span] #[label] pub span: Span, @@ -1109,7 +1118,7 @@ pub struct BreakInsideCoroutine<'a> { #[derive(Diagnostic)] #[diag(passes_outside_loop, code = E0268)] -pub struct OutsideLoop<'a> { +pub(crate) struct OutsideLoop<'a> { #[primary_span] #[label] pub spans: Vec<Span>, @@ -1120,7 +1129,7 @@ pub struct OutsideLoop<'a> { } #[derive(Subdiagnostic)] #[multipart_suggestion(passes_outside_loop_suggestion, applicability = "maybe-incorrect")] -pub struct OutsideLoopSuggestion { +pub(crate) struct OutsideLoopSuggestion { #[suggestion_part(code = "'block: ")] pub block_span: Span, #[suggestion_part(code = " 'block")] @@ -1129,7 +1138,7 @@ pub struct OutsideLoopSuggestion { #[derive(Diagnostic)] #[diag(passes_unlabeled_in_labeled_block, code = E0695)] -pub struct UnlabeledInLabeledBlock<'a> { +pub(crate) struct UnlabeledInLabeledBlock<'a> { #[primary_span] #[label] pub span: Span, @@ -1138,7 +1147,7 @@ pub struct UnlabeledInLabeledBlock<'a> { #[derive(Diagnostic)] #[diag(passes_unlabeled_cf_in_while_condition, code = E0590)] -pub struct UnlabeledCfInWhileCondition<'a> { +pub(crate) struct UnlabeledCfInWhileCondition<'a> { #[primary_span] #[label] pub span: Span, @@ -1147,11 +1156,11 @@ pub struct UnlabeledCfInWhileCondition<'a> { #[derive(LintDiagnostic)] #[diag(passes_undefined_naked_function_abi)] -pub struct UndefinedNakedFunctionAbi; +pub(crate) struct UndefinedNakedFunctionAbi; #[derive(Diagnostic)] #[diag(passes_no_patterns)] -pub struct NoPatterns { +pub(crate) struct NoPatterns { #[primary_span] pub span: Span, } @@ -1159,12 +1168,12 @@ pub struct NoPatterns { #[derive(Diagnostic)] #[diag(passes_params_not_allowed)] #[help] -pub struct ParamsNotAllowed { +pub(crate) struct ParamsNotAllowed { #[primary_span] pub span: Span, } -pub struct NakedFunctionsAsmBlock { +pub(crate) struct NakedFunctionsAsmBlock { pub span: Span, pub multiple_asms: Vec<Span>, pub non_asms: Vec<Span>, @@ -1188,14 +1197,14 @@ impl<G: EmissionGuarantee> Diagnostic<'_, G> for NakedFunctionsAsmBlock { #[derive(Diagnostic)] #[diag(passes_naked_functions_operands, code = E0787)] -pub struct NakedFunctionsOperands { +pub(crate) struct NakedFunctionsOperands { #[primary_span] pub unsupported_operands: Vec<Span>, } #[derive(Diagnostic)] #[diag(passes_naked_functions_asm_options, code = E0787)] -pub struct NakedFunctionsAsmOptions { +pub(crate) struct NakedFunctionsAsmOptions { #[primary_span] pub span: Span, pub unsupported_options: String, @@ -1203,7 +1212,7 @@ pub struct NakedFunctionsAsmOptions { #[derive(Diagnostic)] #[diag(passes_naked_functions_must_use_noreturn, code = E0787)] -pub struct NakedFunctionsMustUseNoreturn { +pub(crate) struct NakedFunctionsMustUseNoreturn { #[primary_span] pub span: Span, #[suggestion(code = ", options(noreturn)", applicability = "machine-applicable")] @@ -1212,7 +1221,7 @@ pub struct NakedFunctionsMustUseNoreturn { #[derive(Diagnostic)] #[diag(passes_naked_functions_incompatible_attribute, code = E0736)] -pub struct NakedFunctionIncompatibleAttribute { +pub(crate) struct NakedFunctionIncompatibleAttribute { #[primary_span] #[label] pub span: Span, @@ -1223,7 +1232,7 @@ pub struct NakedFunctionIncompatibleAttribute { #[derive(Diagnostic)] #[diag(passes_attr_only_in_functions)] -pub struct AttrOnlyInFunctions { +pub(crate) struct AttrOnlyInFunctions { #[primary_span] pub span: Span, pub attr: Symbol, @@ -1231,7 +1240,7 @@ pub struct AttrOnlyInFunctions { #[derive(Diagnostic)] #[diag(passes_multiple_rustc_main, code = E0137)] -pub struct MultipleRustcMain { +pub(crate) struct MultipleRustcMain { #[primary_span] pub span: Span, #[label(passes_first)] @@ -1242,7 +1251,7 @@ pub struct MultipleRustcMain { #[derive(Diagnostic)] #[diag(passes_multiple_start_functions, code = E0138)] -pub struct MultipleStartFunctions { +pub(crate) struct MultipleStartFunctions { #[primary_span] pub span: Span, #[label] @@ -1253,12 +1262,12 @@ pub struct MultipleStartFunctions { #[derive(Diagnostic)] #[diag(passes_extern_main)] -pub struct ExternMain { +pub(crate) struct ExternMain { #[primary_span] pub span: Span, } -pub struct NoMainErr { +pub(crate) struct NoMainErr { pub sp: Span, pub crate_name: Symbol, pub has_filename: bool, @@ -1312,7 +1321,7 @@ impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for NoMainErr { } } -pub struct DuplicateLangItem { +pub(crate) struct DuplicateLangItem { pub local_span: Option<Span>, pub lang_item_name: Symbol, pub crate_name: Symbol, @@ -1377,7 +1386,7 @@ impl<G: EmissionGuarantee> Diagnostic<'_, G> for DuplicateLangItem { #[derive(Diagnostic)] #[diag(passes_incorrect_target, code = E0718)] -pub struct IncorrectTarget<'a> { +pub(crate) struct IncorrectTarget<'a> { #[primary_span] pub span: Span, #[label] @@ -1391,21 +1400,21 @@ pub struct IncorrectTarget<'a> { #[derive(LintDiagnostic)] #[diag(passes_useless_assignment)] -pub struct UselessAssignment<'a> { +pub(crate) struct UselessAssignment<'a> { pub is_field_assign: bool, pub ty: Ty<'a>, } #[derive(LintDiagnostic)] #[diag(passes_only_has_effect_on)] -pub struct OnlyHasEffectOn { +pub(crate) struct OnlyHasEffectOn { pub attr_name: Symbol, pub target_name: String, } #[derive(Diagnostic)] #[diag(passes_object_lifetime_err)] -pub struct ObjectLifetimeErr { +pub(crate) struct ObjectLifetimeErr { #[primary_span] pub span: Span, pub repr: String, @@ -1414,13 +1423,13 @@ pub struct ObjectLifetimeErr { #[derive(Diagnostic)] #[diag(passes_unrecognized_repr_hint, code = E0552)] #[help] -pub struct UnrecognizedReprHint { +pub(crate) struct UnrecognizedReprHint { #[primary_span] pub span: Span, } #[derive(Diagnostic)] -pub enum AttrApplication { +pub(crate) enum AttrApplication { #[diag(passes_attr_application_enum, code = E0517)] Enum { #[primary_span] @@ -1460,7 +1469,7 @@ pub enum AttrApplication { #[derive(Diagnostic)] #[diag(passes_transparent_incompatible, code = E0692)] -pub struct TransparentIncompatible { +pub(crate) struct TransparentIncompatible { #[primary_span] pub hint_spans: Vec<Span>, pub target: String, @@ -1468,14 +1477,14 @@ pub struct TransparentIncompatible { #[derive(Diagnostic)] #[diag(passes_deprecated_attribute, code = E0549)] -pub struct DeprecatedAttribute { +pub(crate) struct DeprecatedAttribute { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(passes_useless_stability)] -pub struct UselessStability { +pub(crate) struct UselessStability { #[primary_span] #[label] pub span: Span, @@ -1485,7 +1494,7 @@ pub struct UselessStability { #[derive(Diagnostic)] #[diag(passes_cannot_stabilize_deprecated)] -pub struct CannotStabilizeDeprecated { +pub(crate) struct CannotStabilizeDeprecated { #[primary_span] #[label] pub span: Span, @@ -1495,7 +1504,7 @@ pub struct CannotStabilizeDeprecated { #[derive(Diagnostic)] #[diag(passes_missing_stability_attr)] -pub struct MissingStabilityAttr<'a> { +pub(crate) struct MissingStabilityAttr<'a> { #[primary_span] pub span: Span, pub descr: &'a str, @@ -1503,7 +1512,7 @@ pub struct MissingStabilityAttr<'a> { #[derive(Diagnostic)] #[diag(passes_missing_const_stab_attr)] -pub struct MissingConstStabAttr<'a> { +pub(crate) struct MissingConstStabAttr<'a> { #[primary_span] pub span: Span, pub descr: &'a str, @@ -1512,14 +1521,14 @@ pub struct MissingConstStabAttr<'a> { #[derive(Diagnostic)] #[diag(passes_trait_impl_const_stable)] #[note] -pub struct TraitImplConstStable { +pub(crate) struct TraitImplConstStable { #[primary_span] pub span: Span, } #[derive(Diagnostic)] #[diag(passes_unknown_feature, code = E0635)] -pub struct UnknownFeature { +pub(crate) struct UnknownFeature { #[primary_span] pub span: Span, pub feature: Symbol, @@ -1527,7 +1536,7 @@ pub struct UnknownFeature { #[derive(Diagnostic)] #[diag(passes_implied_feature_not_exist)] -pub struct ImpliedFeatureNotExist { +pub(crate) struct ImpliedFeatureNotExist { #[primary_span] pub span: Span, pub feature: Symbol, @@ -1536,14 +1545,14 @@ pub struct ImpliedFeatureNotExist { #[derive(Diagnostic)] #[diag(passes_duplicate_feature_err, code = E0636)] -pub struct DuplicateFeatureErr { +pub(crate) struct DuplicateFeatureErr { #[primary_span] pub span: Span, pub feature: Symbol, } #[derive(Diagnostic)] #[diag(passes_missing_const_err)] -pub struct MissingConstErr { +pub(crate) struct MissingConstErr { #[primary_span] #[help] pub fn_sig_span: Span, @@ -1552,7 +1561,7 @@ pub struct MissingConstErr { } #[derive(LintDiagnostic)] -pub enum MultipleDeadCodes<'tcx> { +pub(crate) enum MultipleDeadCodes<'tcx> { #[diag(passes_dead_codes)] DeadCodes { multiple: bool, @@ -1583,7 +1592,7 @@ pub enum MultipleDeadCodes<'tcx> { #[derive(Subdiagnostic)] #[label(passes_parent_info)] -pub struct ParentInfo<'tcx> { +pub(crate) struct ParentInfo<'tcx> { pub num: usize, pub descr: &'tcx str, pub parent_descr: &'tcx str, @@ -1593,14 +1602,14 @@ pub struct ParentInfo<'tcx> { #[derive(Subdiagnostic)] #[note(passes_ignored_derived_impls)] -pub struct IgnoredDerivedImpls { +pub(crate) struct IgnoredDerivedImpls { pub name: Symbol, pub trait_list: DiagSymbolList, pub trait_list_len: usize, } #[derive(Subdiagnostic)] -pub enum ChangeFields { +pub(crate) enum ChangeFields { #[multipart_suggestion( passes_change_fields_to_be_of_unit_type, applicability = "has-placeholders" @@ -1624,14 +1633,14 @@ pub(crate) struct ProcMacroBadSig { #[derive(Diagnostic)] #[diag(passes_skipping_const_checks)] -pub struct SkippingConstChecks { +pub(crate) struct SkippingConstChecks { #[primary_span] pub span: Span, } #[derive(LintDiagnostic)] #[diag(passes_unreachable_due_to_uninhabited)] -pub struct UnreachableDueToUninhabited<'desc, 'tcx> { +pub(crate) struct UnreachableDueToUninhabited<'desc, 'tcx> { pub descr: &'desc str, #[label] pub expr: Span, @@ -1644,20 +1653,20 @@ pub struct UnreachableDueToUninhabited<'desc, 'tcx> { #[derive(LintDiagnostic)] #[diag(passes_unused_var_maybe_capture_ref)] #[help] -pub struct UnusedVarMaybeCaptureRef { +pub(crate) struct UnusedVarMaybeCaptureRef { pub name: String, } #[derive(LintDiagnostic)] #[diag(passes_unused_capture_maybe_capture_ref)] #[help] -pub struct UnusedCaptureMaybeCaptureRef { +pub(crate) struct UnusedCaptureMaybeCaptureRef { pub name: String, } #[derive(LintDiagnostic)] #[diag(passes_unused_var_remove_field)] -pub struct UnusedVarRemoveField { +pub(crate) struct UnusedVarRemoveField { pub name: String, #[subdiagnostic] pub sugg: UnusedVarRemoveFieldSugg, @@ -1668,7 +1677,7 @@ pub struct UnusedVarRemoveField { passes_unused_var_remove_field_suggestion, applicability = "machine-applicable" )] -pub struct UnusedVarRemoveFieldSugg { +pub(crate) struct UnusedVarRemoveFieldSugg { #[suggestion_part(code = "")] pub spans: Vec<Span>, } @@ -1676,20 +1685,20 @@ pub struct UnusedVarRemoveFieldSugg { #[derive(LintDiagnostic)] #[diag(passes_unused_var_assigned_only)] #[note] -pub struct UnusedVarAssignedOnly { +pub(crate) struct UnusedVarAssignedOnly { pub name: String, } #[derive(LintDiagnostic)] #[diag(passes_unnecessary_stable_feature)] -pub struct UnnecessaryStableFeature { +pub(crate) struct UnnecessaryStableFeature { pub feature: Symbol, pub since: Symbol, } #[derive(LintDiagnostic)] #[diag(passes_unnecessary_partial_stable_feature)] -pub struct UnnecessaryPartialStableFeature { +pub(crate) struct UnnecessaryPartialStableFeature { #[suggestion(code = "{implies}", applicability = "maybe-incorrect")] pub span: Span, #[suggestion(passes_suggestion_remove, code = "", applicability = "maybe-incorrect")] @@ -1702,25 +1711,25 @@ pub struct UnnecessaryPartialStableFeature { #[derive(LintDiagnostic)] #[diag(passes_ineffective_unstable_impl)] #[note] -pub struct IneffectiveUnstableImpl; +pub(crate) struct IneffectiveUnstableImpl; #[derive(LintDiagnostic)] #[diag(passes_unused_assign)] #[help] -pub struct UnusedAssign { +pub(crate) struct UnusedAssign { pub name: String, } #[derive(LintDiagnostic)] #[diag(passes_unused_assign_passed)] #[help] -pub struct UnusedAssignPassed { +pub(crate) struct UnusedAssignPassed { pub name: String, } #[derive(LintDiagnostic)] #[diag(passes_unused_variable_try_prefix)] -pub struct UnusedVariableTryPrefix { +pub(crate) struct UnusedVariableTryPrefix { #[label] pub label: Option<Span>, #[subdiagnostic] @@ -1731,7 +1740,7 @@ pub struct UnusedVariableTryPrefix { } #[derive(Subdiagnostic)] -pub enum UnusedVariableSugg { +pub(crate) enum UnusedVariableSugg { #[multipart_suggestion(passes_suggestion, applicability = "maybe-incorrect")] TryPrefixSugg { #[suggestion_part(code = "_{name}")] @@ -1746,7 +1755,7 @@ pub enum UnusedVariableSugg { }, } -pub struct UnusedVariableStringInterp { +pub(crate) struct UnusedVariableStringInterp { pub lit: Span, pub lo: Span, pub hi: Span, @@ -1769,14 +1778,14 @@ impl Subdiagnostic for UnusedVariableStringInterp { #[derive(LintDiagnostic)] #[diag(passes_unused_variable_try_ignore)] -pub struct UnusedVarTryIgnore { +pub(crate) struct UnusedVarTryIgnore { #[subdiagnostic] pub sugg: UnusedVarTryIgnoreSugg, } #[derive(Subdiagnostic)] #[multipart_suggestion(passes_suggestion, applicability = "maybe-incorrect")] -pub struct UnusedVarTryIgnoreSugg { +pub(crate) struct UnusedVarTryIgnoreSugg { #[suggestion_part(code = "{name}: _")] pub shorthands: Vec<Span>, #[suggestion_part(code = "_")] @@ -1787,14 +1796,14 @@ pub struct UnusedVarTryIgnoreSugg { #[derive(LintDiagnostic)] #[diag(passes_attr_crate_level)] #[note] -pub struct AttrCrateLevelOnly { +pub(crate) struct AttrCrateLevelOnly { #[subdiagnostic] pub sugg: Option<AttrCrateLevelOnlySugg>, } #[derive(Subdiagnostic)] #[suggestion(passes_suggestion, applicability = "maybe-incorrect", code = "!", style = "verbose")] -pub struct AttrCrateLevelOnlySugg { +pub(crate) struct AttrCrateLevelOnlySugg { #[primary_span] pub attr: Span, } diff --git a/compiler/rustc_passes/src/lang_items.rs b/compiler/rustc_passes/src/lang_items.rs index 71b0ebb0e21..8038afb955e 100644 --- a/compiler/rustc_passes/src/lang_items.rs +++ b/compiler/rustc_passes/src/lang_items.rs @@ -359,6 +359,6 @@ impl<'ast, 'tcx> visit::Visitor<'ast> for LanguageItemCollector<'ast, 'tcx> { } } -pub fn provide(providers: &mut Providers) { +pub(crate) fn provide(providers: &mut Providers) { providers.get_lang_items = get_lang_items; } diff --git a/compiler/rustc_passes/src/lib.rs b/compiler/rustc_passes/src/lib.rs index a0f5f98aafc..664da65068d 100644 --- a/compiler/rustc_passes/src/lib.rs +++ b/compiler/rustc_passes/src/lib.rs @@ -12,6 +12,7 @@ #![feature(map_try_insert)] #![feature(rustdoc_internals)] #![feature(try_blocks)] +#![warn(unreachable_pub)] // tidy-alphabetical-end use rustc_middle::query::Providers; diff --git a/compiler/rustc_passes/src/lib_features.rs b/compiler/rustc_passes/src/lib_features.rs index e60985ba16f..9d5766865c7 100644 --- a/compiler/rustc_passes/src/lib_features.rs +++ b/compiler/rustc_passes/src/lib_features.rs @@ -16,7 +16,7 @@ use rustc_span::{sym, Span}; use crate::errors::{FeaturePreviouslyDeclared, FeatureStableTwice}; -pub struct LibFeatureCollector<'tcx> { +struct LibFeatureCollector<'tcx> { tcx: TyCtxt<'tcx>, lib_features: LibFeatures, } @@ -153,6 +153,6 @@ fn lib_features(tcx: TyCtxt<'_>, LocalCrate: LocalCrate) -> LibFeatures { collector.lib_features } -pub fn provide(providers: &mut Providers) { +pub(crate) fn provide(providers: &mut Providers) { providers.lib_features = lib_features; } diff --git a/compiler/rustc_passes/src/liveness.rs b/compiler/rustc_passes/src/liveness.rs index d3b85da4630..db3eaea68b5 100644 --- a/compiler/rustc_passes/src/liveness.rs +++ b/compiler/rustc_passes/src/liveness.rs @@ -178,7 +178,7 @@ fn check_liveness(tcx: TyCtxt<'_>, def_id: LocalDefId) { lsets.warn_about_unused_args(&body, entry_ln); } -pub fn provide(providers: &mut Providers) { +pub(crate) fn provide(providers: &mut Providers) { *providers = Providers { check_liveness, ..*providers }; } diff --git a/compiler/rustc_passes/src/reachable.rs b/compiler/rustc_passes/src/reachable.rs index dee8ba7e87d..8d9e00b9f3c 100644 --- a/compiler/rustc_passes/src/reachable.rs +++ b/compiler/rustc_passes/src/reachable.rs @@ -500,6 +500,6 @@ fn reachable_set(tcx: TyCtxt<'_>, (): ()) -> LocalDefIdSet { reachable_context.reachable_symbols } -pub fn provide(providers: &mut Providers) { +pub(crate) fn provide(providers: &mut Providers) { *providers = Providers { reachable_set, ..*providers }; } diff --git a/compiler/rustc_passes/src/upvars.rs b/compiler/rustc_passes/src/upvars.rs index f2454514e4d..0544d08f5b1 100644 --- a/compiler/rustc_passes/src/upvars.rs +++ b/compiler/rustc_passes/src/upvars.rs @@ -9,7 +9,7 @@ use rustc_middle::query::Providers; use rustc_middle::ty::TyCtxt; use rustc_span::Span; -pub fn provide(providers: &mut Providers) { +pub(crate) fn provide(providers: &mut Providers) { providers.upvars_mentioned = |tcx, def_id| { if !tcx.is_closure_like(def_id) { return None; diff --git a/compiler/rustc_passes/src/weak_lang_items.rs b/compiler/rustc_passes/src/weak_lang_items.rs index 90691ca1790..020128f29c5 100644 --- a/compiler/rustc_passes/src/weak_lang_items.rs +++ b/compiler/rustc_passes/src/weak_lang_items.rs @@ -15,7 +15,11 @@ use crate::errors::{ /// Checks the crate for usage of weak lang items, returning a vector of all the /// lang items required by this crate, but not defined yet. -pub fn check_crate(tcx: TyCtxt<'_>, items: &mut lang_items::LanguageItems, krate: &ast::Crate) { +pub(crate) fn check_crate( + tcx: TyCtxt<'_>, + items: &mut lang_items::LanguageItems, + krate: &ast::Crate, +) { // These are never called by user code, they're generated by the compiler. // They will never implicitly be added to the `missing` array unless we do // so here. diff --git a/compiler/rustc_pattern_analysis/src/lib.rs b/compiler/rustc_pattern_analysis/src/lib.rs index 6c9c848bb10..fec44d5af55 100644 --- a/compiler/rustc_pattern_analysis/src/lib.rs +++ b/compiler/rustc_pattern_analysis/src/lib.rs @@ -6,6 +6,7 @@ #![allow(rustc::diagnostic_outside_of_impl)] #![allow(rustc::untranslatable_diagnostic)] #![cfg_attr(feature = "rustc", feature(let_chains))] +#![warn(unreachable_pub)] // tidy-alphabetical-end pub mod constructor; diff --git a/compiler/rustc_privacy/src/errors.rs b/compiler/rustc_privacy/src/errors.rs index 89face10750..34553c2b90a 100644 --- a/compiler/rustc_privacy/src/errors.rs +++ b/compiler/rustc_privacy/src/errors.rs @@ -5,7 +5,7 @@ use rustc_span::{Span, Symbol}; #[derive(Diagnostic)] #[diag(privacy_field_is_private, code = E0451)] -pub struct FieldIsPrivate { +pub(crate) struct FieldIsPrivate { #[primary_span] pub span: Span, pub field_name: Symbol, @@ -16,7 +16,7 @@ pub struct FieldIsPrivate { } #[derive(Subdiagnostic)] -pub enum FieldIsPrivateLabel { +pub(crate) enum FieldIsPrivateLabel { #[label(privacy_field_is_private_is_update_syntax_label)] IsUpdateSyntax { #[primary_span] @@ -32,7 +32,7 @@ pub enum FieldIsPrivateLabel { #[derive(Diagnostic)] #[diag(privacy_item_is_private)] -pub struct ItemIsPrivate<'a> { +pub(crate) struct ItemIsPrivate<'a> { #[primary_span] #[label] pub span: Span, @@ -42,7 +42,7 @@ pub struct ItemIsPrivate<'a> { #[derive(Diagnostic)] #[diag(privacy_unnamed_item_is_private)] -pub struct UnnamedItemIsPrivate { +pub(crate) struct UnnamedItemIsPrivate { #[primary_span] pub span: Span, pub kind: &'static str, @@ -50,7 +50,7 @@ pub struct UnnamedItemIsPrivate { #[derive(Diagnostic)] #[diag(privacy_in_public_interface, code = E0446)] -pub struct InPublicInterface<'a> { +pub(crate) struct InPublicInterface<'a> { #[primary_span] #[label] pub span: Span, @@ -63,7 +63,7 @@ pub struct InPublicInterface<'a> { #[derive(Diagnostic)] #[diag(privacy_report_effective_visibility)] -pub struct ReportEffectiveVisibility { +pub(crate) struct ReportEffectiveVisibility { #[primary_span] pub span: Span, pub descr: String, @@ -71,7 +71,7 @@ pub struct ReportEffectiveVisibility { #[derive(LintDiagnostic)] #[diag(privacy_from_private_dep_in_public_interface)] -pub struct FromPrivateDependencyInPublicInterface<'a> { +pub(crate) struct FromPrivateDependencyInPublicInterface<'a> { pub kind: &'a str, pub descr: DiagArgFromDisplay<'a>, pub krate: Symbol, @@ -79,7 +79,7 @@ pub struct FromPrivateDependencyInPublicInterface<'a> { #[derive(LintDiagnostic)] #[diag(privacy_unnameable_types_lint)] -pub struct UnnameableTypesLint<'a> { +pub(crate) struct UnnameableTypesLint<'a> { #[label] pub span: Span, pub kind: &'a str, @@ -93,7 +93,7 @@ pub struct UnnameableTypesLint<'a> { // See https://rust-lang.github.io/rfcs/2145-type-privacy.html for more details. #[derive(LintDiagnostic)] #[diag(privacy_private_interface_or_bounds_lint)] -pub struct PrivateInterfacesOrBoundsLint<'a> { +pub(crate) struct PrivateInterfacesOrBoundsLint<'a> { #[label(privacy_item_label)] pub item_span: Span, pub item_kind: &'a str, diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index d1d1e5e901f..572f71d7c77 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -6,6 +6,7 @@ #![feature(let_chains)] #![feature(rustdoc_internals)] #![feature(try_blocks)] +#![warn(unreachable_pub)] // tidy-alphabetical-end mod errors; @@ -626,7 +627,8 @@ impl<'tcx> EmbargoVisitor<'tcx> { | DefKind::Field | DefKind::GlobalAsm | DefKind::Impl { .. } - | DefKind::Closure => (), + | DefKind::Closure + | DefKind::SyntheticCoroutineBody => (), } } } @@ -1496,7 +1498,7 @@ impl<'tcx> PrivateItemsInPublicInterfacesChecker<'tcx, '_> { self.effective_visibilities.effective_vis(def_id).copied() } - pub fn check_item(&mut self, id: ItemId) { + fn check_item(&mut self, id: ItemId) { let tcx = self.tcx; let def_id = id.owner_id.def_id; let item_visibility = tcx.local_visibility(def_id); diff --git a/compiler/rustc_query_impl/src/lib.rs b/compiler/rustc_query_impl/src/lib.rs index f4a4c602f69..a6c863a6b7b 100644 --- a/compiler/rustc_query_impl/src/lib.rs +++ b/compiler/rustc_query_impl/src/lib.rs @@ -8,6 +8,7 @@ #![feature(min_specialization)] #![feature(rustc_attrs)] #![feature(rustdoc_internals)] +#![warn(unreachable_pub)] // tidy-alphabetical-end use field_offset::offset_of; diff --git a/compiler/rustc_query_impl/src/plumbing.rs b/compiler/rustc_query_impl/src/plumbing.rs index c064b2bd6c1..6a6698b019c 100644 --- a/compiler/rustc_query_impl/src/plumbing.rs +++ b/compiler/rustc_query_impl/src/plumbing.rs @@ -541,7 +541,7 @@ macro_rules! expand_if_cached { /// Don't show the backtrace for query system by default /// use `RUST_BACKTRACE=full` to show all the backtraces #[inline(never)] -pub fn __rust_begin_short_backtrace<F, T>(f: F) -> T +pub(crate) fn __rust_begin_short_backtrace<F, T>(f: F) -> T where F: FnOnce() -> T, { @@ -557,17 +557,17 @@ macro_rules! define_queries { $($(#[$attr:meta])* [$($modifiers:tt)*] fn $name:ident($($K:tt)*) -> $V:ty,)*) => { - pub(crate) mod query_impl { $(pub mod $name { + pub(crate) mod query_impl { $(pub(crate) mod $name { use super::super::*; use std::marker::PhantomData; - pub mod get_query_incr { + pub(crate) mod get_query_incr { use super::*; // Adding `__rust_end_short_backtrace` marker to backtraces so that we emit the frames // when `RUST_BACKTRACE=1`, add a new mod with `$name` here is to allow duplicate naming #[inline(never)] - pub fn __rust_end_short_backtrace<'tcx>( + pub(crate) fn __rust_end_short_backtrace<'tcx>( tcx: TyCtxt<'tcx>, span: Span, key: queries::$name::Key<'tcx>, @@ -585,11 +585,11 @@ macro_rules! define_queries { } } - pub mod get_query_non_incr { + pub(crate) mod get_query_non_incr { use super::*; #[inline(never)] - pub fn __rust_end_short_backtrace<'tcx>( + pub(crate) fn __rust_end_short_backtrace<'tcx>( tcx: TyCtxt<'tcx>, span: Span, key: queries::$name::Key<'tcx>, @@ -604,7 +604,9 @@ macro_rules! define_queries { } } - pub fn dynamic_query<'tcx>() -> DynamicQuery<'tcx, queries::$name::Storage<'tcx>> { + pub(crate) fn dynamic_query<'tcx>() + -> DynamicQuery<'tcx, queries::$name::Storage<'tcx>> + { DynamicQuery { name: stringify!($name), eval_always: is_eval_always!([$($modifiers)*]), @@ -667,7 +669,7 @@ macro_rules! define_queries { } #[derive(Copy, Clone, Default)] - pub struct QueryType<'tcx> { + pub(crate) struct QueryType<'tcx> { data: PhantomData<&'tcx ()> } @@ -696,7 +698,7 @@ macro_rules! define_queries { } } - pub fn try_collect_active_jobs<'tcx>(tcx: TyCtxt<'tcx>, qmap: &mut QueryMap) { + pub(crate) fn try_collect_active_jobs<'tcx>(tcx: TyCtxt<'tcx>, qmap: &mut QueryMap) { let make_query = |tcx, key| { let kind = rustc_middle::dep_graph::dep_kinds::$name; let name = stringify!($name); @@ -711,11 +713,17 @@ macro_rules! define_queries { // don't `unwrap()` here, just manually check for `None` and do best-effort error // reporting. if res.is_none() { - tracing::warn!("Failed to collect active jobs for query with name `{}`!", stringify!($name)); + tracing::warn!( + "Failed to collect active jobs for query with name `{}`!", + stringify!($name) + ); } } - pub fn alloc_self_profile_query_strings<'tcx>(tcx: TyCtxt<'tcx>, string_cache: &mut QueryKeyStringCache) { + pub(crate) fn alloc_self_profile_query_strings<'tcx>( + tcx: TyCtxt<'tcx>, + string_cache: &mut QueryKeyStringCache + ) { $crate::profiling_support::alloc_self_profile_query_strings_for_query_cache( tcx, stringify!($name), @@ -725,7 +733,7 @@ macro_rules! define_queries { } item_if_cached! { [$($modifiers)*] { - pub fn encode_query_results<'tcx>( + pub(crate) fn encode_query_results<'tcx>( tcx: TyCtxt<'tcx>, encoder: &mut CacheEncoder<'_, 'tcx>, query_result_index: &mut EncodedDepNodeIndex @@ -739,7 +747,7 @@ macro_rules! define_queries { } }} - pub fn query_key_hash_verify<'tcx>(tcx: TyCtxt<'tcx>) { + pub(crate) fn query_key_hash_verify<'tcx>(tcx: TyCtxt<'tcx>) { $crate::plumbing::query_key_hash_verify( query_impl::$name::QueryType::config(tcx), QueryCtxt::new(tcx), @@ -795,7 +803,7 @@ macro_rules! define_queries { use rustc_query_system::dep_graph::FingerprintStyle; // We use this for most things when incr. comp. is turned off. - pub fn Null<'tcx>() -> DepKindStruct<'tcx> { + pub(crate) fn Null<'tcx>() -> DepKindStruct<'tcx> { DepKindStruct { is_anon: false, is_eval_always: false, @@ -807,7 +815,7 @@ macro_rules! define_queries { } // We use this for the forever-red node. - pub fn Red<'tcx>() -> DepKindStruct<'tcx> { + pub(crate) fn Red<'tcx>() -> DepKindStruct<'tcx> { DepKindStruct { is_anon: false, is_eval_always: false, @@ -818,7 +826,7 @@ macro_rules! define_queries { } } - pub fn TraitSelect<'tcx>() -> DepKindStruct<'tcx> { + pub(crate) fn TraitSelect<'tcx>() -> DepKindStruct<'tcx> { DepKindStruct { is_anon: true, is_eval_always: false, @@ -829,7 +837,7 @@ macro_rules! define_queries { } } - pub fn CompileCodegenUnit<'tcx>() -> DepKindStruct<'tcx> { + pub(crate) fn CompileCodegenUnit<'tcx>() -> DepKindStruct<'tcx> { DepKindStruct { is_anon: false, is_eval_always: false, @@ -840,7 +848,7 @@ macro_rules! define_queries { } } - pub fn CompileMonoItem<'tcx>() -> DepKindStruct<'tcx> { + pub(crate) fn CompileMonoItem<'tcx>() -> DepKindStruct<'tcx> { DepKindStruct { is_anon: false, is_eval_always: false, diff --git a/compiler/rustc_query_system/src/dep_graph/serialized.rs b/compiler/rustc_query_system/src/dep_graph/serialized.rs index ab4a8be0fbf..a4fb0a5b072 100644 --- a/compiler/rustc_query_system/src/dep_graph/serialized.rs +++ b/compiler/rustc_query_system/src/dep_graph/serialized.rs @@ -617,14 +617,14 @@ impl<D: Deps> EncoderState<D> { } } -pub struct GraphEncoder<D: Deps> { +pub(crate) struct GraphEncoder<D: Deps> { profiler: SelfProfilerRef, status: Lock<Option<EncoderState<D>>>, record_graph: Option<Lock<DepGraphQuery>>, } impl<D: Deps> GraphEncoder<D> { - pub fn new( + pub(crate) fn new( encoder: FileEncoder, prev_node_count: usize, record_graph: bool, @@ -723,7 +723,7 @@ impl<D: Deps> GraphEncoder<D> { ) } - pub fn finish(&self) -> FileEncodeResult { + pub(crate) fn finish(&self) -> FileEncodeResult { let _prof_timer = self.profiler.generic_activity("incr_comp_encode_dep_graph_finish"); self.status.lock().take().unwrap().finish(&self.profiler) diff --git a/compiler/rustc_query_system/src/error.rs b/compiler/rustc_query_system/src/error.rs index 9db6fac8036..860f2e66915 100644 --- a/compiler/rustc_query_system/src/error.rs +++ b/compiler/rustc_query_system/src/error.rs @@ -5,7 +5,7 @@ use rustc_span::{Span, Symbol}; #[derive(Subdiagnostic)] #[note(query_system_cycle_stack_middle)] -pub struct CycleStack { +pub(crate) struct CycleStack { #[primary_span] pub span: Span, pub desc: String, @@ -20,7 +20,7 @@ pub enum HandleCycleError { } #[derive(Subdiagnostic)] -pub enum StackCount { +pub(crate) enum StackCount { #[note(query_system_cycle_stack_single)] Single, #[note(query_system_cycle_stack_multiple)] @@ -28,7 +28,7 @@ pub enum StackCount { } #[derive(Subdiagnostic)] -pub enum Alias { +pub(crate) enum Alias { #[note(query_system_cycle_recursive_ty_alias)] #[help(query_system_cycle_recursive_ty_alias_help1)] #[help(query_system_cycle_recursive_ty_alias_help2)] @@ -39,7 +39,7 @@ pub enum Alias { #[derive(Subdiagnostic)] #[note(query_system_cycle_usage)] -pub struct CycleUsage { +pub(crate) struct CycleUsage { #[primary_span] pub span: Span, pub usage: String, @@ -47,7 +47,7 @@ pub struct CycleUsage { #[derive(Diagnostic)] #[diag(query_system_cycle, code = E0391)] -pub struct Cycle { +pub(crate) struct Cycle { #[primary_span] pub span: Span, pub stack_bottom: String, @@ -65,14 +65,14 @@ pub struct Cycle { #[derive(Diagnostic)] #[diag(query_system_reentrant)] -pub struct Reentrant; +pub(crate) struct Reentrant; #[derive(Diagnostic)] #[diag(query_system_increment_compilation)] #[help] #[note(query_system_increment_compilation_note1)] #[note(query_system_increment_compilation_note2)] -pub struct IncrementCompilation { +pub(crate) struct IncrementCompilation { pub run_cmd: String, pub dep_node: String, } diff --git a/compiler/rustc_query_system/src/lib.rs b/compiler/rustc_query_system/src/lib.rs index 7a50a9534c2..ba7a631fb54 100644 --- a/compiler/rustc_query_system/src/lib.rs +++ b/compiler/rustc_query_system/src/lib.rs @@ -5,6 +5,7 @@ #![feature(hash_raw_entry)] #![feature(let_chains)] #![feature(min_specialization)] +#![warn(unreachable_pub)] // tidy-alphabetical-end pub mod cache; diff --git a/compiler/rustc_resolve/src/build_reduced_graph.rs b/compiler/rustc_resolve/src/build_reduced_graph.rs index 2ac7b200452..3ea782b62f1 100644 --- a/compiler/rustc_resolve/src/build_reduced_graph.rs +++ b/compiler/rustc_resolve/src/build_reduced_graph.rs @@ -260,6 +260,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { | DefKind::LifetimeParam | DefKind::GlobalAsm | DefKind::Closure + | DefKind::SyntheticCoroutineBody | DefKind::Impl { .. }, _, ) diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index 02fdc1ae668..8ffd00d1b2e 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -21,6 +21,7 @@ #![feature(let_chains)] #![feature(rustc_attrs)] #![feature(rustdoc_internals)] +#![warn(unreachable_pub)] // tidy-alphabetical-end use std::cell::{Cell, RefCell}; diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index 95d171409d8..fbdb3cb1534 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -22,7 +22,9 @@ use rustc_feature::UnstableFeatures; use rustc_macros::{Decodable, Encodable, HashStable_Generic}; use rustc_span::edition::{Edition, DEFAULT_EDITION, EDITION_NAME_LIST, LATEST_STABLE_EDITION}; use rustc_span::source_map::FilePathMapping; -use rustc_span::{FileName, FileNameDisplayPreference, RealFileName, SourceFileHashAlgorithm}; +use rustc_span::{ + sym, FileName, FileNameDisplayPreference, RealFileName, SourceFileHashAlgorithm, Symbol, +}; use rustc_target::spec::{ FramePointer, LinkSelfContainedComponents, LinkerFeatures, SplitDebuginfo, Target, TargetTriple, }; @@ -402,6 +404,23 @@ impl LocationDetail { } } +/// Values for the `-Z fmt-debug` flag. +#[derive(Copy, Clone, PartialEq, Hash, Debug)] +pub enum FmtDebug { + /// Derive fully-featured implementation + Full, + /// Print only type name, without fields + Shallow, + /// `#[derive(Debug)]` and `{:?}` are no-ops + None, +} + +impl FmtDebug { + pub(crate) fn all() -> [Symbol; 3] { + [sym::full, sym::none, sym::shallow] + } +} + #[derive(Clone, PartialEq, Hash, Debug)] pub enum SwitchWithOptPath { Enabled(Option<PathBuf>), @@ -2893,6 +2912,7 @@ pub enum PpHirMode { } #[derive(Copy, Clone, PartialEq, Debug)] +/// Pretty print mode pub enum PpMode { /// Options that print the source code, i.e. /// `-Zunpretty=normal` and `-Zunpretty=expanded` @@ -2993,7 +3013,7 @@ pub(crate) mod dep_tracking { use super::{ BranchProtection, CFGuard, CFProtection, CollapseMacroDebuginfo, CoverageOptions, - CrateType, DebugInfo, DebugInfoCompression, ErrorOutputType, FunctionReturn, + CrateType, DebugInfo, DebugInfoCompression, ErrorOutputType, FmtDebug, FunctionReturn, InliningThreshold, InstrumentCoverage, InstrumentXRay, LinkerPluginLto, LocationDetail, LtoCli, NextSolverConfig, OomStrategy, OptLevel, OutFileName, OutputType, OutputTypes, PatchableFunctionEntry, Polonius, RemapPathScopeComponents, ResolveDocLinks, @@ -3087,6 +3107,7 @@ pub(crate) mod dep_tracking { OutputType, RealFileName, LocationDetail, + FmtDebug, BranchProtection, OomStrategy, LanguageIdentifier, diff --git a/compiler/rustc_session/src/config/cfg.rs b/compiler/rustc_session/src/config/cfg.rs index a64b1e21e9e..0fa776ecb5c 100644 --- a/compiler/rustc_session/src/config/cfg.rs +++ b/compiler/rustc_session/src/config/cfg.rs @@ -31,7 +31,7 @@ use rustc_span::symbol::{sym, Symbol}; use rustc_target::abi::Align; use rustc_target::spec::{PanicStrategy, RelocModel, SanitizerSet, Target, TargetTriple, TARGETS}; -use crate::config::CrateType; +use crate::config::{CrateType, FmtDebug}; use crate::Session; /// The parsed `--cfg` options that define the compilation environment of the @@ -142,6 +142,7 @@ pub(crate) fn disallow_cfgs(sess: &Session, user_cfgs: &Cfg) { | (sym::target_has_atomic_equal_alignment, Some(_)) | (sym::target_has_atomic_load_store, Some(_)) | (sym::target_thread_local, None) => disallow(cfg, "--target"), + (sym::fmt_debug, None | Some(_)) => disallow(cfg, "-Z fmt-debug"), _ => {} } } @@ -179,6 +180,20 @@ pub(crate) fn default_configuration(sess: &Session) -> Cfg { ins_none!(sym::debug_assertions); } + if sess.is_nightly_build() { + match sess.opts.unstable_opts.fmt_debug { + FmtDebug::Full => { + ins_sym!(sym::fmt_debug, sym::full); + } + FmtDebug::Shallow => { + ins_sym!(sym::fmt_debug, sym::shallow); + } + FmtDebug::None => { + ins_sym!(sym::fmt_debug, sym::none); + } + } + } + if sess.overflow_checks() { ins_none!(sym::overflow_checks); } @@ -326,6 +341,8 @@ impl CheckCfg { ins!(sym::debug_assertions, no_values); + ins!(sym::fmt_debug, empty_values).extend(FmtDebug::all()); + // These four are never set by rustc, but we set them anyway; they // should not trigger the lint because `cargo clippy`, `cargo doc`, // `cargo test`, `cargo miri run` and `cargo fmt` (respectively) diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index 23231fbffbf..4492ad09357 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -408,6 +408,7 @@ mod desc { pub const parse_linker_plugin_lto: &str = "either a boolean (`yes`, `no`, `on`, `off`, etc), or the path to the linker plugin"; pub const parse_location_detail: &str = "either `none`, or a comma separated list of location details to track: `file`, `line`, or `column`"; + pub const parse_fmt_debug: &str = "either `full`, `shallow`, or `none`"; pub const parse_switch_with_opt_path: &str = "an optional path to the profiling data output directory"; pub const parse_merge_functions: &str = "one of: `disabled`, `trampolines`, or `aliases`"; @@ -589,6 +590,16 @@ mod parse { } } + pub(crate) fn parse_fmt_debug(opt: &mut FmtDebug, v: Option<&str>) -> bool { + *opt = match v { + Some("full") => FmtDebug::Full, + Some("shallow") => FmtDebug::Shallow, + Some("none") => FmtDebug::None, + _ => return false, + }; + true + } + pub(crate) fn parse_location_detail(ld: &mut LocationDetail, v: Option<&str>) -> bool { if let Some(v) = v { ld.line = false; @@ -1724,6 +1735,9 @@ options! { flatten_format_args: bool = (true, parse_bool, [TRACKED], "flatten nested format_args!() and literals into a simplified format_args!() call \ (default: yes)"), + fmt_debug: FmtDebug = (FmtDebug::Full, parse_fmt_debug, [TRACKED], + "how detailed `#[derive(Debug)]` should be. `full` prints types recursively, \ + `shallow` prints only type names, `none` prints nothing and disables `{:?}`. (default: `full`)"), force_unstable_if_unmarked: bool = (false, parse_bool, [TRACKED], "force all crates to be `rustc_private` unstable (default: no)"), fuel: Option<(String, u64)> = (None, parse_optimization_fuel, [TRACKED], @@ -1797,6 +1811,8 @@ options! { "link the `.rlink` file generated by `-Z no-link` (default: no)"), linker_features: LinkerFeaturesCli = (LinkerFeaturesCli::default(), parse_linker_features, [UNTRACKED], "a comma-separated list of linker features to enable (+) or disable (-): `lld`"), + lint_llvm_ir: bool = (false, parse_bool, [TRACKED], + "lint LLVM IR (default: no)"), lint_mir: bool = (false, parse_bool, [UNTRACKED], "lint MIR before and after each transformation"), llvm_module_flag: Vec<(String, u32, String)> = (Vec::new(), parse_llvm_module_flag, [TRACKED], diff --git a/compiler/rustc_smir/src/rustc_smir/convert/ty.rs b/compiler/rustc_smir/src/rustc_smir/convert/ty.rs index 332fe22d869..9afd732486c 100644 --- a/compiler/rustc_smir/src/rustc_smir/convert/ty.rs +++ b/compiler/rustc_smir/src/rustc_smir/convert/ty.rs @@ -851,7 +851,6 @@ impl<'tcx> Stable<'tcx> for ty::Instance<'tcx> { | ty::InstanceKind::FnPtrAddrShim(..) | ty::InstanceKind::ClosureOnceShim { .. } | ty::InstanceKind::ConstructCoroutineInClosureShim { .. } - | ty::InstanceKind::CoroutineKindShim { .. } | ty::InstanceKind::ThreadLocalShim(..) | ty::InstanceKind::DropGlue(..) | ty::InstanceKind::CloneShim(..) diff --git a/compiler/rustc_smir/src/rustc_smir/mod.rs b/compiler/rustc_smir/src/rustc_smir/mod.rs index 41e9698242b..9b27b94fb5a 100644 --- a/compiler/rustc_smir/src/rustc_smir/mod.rs +++ b/compiler/rustc_smir/src/rustc_smir/mod.rs @@ -114,7 +114,9 @@ pub(crate) fn new_item_kind(kind: DefKind) -> ItemKind { | DefKind::GlobalAsm => { unreachable!("Not a valid item kind: {kind:?}"); } - DefKind::Closure | DefKind::AssocFn | DefKind::Fn => ItemKind::Fn, + DefKind::Closure | DefKind::AssocFn | DefKind::Fn | DefKind::SyntheticCoroutineBody => { + ItemKind::Fn + } DefKind::Const | DefKind::InlineConst | DefKind::AssocConst | DefKind::AnonConst => { ItemKind::Const } diff --git a/compiler/rustc_span/src/lib.rs b/compiler/rustc_span/src/lib.rs index 35fe28c5d42..7b020f11cdd 100644 --- a/compiler/rustc_span/src/lib.rs +++ b/compiler/rustc_span/src/lib.rs @@ -26,7 +26,6 @@ #![feature(let_chains)] #![feature(min_specialization)] #![feature(negative_impls)] -#![feature(new_uninit)] #![feature(read_buf)] #![feature(round_char_boundary)] #![feature(rustc_attrs)] diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 2957105288b..16f5e55835e 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -356,6 +356,7 @@ symbols! { _task_context, a32, aarch64_target_feature, + aarch64_unstable_target_feature, aarch64_ver_target_feature, abi, abi_amdgpu_kernel, @@ -535,6 +536,7 @@ symbols! { cfg_attr_multi, cfg_doctest, cfg_eval, + cfg_fmt_debug, cfg_hide, cfg_overflow_checks, cfg_panic, @@ -894,6 +896,7 @@ symbols! { fmaf32, fmaf64, fmt, + fmt_debug, fmul_algebraic, fmul_fast, fn_align, @@ -937,6 +940,7 @@ symbols! { fs_create_dir, fsub_algebraic, fsub_fast, + full, fundamental, fused_iterator, future, @@ -1280,6 +1284,7 @@ symbols! { new_binary, new_const, new_debug, + new_debug_noop, new_display, new_lower_exp, new_lower_hex, @@ -1714,6 +1719,7 @@ symbols! { semitransparent, sha512_sm_x86, shadow_call_stack, + shallow, shl, shl_assign, shorter_tail_lifetimes, @@ -1852,6 +1858,7 @@ symbols! { stringify, struct_field_attributes, struct_inherit, + struct_target_features, struct_variant, structural_match, structural_peq, @@ -1896,6 +1903,7 @@ symbols! { three_way_compare, thumb2, thumb_mode: "thumb-mode", + time, tmm_reg, to_owned_method, to_string, diff --git a/compiler/rustc_symbol_mangling/src/legacy.rs b/compiler/rustc_symbol_mangling/src/legacy.rs index 0f91684a3a4..59ccd6dff85 100644 --- a/compiler/rustc_symbol_mangling/src/legacy.rs +++ b/compiler/rustc_symbol_mangling/src/legacy.rs @@ -92,9 +92,6 @@ pub(super) fn mangle<'tcx>( .write_str(if receiver_by_ref { "{{by-move-shim}}" } else { "{{by-ref-shim}}" }) .unwrap(); } - ty::InstanceKind::CoroutineKindShim { .. } => { - printer.write_str("{{by-move-body-shim}}").unwrap(); - } _ => {} } diff --git a/compiler/rustc_symbol_mangling/src/v0.rs b/compiler/rustc_symbol_mangling/src/v0.rs index 3a606f244e3..75f4499352b 100644 --- a/compiler/rustc_symbol_mangling/src/v0.rs +++ b/compiler/rustc_symbol_mangling/src/v0.rs @@ -56,7 +56,6 @@ pub(super) fn mangle<'tcx>( ty::InstanceKind::ConstructCoroutineInClosureShim { receiver_by_ref: false, .. } => { Some("by_ref") } - ty::InstanceKind::CoroutineKindShim { .. } => Some("by_move_body"), _ => None, }; diff --git a/compiler/rustc_target/src/abi/call/mod.rs b/compiler/rustc_target/src/abi/call/mod.rs index c1ddfcb2f90..082c169b210 100644 --- a/compiler/rustc_target/src/abi/call/mod.rs +++ b/compiler/rustc_target/src/abi/call/mod.rs @@ -745,10 +745,25 @@ impl<'a, Ty> ArgAbi<'a, Ty> { /// Checks if these two `ArgAbi` are equal enough to be considered "the same for all /// function call ABIs". - pub fn eq_abi(&self, other: &Self) -> bool { + pub fn eq_abi(&self, other: &Self) -> bool + where + Ty: PartialEq, + { // Ideally we'd just compare the `mode`, but that is not enough -- for some modes LLVM will look // at the type. - self.layout.eq_abi(&other.layout) && self.mode.eq_abi(&other.mode) + self.layout.eq_abi(&other.layout) && self.mode.eq_abi(&other.mode) && { + // `fn_arg_sanity_check` accepts `PassMode::Direct` for some aggregates. + // That elevates any type difference to an ABI difference since we just use the + // full Rust type as the LLVM argument/return type. + if matches!(self.mode, PassMode::Direct(..)) + && matches!(self.layout.abi, Abi::Aggregate { .. }) + { + // For aggregates in `Direct` mode to be compatible, the types need to be equal. + self.layout.ty == other.layout.ty + } else { + true + } + } } } diff --git a/compiler/rustc_target/src/spec/abi/mod.rs b/compiler/rustc_target/src/spec/abi/mod.rs index 0d61345a70e..cc383f88fbc 100644 --- a/compiler/rustc_target/src/spec/abi/mod.rs +++ b/compiler/rustc_target/src/spec/abi/mod.rs @@ -53,6 +53,8 @@ pub enum Abi { }, RustIntrinsic, RustCall, + /// *Not* a stable ABI, just directly use the Rust types to describe the ABI for LLVM. Even + /// normally ABI-compatible Rust types can become ABI-incompatible with this ABI! Unadjusted, /// For things unlikely to be called, where reducing register pressure in /// `extern "Rust"` callers is worth paying extra cost in the callee. diff --git a/compiler/rustc_target/src/spec/targets/aarch64_unknown_trusty.rs b/compiler/rustc_target/src/spec/targets/aarch64_unknown_trusty.rs index 1525faf9b7e..9fd7c246498 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_unknown_trusty.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_unknown_trusty.rs @@ -7,7 +7,7 @@ pub fn target() -> Target { llvm_target: "aarch64-unknown-unknown-musl".into(), metadata: crate::spec::TargetMetadata { description: Some("ARM64 Trusty".into()), - tier: Some(2), + tier: Some(3), host_tools: Some(false), std: Some(false), }, diff --git a/compiler/rustc_target/src/spec/targets/armv7_unknown_trusty.rs b/compiler/rustc_target/src/spec/targets/armv7_unknown_trusty.rs index ae73de5e64d..889cc201569 100644 --- a/compiler/rustc_target/src/spec/targets/armv7_unknown_trusty.rs +++ b/compiler/rustc_target/src/spec/targets/armv7_unknown_trusty.rs @@ -8,7 +8,7 @@ pub fn target() -> Target { llvm_target: "armv7-unknown-unknown-gnueabi".into(), metadata: crate::spec::TargetMetadata { description: Some("Armv7-A Trusty".into()), - tier: Some(2), + tier: Some(3), host_tools: Some(false), std: Some(false), }, diff --git a/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_none_elf.rs b/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_none_elf.rs index bfd88bd042e..61226809e52 100644 --- a/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_none_elf.rs +++ b/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_none_elf.rs @@ -28,7 +28,7 @@ pub fn target() -> Target { code_model: Some(CodeModel::Medium), emit_debug_gdb_scripts: false, eh_frame_header: false, - supported_sanitizers: SanitizerSet::KERNELADDRESS, + supported_sanitizers: SanitizerSet::KERNELADDRESS | SanitizerSet::SHADOWCALLSTACK, ..Default::default() }, } diff --git a/compiler/rustc_target/src/spec/targets/riscv64imac_unknown_none_elf.rs b/compiler/rustc_target/src/spec/targets/riscv64imac_unknown_none_elf.rs index fa3f1eff457..b7444df04cd 100644 --- a/compiler/rustc_target/src/spec/targets/riscv64imac_unknown_none_elf.rs +++ b/compiler/rustc_target/src/spec/targets/riscv64imac_unknown_none_elf.rs @@ -27,7 +27,7 @@ pub fn target() -> Target { code_model: Some(CodeModel::Medium), emit_debug_gdb_scripts: false, eh_frame_header: false, - supported_sanitizers: SanitizerSet::KERNELADDRESS, + supported_sanitizers: SanitizerSet::KERNELADDRESS | SanitizerSet::SHADOWCALLSTACK, ..Default::default() }, } diff --git a/compiler/rustc_target/src/target_features.rs b/compiler/rustc_target/src/target_features.rs index da66ba270b3..8319cb880cc 100644 --- a/compiler/rustc_target/src/target_features.rs +++ b/compiler/rustc_target/src/target_features.rs @@ -99,6 +99,8 @@ const AARCH64_ALLOWED_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ ("bti", Stable, &[]), // FEAT_CRC ("crc", Stable, &[]), + // FEAT_CSSC + ("cssc", Unstable(sym::aarch64_unstable_target_feature), &[]), // FEAT_DIT ("dit", Stable, &[]), // FEAT_DotProd @@ -107,21 +109,37 @@ const AARCH64_ALLOWED_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ ("dpb", Stable, &[]), // FEAT_DPB2 ("dpb2", Stable, &["dpb"]), + // FEAT_ECV + ("ecv", Unstable(sym::aarch64_unstable_target_feature), &[]), // FEAT_F32MM ("f32mm", Stable, &["sve"]), // FEAT_F64MM ("f64mm", Stable, &["sve"]), + // FEAT_FAMINMAX + ("faminmax", Unstable(sym::aarch64_unstable_target_feature), &[]), // FEAT_FCMA ("fcma", Stable, &["neon"]), // FEAT_FHM ("fhm", Stable, &["fp16"]), // FEAT_FLAGM ("flagm", Stable, &[]), + // FEAT_FLAGM2 + ("flagm2", Unstable(sym::aarch64_unstable_target_feature), &[]), // FEAT_FP16 // Rust ties FP and Neon: https://github.com/rust-lang/rust/pull/91608 ("fp16", Stable, &["neon"]), + // FEAT_FP8 + ("fp8", Unstable(sym::aarch64_unstable_target_feature), &["faminmax", "lut", "bf16"]), + // FEAT_FP8DOT2 + ("fp8dot2", Unstable(sym::aarch64_unstable_target_feature), &["fp8dot4"]), + // FEAT_FP8DOT4 + ("fp8dot4", Unstable(sym::aarch64_unstable_target_feature), &["fp8fma"]), + // FEAT_FP8FMA + ("fp8fma", Unstable(sym::aarch64_unstable_target_feature), &["fp8"]), // FEAT_FRINTTS ("frintts", Stable, &[]), + // FEAT_HBC + ("hbc", Unstable(sym::aarch64_unstable_target_feature), &[]), // FEAT_I8MM ("i8mm", Stable, &[]), // FEAT_JSCVT @@ -131,6 +149,14 @@ const AARCH64_ALLOWED_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ ("lor", Stable, &[]), // FEAT_LSE ("lse", Stable, &[]), + // FEAT_LSE128 + ("lse128", Unstable(sym::aarch64_unstable_target_feature), &["lse"]), + // FEAT_LSE2 + ("lse2", Unstable(sym::aarch64_unstable_target_feature), &[]), + // FEAT_LUT + ("lut", Unstable(sym::aarch64_unstable_target_feature), &[]), + // FEAT_MOPS + ("mops", Unstable(sym::aarch64_unstable_target_feature), &[]), // FEAT_MTE & FEAT_MTE2 ("mte", Stable, &[]), // FEAT_AdvSimd & FEAT_FP @@ -143,14 +169,16 @@ const AARCH64_ALLOWED_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ ("pan", Stable, &[]), // FEAT_PMUv3 ("pmuv3", Stable, &[]), - // FEAT_RAND + // FEAT_RNG ("rand", Stable, &[]), // FEAT_RAS & FEAT_RASv1p1 ("ras", Stable, &[]), - // FEAT_RCPC + // FEAT_LRCPC ("rcpc", Stable, &[]), - // FEAT_RCPC2 + // FEAT_LRCPC2 ("rcpc2", Stable, &["rcpc"]), + // FEAT_LRCPC3 + ("rcpc3", Unstable(sym::aarch64_unstable_target_feature), &["rcpc2"]), // FEAT_RDM ("rdm", Stable, &["neon"]), // FEAT_SB @@ -161,10 +189,36 @@ const AARCH64_ALLOWED_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ ("sha3", Stable, &["sha2"]), // FEAT_SM3 & FEAT_SM4 ("sm4", Stable, &["neon"]), + // FEAT_SME + ("sme", Unstable(sym::aarch64_unstable_target_feature), &["bf16"]), + // FEAT_SME_F16F16 + ("sme-f16f16", Unstable(sym::aarch64_unstable_target_feature), &["sme2"]), + // FEAT_SME_F64F64 + ("sme-f64f64", Unstable(sym::aarch64_unstable_target_feature), &["sme"]), + // FEAT_SME_F8F16 + ("sme-f8f16", Unstable(sym::aarch64_unstable_target_feature), &["sme-f8f32"]), + // FEAT_SME_F8F32 + ("sme-f8f32", Unstable(sym::aarch64_unstable_target_feature), &["sme2", "fp8"]), + // FEAT_SME_FA64 + ("sme-fa64", Unstable(sym::aarch64_unstable_target_feature), &["sme", "sve2"]), + // FEAT_SME_I16I64 + ("sme-i16i64", Unstable(sym::aarch64_unstable_target_feature), &["sme"]), + // FEAT_SME_LUTv2 + ("sme-lutv2", Unstable(sym::aarch64_unstable_target_feature), &[]), + // FEAT_SME2 + ("sme2", Unstable(sym::aarch64_unstable_target_feature), &["sme"]), + // FEAT_SME2p1 + ("sme2p1", Unstable(sym::aarch64_unstable_target_feature), &["sme2"]), // FEAT_SPE ("spe", Stable, &[]), // FEAT_SSBS & FEAT_SSBS2 ("ssbs", Stable, &[]), + // FEAT_SSVE_FP8FDOT2 + ("ssve-fp8dot2", Unstable(sym::aarch64_unstable_target_feature), &["ssve-fp8dot4"]), + // FEAT_SSVE_FP8FDOT4 + ("ssve-fp8dot4", Unstable(sym::aarch64_unstable_target_feature), &["ssve-fp8fma"]), + // FEAT_SSVE_FP8FMA + ("ssve-fp8fma", Unstable(sym::aarch64_unstable_target_feature), &["sme2", "fp8"]), // FEAT_SVE // It was decided that SVE requires Neon: https://github.com/rust-lang/rust/pull/91608 // @@ -173,9 +227,11 @@ const AARCH64_ALLOWED_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ // // "For backwards compatibility, Neon and VFP are required in the latest architectures." ("sve", Stable, &["neon"]), + // FEAT_SVE_B16B16 (SVE or SME Instructions) + ("sve-b16b16", Unstable(sym::aarch64_unstable_target_feature), &["bf16"]), // FEAT_SVE2 ("sve2", Stable, &["sve"]), - // FEAT_SVE2_AES + // FEAT_SVE_AES & FEAT_SVE_PMULL128 ("sve2-aes", Stable, &["sve2", "aes"]), // FEAT_SVE2_BitPerm ("sve2-bitperm", Stable, &["sve2"]), @@ -183,6 +239,8 @@ const AARCH64_ALLOWED_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ ("sve2-sha3", Stable, &["sve2", "sha3"]), // FEAT_SVE2_SM4 ("sve2-sm4", Stable, &["sve2", "sm4"]), + // FEAT_SVE2p1 + ("sve2p1", Unstable(sym::aarch64_unstable_target_feature), &["sve2"]), // FEAT_TME ("tme", Stable, &[]), ( @@ -199,9 +257,19 @@ const AARCH64_ALLOWED_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ ("v8.4a", Unstable(sym::aarch64_ver_target_feature), &["v8.3a", "dotprod", "dit", "flagm"]), ("v8.5a", Unstable(sym::aarch64_ver_target_feature), &["v8.4a", "ssbs", "sb", "dpb2", "bti"]), ("v8.6a", Unstable(sym::aarch64_ver_target_feature), &["v8.5a", "bf16", "i8mm"]), - ("v8.7a", Unstable(sym::aarch64_ver_target_feature), &[]), + ("v8.7a", Unstable(sym::aarch64_ver_target_feature), &["v8.6a", "wfxt"]), + ("v8.8a", Unstable(sym::aarch64_ver_target_feature), &["v8.7a", "hbc", "mops"]), + ("v8.9a", Unstable(sym::aarch64_ver_target_feature), &["v8.8a", "cssc"]), + ("v9.1a", Unstable(sym::aarch64_ver_target_feature), &["v9a", "v8.6a"]), + ("v9.2a", Unstable(sym::aarch64_ver_target_feature), &["v9.1a", "v8.7a"]), + ("v9.3a", Unstable(sym::aarch64_ver_target_feature), &["v9.2a", "v8.8a"]), + ("v9.4a", Unstable(sym::aarch64_ver_target_feature), &["v9.3a", "v8.9a"]), + ("v9.5a", Unstable(sym::aarch64_ver_target_feature), &["v9.4a"]), + ("v9a", Unstable(sym::aarch64_ver_target_feature), &["v8.5a", "sve2"]), // FEAT_VHE ("vh", Stable, &[]), + // FEAT_WFxT + ("wfxt", Unstable(sym::aarch64_unstable_target_feature), &[]), // tidy-alphabetical-end ]; diff --git a/compiler/rustc_trait_selection/messages.ftl b/compiler/rustc_trait_selection/messages.ftl index 137850f31d3..3ddd23924b5 100644 --- a/compiler/rustc_trait_selection/messages.ftl +++ b/compiler/rustc_trait_selection/messages.ftl @@ -446,6 +446,8 @@ trait_selection_type_annotations_needed = {$source_kind -> } .label = type must be known at this point +trait_selection_type_annotations_needed_error_time = this is an inference error on crate `time` caused by an API change in Rust 1.80.0; update `time` to version `>=0.3.35` by calling `cargo update` + trait_selection_types_declared_different = these two types are declared with different lifetimes... trait_selection_unable_to_construct_constant_value = unable to construct a constant value for the unevaluated constant {$unevaluated} diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs index 173671059ca..53f013ac153 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs @@ -6,7 +6,7 @@ use rustc_errors::codes::*; use rustc_errors::{Diag, IntoDiagArg}; use rustc_hir as hir; use rustc_hir::def::{CtorOf, DefKind, Namespace, Res}; -use rustc_hir::def_id::{DefId, LocalDefId}; +use rustc_hir::def_id::{DefId, LocalDefId, LOCAL_CRATE}; use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::{Body, Closure, Expr, ExprKind, FnRetTy, HirId, LetStmt, LocalSource}; use rustc_middle::bug; @@ -18,7 +18,7 @@ use rustc_middle::ty::{ TypeFoldable, TypeFolder, TypeSuperFoldable, TypeckResults, }; use rustc_span::symbol::{sym, Ident}; -use rustc_span::{BytePos, Span, DUMMY_SP}; +use rustc_span::{BytePos, FileName, Span, DUMMY_SP}; use crate::error_reporting::TypeErrCtxt; use crate::errors::{ @@ -384,6 +384,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { bad_label, was_written: false, path: Default::default(), + time_version: false, }), TypeAnnotationNeeded::E0283 => self.dcx().create_err(AmbiguousImpl { span, @@ -577,6 +578,10 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } } } + + let time_version = + self.detect_old_time_crate_version(failure_span, &kind, &mut infer_subdiags); + match error_code { TypeAnnotationNeeded::E0282 => self.dcx().create_err(AnnotationRequired { span, @@ -588,6 +593,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { bad_label: None, was_written: path.is_some(), path: path.unwrap_or_default(), + time_version, }), TypeAnnotationNeeded::E0283 => self.dcx().create_err(AmbiguousImpl { span, @@ -613,6 +619,42 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { }), } } + + /// Detect the inference regression on crate `time` <= 0.3.35 and emit a more targeted error. + /// <https://github.com/rust-lang/rust/issues/127343> + // FIXME: we should figure out a more generic version of doing this, ideally in cargo itself. + fn detect_old_time_crate_version( + &self, + span: Option<Span>, + kind: &InferSourceKind<'_>, + // We will clear the non-actionable suggestion from the error to reduce noise. + infer_subdiags: &mut Vec<SourceKindSubdiag<'_>>, + ) -> bool { + // FIXME(#129461): We are time-boxing this code in the compiler. It'll start failing + // compilation once we promote 1.89 to beta, which will happen in 9 months from now. + #[cfg(not(version("1.89")))] + const fn version_check() {} + #[cfg(version("1.89"))] + const fn version_check() { + panic!("remove this check as presumably the ecosystem has moved from needing it"); + } + const { version_check() }; + // Only relevant when building the `time` crate. + if self.infcx.tcx.crate_name(LOCAL_CRATE) == sym::time + && let Some(span) = span + && let InferSourceKind::LetBinding { pattern_name, .. } = kind + && let Some(name) = pattern_name + && name.as_str() == "items" + && let FileName::Real(file) = self.infcx.tcx.sess.source_map().span_to_filename(span) + { + let path = file.local_path_if_available().to_string_lossy(); + if path.contains("format_description") && path.contains("parse") { + infer_subdiags.clear(); + return true; + } + } + false + } } #[derive(Debug)] 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 9f0282319ec..def9d6e9a31 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 @@ -438,6 +438,8 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { let is_target_feature_fn = if let ty::FnDef(def_id, _) = *leaf_trait_ref.skip_binder().self_ty().kind() { + // FIXME(struct_target_features): should a function that inherits + // target_features through arguments implement Fn traits? !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty() } else { false diff --git a/compiler/rustc_trait_selection/src/errors.rs b/compiler/rustc_trait_selection/src/errors.rs index 5384084f6d7..ebaec0b9059 100644 --- a/compiler/rustc_trait_selection/src/errors.rs +++ b/compiler/rustc_trait_selection/src/errors.rs @@ -205,6 +205,8 @@ pub struct AnnotationRequired<'a> { #[note(trait_selection_full_type_written)] pub was_written: bool, pub path: PathBuf, + #[note(trait_selection_type_annotations_needed_error_time)] + pub time_version: bool, } // Copy of `AnnotationRequired` for E0283 diff --git a/compiler/rustc_trait_selection/src/lib.rs b/compiler/rustc_trait_selection/src/lib.rs index 1bd66266936..c98d6c5f1df 100644 --- a/compiler/rustc_trait_selection/src/lib.rs +++ b/compiler/rustc_trait_selection/src/lib.rs @@ -19,6 +19,7 @@ #![feature(assert_matches)] #![feature(associated_type_defaults)] #![feature(box_patterns)] +#![feature(cfg_version)] #![feature(control_flow_enum)] #![feature(extract_if)] #![feature(if_let_guard)] diff --git a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs index cb8deeaedb6..a21feec4b1a 100644 --- a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs +++ b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs @@ -545,6 +545,8 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { // Provide an impl for suitable functions, rejecting `#[target_feature]` functions (RFC 2396). ty::FnDef(def_id, args) => { let tcx = self.tcx(); + // FIXME(struct_target_features): should a function that inherits target_features + // through an argument implement Fn traits? if tcx.fn_sig(def_id).skip_binder().is_fn_trait_compatible() && tcx.codegen_fn_attrs(def_id).target_features.is_empty() { diff --git a/compiler/rustc_ty_utils/src/abi.rs b/compiler/rustc_ty_utils/src/abi.rs index 7e3c30f2383..16cd147b7d4 100644 --- a/compiler/rustc_ty_utils/src/abi.rs +++ b/compiler/rustc_ty_utils/src/abi.rs @@ -169,39 +169,6 @@ fn fn_sig_for_fn_abi<'tcx>( kind: ty::BoundRegionKind::BrEnv, }; - let mut ty = ty; - // When this `Closure` comes from a `CoroutineKindShim`, - // make sure we respect the `target_kind` in that shim. - // FIXME(async_closures): This shouldn't be needed, and we should be populating - // a separate def-id for these bodies. - if let InstanceKind::CoroutineKindShim { .. } = instance.def { - // Grab the parent coroutine-closure. It has the same args for the purposes - // of instantiation, so this will be okay to do. - let ty::CoroutineClosure(_, coroutine_closure_args) = *tcx - .instantiate_and_normalize_erasing_regions( - args, - param_env, - tcx.type_of(tcx.parent(did)), - ) - .kind() - else { - bug!("CoroutineKindShim comes from calling a coroutine-closure"); - }; - let coroutine_closure_args = coroutine_closure_args.as_coroutine_closure(); - ty = tcx.instantiate_bound_regions_with_erased( - coroutine_closure_args.coroutine_closure_sig().map_bound(|sig| { - sig.to_coroutine_given_kind_and_upvars( - tcx, - coroutine_closure_args.parent_args(), - did, - ty::ClosureKind::FnOnce, - tcx.lifetimes.re_erased, - coroutine_closure_args.tupled_upvars_ty(), - coroutine_closure_args.coroutine_captures_by_ref_ty(), - ) - }), - ); - } let env_ty = Ty::new_mut_ref(tcx, ty::Region::new_bound(tcx, ty::INNERMOST, br), ty); let pin_did = tcx.require_lang_item(LangItem::Pin, None); diff --git a/compiler/rustc_ty_utils/src/implied_bounds.rs b/compiler/rustc_ty_utils/src/implied_bounds.rs index 8812260b3af..70321a071a2 100644 --- a/compiler/rustc_ty_utils/src/implied_bounds.rs +++ b/compiler/rustc_ty_utils/src/implied_bounds.rs @@ -144,7 +144,8 @@ fn assumed_wf_types<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx [(Ty<' | DefKind::Field | DefKind::LifetimeParam | DefKind::GlobalAsm - | DefKind::Closure => ty::List::empty(), + | DefKind::Closure + | DefKind::SyntheticCoroutineBody => ty::List::empty(), } } diff --git a/compiler/rustc_ty_utils/src/opaque_types.rs b/compiler/rustc_ty_utils/src/opaque_types.rs index 6680b451b7c..e899284674c 100644 --- a/compiler/rustc_ty_utils/src/opaque_types.rs +++ b/compiler/rustc_ty_utils/src/opaque_types.rs @@ -348,7 +348,8 @@ fn opaque_types_defined_by<'tcx>( | DefKind::Field | DefKind::LifetimeParam | DefKind::GlobalAsm - | DefKind::Impl { .. } => {} + | DefKind::Impl { .. } + | DefKind::SyntheticCoroutineBody => {} // Closures and coroutines are type checked with their parent, so we need to allow all // opaques from the closure signature *and* from the parent body. DefKind::Closure | DefKind::InlineConst => { diff --git a/compiler/rustc_ty_utils/src/sig_types.rs b/compiler/rustc_ty_utils/src/sig_types.rs index 568b9383ffb..6f1cbb0fee7 100644 --- a/compiler/rustc_ty_utils/src/sig_types.rs +++ b/compiler/rustc_ty_utils/src/sig_types.rs @@ -87,7 +87,7 @@ pub fn walk_types<'tcx, V: SpannedTypeVisitor<'tcx>>( // These are not part of a public API, they can only appear as hidden types, and there // the interesting parts are solely in the signature of the containing item's opaque type // or dyn type. - DefKind::InlineConst | DefKind::Closure => {} + DefKind::InlineConst | DefKind::Closure | DefKind::SyntheticCoroutineBody => {} DefKind::Impl { of_trait } => { if of_trait { let span = tcx.hir_node_by_def_id(item).expect_item().expect_impl().of_trait.unwrap().path.span; diff --git a/compiler/stable_mir/src/mir/visit.rs b/compiler/stable_mir/src/mir/visit.rs index 50d7bae21db..aeae866e9d3 100644 --- a/compiler/stable_mir/src/mir/visit.rs +++ b/compiler/stable_mir/src/mir/visit.rs @@ -465,6 +465,22 @@ impl Location { } } +/// Location of the statement at the given index for a given basic block. Assumes that `stmt_idx` +/// and `bb_idx` are valid for a given body. +pub fn statement_location(body: &Body, bb_idx: &BasicBlockIdx, stmt_idx: usize) -> Location { + let bb = &body.blocks[*bb_idx]; + let stmt = &bb.statements[stmt_idx]; + Location(stmt.span) +} + +/// Location of the terminator for a given basic block. Assumes that `bb_idx` is valid for a given +/// body. +pub fn terminator_location(body: &Body, bb_idx: &BasicBlockIdx) -> Location { + let bb = &body.blocks[*bb_idx]; + let terminator = &bb.terminator; + Location(terminator.span) +} + /// Reference to a place used to represent a partial projection. pub struct PlaceRef<'a> { pub local: Local, diff --git a/library/Cargo.lock b/library/Cargo.lock index aa22181a463..54ad052c523 100644 --- a/library/Cargo.lock +++ b/library/Cargo.lock @@ -58,9 +58,9 @@ dependencies = [ [[package]] name = "compiler_builtins" -version = "0.1.121" +version = "0.1.123" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce956e6dc07082ec481f0935a51e83b343f8ca51be560452c0ebf830d0bdf5a5" +checksum = "b47fcbecb558bdad78c7d3a998523c60a50dd6cd046d5fe74163e309e878fff7" dependencies = [ "cc", "rustc-std-workspace-core", diff --git a/library/alloc/Cargo.toml b/library/alloc/Cargo.toml index a39a0a6ce0e..4365bcc4ad0 100644 --- a/library/alloc/Cargo.toml +++ b/library/alloc/Cargo.toml @@ -10,7 +10,7 @@ edition = "2021" [dependencies] core = { path = "../core" } -compiler_builtins = { version = "0.1.121", features = ['rustc-dep-of-std'] } +compiler_builtins = { version = "0.1.123", features = ['rustc-dep-of-std'] } [dev-dependencies] rand = { version = "0.8.5", default-features = false, features = ["alloc"] } diff --git a/library/alloc/src/boxed.rs b/library/alloc/src/boxed.rs index caaf37f0465..38b1766c174 100644 --- a/library/alloc/src/boxed.rs +++ b/library/alloc/src/boxed.rs @@ -262,8 +262,6 @@ impl<T> Box<T> { /// # Examples /// /// ``` - /// #![feature(new_uninit)] - /// /// let mut five = Box::<u32>::new_uninit(); /// /// let five = unsafe { @@ -276,7 +274,7 @@ impl<T> Box<T> { /// assert_eq!(*five, 5) /// ``` #[cfg(not(no_global_oom_handling))] - #[unstable(feature = "new_uninit", issue = "63291")] + #[stable(feature = "new_uninit", since = "CURRENT_RUSTC_VERSION")] #[must_use] #[inline] pub fn new_uninit() -> Box<mem::MaybeUninit<T>> { @@ -292,7 +290,6 @@ impl<T> Box<T> { /// # Examples /// /// ``` - /// #![feature(new_uninit)] /// #![feature(new_zeroed_alloc)] /// /// let zero = Box::<u32>::new_zeroed(); @@ -350,7 +347,7 @@ impl<T> Box<T> { /// # Examples /// /// ``` - /// #![feature(allocator_api, new_uninit)] + /// #![feature(allocator_api)] /// /// let mut five = Box::<u32>::try_new_uninit()?; /// @@ -380,7 +377,7 @@ impl<T> Box<T> { /// # Examples /// /// ``` - /// #![feature(allocator_api, new_uninit)] + /// #![feature(allocator_api)] /// /// let zero = Box::<u32>::try_new_zeroed()?; /// let zero = unsafe { zero.assume_init() }; @@ -460,7 +457,7 @@ impl<T, A: Allocator> Box<T, A> { /// # Examples /// /// ``` - /// #![feature(allocator_api, new_uninit)] + /// #![feature(allocator_api)] /// /// use std::alloc::System; /// @@ -498,7 +495,7 @@ impl<T, A: Allocator> Box<T, A> { /// # Examples /// /// ``` - /// #![feature(allocator_api, new_uninit)] + /// #![feature(allocator_api)] /// /// use std::alloc::System; /// @@ -538,7 +535,7 @@ impl<T, A: Allocator> Box<T, A> { /// # Examples /// /// ``` - /// #![feature(allocator_api, new_uninit)] + /// #![feature(allocator_api)] /// /// use std::alloc::System; /// @@ -576,7 +573,7 @@ impl<T, A: Allocator> Box<T, A> { /// # Examples /// /// ``` - /// #![feature(allocator_api, new_uninit)] + /// #![feature(allocator_api)] /// /// use std::alloc::System; /// @@ -654,8 +651,6 @@ impl<T> Box<[T]> { /// # Examples /// /// ``` - /// #![feature(new_uninit)] - /// /// let mut values = Box::<[u32]>::new_uninit_slice(3); /// /// let values = unsafe { @@ -670,7 +665,7 @@ impl<T> Box<[T]> { /// assert_eq!(*values, [1, 2, 3]) /// ``` #[cfg(not(no_global_oom_handling))] - #[unstable(feature = "new_uninit", issue = "63291")] + #[stable(feature = "new_uninit", since = "CURRENT_RUSTC_VERSION")] #[must_use] pub fn new_uninit_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> { unsafe { RawVec::with_capacity(len).into_box(len) } @@ -686,7 +681,6 @@ impl<T> Box<[T]> { /// /// ``` /// #![feature(new_zeroed_alloc)] - /// #![feature(new_uninit)] /// /// let values = Box::<[u32]>::new_zeroed_slice(3); /// let values = unsafe { values.assume_init() }; @@ -708,7 +702,7 @@ impl<T> Box<[T]> { /// # Examples /// /// ``` - /// #![feature(allocator_api, new_uninit)] + /// #![feature(allocator_api)] /// /// let mut values = Box::<[u32]>::try_new_uninit_slice(3)?; /// let values = unsafe { @@ -746,7 +740,7 @@ impl<T> Box<[T]> { /// # Examples /// /// ``` - /// #![feature(allocator_api, new_uninit)] + /// #![feature(allocator_api)] /// /// let values = Box::<[u32]>::try_new_zeroed_slice(3)?; /// let values = unsafe { values.assume_init() }; @@ -778,7 +772,7 @@ impl<T, A: Allocator> Box<[T], A> { /// # Examples /// /// ``` - /// #![feature(allocator_api, new_uninit)] + /// #![feature(allocator_api)] /// /// use std::alloc::System; /// @@ -812,7 +806,7 @@ impl<T, A: Allocator> Box<[T], A> { /// # Examples /// /// ``` - /// #![feature(allocator_api, new_uninit)] + /// #![feature(allocator_api)] /// /// use std::alloc::System; /// @@ -837,7 +831,7 @@ impl<T, A: Allocator> Box<[T], A> { /// # Examples /// /// ``` - /// #![feature(allocator_api, new_uninit)] + /// #![feature(allocator_api)] /// /// use std::alloc::System; /// @@ -880,7 +874,7 @@ impl<T, A: Allocator> Box<[T], A> { /// # Examples /// /// ``` - /// #![feature(allocator_api, new_uninit)] + /// #![feature(allocator_api)] /// /// use std::alloc::System; /// @@ -927,8 +921,6 @@ impl<T, A: Allocator> Box<mem::MaybeUninit<T>, A> { /// # Examples /// /// ``` - /// #![feature(new_uninit)] - /// /// let mut five = Box::<u32>::new_uninit(); /// /// let five: Box<u32> = unsafe { @@ -940,7 +932,7 @@ impl<T, A: Allocator> Box<mem::MaybeUninit<T>, A> { /// /// assert_eq!(*five, 5) /// ``` - #[unstable(feature = "new_uninit", issue = "63291")] + #[stable(feature = "new_uninit", since = "CURRENT_RUSTC_VERSION")] #[inline] pub unsafe fn assume_init(self) -> Box<T, A> { let (raw, alloc) = Box::into_raw_with_allocator(self); @@ -958,7 +950,6 @@ impl<T, A: Allocator> Box<mem::MaybeUninit<T>, A> { /// /// ``` /// #![feature(box_uninit_write)] - /// #![feature(new_uninit)] /// /// let big_box = Box::<[usize; 1024]>::new_uninit(); /// @@ -1001,8 +992,6 @@ impl<T, A: Allocator> Box<[mem::MaybeUninit<T>], A> { /// # Examples /// /// ``` - /// #![feature(new_uninit)] - /// /// let mut values = Box::<[u32]>::new_uninit_slice(3); /// /// let values = unsafe { @@ -1016,7 +1005,7 @@ impl<T, A: Allocator> Box<[mem::MaybeUninit<T>], A> { /// /// assert_eq!(*values, [1, 2, 3]) /// ``` - #[unstable(feature = "new_uninit", issue = "63291")] + #[stable(feature = "new_uninit", since = "CURRENT_RUSTC_VERSION")] #[inline] pub unsafe fn assume_init(self) -> Box<[T], A> { let (raw, alloc) = Box::into_raw_with_allocator(self); diff --git a/library/alloc/src/lib.rs b/library/alloc/src/lib.rs index 5e4b08df6cb..c459a8da820 100644 --- a/library/alloc/src/lib.rs +++ b/library/alloc/src/lib.rs @@ -93,7 +93,6 @@ // tidy-alphabetical-start #![cfg_attr(not(no_global_oom_handling), feature(const_alloc_error))] #![cfg_attr(not(no_global_oom_handling), feature(const_btree_len))] -#![cfg_attr(test, feature(new_uninit))] #![feature(alloc_layout_extra)] #![feature(allocator_api)] #![feature(array_chunks)] diff --git a/library/alloc/src/rc.rs b/library/alloc/src/rc.rs index f153aa6d3be..1b31a78394e 100644 --- a/library/alloc/src/rc.rs +++ b/library/alloc/src/rc.rs @@ -503,7 +503,6 @@ impl<T> Rc<T> { /// # Examples /// /// ``` - /// #![feature(new_uninit)] /// #![feature(get_mut_unchecked)] /// /// use std::rc::Rc; @@ -518,7 +517,7 @@ impl<T> Rc<T> { /// assert_eq!(*five, 5) /// ``` #[cfg(not(no_global_oom_handling))] - #[unstable(feature = "new_uninit", issue = "63291")] + #[stable(feature = "new_uninit", since = "CURRENT_RUSTC_VERSION")] #[must_use] pub fn new_uninit() -> Rc<mem::MaybeUninit<T>> { unsafe { @@ -540,7 +539,6 @@ impl<T> Rc<T> { /// /// ``` /// #![feature(new_zeroed_alloc)] - /// #![feature(new_uninit)] /// /// use std::rc::Rc; /// @@ -594,7 +592,7 @@ impl<T> Rc<T> { /// # Examples /// /// ``` - /// #![feature(allocator_api, new_uninit)] + /// #![feature(allocator_api)] /// #![feature(get_mut_unchecked)] /// /// use std::rc::Rc; @@ -630,7 +628,7 @@ impl<T> Rc<T> { /// # Examples /// /// ``` - /// #![feature(allocator_api, new_uninit)] + /// #![feature(allocator_api)] /// /// use std::rc::Rc; /// @@ -692,7 +690,6 @@ impl<T, A: Allocator> Rc<T, A> { /// # Examples /// /// ``` - /// #![feature(new_uninit)] /// #![feature(get_mut_unchecked)] /// #![feature(allocator_api)] /// @@ -736,7 +733,6 @@ impl<T, A: Allocator> Rc<T, A> { /// # Examples /// /// ``` - /// #![feature(new_uninit)] /// #![feature(allocator_api)] /// /// use std::rc::Rc; @@ -799,7 +795,7 @@ impl<T, A: Allocator> Rc<T, A> { /// # Examples /// /// ``` - /// #![feature(allocator_api, new_uninit)] + /// #![feature(allocator_api)] /// #![feature(get_mut_unchecked)] /// /// use std::rc::Rc; @@ -843,7 +839,7 @@ impl<T, A: Allocator> Rc<T, A> { /// # Examples /// /// ``` - /// #![feature(allocator_api, new_uninit)] + /// #![feature(allocator_api)] /// /// use std::rc::Rc; /// use std::alloc::System; @@ -967,7 +963,6 @@ impl<T> Rc<[T]> { /// # Examples /// /// ``` - /// #![feature(new_uninit)] /// #![feature(get_mut_unchecked)] /// /// use std::rc::Rc; @@ -985,7 +980,7 @@ impl<T> Rc<[T]> { /// assert_eq!(*values, [1, 2, 3]) /// ``` #[cfg(not(no_global_oom_handling))] - #[unstable(feature = "new_uninit", issue = "63291")] + #[stable(feature = "new_uninit", since = "CURRENT_RUSTC_VERSION")] #[must_use] pub fn new_uninit_slice(len: usize) -> Rc<[mem::MaybeUninit<T>]> { unsafe { Rc::from_ptr(Rc::allocate_for_slice(len)) } @@ -1000,7 +995,6 @@ impl<T> Rc<[T]> { /// # Examples /// /// ``` - /// #![feature(new_uninit)] /// #![feature(new_zeroed_alloc)] /// /// use std::rc::Rc; @@ -1035,7 +1029,6 @@ impl<T, A: Allocator> Rc<[T], A> { /// # Examples /// /// ``` - /// #![feature(new_uninit)] /// #![feature(get_mut_unchecked)] /// #![feature(allocator_api)] /// @@ -1072,7 +1065,6 @@ impl<T, A: Allocator> Rc<[T], A> { /// # Examples /// /// ``` - /// #![feature(new_uninit)] /// #![feature(allocator_api)] /// /// use std::rc::Rc; @@ -1122,7 +1114,6 @@ impl<T, A: Allocator> Rc<mem::MaybeUninit<T>, A> { /// # Examples /// /// ``` - /// #![feature(new_uninit)] /// #![feature(get_mut_unchecked)] /// /// use std::rc::Rc; @@ -1136,7 +1127,7 @@ impl<T, A: Allocator> Rc<mem::MaybeUninit<T>, A> { /// /// assert_eq!(*five, 5) /// ``` - #[unstable(feature = "new_uninit", issue = "63291")] + #[stable(feature = "new_uninit", since = "CURRENT_RUSTC_VERSION")] #[inline] pub unsafe fn assume_init(self) -> Rc<T, A> { let (ptr, alloc) = Rc::into_inner_with_allocator(self); @@ -1160,7 +1151,6 @@ impl<T, A: Allocator> Rc<[mem::MaybeUninit<T>], A> { /// # Examples /// /// ``` - /// #![feature(new_uninit)] /// #![feature(get_mut_unchecked)] /// /// use std::rc::Rc; @@ -1177,7 +1167,7 @@ impl<T, A: Allocator> Rc<[mem::MaybeUninit<T>], A> { /// /// assert_eq!(*values, [1, 2, 3]) /// ``` - #[unstable(feature = "new_uninit", issue = "63291")] + #[stable(feature = "new_uninit", since = "CURRENT_RUSTC_VERSION")] #[inline] pub unsafe fn assume_init(self) -> Rc<[T], A> { let (ptr, alloc) = Rc::into_inner_with_allocator(self); diff --git a/library/alloc/src/sync.rs b/library/alloc/src/sync.rs index 4a3522f1a64..024a794f17b 100644 --- a/library/alloc/src/sync.rs +++ b/library/alloc/src/sync.rs @@ -335,7 +335,7 @@ impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized<Weak<U, A>> f impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Weak<U>> for Weak<T> {} #[stable(feature = "arc_weak", since = "1.4.0")] -impl<T: ?Sized> fmt::Debug for Weak<T> { +impl<T: ?Sized, A: Allocator> fmt::Debug for Weak<T, A> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "(Weak)") } @@ -505,7 +505,6 @@ impl<T> Arc<T> { /// # Examples /// /// ``` - /// #![feature(new_uninit)] /// #![feature(get_mut_unchecked)] /// /// use std::sync::Arc; @@ -521,7 +520,7 @@ impl<T> Arc<T> { /// ``` #[cfg(not(no_global_oom_handling))] #[inline] - #[unstable(feature = "new_uninit", issue = "63291")] + #[stable(feature = "new_uninit", since = "CURRENT_RUSTC_VERSION")] #[must_use] pub fn new_uninit() -> Arc<mem::MaybeUninit<T>> { unsafe { @@ -543,7 +542,6 @@ impl<T> Arc<T> { /// /// ``` /// #![feature(new_zeroed_alloc)] - /// #![feature(new_uninit)] /// /// use std::sync::Arc; /// @@ -614,7 +612,7 @@ impl<T> Arc<T> { /// # Examples /// /// ``` - /// #![feature(new_uninit, allocator_api)] + /// #![feature(allocator_api)] /// #![feature(get_mut_unchecked)] /// /// use std::sync::Arc; @@ -650,7 +648,7 @@ impl<T> Arc<T> { /// # Examples /// /// ``` - /// #![feature(new_uninit, allocator_api)] + /// #![feature( allocator_api)] /// /// use std::sync::Arc; /// @@ -711,7 +709,6 @@ impl<T, A: Allocator> Arc<T, A> { /// # Examples /// /// ``` - /// #![feature(new_uninit)] /// #![feature(get_mut_unchecked)] /// #![feature(allocator_api)] /// @@ -755,7 +752,6 @@ impl<T, A: Allocator> Arc<T, A> { /// # Examples /// /// ``` - /// #![feature(new_uninit)] /// #![feature(allocator_api)] /// /// use std::sync::Arc; @@ -845,7 +841,7 @@ impl<T, A: Allocator> Arc<T, A> { /// # Examples /// /// ``` - /// #![feature(new_uninit, allocator_api)] + /// #![feature(allocator_api)] /// #![feature(get_mut_unchecked)] /// /// use std::sync::Arc; @@ -889,7 +885,7 @@ impl<T, A: Allocator> Arc<T, A> { /// # Examples /// /// ``` - /// #![feature(new_uninit, allocator_api)] + /// #![feature(allocator_api)] /// /// use std::sync::Arc; /// use std::alloc::System; @@ -1101,7 +1097,6 @@ impl<T> Arc<[T]> { /// # Examples /// /// ``` - /// #![feature(new_uninit)] /// #![feature(get_mut_unchecked)] /// /// use std::sync::Arc; @@ -1120,7 +1115,7 @@ impl<T> Arc<[T]> { /// ``` #[cfg(not(no_global_oom_handling))] #[inline] - #[unstable(feature = "new_uninit", issue = "63291")] + #[stable(feature = "new_uninit", since = "CURRENT_RUSTC_VERSION")] #[must_use] pub fn new_uninit_slice(len: usize) -> Arc<[mem::MaybeUninit<T>]> { unsafe { Arc::from_ptr(Arc::allocate_for_slice(len)) } @@ -1136,7 +1131,6 @@ impl<T> Arc<[T]> { /// /// ``` /// #![feature(new_zeroed_alloc)] - /// #![feature(new_uninit)] /// /// use std::sync::Arc; /// @@ -1172,7 +1166,6 @@ impl<T, A: Allocator> Arc<[T], A> { /// # Examples /// /// ``` - /// #![feature(new_uninit)] /// #![feature(get_mut_unchecked)] /// #![feature(allocator_api)] /// @@ -1208,7 +1201,6 @@ impl<T, A: Allocator> Arc<[T], A> { /// # Examples /// /// ``` - /// #![feature(new_uninit)] /// #![feature(allocator_api)] /// /// use std::sync::Arc; @@ -1257,7 +1249,6 @@ impl<T, A: Allocator> Arc<mem::MaybeUninit<T>, A> { /// # Examples /// /// ``` - /// #![feature(new_uninit)] /// #![feature(get_mut_unchecked)] /// /// use std::sync::Arc; @@ -1271,7 +1262,7 @@ impl<T, A: Allocator> Arc<mem::MaybeUninit<T>, A> { /// /// assert_eq!(*five, 5) /// ``` - #[unstable(feature = "new_uninit", issue = "63291")] + #[stable(feature = "new_uninit", since = "CURRENT_RUSTC_VERSION")] #[must_use = "`self` will be dropped if the result is not used"] #[inline] pub unsafe fn assume_init(self) -> Arc<T, A> { @@ -1296,7 +1287,6 @@ impl<T, A: Allocator> Arc<[mem::MaybeUninit<T>], A> { /// # Examples /// /// ``` - /// #![feature(new_uninit)] /// #![feature(get_mut_unchecked)] /// /// use std::sync::Arc; @@ -1313,7 +1303,7 @@ impl<T, A: Allocator> Arc<[mem::MaybeUninit<T>], A> { /// /// assert_eq!(*values, [1, 2, 3]) /// ``` - #[unstable(feature = "new_uninit", issue = "63291")] + #[stable(feature = "new_uninit", since = "CURRENT_RUSTC_VERSION")] #[must_use = "`self` will be dropped if the result is not used"] #[inline] pub unsafe fn assume_init(self) -> Arc<[T], A> { diff --git a/library/alloc/tests/lib.rs b/library/alloc/tests/lib.rs index 3d4add6fae4..c5c6a122cfe 100644 --- a/library/alloc/tests/lib.rs +++ b/library/alloc/tests/lib.rs @@ -15,7 +15,6 @@ #![feature(exact_size_is_empty)] #![feature(linked_list_cursors)] #![feature(map_try_insert)] -#![feature(new_uninit)] #![feature(pattern)] #![feature(trusted_len)] #![feature(try_reserve_kind)] diff --git a/library/core/benches/lib.rs b/library/core/benches/lib.rs index 32d15c386cb..3f1c58bbd72 100644 --- a/library/core/benches/lib.rs +++ b/library/core/benches/lib.rs @@ -8,6 +8,7 @@ #![feature(iter_array_chunks)] #![feature(iter_next_chunk)] #![feature(iter_advance_by)] +#![feature(isqrt)] extern crate test; diff --git a/library/core/benches/num/int_sqrt/mod.rs b/library/core/benches/num/int_sqrt/mod.rs new file mode 100644 index 00000000000..3c9d173e456 --- /dev/null +++ b/library/core/benches/num/int_sqrt/mod.rs @@ -0,0 +1,62 @@ +use rand::Rng; +use test::{black_box, Bencher}; + +macro_rules! int_sqrt_bench { + ($t:ty, $predictable:ident, $random:ident, $random_small:ident, $random_uniform:ident) => { + #[bench] + fn $predictable(bench: &mut Bencher) { + bench.iter(|| { + for n in 0..(<$t>::BITS / 8) { + for i in 1..=(100 as $t) { + let x = black_box(i << (n * 8)); + black_box(x.isqrt()); + } + } + }); + } + + #[bench] + fn $random(bench: &mut Bencher) { + let mut rng = crate::bench_rng(); + /* Exponentially distributed random numbers from the whole range of the type. */ + let numbers: Vec<$t> = + (0..256).map(|_| rng.gen::<$t>() >> rng.gen_range(0..<$t>::BITS)).collect(); + bench.iter(|| { + for x in &numbers { + black_box(black_box(x).isqrt()); + } + }); + } + + #[bench] + fn $random_small(bench: &mut Bencher) { + let mut rng = crate::bench_rng(); + /* Exponentially distributed random numbers from the range 0..256. */ + let numbers: Vec<$t> = + (0..256).map(|_| (rng.gen::<u8>() >> rng.gen_range(0..u8::BITS)) as $t).collect(); + bench.iter(|| { + for x in &numbers { + black_box(black_box(x).isqrt()); + } + }); + } + + #[bench] + fn $random_uniform(bench: &mut Bencher) { + let mut rng = crate::bench_rng(); + /* Exponentially distributed random numbers from the whole range of the type. */ + let numbers: Vec<$t> = (0..256).map(|_| rng.gen::<$t>()).collect(); + bench.iter(|| { + for x in &numbers { + black_box(black_box(x).isqrt()); + } + }); + } + }; +} + +int_sqrt_bench! {u8, u8_sqrt_predictable, u8_sqrt_random, u8_sqrt_random_small, u8_sqrt_uniform} +int_sqrt_bench! {u16, u16_sqrt_predictable, u16_sqrt_random, u16_sqrt_random_small, u16_sqrt_uniform} +int_sqrt_bench! {u32, u32_sqrt_predictable, u32_sqrt_random, u32_sqrt_random_small, u32_sqrt_uniform} +int_sqrt_bench! {u64, u64_sqrt_predictable, u64_sqrt_random, u64_sqrt_random_small, u64_sqrt_uniform} +int_sqrt_bench! {u128, u128_sqrt_predictable, u128_sqrt_random, u128_sqrt_random_small, u128_sqrt_uniform} diff --git a/library/core/benches/num/mod.rs b/library/core/benches/num/mod.rs index c1dc3a30622..7ff7443cfa7 100644 --- a/library/core/benches/num/mod.rs +++ b/library/core/benches/num/mod.rs @@ -2,6 +2,7 @@ mod dec2flt; mod flt2dec; mod int_log; mod int_pow; +mod int_sqrt; use std::str::FromStr; diff --git a/library/core/src/fmt/rt.rs b/library/core/src/fmt/rt.rs index 65a4d537cc7..f29ac99b292 100644 --- a/library/core/src/fmt/rt.rs +++ b/library/core/src/fmt/rt.rs @@ -118,6 +118,10 @@ impl<'a> Argument<'a> { Self::new(x, Debug::fmt) } #[inline(always)] + pub fn new_debug_noop<'b, T: Debug>(x: &'b T) -> Argument<'_> { + Self::new(x, |_, _| Ok(())) + } + #[inline(always)] pub fn new_octal<'b, T: Octal>(x: &'b T) -> Argument<'_> { Self::new(x, Octal::fmt) } diff --git a/library/core/src/intrinsics.rs b/library/core/src/intrinsics.rs index bd99e90376a..8cb9accd59d 100644 --- a/library/core/src/intrinsics.rs +++ b/library/core/src/intrinsics.rs @@ -2949,7 +2949,7 @@ pub const unsafe fn typed_swap<T>(x: *mut T, y: *mut T) { /// sysroot which is built without ub_checks but with `#[rustc_preserve_ub_checks]`. /// For code that gets monomorphized in the user crate (i.e., generic functions and functions with /// `#[inline]`), gating assertions on `ub_checks()` rather than `cfg!(ub_checks)` means that -/// assertions are enabled whenever the *user crate* has UB checks enabled. However if the +/// assertions are enabled whenever the *user crate* has UB checks enabled. However, if the /// user has UB checks disabled, the checks will still get optimized out. This intrinsic is /// primarily used by [`ub_checks::assert_unsafe_precondition`]. #[rustc_const_unstable(feature = "const_ub_checks", issue = "none")] @@ -2957,7 +2957,7 @@ pub const unsafe fn typed_swap<T>(x: *mut T, y: *mut T) { #[inline(always)] #[rustc_intrinsic] pub const fn ub_checks() -> bool { - cfg!(debug_assertions) + cfg!(ub_checks) } /// Allocates a block of memory at compile time. diff --git a/library/core/src/lib.rs b/library/core/src/lib.rs index 7f0efede240..06a745b690a 100644 --- a/library/core/src/lib.rs +++ b/library/core/src/lib.rs @@ -203,6 +203,7 @@ #![feature(cfg_sanitize)] #![feature(cfg_target_has_atomic)] #![feature(cfg_target_has_atomic_equal_alignment)] +#![feature(cfg_ub_checks)] #![feature(const_for)] #![feature(const_mut_refs)] #![feature(const_precise_live_drops)] diff --git a/library/core/src/mem/mod.rs b/library/core/src/mem/mod.rs index 7a9ca4011be..e602b497d17 100644 --- a/library/core/src/mem/mod.rs +++ b/library/core/src/mem/mod.rs @@ -19,7 +19,7 @@ pub use maybe_uninit::MaybeUninit; mod transmutability; #[unstable(feature = "transmutability", issue = "99571")] -pub use transmutability::{Assume, BikeshedIntrinsicFrom}; +pub use transmutability::{Assume, TransmuteFrom}; #[stable(feature = "rust1", since = "1.0.0")] #[doc(inline)] diff --git a/library/core/src/mem/transmutability.rs b/library/core/src/mem/transmutability.rs index 62d454a5289..049b32ede9c 100644 --- a/library/core/src/mem/transmutability.rs +++ b/library/core/src/mem/transmutability.rs @@ -11,10 +11,10 @@ use crate::marker::{ConstParamTy_, UnsizedConstParamTy}; /// /// # Safety /// -/// If `Dst: BikeshedIntrinsicFrom<Src, ASSUMPTIONS>`, the compiler guarantees -/// that `Src` is soundly *union-transmutable* into a value of type `Dst`, -/// provided that the programmer has guaranteed that the given -/// [`ASSUMPTIONS`](Assume) are satisfied. +/// If `Dst: TransmuteFrom<Src, ASSUMPTIONS>`, the compiler guarantees that +/// `Src` is soundly *union-transmutable* into a value of type `Dst`, provided +/// that the programmer has guaranteed that the given [`ASSUMPTIONS`](Assume) +/// are satisfied. /// /// A union-transmute is any bit-reinterpretation conversion in the form of: /// @@ -47,7 +47,7 @@ use crate::marker::{ConstParamTy_, UnsizedConstParamTy}; #[cfg_attr(not(bootstrap), doc = "```rust")] /// #![feature(transmutability)] /// -/// use core::mem::{Assume, BikeshedIntrinsicFrom}; +/// use core::mem::{Assume, TransmuteFrom}; /// /// let src = 42u8; // size = 1 /// @@ -55,7 +55,7 @@ use crate::marker::{ConstParamTy_, UnsizedConstParamTy}; /// struct Dst(u8); // size = 2 // /// let _ = unsafe { -/// <Dst as BikeshedIntrinsicFrom<u8, { Assume::SAFETY }>>::transmute(src) +/// <Dst as TransmuteFrom<u8, { Assume::SAFETY }>>::transmute(src) /// }; /// ``` /// @@ -87,7 +87,7 @@ use crate::marker::{ConstParamTy_, UnsizedConstParamTy}; #[lang = "transmute_trait"] #[rustc_deny_explicit_impl(implement_via_object = false)] #[rustc_coinductive] -pub unsafe trait BikeshedIntrinsicFrom<Src, const ASSUME: Assume = { Assume::NOTHING }> +pub unsafe trait TransmuteFrom<Src, const ASSUME: Assume = { Assume::NOTHING }> where Src: ?Sized, { @@ -140,23 +140,21 @@ where } } -/// Configurable proof assumptions of [`BikeshedIntrinsicFrom`]. +/// Configurable proof assumptions of [`TransmuteFrom`]. /// /// When `false`, the respective proof obligation belongs to the compiler. When /// `true`, the onus of the safety proof belongs to the programmer. -/// [`BikeshedIntrinsicFrom`]. #[unstable(feature = "transmutability", issue = "99571")] #[lang = "transmute_opts"] #[derive(PartialEq, Eq, Clone, Copy, Debug)] pub struct Assume { - /// When `false`, [`BikeshedIntrinsicFrom`] is not implemented for - /// transmutations that might violate the the alignment requirements of - /// references; e.g.: + /// When `false`, [`TransmuteFrom`] is not implemented for transmutations + /// that might violate the the alignment requirements of references; e.g.: /// #[cfg_attr(bootstrap, doc = "```rust,ignore not runnable on bootstrap")] #[cfg_attr(not(bootstrap), doc = "```compile_fail,E0277")] /// #![feature(transmutability)] - /// use core::mem::{align_of, BikeshedIntrinsicFrom}; + /// use core::mem::{align_of, TransmuteFrom}; /// /// assert_eq!(align_of::<[u8; 2]>(), 1); /// assert_eq!(align_of::<u16>(), 2); @@ -165,18 +163,18 @@ pub struct Assume { /// /// // SAFETY: No safety obligations. /// let dst: &u16 = unsafe { - /// <_ as BikeshedIntrinsicFrom<_>>::transmute(src) + /// <_ as TransmuteFrom<_>>::transmute(src) /// }; /// ``` /// - /// When `true`, [`BikeshedIntrinsicFrom`] assumes that *you* have ensured + /// When `true`, [`TransmuteFrom`] assumes that *you* have ensured /// that references in the transmuted value satisfy the alignment /// requirements of their referent types; e.g.: /// #[cfg_attr(bootstrap, doc = "```rust,ignore not runnable on bootstrap")] #[cfg_attr(not(bootstrap), doc = "```rust")] /// #![feature(pointer_is_aligned_to, transmutability)] - /// use core::mem::{align_of, Assume, BikeshedIntrinsicFrom}; + /// use core::mem::{align_of, Assume, TransmuteFrom}; /// /// let src: &[u8; 2] = &[0xFF, 0xFF]; /// @@ -184,7 +182,7 @@ pub struct Assume { /// // SAFETY: We have checked above that the address of `src` satisfies the /// // alignment requirements of `u16`. /// Some(unsafe { - /// <_ as BikeshedIntrinsicFrom<_, { Assume::ALIGNMENT }>>::transmute(src) + /// <_ as TransmuteFrom<_, { Assume::ALIGNMENT }>>::transmute(src) /// }) /// } else { /// None @@ -194,21 +192,21 @@ pub struct Assume { /// ``` pub alignment: bool, - /// When `false`, [`BikeshedIntrinsicFrom`] is not implemented for - /// transmutations that extend the lifetimes of references. + /// When `false`, [`TransmuteFrom`] is not implemented for transmutations + /// that extend the lifetimes of references. /// - /// When `true`, [`BikeshedIntrinsicFrom`] assumes that *you* have ensured - /// that references in the transmuted value do not outlive their referents. + /// When `true`, [`TransmuteFrom`] assumes that *you* have ensured that + /// references in the transmuted value do not outlive their referents. pub lifetimes: bool, - /// When `false`, [`BikeshedIntrinsicFrom`] is not implemented for - /// transmutations that might violate the library safety invariants of the - /// destination type; e.g.: + /// When `false`, [`TransmuteFrom`] is not implemented for transmutations + /// that might violate the library safety invariants of the destination + /// type; e.g.: /// #[cfg_attr(bootstrap, doc = "```rust,ignore not runnable on bootstrap")] #[cfg_attr(not(bootstrap), doc = "```compile_fail,E0277")] /// #![feature(transmutability)] - /// use core::mem::BikeshedIntrinsicFrom; + /// use core::mem::TransmuteFrom; /// /// let src: u8 = 3; /// @@ -219,18 +217,18 @@ pub struct Assume { /// /// // SAFETY: No safety obligations. /// let dst: EvenU8 = unsafe { - /// <_ as BikeshedIntrinsicFrom<_>>::transmute(src) + /// <_ as TransmuteFrom<_>>::transmute(src) /// }; /// ``` /// - /// When `true`, [`BikeshedIntrinsicFrom`] assumes that *you* have ensured + /// When `true`, [`TransmuteFrom`] assumes that *you* have ensured /// that undefined behavior does not arise from using the transmuted value; /// e.g.: /// #[cfg_attr(bootstrap, doc = "```rust,ignore not runnable on bootstrap")] #[cfg_attr(not(bootstrap), doc = "```rust")] /// #![feature(transmutability)] - /// use core::mem::{Assume, BikeshedIntrinsicFrom}; + /// use core::mem::{Assume, TransmuteFrom}; /// /// let src: u8 = 42; /// @@ -242,7 +240,7 @@ pub struct Assume { /// let maybe_dst: Option<EvenU8> = if src % 2 == 0 { /// // SAFETY: We have checked above that the value of `src` is even. /// Some(unsafe { - /// <_ as BikeshedIntrinsicFrom<_, { Assume::SAFETY }>>::transmute(src) + /// <_ as TransmuteFrom<_, { Assume::SAFETY }>>::transmute(src) /// }) /// } else { /// None @@ -252,31 +250,31 @@ pub struct Assume { /// ``` pub safety: bool, - /// When `false`, [`BikeshedIntrinsicFrom`] is not implemented for - /// transmutations that might violate the language-level bit-validity - /// invariant of the destination type; e.g.: + /// When `false`, [`TransmuteFrom`] is not implemented for transmutations + /// that might violate the language-level bit-validity invariant of the + /// destination type; e.g.: /// #[cfg_attr(bootstrap, doc = "```rust,ignore not runnable on bootstrap")] #[cfg_attr(not(bootstrap), doc = "```compile_fail,E0277")] /// #![feature(transmutability)] - /// use core::mem::BikeshedIntrinsicFrom; + /// use core::mem::TransmuteFrom; /// /// let src: u8 = 3; /// /// // SAFETY: No safety obligations. /// let dst: bool = unsafe { - /// <_ as BikeshedIntrinsicFrom<_>>::transmute(src) + /// <_ as TransmuteFrom<_>>::transmute(src) /// }; /// ``` /// - /// When `true`, [`BikeshedIntrinsicFrom`] assumes that *you* have ensured + /// When `true`, [`TransmuteFrom`] assumes that *you* have ensured /// that the value being transmuted is a bit-valid instance of the /// transmuted value; e.g.: /// #[cfg_attr(bootstrap, doc = "```rust,ignore not runnable on bootstrap")] #[cfg_attr(not(bootstrap), doc = "```rust")] /// #![feature(transmutability)] - /// use core::mem::{Assume, BikeshedIntrinsicFrom}; + /// use core::mem::{Assume, TransmuteFrom}; /// /// let src: u8 = 1; /// @@ -284,7 +282,7 @@ pub struct Assume { /// // SAFETY: We have checked above that the value of `src` is a bit-valid /// // instance of `bool`. /// Some(unsafe { - /// <_ as BikeshedIntrinsicFrom<_, { Assume::VALIDITY }>>::transmute(src) + /// <_ as TransmuteFrom<_, { Assume::VALIDITY }>>::transmute(src) /// }) /// } else { /// None @@ -301,35 +299,34 @@ impl ConstParamTy_ for Assume {} impl UnsizedConstParamTy for Assume {} impl Assume { - /// With this, [`BikeshedIntrinsicFrom`] does not assume you have ensured - /// any safety obligations are met, and relies only upon its own analysis to - /// (dis)prove transmutability. + /// With this, [`TransmuteFrom`] does not assume you have ensured any safety + /// obligations are met, and relies only upon its own analysis to (dis)prove + /// transmutability. #[unstable(feature = "transmutability", issue = "99571")] pub const NOTHING: Self = Self { alignment: false, lifetimes: false, safety: false, validity: false }; - /// With this, [`BikeshedIntrinsicFrom`] assumes only that you have ensured - /// that references in the transmuted value satisfy the alignment - /// requirements of their referent types. See [`Assume::alignment`] for - /// examples. + /// With this, [`TransmuteFrom`] assumes only that you have ensured that + /// references in the transmuted value satisfy the alignment requirements of + /// their referent types. See [`Assume::alignment`] for examples. #[unstable(feature = "transmutability", issue = "99571")] pub const ALIGNMENT: Self = Self { alignment: true, ..Self::NOTHING }; - /// With this, [`BikeshedIntrinsicFrom`] assumes only that you have ensured - /// that references in the transmuted value do not outlive their referents. - /// See [`Assume::lifetimes`] for examples. + /// With this, [`TransmuteFrom`] assumes only that you have ensured that + /// references in the transmuted value do not outlive their referents. See + /// [`Assume::lifetimes`] for examples. #[unstable(feature = "transmutability", issue = "99571")] pub const LIFETIMES: Self = Self { lifetimes: true, ..Self::NOTHING }; - /// With this, [`BikeshedIntrinsicFrom`] assumes only that you have ensured - /// that undefined behavior does not arise from using the transmuted value. - /// See [`Assume::safety`] for examples. + /// With this, [`TransmuteFrom`] assumes only that you have ensured that + /// undefined behavior does not arise from using the transmuted value. See + /// [`Assume::safety`] for examples. #[unstable(feature = "transmutability", issue = "99571")] pub const SAFETY: Self = Self { safety: true, ..Self::NOTHING }; - /// With this, [`BikeshedIntrinsicFrom`] assumes only that you have ensured - /// that the value being transmuted is a bit-valid instance of the - /// transmuted value. See [`Assume::validity`] for examples. + /// With this, [`TransmuteFrom`] assumes only that you have ensured that the + /// value being transmuted is a bit-valid instance of the transmuted value. + /// See [`Assume::validity`] for examples. #[unstable(feature = "transmutability", issue = "99571")] pub const VALIDITY: Self = Self { validity: true, ..Self::NOTHING }; @@ -348,7 +345,7 @@ impl Assume { /// transmutability, /// )] /// #![allow(incomplete_features)] - /// use core::mem::{align_of, Assume, BikeshedIntrinsicFrom}; + /// use core::mem::{align_of, Assume, TransmuteFrom}; /// /// /// Attempts to transmute `src` to `&Dst`. /// /// @@ -360,7 +357,7 @@ impl Assume { /// /// alignment, are satisfied. /// unsafe fn try_transmute_ref<'a, Src, Dst, const ASSUME: Assume>(src: &'a Src) -> Option<&'a Dst> /// where - /// &'a Dst: BikeshedIntrinsicFrom<&'a Src, { ASSUME.and(Assume::ALIGNMENT) }>, + /// &'a Dst: TransmuteFrom<&'a Src, { ASSUME.and(Assume::ALIGNMENT) }>, /// { /// if <*const _>::is_aligned_to(src, align_of::<Dst>()) { /// // SAFETY: By the above dynamic check, we have ensured that the address @@ -368,7 +365,7 @@ impl Assume { /// // on the caller, the safety obligations required by `ASSUME` have also /// // been satisfied. /// Some(unsafe { - /// <_ as BikeshedIntrinsicFrom<_, { ASSUME.and(Assume::ALIGNMENT) }>>::transmute(src) + /// <_ as TransmuteFrom<_, { ASSUME.and(Assume::ALIGNMENT) }>>::transmute(src) /// }) /// } else { /// None diff --git a/library/core/src/num/int_macros.rs b/library/core/src/num/int_macros.rs index 229cd89bea3..878a911dde5 100644 --- a/library/core/src/num/int_macros.rs +++ b/library/core/src/num/int_macros.rs @@ -1641,7 +1641,33 @@ macro_rules! int_impl { if self < 0 { None } else { - Some((self as $UnsignedT).isqrt() as Self) + // SAFETY: Input is nonnegative in this `else` branch. + let result = unsafe { + crate::num::int_sqrt::$ActualT(self as $ActualT) as $SelfT + }; + + // Inform the optimizer what the range of outputs is. If + // testing `core` crashes with no panic message and a + // `num::int_sqrt::i*` test failed, it's because your edits + // caused these assertions to become false. + // + // SAFETY: Integer square root is a monotonically nondecreasing + // function, which means that increasing the input will never + // cause the output to decrease. Thus, since the input for + // nonnegative signed integers is bounded by + // `[0, <$ActualT>::MAX]`, sqrt(n) will be bounded by + // `[sqrt(0), sqrt(<$ActualT>::MAX)]`. + unsafe { + // SAFETY: `<$ActualT>::MAX` is nonnegative. + const MAX_RESULT: $SelfT = unsafe { + crate::num::int_sqrt::$ActualT(<$ActualT>::MAX) as $SelfT + }; + + crate::hint::assert_unchecked(result >= 0); + crate::hint::assert_unchecked(result <= MAX_RESULT); + } + + Some(result) } } @@ -2862,15 +2888,11 @@ macro_rules! int_impl { #[must_use = "this returns the result of the operation, \ without modifying the original"] #[inline] + #[track_caller] pub const fn isqrt(self) -> Self { - // I would like to implement it as - // ``` - // self.checked_isqrt().expect("argument of integer square root must be non-negative") - // ``` - // but `expect` is not yet stable as a `const fn`. match self.checked_isqrt() { Some(sqrt) => sqrt, - None => panic!("argument of integer square root must be non-negative"), + None => crate::num::int_sqrt::panic_for_negative_argument(), } } @@ -2888,8 +2910,8 @@ macro_rules! int_impl { /// /// # Panics /// - /// This function will panic if `rhs` is 0 or if `self` is -1 and `rhs` is - /// `Self::MIN`. This behavior is not affected by the `overflow-checks` flag. + /// This function will panic if `rhs` is 0 or if `self` is `Self::MIN` + /// and `rhs` is -1. This behavior is not affected by the `overflow-checks` flag. /// /// # Examples /// @@ -2927,8 +2949,8 @@ macro_rules! int_impl { /// /// # Panics /// - /// This function will panic if `rhs` is 0 or if `self` is -1 and `rhs` is - /// `Self::MIN`. This behavior is not affected by the `overflow-checks` flag. + /// This function will panic if `rhs` is 0 or if `self` is `Self::MIN` and + /// `rhs` is -1. This behavior is not affected by the `overflow-checks` flag. /// /// # Examples /// @@ -2943,6 +2965,11 @@ macro_rules! int_impl { /// assert_eq!(a.rem_euclid(-b), 3); /// assert_eq!((-a).rem_euclid(-b), 1); /// ``` + /// + /// This will panic: + /// ```should_panic + #[doc = concat!("let _ = ", stringify!($SelfT), "::MIN.rem_euclid(-1);")] + /// ``` #[doc(alias = "modulo", alias = "mod")] #[stable(feature = "euclidean_division", since = "1.38.0")] #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")] @@ -2971,8 +2998,8 @@ macro_rules! int_impl { /// /// # Panics /// - /// This function will panic if `rhs` is 0 or if `self` is -1 and `rhs` is - /// `Self::MIN`. This behavior is not affected by the `overflow-checks` flag. + /// This function will panic if `rhs` is 0 or if `self` is `Self::MIN` + /// and `rhs` is -1. This behavior is not affected by the `overflow-checks` flag. /// /// # Examples /// @@ -3007,8 +3034,8 @@ macro_rules! int_impl { /// /// # Panics /// - /// This function will panic if `rhs` is 0 or if `self` is -1 and `rhs` is - /// `Self::MIN`. This behavior is not affected by the `overflow-checks` flag. + /// This function will panic if `rhs` is 0 or if `self` is `Self::MIN` + /// and `rhs` is -1. This behavior is not affected by the `overflow-checks` flag. /// /// # Examples /// diff --git a/library/core/src/num/int_sqrt.rs b/library/core/src/num/int_sqrt.rs new file mode 100644 index 00000000000..601e81f6993 --- /dev/null +++ b/library/core/src/num/int_sqrt.rs @@ -0,0 +1,316 @@ +//! These functions use the [Karatsuba square root algorithm][1] to compute the +//! [integer square root](https://en.wikipedia.org/wiki/Integer_square_root) +//! for the primitive integer types. +//! +//! The signed integer functions can only handle **nonnegative** inputs, so +//! that must be checked before calling those. +//! +//! [1]: <https://web.archive.org/web/20230511212802/https://inria.hal.science/inria-00072854v1/file/RR-3805.pdf> +//! "Paul Zimmermann. Karatsuba Square Root. \[Research Report\] RR-3805, +//! INRIA. 1999, pp.8. (inria-00072854)" + +/// This array stores the [integer square roots]( +/// https://en.wikipedia.org/wiki/Integer_square_root) and remainders of each +/// [`u8`](prim@u8) value. For example, `U8_ISQRT_WITH_REMAINDER[17]` will be +/// `(4, 1)` because the integer square root of 17 is 4 and because 17 is 1 +/// higher than 4 squared. +const U8_ISQRT_WITH_REMAINDER: [(u8, u8); 256] = { + let mut result = [(0, 0); 256]; + + let mut n: usize = 0; + let mut isqrt_n: usize = 0; + while n < result.len() { + result[n] = (isqrt_n as u8, (n - isqrt_n.pow(2)) as u8); + + n += 1; + if n == (isqrt_n + 1).pow(2) { + isqrt_n += 1; + } + } + + result +}; + +/// Returns the [integer square root]( +/// https://en.wikipedia.org/wiki/Integer_square_root) of any [`u8`](prim@u8) +/// input. +#[must_use = "this returns the result of the operation, \ + without modifying the original"] +#[inline] +pub const fn u8(n: u8) -> u8 { + U8_ISQRT_WITH_REMAINDER[n as usize].0 +} + +/// Generates an `i*` function that returns the [integer square root]( +/// https://en.wikipedia.org/wiki/Integer_square_root) of any **nonnegative** +/// input of a specific signed integer type. +macro_rules! signed_fn { + ($SignedT:ident, $UnsignedT:ident) => { + /// Returns the [integer square root]( + /// https://en.wikipedia.org/wiki/Integer_square_root) of any + /// **nonnegative** + #[doc = concat!("[`", stringify!($SignedT), "`](prim@", stringify!($SignedT), ")")] + /// input. + /// + /// # Safety + /// + /// This results in undefined behavior when the input is negative. + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline] + pub const unsafe fn $SignedT(n: $SignedT) -> $SignedT { + debug_assert!(n >= 0, "Negative input inside `isqrt`."); + $UnsignedT(n as $UnsignedT) as $SignedT + } + }; +} + +signed_fn!(i8, u8); +signed_fn!(i16, u16); +signed_fn!(i32, u32); +signed_fn!(i64, u64); +signed_fn!(i128, u128); + +/// Generates a `u*` function that returns the [integer square root]( +/// https://en.wikipedia.org/wiki/Integer_square_root) of any input of +/// a specific unsigned integer type. +macro_rules! unsigned_fn { + ($UnsignedT:ident, $HalfBitsT:ident, $stages:ident) => { + /// Returns the [integer square root]( + /// https://en.wikipedia.org/wiki/Integer_square_root) of any + #[doc = concat!("[`", stringify!($UnsignedT), "`](prim@", stringify!($UnsignedT), ")")] + /// input. + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline] + pub const fn $UnsignedT(mut n: $UnsignedT) -> $UnsignedT { + if n <= <$HalfBitsT>::MAX as $UnsignedT { + $HalfBitsT(n as $HalfBitsT) as $UnsignedT + } else { + // The normalization shift satisfies the Karatsuba square root + // algorithm precondition "a₃ ≥ b/4" where a₃ is the most + // significant quarter of `n`'s bits and b is the number of + // values that can be represented by that quarter of the bits. + // + // b/4 would then be all 0s except the second most significant + // bit (010...0) in binary. Since a₃ must be at least b/4, a₃'s + // most significant bit or its neighbor must be a 1. Since a₃'s + // most significant bits are `n`'s most significant bits, the + // same applies to `n`. + // + // The reason to shift by an even number of bits is because an + // even number of bits produces the square root shifted to the + // left by half of the normalization shift: + // + // sqrt(n << (2 * p)) + // sqrt(2.pow(2 * p) * n) + // sqrt(2.pow(2 * p)) * sqrt(n) + // 2.pow(p) * sqrt(n) + // sqrt(n) << p + // + // Shifting by an odd number of bits leaves an ugly sqrt(2) + // multiplied in: + // + // sqrt(n << (2 * p + 1)) + // sqrt(2.pow(2 * p + 1) * n) + // sqrt(2 * 2.pow(2 * p) * n) + // sqrt(2) * sqrt(2.pow(2 * p)) * sqrt(n) + // sqrt(2) * 2.pow(p) * sqrt(n) + // sqrt(2) * (sqrt(n) << p) + const EVEN_MAKING_BITMASK: u32 = !1; + let normalization_shift = n.leading_zeros() & EVEN_MAKING_BITMASK; + n <<= normalization_shift; + + let s = $stages(n); + + let denormalization_shift = normalization_shift >> 1; + s >> denormalization_shift + } + } + }; +} + +/// Generates the first stage of the computation after normalization. +/// +/// # Safety +/// +/// `$n` must be nonzero. +macro_rules! first_stage { + ($original_bits:literal, $n:ident) => {{ + debug_assert!($n != 0, "`$n` is zero in `first_stage!`."); + + const N_SHIFT: u32 = $original_bits - 8; + let n = $n >> N_SHIFT; + + let (s, r) = U8_ISQRT_WITH_REMAINDER[n as usize]; + + // Inform the optimizer that `s` is nonzero. This will allow it to + // avoid generating code to handle division-by-zero panics in the next + // stage. + // + // SAFETY: If the original `$n` is zero, the top of the `unsigned_fn` + // macro recurses instead of continuing to this point, so the original + // `$n` wasn't a 0 if we've reached here. + // + // Then the `unsigned_fn` macro normalizes `$n` so that at least one of + // its two most-significant bits is a 1. + // + // Then this stage puts the eight most-significant bits of `$n` into + // `n`. This means that `n` here has at least one 1 bit in its two + // most-significant bits, making `n` nonzero. + // + // `U8_ISQRT_WITH_REMAINDER[n as usize]` will give a nonzero `s` when + // given a nonzero `n`. + unsafe { crate::hint::assert_unchecked(s != 0) }; + (s, r) + }}; +} + +/// Generates a middle stage of the computation. +/// +/// # Safety +/// +/// `$s` must be nonzero. +macro_rules! middle_stage { + ($original_bits:literal, $ty:ty, $n:ident, $s:ident, $r:ident) => {{ + debug_assert!($s != 0, "`$s` is zero in `middle_stage!`."); + + const N_SHIFT: u32 = $original_bits - <$ty>::BITS; + let n = ($n >> N_SHIFT) as $ty; + + const HALF_BITS: u32 = <$ty>::BITS >> 1; + const QUARTER_BITS: u32 = <$ty>::BITS >> 2; + const LOWER_HALF_1_BITS: $ty = (1 << HALF_BITS) - 1; + const LOWEST_QUARTER_1_BITS: $ty = (1 << QUARTER_BITS) - 1; + + let lo = n & LOWER_HALF_1_BITS; + let numerator = (($r as $ty) << QUARTER_BITS) | (lo >> QUARTER_BITS); + let denominator = ($s as $ty) << 1; + let q = numerator / denominator; + let u = numerator % denominator; + + let mut s = ($s << QUARTER_BITS) as $ty + q; + let (mut r, overflow) = + ((u << QUARTER_BITS) | (lo & LOWEST_QUARTER_1_BITS)).overflowing_sub(q * q); + if overflow { + r = r.wrapping_add(2 * s - 1); + s -= 1; + } + + // Inform the optimizer that `s` is nonzero. This will allow it to + // avoid generating code to handle division-by-zero panics in the next + // stage. + // + // SAFETY: If the original `$n` is zero, the top of the `unsigned_fn` + // macro recurses instead of continuing to this point, so the original + // `$n` wasn't a 0 if we've reached here. + // + // Then the `unsigned_fn` macro normalizes `$n` so that at least one of + // its two most-significant bits is a 1. + // + // Then these stages take as many of the most-significant bits of `$n` + // as will fit in this stage's type. For example, the stage that + // handles `u32` deals with the 32 most-significant bits of `$n`. This + // means that each stage has at least one 1 bit in `n`'s two + // most-significant bits, making `n` nonzero. + // + // Then this stage will produce the correct integer square root for + // that `n` value. Since `n` is nonzero, `s` will also be nonzero. + unsafe { crate::hint::assert_unchecked(s != 0) }; + (s, r) + }}; +} + +/// Generates the last stage of the computation before denormalization. +/// +/// # Safety +/// +/// `$s` must be nonzero. +macro_rules! last_stage { + ($ty:ty, $n:ident, $s:ident, $r:ident) => {{ + debug_assert!($s != 0, "`$s` is zero in `last_stage!`."); + + const HALF_BITS: u32 = <$ty>::BITS >> 1; + const QUARTER_BITS: u32 = <$ty>::BITS >> 2; + const LOWER_HALF_1_BITS: $ty = (1 << HALF_BITS) - 1; + + let lo = $n & LOWER_HALF_1_BITS; + let numerator = (($r as $ty) << QUARTER_BITS) | (lo >> QUARTER_BITS); + let denominator = ($s as $ty) << 1; + + let q = numerator / denominator; + let mut s = ($s << QUARTER_BITS) as $ty + q; + let (s_squared, overflow) = s.overflowing_mul(s); + if overflow || s_squared > $n { + s -= 1; + } + s + }}; +} + +/// Takes the normalized [`u16`](prim@u16) input and gets its normalized +/// [integer square root](https://en.wikipedia.org/wiki/Integer_square_root). +/// +/// # Safety +/// +/// `n` must be nonzero. +#[inline] +const fn u16_stages(n: u16) -> u16 { + let (s, r) = first_stage!(16, n); + last_stage!(u16, n, s, r) +} + +/// Takes the normalized [`u32`](prim@u32) input and gets its normalized +/// [integer square root](https://en.wikipedia.org/wiki/Integer_square_root). +/// +/// # Safety +/// +/// `n` must be nonzero. +#[inline] +const fn u32_stages(n: u32) -> u32 { + let (s, r) = first_stage!(32, n); + let (s, r) = middle_stage!(32, u16, n, s, r); + last_stage!(u32, n, s, r) +} + +/// Takes the normalized [`u64`](prim@u64) input and gets its normalized +/// [integer square root](https://en.wikipedia.org/wiki/Integer_square_root). +/// +/// # Safety +/// +/// `n` must be nonzero. +#[inline] +const fn u64_stages(n: u64) -> u64 { + let (s, r) = first_stage!(64, n); + let (s, r) = middle_stage!(64, u16, n, s, r); + let (s, r) = middle_stage!(64, u32, n, s, r); + last_stage!(u64, n, s, r) +} + +/// Takes the normalized [`u128`](prim@u128) input and gets its normalized +/// [integer square root](https://en.wikipedia.org/wiki/Integer_square_root). +/// +/// # Safety +/// +/// `n` must be nonzero. +#[inline] +const fn u128_stages(n: u128) -> u128 { + let (s, r) = first_stage!(128, n); + let (s, r) = middle_stage!(128, u16, n, s, r); + let (s, r) = middle_stage!(128, u32, n, s, r); + let (s, r) = middle_stage!(128, u64, n, s, r); + last_stage!(u128, n, s, r) +} + +unsigned_fn!(u16, u8, u16_stages); +unsigned_fn!(u32, u16, u32_stages); +unsigned_fn!(u64, u32, u64_stages); +unsigned_fn!(u128, u64, u128_stages); + +/// Instantiate this panic logic once, rather than for all the isqrt methods +/// on every single primitive type. +#[cold] +#[track_caller] +pub const fn panic_for_negative_argument() -> ! { + panic!("argument of integer square root cannot be negative") +} diff --git a/library/core/src/num/mod.rs b/library/core/src/num/mod.rs index 309e1ba958a..e9e5324666a 100644 --- a/library/core/src/num/mod.rs +++ b/library/core/src/num/mod.rs @@ -41,6 +41,7 @@ mod uint_macros; // import uint_impl! mod error; mod int_log10; +mod int_sqrt; mod nonzero; mod overflow_panic; mod saturating; diff --git a/library/core/src/num/nonzero.rs b/library/core/src/num/nonzero.rs index c6e9c249048..8b888f12da0 100644 --- a/library/core/src/num/nonzero.rs +++ b/library/core/src/num/nonzero.rs @@ -7,7 +7,7 @@ use crate::marker::{Freeze, StructuralPartialEq}; use crate::ops::{BitOr, BitOrAssign, Div, DivAssign, Neg, Rem, RemAssign}; use crate::panic::{RefUnwindSafe, UnwindSafe}; use crate::str::FromStr; -use crate::{fmt, hint, intrinsics, ptr, ub_checks}; +use crate::{fmt, intrinsics, ptr, ub_checks}; /// A marker trait for primitive types which can be zero. /// @@ -1545,31 +1545,14 @@ macro_rules! nonzero_integer_signedness_dependent_methods { without modifying the original"] #[inline] pub const fn isqrt(self) -> Self { - // The algorithm is based on the one presented in - // <https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Binary_numeral_system_(base_2)> - // which cites as source the following C code: - // <https://web.archive.org/web/20120306040058/http://medialab.freaknet.org/martin/src/sqrt/sqrt.c>. - - let mut op = self.get(); - let mut res = 0; - let mut one = 1 << (self.ilog2() & !1); - - while one != 0 { - if op >= res + one { - op -= res + one; - res = (res >> 1) + one; - } else { - res >>= 1; - } - one >>= 2; - } + let result = self.get().isqrt(); - // SAFETY: The result fits in an integer with half as many bits. - // Inform the optimizer about it. - unsafe { hint::assert_unchecked(res < 1 << (Self::BITS / 2)) }; - - // SAFETY: The square root of an integer >= 1 is always >= 1. - unsafe { Self::new_unchecked(res) } + // SAFETY: Integer square root is a monotonically nondecreasing + // function, which means that increasing the input will never cause + // the output to decrease. Thus, since the input for nonzero + // unsigned integers has a lower bound of 1, the lower bound of the + // results will be sqrt(1), which is 1, so a result can't be zero. + unsafe { Self::new_unchecked(result) } } }; diff --git a/library/core/src/num/uint_macros.rs b/library/core/src/num/uint_macros.rs index 0d0bbc5256f..d9036abecc5 100644 --- a/library/core/src/num/uint_macros.rs +++ b/library/core/src/num/uint_macros.rs @@ -2762,10 +2762,24 @@ macro_rules! uint_impl { without modifying the original"] #[inline] pub const fn isqrt(self) -> Self { - match NonZero::new(self) { - Some(x) => x.isqrt().get(), - None => 0, + let result = crate::num::int_sqrt::$ActualT(self as $ActualT) as $SelfT; + + // Inform the optimizer what the range of outputs is. If testing + // `core` crashes with no panic message and a `num::int_sqrt::u*` + // test failed, it's because your edits caused these assertions or + // the assertions in `fn isqrt` of `nonzero.rs` to become false. + // + // SAFETY: Integer square root is a monotonically nondecreasing + // function, which means that increasing the input will never + // cause the output to decrease. Thus, since the input for unsigned + // integers is bounded by `[0, <$ActualT>::MAX]`, sqrt(n) will be + // bounded by `[sqrt(0), sqrt(<$ActualT>::MAX)]`. + unsafe { + const MAX_RESULT: $SelfT = crate::num::int_sqrt::$ActualT(<$ActualT>::MAX) as $SelfT; + crate::hint::assert_unchecked(result <= MAX_RESULT); } + + result } /// Performs Euclidean division. diff --git a/library/core/src/panic/location.rs b/library/core/src/panic/location.rs index 930edffd505..e2a842046a9 100644 --- a/library/core/src/panic/location.rs +++ b/library/core/src/panic/location.rs @@ -195,6 +195,7 @@ impl<'a> Location<'a> { #[stable(feature = "panic_hook_display", since = "1.26.0")] impl fmt::Display for Location<'_> { + #[inline] fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { write!(formatter, "{}:{}:{}", self.file, self.line, self.col) } diff --git a/library/core/src/pin.rs b/library/core/src/pin.rs index 780e476f531..65f6bfb7ee1 100644 --- a/library/core/src/pin.rs +++ b/library/core/src/pin.rs @@ -1370,7 +1370,15 @@ impl<Ptr: Deref> Pin<Ptr> { // SAFETY: see documentation on this function unsafe { Pin::new_unchecked(&*self.__pointer) } } +} +// These methods being in a `Ptr: DerefMut` impl block concerns semver stability. +// Currently, calling e.g. `.set()` on a `Pin<&T>` sees that `Ptr: DerefMut` +// doesn't hold, and goes to check for a `.set()` method on `T`. But, if the +// `where Ptr: DerefMut` bound is moved to the method, rustc sees the impl block +// as a valid candidate, and doesn't go on to check other candidates when it +// sees that the bound on the method. +impl<Ptr: DerefMut> Pin<Ptr> { /// Gets a mutable reference to the pinned value this `Pin<Ptr>` points to. /// /// This is a generic method to go from `&mut Pin<Pointer<T>>` to `Pin<&mut T>`. @@ -1402,10 +1410,7 @@ impl<Ptr: Deref> Pin<Ptr> { /// ``` #[stable(feature = "pin", since = "1.33.0")] #[inline(always)] - pub fn as_mut(&mut self) -> Pin<&mut Ptr::Target> - where - Ptr: DerefMut, - { + pub fn as_mut(&mut self) -> Pin<&mut Ptr::Target> { // SAFETY: see documentation on this function unsafe { Pin::new_unchecked(&mut *self.__pointer) } } @@ -1420,10 +1425,7 @@ impl<Ptr: Deref> Pin<Ptr> { #[unstable(feature = "pin_deref_mut", issue = "86918")] #[must_use = "`self` will be dropped if the result is not used"] #[inline(always)] - pub fn as_deref_mut(self: Pin<&mut Pin<Ptr>>) -> Pin<&mut Ptr::Target> - where - Ptr: DerefMut, - { + pub fn as_deref_mut(self: Pin<&mut Pin<Ptr>>) -> Pin<&mut Ptr::Target> { // SAFETY: What we're asserting here is that going from // // Pin<&mut Pin<Ptr>> @@ -1475,12 +1477,13 @@ impl<Ptr: Deref> Pin<Ptr> { #[inline(always)] pub fn set(&mut self, value: Ptr::Target) where - Ptr: DerefMut, Ptr::Target: Sized, { *(self.__pointer) = value; } +} +impl<Ptr: Deref> Pin<Ptr> { /// Unwraps this `Pin<Ptr>`, returning the underlying `Ptr`. /// /// # Safety diff --git a/library/core/src/primitive_docs.rs b/library/core/src/primitive_docs.rs index 7f35c7789e2..fe6ed7e0cf3 100644 --- a/library/core/src/primitive_docs.rs +++ b/library/core/src/primitive_docs.rs @@ -1130,8 +1130,8 @@ impl<T> (T,) {} /// A 16-bit floating point type (specifically, the "binary16" type defined in IEEE 754-2008). /// /// This type is very similar to [`prim@f32`] but has decreased precision because it uses half as many -/// bits. Please see [the documentation for [`prim@f32`] or [Wikipedia on -/// half-precision values][wikipedia] for more information. +/// bits. Please see [the documentation for `f32`](prim@f32) or [Wikipedia on half-precision +/// values][wikipedia] for more information. /// /// Note that most common platforms will not support `f16` in hardware without enabling extra target /// features, with the notable exception of Apple Silicon (also known as M1, M2, etc.) processors. @@ -1296,14 +1296,12 @@ mod prim_f32 {} #[doc(alias = "double")] /// A 64-bit floating point type (specifically, the "binary64" type defined in IEEE 754-2008). /// -/// This type is very similar to [`f32`], but has increased -/// precision by using twice as many bits. Please see [the documentation for -/// `f32`][`f32`] or [Wikipedia on double precision +/// This type is very similar to [`prim@f32`], but has increased precision by using twice as many +/// bits. Please see [the documentation for `f32`](prim@f32) or [Wikipedia on double-precision /// values][wikipedia] for more information. /// /// *[See also the `std::f64::consts` module](crate::f64::consts).* /// -/// [`f32`]: prim@f32 /// [wikipedia]: https://en.wikipedia.org/wiki/Double-precision_floating-point_format #[stable(feature = "rust1", since = "1.0.0")] mod prim_f64 {} @@ -1313,12 +1311,12 @@ mod prim_f64 {} /// A 128-bit floating point type (specifically, the "binary128" type defined in IEEE 754-2008). /// /// This type is very similar to [`prim@f32`] and [`prim@f64`], but has increased precision by using twice -/// as many bits as `f64`. Please see [the documentation for [`prim@f32`] or [Wikipedia on +/// as many bits as `f64`. Please see [the documentation for `f32`](prim@f32) or [Wikipedia on /// quad-precision values][wikipedia] for more information. /// /// Note that no platforms have hardware support for `f128` without enabling target specific features, /// as for all instruction set architectures `f128` is considered an optional feature. -/// Only Power ISA ("PowerPC") and RISCV specify it, and only certain microarchitectures +/// Only Power ISA ("PowerPC") and RISC-V specify it, and only certain microarchitectures /// actually implement it. For x86-64 and AArch64, ISA support is not even specified, /// so it will always be a software implementation significantly slower than `f64`. /// diff --git a/library/core/src/ptr/mod.rs b/library/core/src/ptr/mod.rs index 859fad9e069..d7ed4edcc00 100644 --- a/library/core/src/ptr/mod.rs +++ b/library/core/src/ptr/mod.rs @@ -57,50 +57,42 @@ //! [`NonNull::dangling`] in such cases. //! //! ## Pointer to reference conversion -//! When converting a pointer to a reference `&T` using `&*`, +//! +//! When converting a pointer to a reference (e.g. via `&*ptr` or `&mut *ptr`), //! there are several rules that must be followed: //! //! * The pointer must be properly aligned. //! -// some microprocessors may use address 0 for an interrupt vector. -// users of these microprocessors must always read/write address 0 through -// a raw pointer, not a reference. //! * It must be non-null. //! //! * It must be "dereferenceable" in the sense defined above. //! -//! * The pointer must point to a valid value of type `T`. -//! This means that the created reference can only refer to -//! uninitialized memory through careful use of `MaybeUninit`, -//! or if the uninitialized memory is entirely contained within -//! padding bytes, since -//! [padding has the same validity invariant as `MaybeUninit`][ucg-pad]. -//! -//! * You must enforce Rust's aliasing rules, since the lifetime of the -//! created reference is arbitrarily chosen, -//! and does not necessarily reflect the actual lifetime of the data. -//! In particular, while this reference exists, -//! the memory the pointer points to must -//! not get accessed (read or written) through any raw pointer, -//! except for data inside an `UnsafeCell`. -//! Note that aliased writes are always UB for mutable references, -//! even if they only modify `UnsafeCell` data. +//! * The pointer must point to a [valid value] of type `T`. +//! +//! * You must enforce Rust's aliasing rules. The exact aliasing rules are not decided yet, so we +//! only give a rough overview here. The rules also depend on whether a mutable or a shared +//! reference is being created. +//! * When creating a mutable reference, then while this reference exists, the memory it points to +//! must not get accessed (read or written) through any other pointer or reference not derived +//! from this reference. +//! * When creating a shared reference, then while this reference exists, the memory it points to +//! must not get mutated (except inside `UnsafeCell`). //! //! If a pointer follows all of these rules, it is said to be -//! *convertible to a reference*. +//! *convertible to a (mutable or shared) reference*. // ^ we use this term instead of saying that the produced reference must // be valid, as the validity of a reference is easily confused for the // validity of the thing it refers to, and while the two concepts are // closly related, they are not identical. //! -//! These apply even if the result is unused! +//! These rules apply even if the result is unused! //! (The part about being initialized is not yet fully decided, but until //! it is, the only safe approach is to ensure that they are indeed initialized.) //! //! An example of the implications of the above rules is that an expression such //! as `unsafe { &*(0 as *const u8) }` is Immediate Undefined Behavior. //! -//! [ucgpad]: https://rust-lang.github.io/unsafe-code-guidelines/glossary.html#padding +//! [valid value]: ../../reference/behavior-considered-undefined.html#invalid-values //! //! ## Allocated object //! diff --git a/library/core/src/slice/mod.rs b/library/core/src/slice/mod.rs index c76157720b7..c7918499d4a 100644 --- a/library/core/src/slice/mod.rs +++ b/library/core/src/slice/mod.rs @@ -3667,8 +3667,8 @@ impl<T> [T] { { // The panic code path was put into a cold function to not bloat the // call site. - #[inline(never)] - #[cold] + #[cfg_attr(not(feature = "panic_immediate_abort"), inline(never), cold)] + #[cfg_attr(feature = "panic_immediate_abort", inline)] #[track_caller] fn len_mismatch_fail(dst_len: usize, src_len: usize) -> ! { panic!( diff --git a/library/core/src/slice/sort/shared/smallsort.rs b/library/core/src/slice/sort/shared/smallsort.rs index db0c5c72822..fae628a7c14 100644 --- a/library/core/src/slice/sort/shared/smallsort.rs +++ b/library/core/src/slice/sort/shared/smallsort.rs @@ -840,7 +840,8 @@ unsafe fn bidirectional_merge<T: FreezeMarker, F: FnMut(&T, &T) -> bool>( } } -#[inline(never)] +#[cfg_attr(not(feature = "panic_immediate_abort"), inline(never), cold)] +#[cfg_attr(feature = "panic_immediate_abort", inline)] fn panic_on_ord_violation() -> ! { // This is indicative of a logic bug in the user-provided comparison function or Ord // implementation. They are expected to implement a total order as explained in the Ord diff --git a/library/core/tests/num/int_macros.rs b/library/core/tests/num/int_macros.rs index 7cd3b54e3f3..830a96204ca 100644 --- a/library/core/tests/num/int_macros.rs +++ b/library/core/tests/num/int_macros.rs @@ -289,38 +289,6 @@ macro_rules! int_module { } #[test] - fn test_isqrt() { - assert_eq!($T::MIN.checked_isqrt(), None); - assert_eq!((-1 as $T).checked_isqrt(), None); - assert_eq!((0 as $T).isqrt(), 0 as $T); - assert_eq!((1 as $T).isqrt(), 1 as $T); - assert_eq!((2 as $T).isqrt(), 1 as $T); - assert_eq!((99 as $T).isqrt(), 9 as $T); - assert_eq!((100 as $T).isqrt(), 10 as $T); - } - - #[cfg(not(miri))] // Miri is too slow - #[test] - fn test_lots_of_isqrt() { - let n_max: $T = (1024 * 1024).min($T::MAX as u128) as $T; - for n in 0..=n_max { - let isqrt: $T = n.isqrt(); - - assert!(isqrt.pow(2) <= n); - let (square, overflow) = (isqrt + 1).overflowing_pow(2); - assert!(overflow || square > n); - } - - for n in ($T::MAX - 127)..=$T::MAX { - let isqrt: $T = n.isqrt(); - - assert!(isqrt.pow(2) <= n); - let (square, overflow) = (isqrt + 1).overflowing_pow(2); - assert!(overflow || square > n); - } - } - - #[test] fn test_div_floor() { let a: $T = 8; let b = 3; diff --git a/library/core/tests/num/int_sqrt.rs b/library/core/tests/num/int_sqrt.rs new file mode 100644 index 00000000000..d68db0787d2 --- /dev/null +++ b/library/core/tests/num/int_sqrt.rs @@ -0,0 +1,248 @@ +macro_rules! tests { + ($isqrt_consistency_check_fn_macro:ident : $($T:ident)+) => { + $( + mod $T { + $isqrt_consistency_check_fn_macro!($T); + + // Check that the following produce the correct values from + // `isqrt`: + // + // * the first and last 128 nonnegative values + // * powers of two, minus one + // * powers of two + // + // For signed types, check that `checked_isqrt` and `isqrt` + // either produce the same numeric value or respectively + // produce `None` and a panic. Make sure to do a consistency + // check for `<$T>::MIN` as well, as no nonnegative values + // negate to it. + // + // For unsigned types check that `isqrt` produces the same + // numeric value for `$T` and `NonZero<$T>`. + #[test] + fn isqrt() { + isqrt_consistency_check(<$T>::MIN); + + for n in (0..=127) + .chain(<$T>::MAX - 127..=<$T>::MAX) + .chain((0..<$T>::MAX.count_ones()).map(|exponent| (1 << exponent) - 1)) + .chain((0..<$T>::MAX.count_ones()).map(|exponent| 1 << exponent)) + { + isqrt_consistency_check(n); + + let isqrt_n = n.isqrt(); + assert!( + isqrt_n + .checked_mul(isqrt_n) + .map(|isqrt_n_squared| isqrt_n_squared <= n) + .unwrap_or(false), + "`{n}.isqrt()` should be lower than {isqrt_n}." + ); + assert!( + (isqrt_n + 1) + .checked_mul(isqrt_n + 1) + .map(|isqrt_n_plus_1_squared| n < isqrt_n_plus_1_squared) + .unwrap_or(true), + "`{n}.isqrt()` should be higher than {isqrt_n})." + ); + } + } + + // Check the square roots of: + // + // * the first 1,024 perfect squares + // * halfway between each of the first 1,024 perfect squares + // and the next perfect square + // * the next perfect square after the each of the first 1,024 + // perfect squares, minus one + // * the last 1,024 perfect squares + // * the last 1,024 perfect squares, minus one + // * halfway between each of the last 1,024 perfect squares + // and the previous perfect square + #[test] + // Skip this test on Miri, as it takes too long to run. + #[cfg(not(miri))] + fn isqrt_extended() { + // The correct value is worked out by using the fact that + // the nth nonzero perfect square is the sum of the first n + // odd numbers: + // + // 1 = 1 + // 4 = 1 + 3 + // 9 = 1 + 3 + 5 + // 16 = 1 + 3 + 5 + 7 + // + // Note also that the last odd number added in is two times + // the square root of the previous perfect square, plus + // one: + // + // 1 = 2*0 + 1 + // 3 = 2*1 + 1 + // 5 = 2*2 + 1 + // 7 = 2*3 + 1 + // + // That means we can add the square root of this perfect + // square once to get about halfway to the next perfect + // square, then we can add the square root of this perfect + // square again to get to the next perfect square, minus + // one, then we can add one to get to the next perfect + // square. + // + // This allows us to, for each of the first 1,024 perfect + // squares, test that the square roots of the following are + // all correct and equal to each other: + // + // * the current perfect square + // * about halfway to the next perfect square + // * the next perfect square, minus one + let mut n: $T = 0; + for sqrt_n in 0..1_024.min((1_u128 << (<$T>::MAX.count_ones()/2)) - 1) as $T { + isqrt_consistency_check(n); + assert_eq!( + n.isqrt(), + sqrt_n, + "`{sqrt_n}.pow(2).isqrt()` should be {sqrt_n}." + ); + + n += sqrt_n; + isqrt_consistency_check(n); + assert_eq!( + n.isqrt(), + sqrt_n, + "{n} is about halfway between `{sqrt_n}.pow(2)` and `{}.pow(2)`, so `{n}.isqrt()` should be {sqrt_n}.", + sqrt_n + 1 + ); + + n += sqrt_n; + isqrt_consistency_check(n); + assert_eq!( + n.isqrt(), + sqrt_n, + "`({}.pow(2) - 1).isqrt()` should be {sqrt_n}.", + sqrt_n + 1 + ); + + n += 1; + } + + // Similarly, for each of the last 1,024 perfect squares, + // check: + // + // * the current perfect square + // * the current perfect square, minus one + // * about halfway to the previous perfect square + // + // `MAX`'s `isqrt` return value is verified in the `isqrt` + // test function above. + let maximum_sqrt = <$T>::MAX.isqrt(); + let mut n = maximum_sqrt * maximum_sqrt; + + for sqrt_n in (maximum_sqrt - 1_024.min((1_u128 << (<$T>::MAX.count_ones()/2)) - 1) as $T..maximum_sqrt).rev() { + isqrt_consistency_check(n); + assert_eq!( + n.isqrt(), + sqrt_n + 1, + "`{0}.pow(2).isqrt()` should be {0}.", + sqrt_n + 1 + ); + + n -= 1; + isqrt_consistency_check(n); + assert_eq!( + n.isqrt(), + sqrt_n, + "`({}.pow(2) - 1).isqrt()` should be {sqrt_n}.", + sqrt_n + 1 + ); + + n -= sqrt_n; + isqrt_consistency_check(n); + assert_eq!( + n.isqrt(), + sqrt_n, + "{n} is about halfway between `{sqrt_n}.pow(2)` and `{}.pow(2)`, so `{n}.isqrt()` should be {sqrt_n}.", + sqrt_n + 1 + ); + + n -= sqrt_n; + } + } + } + )* + }; +} + +macro_rules! signed_check { + ($T:ident) => { + /// This takes an input and, if it's nonnegative or + #[doc = concat!("`", stringify!($T), "::MIN`,")] + /// checks that `isqrt` and `checked_isqrt` produce equivalent results + /// for that input and for the negative of that input. + /// + /// # Note + /// + /// This cannot check that negative inputs to `isqrt` cause panics if + /// panics abort instead of unwind. + fn isqrt_consistency_check(n: $T) { + // `<$T>::MIN` will be negative, so ignore it in this nonnegative + // section. + if n >= 0 { + assert_eq!( + Some(n.isqrt()), + n.checked_isqrt(), + "`{n}.checked_isqrt()` should match `Some({n}.isqrt())`.", + ); + } + + // `wrapping_neg` so that `<$T>::MIN` will negate to itself rather + // than panicking. + let negative_n = n.wrapping_neg(); + + // Zero negated will still be nonnegative, so ignore it in this + // negative section. + if negative_n < 0 { + assert_eq!( + negative_n.checked_isqrt(), + None, + "`({negative_n}).checked_isqrt()` should be `None`, as {negative_n} is negative.", + ); + + // `catch_unwind` only works when panics unwind rather than abort. + #[cfg(panic = "unwind")] + { + std::panic::catch_unwind(core::panic::AssertUnwindSafe(|| (-n).isqrt())).expect_err( + &format!("`({negative_n}).isqrt()` should have panicked, as {negative_n} is negative.") + ); + } + } + } + }; +} + +macro_rules! unsigned_check { + ($T:ident) => { + /// This takes an input and, if it's nonzero, checks that `isqrt` + /// produces the same numeric value for both + #[doc = concat!("`", stringify!($T), "` and ")] + #[doc = concat!("`NonZero<", stringify!($T), ">`.")] + fn isqrt_consistency_check(n: $T) { + // Zero cannot be turned into a `NonZero` value, so ignore it in + // this nonzero section. + if n > 0 { + assert_eq!( + n.isqrt(), + core::num::NonZero::<$T>::new(n) + .expect( + "Was not able to create a new `NonZero` value from a nonzero number." + ) + .isqrt() + .get(), + "`{n}.isqrt` should match `NonZero`'s `{n}.isqrt().get()`.", + ); + } + } + }; +} + +tests!(signed_check: i8 i16 i32 i64 i128); +tests!(unsigned_check: u8 u16 u32 u64 u128); diff --git a/library/core/tests/num/mod.rs b/library/core/tests/num/mod.rs index dad46ad88fe..b14fe0b22c3 100644 --- a/library/core/tests/num/mod.rs +++ b/library/core/tests/num/mod.rs @@ -27,6 +27,7 @@ mod const_from; mod dec2flt; mod flt2dec; mod int_log; +mod int_sqrt; mod ops; mod wrapping; diff --git a/library/proc_macro/src/lib.rs b/library/proc_macro/src/lib.rs index c271ac18706..72b53c60f74 100644 --- a/library/proc_macro/src/lib.rs +++ b/library/proc_macro/src/lib.rs @@ -28,7 +28,6 @@ #![feature(decl_macro)] #![feature(maybe_uninit_write_slice)] #![feature(negative_impls)] -#![feature(new_uninit)] #![feature(panic_can_unwind)] #![feature(restricted_std)] #![feature(rustc_attrs)] diff --git a/library/std/Cargo.toml b/library/std/Cargo.toml index 334c75df231..5f0144922ca 100644 --- a/library/std/Cargo.toml +++ b/library/std/Cargo.toml @@ -17,7 +17,7 @@ cfg-if = { version = "1.0", features = ['rustc-dep-of-std'] } panic_unwind = { path = "../panic_unwind", optional = true } panic_abort = { path = "../panic_abort" } core = { path = "../core", public = true } -compiler_builtins = { version = "0.1.121" } +compiler_builtins = { version = "0.1.123" } profiler_builtins = { path = "../profiler_builtins", optional = true } unwind = { path = "../unwind" } hashbrown = { version = "0.14", default-features = false, features = [ diff --git a/library/std/src/f128.rs b/library/std/src/f128.rs index 506d708d0d2..b436fe9929c 100644 --- a/library/std/src/f128.rs +++ b/library/std/src/f128.rs @@ -250,9 +250,14 @@ impl f128 { /// /// Equal to `self` if the sign of `self` and `sign` are the same, otherwise equal to `-self`. /// If `self` is a NaN, then a NaN with the same payload as `self` and the sign bit of `sign` is - /// returned. Note, however, that conserving the sign bit on NaN across arithmetical operations - /// is not generally guaranteed. See [specification of NaN bit - /// patterns](primitive@f32#nan-bit-patterns) for more info. + /// returned. + /// + /// If `sign` is a NaN, then this operation will still carry over its sign into the result. Note + /// that IEEE 754 doesn't assign any meaning to the sign bit in case of a NaN, and as Rust + /// doesn't guarantee that the bit pattern of NaNs are conserved over arithmetic operations, the + /// result of `copysign` with `sign` being a NaN might produce an unexpected or non-portable + /// result. See the [specification of NaN bit patterns](primitive@f32#nan-bit-patterns) for more + /// info. /// /// # Examples /// diff --git a/library/std/src/f16.rs b/library/std/src/f16.rs index 033a3d45009..b2cd5fae9d0 100644 --- a/library/std/src/f16.rs +++ b/library/std/src/f16.rs @@ -249,9 +249,14 @@ impl f16 { /// /// Equal to `self` if the sign of `self` and `sign` are the same, otherwise equal to `-self`. /// If `self` is a NaN, then a NaN with the same payload as `self` and the sign bit of `sign` is - /// returned. Note, however, that conserving the sign bit on NaN across arithmetical operations - /// is not generally guaranteed. See [specification of NaN bit - /// patterns](primitive@f32#nan-bit-patterns) for more info. + /// returned. + /// + /// If `sign` is a NaN, then this operation will still carry over its sign into the result. Note + /// that IEEE 754 doesn't assign any meaning to the sign bit in case of a NaN, and as Rust + /// doesn't guarantee that the bit pattern of NaNs are conserved over arithmetic operations, the + /// result of `copysign` with `sign` being a NaN might produce an unexpected or non-portable + /// result. See the [specification of NaN bit patterns](primitive@f32#nan-bit-patterns) for more + /// info. /// /// # Examples /// diff --git a/library/std/src/f32.rs b/library/std/src/f32.rs index 35c2a77b533..cafbe9761da 100644 --- a/library/std/src/f32.rs +++ b/library/std/src/f32.rs @@ -228,9 +228,14 @@ impl f32 { /// /// Equal to `self` if the sign of `self` and `sign` are the same, otherwise equal to `-self`. /// If `self` is a NaN, then a NaN with the same payload as `self` and the sign bit of `sign` is - /// returned. Note, however, that conserving the sign bit on NaN across arithmetical operations - /// is not generally guaranteed. See [specification of NaN bit - /// patterns](primitive@f32#nan-bit-patterns) for more info. + /// returned. + /// + /// If `sign` is a NaN, then this operation will still carry over its sign into the result. Note + /// that IEEE 754 doesn't assign any meaning to the sign bit in case of a NaN, and as Rust + /// doesn't guarantee that the bit pattern of NaNs are conserved over arithmetic operations, the + /// result of `copysign` with `sign` being a NaN might produce an unexpected or non-portable + /// result. See the [specification of NaN bit patterns](primitive@f32#nan-bit-patterns) for more + /// info. /// /// # Examples /// diff --git a/library/std/src/f64.rs b/library/std/src/f64.rs index c177f74a97e..fba283e3a44 100644 --- a/library/std/src/f64.rs +++ b/library/std/src/f64.rs @@ -228,9 +228,14 @@ impl f64 { /// /// Equal to `self` if the sign of `self` and `sign` are the same, otherwise equal to `-self`. /// If `self` is a NaN, then a NaN with the same payload as `self` and the sign bit of `sign` is - /// returned. Note, however, that conserving the sign bit on NaN across arithmetical operations - /// is not generally guaranteed. See [specification of NaN bit - /// patterns](primitive@f32#nan-bit-patterns) for more info. + /// returned. + /// + /// If `sign` is a NaN, then this operation will still carry over its sign into the result. Note + /// that IEEE 754 doesn't assign any meaning to the sign bit in case of a NaN, and as Rust + /// doesn't guarantee that the bit pattern of NaNs are conserved over arithmetic operations, the + /// result of `copysign` with `sign` being a NaN might produce an unexpected or non-portable + /// result. See the [specification of NaN bit patterns](primitive@f32#nan-bit-patterns) for more + /// info. /// /// # Examples /// diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index f65e9bc8d8b..bea8eda2619 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -362,7 +362,6 @@ #![feature(allocator_api)] #![feature(get_mut_unchecked)] #![feature(map_try_insert)] -#![feature(new_uninit)] #![feature(new_zeroed_alloc)] #![feature(slice_concat_trait)] #![feature(thin_box)] diff --git a/library/std/src/process.rs b/library/std/src/process.rs index 9ffdebe1b6f..bbea27ebc10 100644 --- a/library/std/src/process.rs +++ b/library/std/src/process.rs @@ -2296,6 +2296,15 @@ impl Child { /// } /// ``` /// +/// In its current implementation, this function will execute exit handlers registered with `atexit` +/// as well as other platform-specific exit handlers (e.g. `fini` sections of ELF shared objects). +/// This means that Rust requires that all exit handlers are safe to execute at any time. In +/// particular, if an exit handler cleans up some state that might be concurrently accessed by other +/// threads, it is required that the exit handler performs suitable synchronization with those +/// threads. (The alternative to this requirement would be to not run exit handlers at all, which is +/// considered undesirable. Note that returning from `main` also calls `exit`, so making `exit` an +/// unsafe operation is not an option.) +/// /// ## Platform-specific behavior /// /// **Unix**: On Unix-like platforms, it is unlikely that all 32 bits of `exit` diff --git a/library/std/src/sys/pal/windows/c.rs b/library/std/src/sys/pal/windows/c.rs index 2f5d75dc4bc..b888eb7d95c 100644 --- a/library/std/src/sys/pal/windows/c.rs +++ b/library/std/src/sys/pal/windows/c.rs @@ -109,19 +109,15 @@ if #[cfg(not(target_vendor = "uwp"))] { } // Use raw-dylib to import ProcessPrng as we can't rely on there being an import library. -cfg_if::cfg_if! { -if #[cfg(not(target_vendor = "win7"))] { - #[cfg(target_arch = "x86")] - #[link(name = "bcryptprimitives", kind = "raw-dylib", import_name_type = "undecorated")] - extern "system" { - pub fn ProcessPrng(pbdata: *mut u8, cbdata: usize) -> BOOL; - } - #[cfg(not(target_arch = "x86"))] - #[link(name = "bcryptprimitives", kind = "raw-dylib")] - extern "system" { - pub fn ProcessPrng(pbdata: *mut u8, cbdata: usize) -> BOOL; - } -}} +#[cfg(not(target_vendor = "win7"))] +#[cfg_attr( + target_arch = "x86", + link(name = "bcryptprimitives", kind = "raw-dylib", import_name_type = "undecorated") +)] +#[cfg_attr(not(target_arch = "x86"), link(name = "bcryptprimitives", kind = "raw-dylib"))] +extern "system" { + pub fn ProcessPrng(pbdata: *mut u8, cbdata: usize) -> BOOL; +} // Functions that aren't available on every version of Windows that we support, // but we still use them and just provide some form of a fallback implementation. diff --git a/library/std/tests/run-time-detect.rs b/library/std/tests/run-time-detect.rs index 69486705656..dcd5cd7f6b9 100644 --- a/library/std/tests/run-time-detect.rs +++ b/library/std/tests/run-time-detect.rs @@ -5,6 +5,10 @@ feature(stdarch_arm_feature_detection) )] #![cfg_attr( + all(target_arch = "aarch64", any(target_os = "linux", target_os = "android")), + feature(stdarch_aarch64_feature_detection) +)] +#![cfg_attr( all(target_arch = "powerpc", target_os = "linux"), feature(stdarch_powerpc_feature_detection) )] @@ -36,21 +40,34 @@ fn aarch64_linux() { println!("bf16: {}", is_aarch64_feature_detected!("bf16")); println!("bti: {}", is_aarch64_feature_detected!("bti")); println!("crc: {}", is_aarch64_feature_detected!("crc")); + println!("cssc: {}", is_aarch64_feature_detected!("cssc")); println!("dit: {}", is_aarch64_feature_detected!("dit")); println!("dotprod: {}", is_aarch64_feature_detected!("dotprod")); println!("dpb2: {}", is_aarch64_feature_detected!("dpb2")); println!("dpb: {}", is_aarch64_feature_detected!("dpb")); + println!("ecv: {}", is_aarch64_feature_detected!("ecv")); println!("f32mm: {}", is_aarch64_feature_detected!("f32mm")); println!("f64mm: {}", is_aarch64_feature_detected!("f64mm")); + println!("faminmax: {}", is_aarch64_feature_detected!("faminmax")); println!("fcma: {}", is_aarch64_feature_detected!("fcma")); println!("fhm: {}", is_aarch64_feature_detected!("fhm")); + println!("flagm2: {}", is_aarch64_feature_detected!("flagm2")); println!("flagm: {}", is_aarch64_feature_detected!("flagm")); println!("fp16: {}", is_aarch64_feature_detected!("fp16")); + println!("fp8: {}", is_aarch64_feature_detected!("fp8")); + println!("fp8dot2: {}", is_aarch64_feature_detected!("fp8dot2")); + println!("fp8dot4: {}", is_aarch64_feature_detected!("fp8dot4")); + println!("fp8fma: {}", is_aarch64_feature_detected!("fp8fma")); + println!("fpmr: {}", is_aarch64_feature_detected!("fpmr")); println!("frintts: {}", is_aarch64_feature_detected!("frintts")); + println!("hbc: {}", is_aarch64_feature_detected!("hbc")); println!("i8mm: {}", is_aarch64_feature_detected!("i8mm")); println!("jsconv: {}", is_aarch64_feature_detected!("jsconv")); + println!("lse128: {}", is_aarch64_feature_detected!("lse128")); println!("lse2: {}", is_aarch64_feature_detected!("lse2")); println!("lse: {}", is_aarch64_feature_detected!("lse")); + println!("lut: {}", is_aarch64_feature_detected!("lut")); + println!("mops: {}", is_aarch64_feature_detected!("mops")); println!("mte: {}", is_aarch64_feature_detected!("mte")); println!("neon: {}", is_aarch64_feature_detected!("neon")); println!("paca: {}", is_aarch64_feature_detected!("paca")); @@ -58,20 +75,37 @@ fn aarch64_linux() { println!("pmull: {}", is_aarch64_feature_detected!("pmull")); println!("rand: {}", is_aarch64_feature_detected!("rand")); println!("rcpc2: {}", is_aarch64_feature_detected!("rcpc2")); + println!("rcpc3: {}", is_aarch64_feature_detected!("rcpc3")); println!("rcpc: {}", is_aarch64_feature_detected!("rcpc")); println!("rdm: {}", is_aarch64_feature_detected!("rdm")); println!("sb: {}", is_aarch64_feature_detected!("sb")); println!("sha2: {}", is_aarch64_feature_detected!("sha2")); println!("sha3: {}", is_aarch64_feature_detected!("sha3")); println!("sm4: {}", is_aarch64_feature_detected!("sm4")); + println!("sme-f16f16: {}", is_aarch64_feature_detected!("sme-f16f16")); + println!("sme-f64f64: {}", is_aarch64_feature_detected!("sme-f64f64")); + println!("sme-f8f16: {}", is_aarch64_feature_detected!("sme-f8f16")); + println!("sme-f8f32: {}", is_aarch64_feature_detected!("sme-f8f32")); + println!("sme-fa64: {}", is_aarch64_feature_detected!("sme-fa64")); + println!("sme-i16i64: {}", is_aarch64_feature_detected!("sme-i16i64")); + println!("sme-lutv2: {}", is_aarch64_feature_detected!("sme-lutv2")); + println!("sme2: {}", is_aarch64_feature_detected!("sme2")); + println!("sme2p1: {}", is_aarch64_feature_detected!("sme2p1")); + println!("sme: {}", is_aarch64_feature_detected!("sme")); println!("ssbs: {}", is_aarch64_feature_detected!("ssbs")); + println!("ssve-fp8dot2: {}", is_aarch64_feature_detected!("ssve-fp8dot2")); + println!("ssve-fp8dot4: {}", is_aarch64_feature_detected!("ssve-fp8dot4")); + println!("ssve-fp8fma: {}", is_aarch64_feature_detected!("ssve-fp8fma")); + println!("sve-b16b16: {}", is_aarch64_feature_detected!("sve-b16b16")); println!("sve2-aes: {}", is_aarch64_feature_detected!("sve2-aes")); println!("sve2-bitperm: {}", is_aarch64_feature_detected!("sve2-bitperm")); println!("sve2-sha3: {}", is_aarch64_feature_detected!("sve2-sha3")); println!("sve2-sm4: {}", is_aarch64_feature_detected!("sve2-sm4")); println!("sve2: {}", is_aarch64_feature_detected!("sve2")); + println!("sve2p1: {}", is_aarch64_feature_detected!("sve2p1")); println!("sve: {}", is_aarch64_feature_detected!("sve")); println!("tme: {}", is_aarch64_feature_detected!("tme")); + println!("wfxt: {}", is_aarch64_feature_detected!("wfxt")); // tidy-alphabetical-end } diff --git a/src/bootstrap/src/core/build_steps/clippy.rs b/src/bootstrap/src/core/build_steps/clippy.rs index 4ee9fbc3142..a2bb03cd5ac 100644 --- a/src/bootstrap/src/core/build_steps/clippy.rs +++ b/src/bootstrap/src/core/build_steps/clippy.rs @@ -313,7 +313,7 @@ lint_any!( RemoteTestServer, "src/tools/remote-test-server", "remote-test-server"; Rls, "src/tools/rls", "rls"; RustAnalyzer, "src/tools/rust-analyzer", "rust-analyzer"; - Rustdoc, "src/tools/rustdoc", "clippy"; + Rustdoc, "src/librustdoc", "clippy"; Rustfmt, "src/tools/rustfmt", "rustfmt"; RustInstaller, "src/tools/rust-installer", "rust-installer"; Tidy, "src/tools/tidy", "tidy"; diff --git a/src/doc/book b/src/doc/book -Subproject 04bc1396bb857f35b5dda1d773c9571e1f25330 +Subproject e7d217be2a75ef1753f0988d6ccaba4d7e37625 diff --git a/src/doc/edition-guide b/src/doc/edition-guide -Subproject aeeb287d41a0332c210da122bea8e0e91844ab3 +Subproject eeba2cb9c37ab74118a4fb5e5233f7397e4a91f diff --git a/src/doc/embedded-book b/src/doc/embedded-book -Subproject 019f3928d8b939ec71b63722dcc2e4633015644 +Subproject ff5d61d56f11e1986bfa9652c6aff7731576c37 diff --git a/src/doc/nomicon b/src/doc/nomicon -Subproject 6ecf95c5f2bfa0e6314dfe282bf775fd1405f7e +Subproject 14649f15d232d509478206ee9ed5105641aa60d diff --git a/src/doc/reference b/src/doc/reference -Subproject 62cd0df95061ba0ac886333f5cd7f3012f149da +Subproject 0668397076da350c404dadcf07b6cbc433ad374 diff --git a/src/doc/rust-by-example b/src/doc/rust-by-example -Subproject 8f94061936e492159f4f6c09c0f917a7521893f +Subproject 859786c5bc99301bbc22fc631a5c2b341860da0 diff --git a/src/doc/rustc-dev-guide b/src/doc/rustc-dev-guide -Subproject 43d83780db545a1ed6d45773312fc578987e396 +Subproject fa928a6d19e1666d8d811dfe3fd35cdad3b4e45 diff --git a/src/doc/rustc/src/check-cfg.md b/src/doc/rustc/src/check-cfg.md index dfc4871b924..992f14a79bf 100644 --- a/src/doc/rustc/src/check-cfg.md +++ b/src/doc/rustc/src/check-cfg.md @@ -99,7 +99,7 @@ the need to specify them manually. Well known names and values are implicitly added as long as at least one `--check-cfg` argument is present. -As of `2024-05-06T`, the list of known names is as follows: +As of `2024-08-20T`, the list of known names is as follows: <!--- See CheckCfg::fill_well_known in compiler/rustc_session/src/config.rs --> @@ -107,6 +107,7 @@ As of `2024-05-06T`, the list of known names is as follows: - `debug_assertions` - `doc` - `doctest` + - `fmt_debug` - `miri` - `overflow_checks` - `panic` diff --git a/src/doc/unstable-book/src/compiler-flags/fmt-debug.md b/src/doc/unstable-book/src/compiler-flags/fmt-debug.md new file mode 100644 index 00000000000..bb8663dceae --- /dev/null +++ b/src/doc/unstable-book/src/compiler-flags/fmt-debug.md @@ -0,0 +1,15 @@ +# `fmt-debug` + +The tracking issue for this feature is: [#129709](https://github.com/rust-lang/rust/issues/129709). + +------------------------ + +Option `-Z fmt-debug=val` controls verbosity of derived `Debug` implementations +and debug formatting in format strings (`{:?}`). + +* `full` — `#[derive(Debug)]` prints types recursively. This is the default behavior. + +* `shallow` — `#[derive(Debug)]` prints only the type name, or name of a variant of a fieldless enums. Details of the `Debug` implementation are not stable and may change in the future. Behavior of custom `fmt::Debug` implementations is not affected. + +* `none` — `#[derive(Debug)]` does not print anything at all. `{:?}` in formatting strings has no effect. + This option may reduce size of binaries, and remove occurrences of type names in the binary that are not removed by striping symbols. However, it may also cause `panic!` and `assert!` messages to be incomplete. diff --git a/src/doc/unstable-book/src/compiler-flags/lint-llvm-ir.md b/src/doc/unstable-book/src/compiler-flags/lint-llvm-ir.md new file mode 100644 index 00000000000..7b99c25a694 --- /dev/null +++ b/src/doc/unstable-book/src/compiler-flags/lint-llvm-ir.md @@ -0,0 +1,7 @@ +# `lint-llvm-ir` + +--------------------- + +This flag will add `LintPass` to the start of the pipeline. +You can use it to check for common errors in the LLVM IR generated by `rustc`. +You can add `-Cllvm-args=-lint-abort-on-error` to abort the process if errors were found. diff --git a/src/doc/unstable-book/src/compiler-flags/sanitizer.md b/src/doc/unstable-book/src/compiler-flags/sanitizer.md index edc63a25ac1..24940f0d6fb 100644 --- a/src/doc/unstable-book/src/compiler-flags/sanitizer.md +++ b/src/doc/unstable-book/src/compiler-flags/sanitizer.md @@ -775,22 +775,47 @@ See the [Clang SafeStack documentation][clang-safestack] for more details. # ShadowCallStack -ShadowCallStack provides backward edge control flow protection by storing a function's return address in a separately allocated 'shadow call stack' and loading the return address from that shadow call stack. - -ShadowCallStack requires a platform ABI which reserves `x18` as the instrumentation makes use of this register. +ShadowCallStack provides backward edge control flow protection by storing a function's return address in a separately allocated 'shadow call stack' +and loading the return address from that shadow call stack. +AArch64 and RISC-V both have a platform register defined in their ABIs, which is `x18` and `x3`/`gp` respectively, that can optionally be reserved for this purpose. +Software support from the operating system and runtime may be required depending on the target platform which is detailed in the remaining section. +See the [Clang ShadowCallStack documentation][clang-scs] for more details. ShadowCallStack can be enabled with `-Zsanitizer=shadow-call-stack` option and is supported on the following targets: -* `aarch64-linux-android` +## AArch64 family -A runtime must be provided by the application or operating system. +ShadowCallStack requires the use of the ABI defined platform register, `x18`, which is required for code generation purposes. +When `x18` is not reserved, and is instead used as a scratch register subsequently, enabling ShadowCallStack would lead to undefined behaviour +due to corruption of return address or invalid memory access when the instrumentation restores return register to the link register `lr` from the +already clobbered `x18` register. +In other words, code that is calling into or called by functions instrumented with ShadowCallStack must reserve the `x18` register or preserve its value. -See the [Clang ShadowCallStack documentation][clang-scs] for more details. +### `aarch64-linux-android` and `aarch64-unknown-fuchsia`/`aarch64-fuchsia` -* `aarch64-unknown-none` +This target already reserves the `x18` register. +A runtime must be provided by the application or operating system. +If `bionic` is used on this target, the software support is provided. +Otherwise, a runtime needs to prepare a memory region and points `x18` to the region which serves as the shadow call stack. + +### `aarch64-unknown-none` In addition to support from a runtime by the application or operating system, the `-Zfixed-x18` flag is also mandatory. +## RISC-V 64 family + +ShadowCallStack uses either the `gp` register for software shadow stack, also known as `x3`, or the `ssp` register if [`Zicfiss`][riscv-zicfiss] extension is available. +`gp`/`x3` is currently always reserved and available for ShadowCallStack instrumentation, and `ssp` in case of `Zicfiss` is only accessible through its dedicated shadow stack instructions. + +Support from the runtime and operating system is required when `gp`/`x3` is used for software shadow stack. +A runtime must prepare a memory region and point `gp`/`x3` to the region before executing the code. + +The following targets support ShadowCallStack. + +* `riscv64imac-unknown-none-elf` +* `riscv64gc-unknown-none-elf` +* `riscv64gc-unknown-fuchsia` + # ThreadSanitizer ThreadSanitizer is a data race detection tool. It is supported on the following @@ -912,3 +937,4 @@ Sanitizers produce symbolized stacktraces when llvm-symbolizer binary is in `PAT [clang-tsan]: https://clang.llvm.org/docs/ThreadSanitizer.html [linux-kasan]: https://www.kernel.org/doc/html/latest/dev-tools/kasan.html [llvm-memtag]: https://llvm.org/docs/MemTagSanitizer.html +[riscv-zicfiss]: https://github.com/riscv/riscv-cfi/blob/3f8e450c481ac303bd5643444f7a89672f24476e/src/cfi_backward.adoc diff --git a/src/doc/unstable-book/src/language-features/struct-target-features.md b/src/doc/unstable-book/src/language-features/struct-target-features.md new file mode 100644 index 00000000000..e814fe90072 --- /dev/null +++ b/src/doc/unstable-book/src/language-features/struct-target-features.md @@ -0,0 +1,7 @@ +# `struct_target_features` + +The tracking issue for this feature is: [#129107] + +[#129107]: https://github.com/rust-lang/rust/issues/129107 + +------------------------ diff --git a/src/librustdoc/clean/auto_trait.rs b/src/librustdoc/clean/auto_trait.rs index f46ffea830e..577b10a31ae 100644 --- a/src/librustdoc/clean/auto_trait.rs +++ b/src/librustdoc/clean/auto_trait.rs @@ -341,7 +341,7 @@ fn clean_region_outlives_constraints<'tcx>( .map(|®ion| { let lifetime = early_bound_region_name(region) .inspect(|name| assert!(region_params.contains(name))) - .map(|name| Lifetime(name)) + .map(Lifetime) .unwrap_or(Lifetime::statik()); clean::GenericBound::Outlives(lifetime) }) diff --git a/src/librustdoc/clean/blanket_impl.rs b/src/librustdoc/clean/blanket_impl.rs index 48c3fb65203..96e7f5c61c3 100644 --- a/src/librustdoc/clean/blanket_impl.rs +++ b/src/librustdoc/clean/blanket_impl.rs @@ -24,7 +24,7 @@ pub(crate) fn synthesize_blanket_impls( let mut blanket_impls = Vec::new(); for trait_def_id in tcx.all_traits() { if !cx.cache.effective_visibilities.is_reachable(tcx, trait_def_id) - || cx.generated_synthetics.get(&(ty.skip_binder(), trait_def_id)).is_some() + || cx.generated_synthetics.contains(&(ty.skip_binder(), trait_def_id)) { continue; } diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs index f8953f0ebcf..962a5a05737 100644 --- a/src/librustdoc/clean/inline.rs +++ b/src/librustdoc/clean/inline.rs @@ -54,7 +54,7 @@ pub(crate) fn try_inline( debug!("attrs={attrs:?}"); let attrs_without_docs = attrs.map(|(attrs, def_id)| { - (attrs.into_iter().filter(|a| a.doc_str().is_none()).cloned().collect::<Vec<_>>(), def_id) + (attrs.iter().filter(|a| a.doc_str().is_none()).cloned().collect::<Vec<_>>(), def_id) }); let attrs_without_docs = attrs_without_docs.as_ref().map(|(attrs, def_id)| (&attrs[..], *def_id)); @@ -288,10 +288,7 @@ pub(crate) fn build_external_trait(cx: &mut DocContext<'_>, did: DefId) -> clean clean::Trait { def_id: did, generics, items: trait_items, bounds: supertrait_bounds } } -pub(crate) fn build_function<'tcx>( - cx: &mut DocContext<'tcx>, - def_id: DefId, -) -> Box<clean::Function> { +pub(crate) fn build_function(cx: &mut DocContext<'_>, def_id: DefId) -> Box<clean::Function> { let sig = cx.tcx.fn_sig(def_id).instantiate_identity(); // The generics need to be cleaned before the signature. let mut generics = @@ -425,7 +422,7 @@ pub(crate) fn merge_attrs( both.cfg(cx.tcx, &cx.cache.hidden_cfg), ) } else { - (Attributes::from_ast(&old_attrs), old_attrs.cfg(cx.tcx, &cx.cache.hidden_cfg)) + (Attributes::from_ast(old_attrs), old_attrs.cfg(cx.tcx, &cx.cache.hidden_cfg)) } } @@ -791,16 +788,15 @@ fn build_macro( /// implementation for `AssociatedType` fn filter_non_trait_generics(trait_did: DefId, mut g: clean::Generics) -> clean::Generics { for pred in &mut g.where_predicates { - match *pred { - clean::WherePredicate::BoundPredicate { ty: clean::SelfTy, ref mut bounds, .. } => { - bounds.retain(|bound| match bound { - clean::GenericBound::TraitBound(clean::PolyTrait { trait_, .. }, _) => { - trait_.def_id() != trait_did - } - _ => true, - }); - } - _ => {} + if let clean::WherePredicate::BoundPredicate { ty: clean::SelfTy, ref mut bounds, .. } = + *pred + { + bounds.retain(|bound| match bound { + clean::GenericBound::TraitBound(clean::PolyTrait { trait_, .. }, _) => { + trait_.def_id() != trait_did + } + _ => true, + }); } } diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 5260e363dd6..3cb02f379e4 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -266,7 +266,7 @@ fn clean_poly_trait_ref_with_constraints<'tcx>( ) } -fn clean_lifetime<'tcx>(lifetime: &hir::Lifetime, cx: &mut DocContext<'tcx>) -> Lifetime { +fn clean_lifetime(lifetime: &hir::Lifetime, cx: &mut DocContext<'_>) -> Lifetime { if let Some( rbv::ResolvedArg::EarlyBound(did) | rbv::ResolvedArg::LateBound(_, _, did) @@ -274,7 +274,7 @@ fn clean_lifetime<'tcx>(lifetime: &hir::Lifetime, cx: &mut DocContext<'tcx>) -> ) = cx.tcx.named_bound_var(lifetime.hir_id) && let Some(lt) = cx.args.get(&did.to_def_id()).and_then(|arg| arg.as_lt()) { - return lt.clone(); + return *lt; } Lifetime(lifetime.ident.name) } @@ -285,7 +285,7 @@ pub(crate) fn clean_const<'tcx>( ) -> ConstantKind { match &constant.kind { hir::ConstArgKind::Path(qpath) => { - ConstantKind::Path { path: qpath_to_string(&qpath).into() } + ConstantKind::Path { path: qpath_to_string(qpath).into() } } hir::ConstArgKind::Anon(anon) => ConstantKind::Anonymous { body: anon.body }, } @@ -299,7 +299,7 @@ pub(crate) fn clean_middle_const<'tcx>( ConstantKind::TyConst { expr: constant.skip_binder().to_string().into() } } -pub(crate) fn clean_middle_region<'tcx>(region: ty::Region<'tcx>) -> Option<Lifetime> { +pub(crate) fn clean_middle_region(region: ty::Region<'_>) -> Option<Lifetime> { match *region { ty::ReStatic => Some(Lifetime::statik()), _ if !region.has_name() => None, @@ -389,8 +389,8 @@ fn clean_poly_trait_predicate<'tcx>( }) } -fn clean_region_outlives_predicate<'tcx>( - pred: ty::RegionOutlivesPredicate<'tcx>, +fn clean_region_outlives_predicate( + pred: ty::RegionOutlivesPredicate<'_>, ) -> Option<WherePredicate> { let ty::OutlivesPredicate(a, b) = pred; @@ -513,10 +513,10 @@ fn projection_to_path_segment<'tcx>( } } -fn clean_generic_param_def<'tcx>( +fn clean_generic_param_def( def: &ty::GenericParamDef, defaults: ParamDefaults, - cx: &mut DocContext<'tcx>, + cx: &mut DocContext<'_>, ) -> GenericParamDef { let (name, kind) = match def.kind { ty::GenericParamDefKind::Lifetime => { @@ -1303,10 +1303,7 @@ pub(crate) fn clean_impl_item<'tcx>( }) } -pub(crate) fn clean_middle_assoc_item<'tcx>( - assoc_item: &ty::AssocItem, - cx: &mut DocContext<'tcx>, -) -> Item { +pub(crate) fn clean_middle_assoc_item(assoc_item: &ty::AssocItem, cx: &mut DocContext<'_>) -> Item { let tcx = cx.tcx; let kind = match assoc_item.kind { ty::AssocKind::Const => { @@ -1459,7 +1456,7 @@ pub(crate) fn clean_middle_assoc_item<'tcx>( // which only has one associated type, which is not a GAT, so whatever. } } - bounds.extend(mem::replace(pred_bounds, Vec::new())); + bounds.extend(mem::take(pred_bounds)); false } _ => true, @@ -1661,7 +1658,7 @@ fn clean_qpath<'tcx>(hir_ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> Type expanded } else { // First we check if it's a private re-export. - let path = if let Some(path) = first_non_private(cx, hir_id, &path) { + let path = if let Some(path) = first_non_private(cx, hir_id, path) { path } else { clean_path(path, cx) @@ -1796,7 +1793,7 @@ fn maybe_expand_private_type_alias<'tcx>( } Some(cx.enter_alias(args, def_id.to_def_id(), |cx| { - cx.with_param_env(def_id.to_def_id(), |cx| clean_ty(&ty, cx)) + cx.with_param_env(def_id.to_def_id(), |cx| clean_ty(ty, cx)) })) } @@ -1806,8 +1803,8 @@ pub(crate) fn clean_ty<'tcx>(ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> T match ty.kind { TyKind::Never => Primitive(PrimitiveType::Never), TyKind::Ptr(ref m) => RawPointer(m.mutbl, Box::new(clean_ty(m.ty, cx))), - TyKind::Ref(ref l, ref m) => { - let lifetime = if l.is_anonymous() { None } else { Some(clean_lifetime(*l, cx)) }; + TyKind::Ref(l, ref m) => { + let lifetime = if l.is_anonymous() { None } else { Some(clean_lifetime(l, cx)) }; BorrowedRef { lifetime, mutability: m.mutbl, type_: Box::new(clean_ty(m.ty, cx)) } } TyKind::Slice(ty) => Slice(Box::new(clean_ty(ty, cx))), @@ -1843,17 +1840,17 @@ pub(crate) fn clean_ty<'tcx>(ty: &hir::Ty<'tcx>, cx: &mut DocContext<'tcx>) -> T TyKind::Tup(tys) => Tuple(tys.iter().map(|ty| clean_ty(ty, cx)).collect()), TyKind::OpaqueDef(item_id, _, _) => { let item = cx.tcx.hir().item(item_id); - if let hir::ItemKind::OpaqueTy(ref ty) = item.kind { + if let hir::ItemKind::OpaqueTy(ty) = item.kind { ImplTrait(ty.bounds.iter().filter_map(|x| clean_generic_bound(x, cx)).collect()) } else { unreachable!() } } TyKind::Path(_) => clean_qpath(ty, cx), - TyKind::TraitObject(bounds, ref lifetime, _) => { + TyKind::TraitObject(bounds, lifetime, _) => { let bounds = bounds.iter().map(|(bound, _)| clean_poly_trait_ref(bound, cx)).collect(); let lifetime = - if !lifetime.is_elided() { Some(clean_lifetime(*lifetime, cx)) } else { None }; + if !lifetime.is_elided() { Some(clean_lifetime(lifetime, cx)) } else { None }; DynTrait(bounds, lifetime) } TyKind::BareFn(barefn) => BareFunction(Box::new(clean_bare_fn_ty(barefn, cx))), @@ -2355,7 +2352,7 @@ pub(crate) fn clean_field<'tcx>(field: &hir::FieldDef<'tcx>, cx: &mut DocContext clean_field_with_def_id(field.def_id.to_def_id(), field.ident.name, clean_ty(field.ty, cx), cx) } -pub(crate) fn clean_middle_field<'tcx>(field: &ty::FieldDef, cx: &mut DocContext<'tcx>) -> Item { +pub(crate) fn clean_middle_field(field: &ty::FieldDef, cx: &mut DocContext<'_>) -> Item { clean_field_with_def_id( field.did, field.name, @@ -2378,7 +2375,7 @@ pub(crate) fn clean_field_with_def_id( Item::from_def_id_and_parts(def_id, Some(name), StructFieldItem(ty), cx) } -pub(crate) fn clean_variant_def<'tcx>(variant: &ty::VariantDef, cx: &mut DocContext<'tcx>) -> Item { +pub(crate) fn clean_variant_def(variant: &ty::VariantDef, cx: &mut DocContext<'_>) -> Item { let discriminant = match variant.discr { ty::VariantDiscr::Explicit(def_id) => Some(Discriminant { expr: None, value: def_id }), ty::VariantDiscr::Relative(_) => None, @@ -2526,7 +2523,7 @@ fn clean_generic_args<'tcx>( .filter_map(|arg| { Some(match arg { hir::GenericArg::Lifetime(lt) if !lt.is_anonymous() => { - GenericArg::Lifetime(clean_lifetime(*lt, cx)) + GenericArg::Lifetime(clean_lifetime(lt, cx)) } hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()), hir::GenericArg::Type(ty) => GenericArg::Type(clean_ty(ty, cx)), @@ -2579,11 +2576,11 @@ fn clean_bare_fn_ty<'tcx>( BareFunctionDecl { safety: bare_fn.safety, abi: bare_fn.abi, decl, generic_params } } -pub(crate) fn reexport_chain<'tcx>( - tcx: TyCtxt<'tcx>, +pub(crate) fn reexport_chain( + tcx: TyCtxt<'_>, import_def_id: LocalDefId, target_def_id: DefId, -) -> &'tcx [Reexport] { +) -> &[Reexport] { for child in tcx.module_children_local(tcx.local_parent(import_def_id)) { if child.res.opt_def_id() == Some(target_def_id) && child.reexport_chain.first().and_then(|r| r.id()) == Some(import_def_id.to_def_id()) @@ -2803,7 +2800,7 @@ fn clean_maybe_renamed_item<'tcx>( fields: variant_data.fields().iter().map(|x| clean_field(x, cx)).collect(), }), ItemKind::Impl(impl_) => return clean_impl(impl_, item.owner_id.def_id, cx), - ItemKind::Macro(ref macro_def, MacroKind::Bang) => { + ItemKind::Macro(macro_def, MacroKind::Bang) => { let ty_vis = cx.tcx.visibility(def_id); MacroItem(Macro { // FIXME this shouldn't be false @@ -3134,9 +3131,7 @@ fn clean_assoc_item_constraint<'tcx>( } } -fn clean_bound_vars<'tcx>( - bound_vars: &'tcx ty::List<ty::BoundVariableKind>, -) -> Vec<GenericParamDef> { +fn clean_bound_vars(bound_vars: &ty::List<ty::BoundVariableKind>) -> Vec<GenericParamDef> { bound_vars .into_iter() .filter_map(|var| match var { diff --git a/src/librustdoc/clean/simplify.rs b/src/librustdoc/clean/simplify.rs index 1d81ae3eb8b..b59f939025e 100644 --- a/src/librustdoc/clean/simplify.rs +++ b/src/librustdoc/clean/simplify.rs @@ -70,7 +70,7 @@ pub(crate) fn where_clauses(cx: &DocContext<'_>, clauses: ThinVec<WP>) -> ThinVe pub(crate) fn merge_bounds( cx: &clean::DocContext<'_>, - bounds: &mut Vec<clean::GenericBound>, + bounds: &mut [clean::GenericBound], trait_did: DefId, assoc: clean::PathSegment, rhs: &clean::Term, diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index 63d71a73cdf..51da252da24 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -368,11 +368,11 @@ fn is_field_vis_inherited(tcx: TyCtxt<'_>, def_id: DefId) -> bool { } impl Item { - pub(crate) fn stability<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Option<Stability> { + pub(crate) fn stability(&self, tcx: TyCtxt<'_>) -> Option<Stability> { self.def_id().and_then(|did| tcx.lookup_stability(did)) } - pub(crate) fn const_stability<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Option<ConstStability> { + pub(crate) fn const_stability(&self, tcx: TyCtxt<'_>) -> Option<ConstStability> { self.def_id().and_then(|did| tcx.lookup_const_stability(did)) } @@ -945,9 +945,9 @@ pub(crate) trait AttributesExt { where Self: 'a; - fn lists<'a>(&'a self, name: Symbol) -> Self::AttributeIterator<'a>; + fn lists(&self, name: Symbol) -> Self::AttributeIterator<'_>; - fn iter<'a>(&'a self) -> Self::Attributes<'a>; + fn iter(&self) -> Self::Attributes<'_>; fn cfg(&self, tcx: TyCtxt<'_>, hidden_cfg: &FxHashSet<Cfg>) -> Option<Arc<Cfg>> { let sess = tcx.sess; @@ -1043,15 +1043,15 @@ impl AttributesExt for [ast::Attribute] { type AttributeIterator<'a> = impl Iterator<Item = ast::NestedMetaItem> + 'a; type Attributes<'a> = impl Iterator<Item = &'a ast::Attribute> + 'a; - fn lists<'a>(&'a self, name: Symbol) -> Self::AttributeIterator<'a> { + fn lists(&self, name: Symbol) -> Self::AttributeIterator<'_> { self.iter() .filter(move |attr| attr.has_name(name)) .filter_map(ast::Attribute::meta_item_list) .flatten() } - fn iter<'a>(&'a self) -> Self::Attributes<'a> { - self.into_iter() + fn iter(&self) -> Self::Attributes<'_> { + self.iter() } } @@ -1061,15 +1061,15 @@ impl AttributesExt for [(Cow<'_, ast::Attribute>, Option<DefId>)] { type Attributes<'a> = impl Iterator<Item = &'a ast::Attribute> + 'a where Self: 'a; - fn lists<'a>(&'a self, name: Symbol) -> Self::AttributeIterator<'a> { + fn lists(&self, name: Symbol) -> Self::AttributeIterator<'_> { AttributesExt::iter(self) .filter(move |attr| attr.has_name(name)) .filter_map(ast::Attribute::meta_item_list) .flatten() } - fn iter<'a>(&'a self) -> Self::Attributes<'a> { - self.into_iter().map(move |(attr, _)| match attr { + fn iter(&self) -> Self::Attributes<'_> { + self.iter().map(move |(attr, _)| match attr { Cow::Borrowed(attr) => *attr, Cow::Owned(attr) => attr, }) @@ -1389,7 +1389,7 @@ pub(crate) struct FnDecl { impl FnDecl { pub(crate) fn receiver_type(&self) -> Option<&Type> { - self.inputs.values.get(0).and_then(|v| v.to_receiver()) + self.inputs.values.first().and_then(|v| v.to_receiver()) } } @@ -1502,7 +1502,7 @@ impl Type { pub(crate) fn without_borrowed_ref(&self) -> &Type { let mut result = self; while let Type::BorrowedRef { type_, .. } = result { - result = &*type_; + result = type_; } result } @@ -1631,10 +1631,7 @@ impl Type { } pub(crate) fn is_self_type(&self) -> bool { - match *self { - SelfTy => true, - _ => false, - } + matches!(*self, Type::SelfTy) } pub(crate) fn generic_args(&self) -> Option<&GenericArgs> { @@ -1673,7 +1670,7 @@ impl Type { pub(crate) fn def_id(&self, cache: &Cache) -> Option<DefId> { let t: PrimitiveType = match *self { Type::Path { ref path } => return Some(path.def_id()), - DynTrait(ref bounds, _) => return bounds.get(0).map(|b| b.trait_.def_id()), + DynTrait(ref bounds, _) => return bounds.first().map(|b| b.trait_.def_id()), Primitive(p) => return cache.primitive_locations.get(&p).cloned(), BorrowedRef { type_: box Generic(..), .. } => PrimitiveType::Reference, BorrowedRef { ref type_, .. } => return type_.def_id(cache), diff --git a/src/librustdoc/clean/utils.rs b/src/librustdoc/clean/utils.rs index 68266f3506a..d826171aa61 100644 --- a/src/librustdoc/clean/utils.rs +++ b/src/librustdoc/clean/utils.rs @@ -321,9 +321,9 @@ pub(crate) fn name_from_pat(p: &hir::Pat<'_>) -> Symbol { "({})", elts.iter().map(|p| name_from_pat(p).to_string()).collect::<Vec<String>>().join(", ") ), - PatKind::Box(p) => return name_from_pat(&*p), - PatKind::Deref(p) => format!("deref!({})", name_from_pat(&*p)), - PatKind::Ref(p, _) => return name_from_pat(&*p), + PatKind::Box(p) => return name_from_pat(p), + PatKind::Deref(p) => format!("deref!({})", name_from_pat(p)), + PatKind::Ref(p, _) => return name_from_pat(p), PatKind::Lit(..) => { warn!( "tried to get argument name from PatKind::Lit, which is silly in function arguments" @@ -333,7 +333,7 @@ pub(crate) fn name_from_pat(p: &hir::Pat<'_>) -> Symbol { PatKind::Range(..) => return kw::Underscore, PatKind::Slice(begin, ref mid, end) => { let begin = begin.iter().map(|p| name_from_pat(p).to_string()); - let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter(); + let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(p))).into_iter(); let end = end.iter().map(|p| name_from_pat(p).to_string()); format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", ")) } @@ -344,7 +344,7 @@ pub(crate) fn print_const(cx: &DocContext<'_>, n: ty::Const<'_>) -> String { match n.kind() { ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, args: _ }) => { let s = if let Some(def) = def.as_local() { - rendered_const(cx.tcx, &cx.tcx.hir().body_owned_by(def), def) + rendered_const(cx.tcx, cx.tcx.hir().body_owned_by(def), def) } else { inline::print_inlined_const(cx.tcx, def) }; @@ -383,7 +383,7 @@ pub(crate) fn print_evaluated_const( fn format_integer_with_underscore_sep(num: &str) -> String { let num_chars: Vec<_> = num.chars().collect(); - let mut num_start_index = if num_chars.get(0) == Some(&'-') { 1 } else { 0 }; + let mut num_start_index = if num_chars.first() == Some(&'-') { 1 } else { 0 }; let chunk_size = match num[num_start_index..].as_bytes() { [b'0', b'b' | b'x', ..] => { num_start_index += 2; diff --git a/src/librustdoc/config.rs b/src/librustdoc/config.rs index 9e9d8f02a2e..9e7b69ec45f 100644 --- a/src/librustdoc/config.rs +++ b/src/librustdoc/config.rs @@ -360,7 +360,7 @@ impl Options { return None; } - if rustc_driver::describe_flag_categories(early_dcx, &matches) { + if rustc_driver::describe_flag_categories(early_dcx, matches) { return None; } @@ -374,7 +374,7 @@ impl Options { let codegen_options = CodegenOptions::build(early_dcx, matches); let unstable_opts = UnstableOptions::build(early_dcx, matches); - let remap_path_prefix = match parse_remap_path_prefix(&matches) { + let remap_path_prefix = match parse_remap_path_prefix(matches) { Ok(prefix_mappings) => prefix_mappings, Err(err) => { early_dcx.early_fatal(err); @@ -486,7 +486,7 @@ impl Options { _ => dcx.fatal("too many file operands"), } }; - let input = make_input(early_dcx, &input); + let input = make_input(early_dcx, input); let externs = parse_externs(early_dcx, matches, &unstable_opts); let extern_html_root_urls = match parse_extern_html_roots(matches) { diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs index 08a4a3f3fb2..760514f40fd 100644 --- a/src/librustdoc/core.rs +++ b/src/librustdoc/core.rs @@ -288,7 +288,7 @@ pub(crate) fn create_config( let hir = tcx.hir(); let body = hir.body_owned_by(def_id); debug!("visiting body for {def_id:?}"); - EmitIgnoredResolutionErrors::new(tcx).visit_body(&body); + EmitIgnoredResolutionErrors::new(tcx).visit_body(body); (rustc_interface::DEFAULT_QUERY_PROVIDERS.typeck)(tcx, def_id) }; }), diff --git a/src/librustdoc/doctest.rs b/src/librustdoc/doctest.rs index 743c1ed507e..1ae66fddda6 100644 --- a/src/librustdoc/doctest.rs +++ b/src/librustdoc/doctest.rs @@ -272,7 +272,7 @@ pub(crate) fn run_tests( let mut tests_runner = runner::DocTestRunner::new(); let rustdoc_test_options = IndividualTestOptions::new( - &rustdoc_options, + rustdoc_options, &Some(format!("merged_doctest_{edition}")), PathBuf::from(format!("doctest_{edition}.rs")), ); @@ -307,7 +307,7 @@ pub(crate) fn run_tests( doctest, scraped_test, opts.clone(), - Arc::clone(&rustdoc_options), + Arc::clone(rustdoc_options), unused_extern_reports.clone(), )); } @@ -316,7 +316,7 @@ pub(crate) fn run_tests( // We need to call `test_main` even if there is no doctest to run to get the output // `running 0 tests...`. if ran_edition_tests == 0 || !standalone_tests.is_empty() { - standalone_tests.sort_by(|a, b| a.desc.name.as_slice().cmp(&b.desc.name.as_slice())); + standalone_tests.sort_by(|a, b| a.desc.name.as_slice().cmp(b.desc.name.as_slice())); test::test_main(&test_args, standalone_tests, None); } if nb_errors != 0 { @@ -421,7 +421,7 @@ fn add_exe_suffix(input: String, target: &TargetTriple) -> String { } fn wrapped_rustc_command(rustc_wrappers: &[PathBuf], rustc_binary: &Path) -> Command { - let mut args = rustc_wrappers.iter().map(PathBuf::as_path).chain([rustc_binary].into_iter()); + let mut args = rustc_wrappers.iter().map(PathBuf::as_path).chain([rustc_binary]); let exe = args.next().expect("unable to create rustc command"); let mut command = Command::new(exe); @@ -452,7 +452,7 @@ pub(crate) struct RunnableDocTest { impl RunnableDocTest { fn path_for_merged_doctest(&self) -> PathBuf { - self.test_opts.outdir.path().join(&format!("doctest_{}.rs", self.edition)) + self.test_opts.outdir.path().join(format!("doctest_{}.rs", self.edition)) } } @@ -477,13 +477,13 @@ fn run_test( .unwrap_or_else(|| rustc_interface::util::rustc_path().expect("found rustc")); let mut compiler = wrapped_rustc_command(&rustdoc_options.test_builder_wrappers, rustc_binary); - compiler.arg(&format!("@{}", doctest.global_opts.args_file.display())); + compiler.arg(format!("@{}", doctest.global_opts.args_file.display())); if let Some(sysroot) = &rustdoc_options.maybe_sysroot { compiler.arg(format!("--sysroot={}", sysroot.display())); } - compiler.arg("--edition").arg(&doctest.edition.to_string()); + compiler.arg("--edition").arg(doctest.edition.to_string()); if !doctest.is_multiple_tests { // Setting these environment variables is unneeded if this is a merged doctest. compiler.env("UNSTABLE_RUSTDOC_TEST_PATH", &doctest.test_opts.path); @@ -692,7 +692,7 @@ impl IndividualTestOptions { fn new(options: &RustdocOptions, test_id: &Option<String>, test_path: PathBuf) -> Self { let outdir = if let Some(ref path) = options.persist_doctests { let mut path = path.clone(); - path.push(&test_id.as_deref().unwrap_or_else(|| "<doctest>")); + path.push(&test_id.as_deref().unwrap_or("<doctest>")); if let Err(err) = std::fs::create_dir_all(&path) { eprintln!("Couldn't create directory for doctest executables: {err}"); diff --git a/src/librustdoc/doctest/make.rs b/src/librustdoc/doctest/make.rs index aed079e5887..9de312a413a 100644 --- a/src/librustdoc/doctest/make.rs +++ b/src/librustdoc/doctest/make.rs @@ -311,7 +311,7 @@ fn parse_source( } ast::ItemKind::ExternCrate(original) => { if !info.found_extern_crate - && let Some(ref crate_name) = crate_name + && let Some(crate_name) = crate_name { info.found_extern_crate = match original { Some(name) => name.as_str() == *crate_name, diff --git a/src/librustdoc/doctest/markdown.rs b/src/librustdoc/doctest/markdown.rs index 4806d865589..9a237f8684d 100644 --- a/src/librustdoc/doctest/markdown.rs +++ b/src/librustdoc/doctest/markdown.rs @@ -73,7 +73,7 @@ pub(crate) fn test(options: Options) -> Result<(), String> { use rustc_session::config::Input; let input_str = match &options.input { Input::File(path) => { - read_to_string(&path).map_err(|err| format!("{}: {err}", path.display()))? + read_to_string(path).map_err(|err| format!("{}: {err}", path.display()))? } Input::Str { name: _, input } => input.clone(), }; diff --git a/src/librustdoc/doctest/runner.rs b/src/librustdoc/doctest/runner.rs index d49fa3ac5ac..9cb220ef7ba 100644 --- a/src/librustdoc/doctest/runner.rs +++ b/src/librustdoc/doctest/runner.rs @@ -98,8 +98,10 @@ impl DocTestRunner { code.push_str("extern crate test;\n"); - let test_args = - test_args.iter().map(|arg| format!("{arg:?}.to_string(),")).collect::<String>(); + let test_args = test_args.iter().fold(String::new(), |mut x, arg| { + write!(x, "{arg:?}.to_string(),").unwrap(); + x + }); write!( code, "\ diff --git a/src/librustdoc/error.rs b/src/librustdoc/error.rs index 6ed7eab1aba..7876125f7fd 100644 --- a/src/librustdoc/error.rs +++ b/src/librustdoc/error.rs @@ -39,7 +39,7 @@ macro_rules! try_none { match $e { Some(e) => e, None => { - return Err(<crate::error::Error as crate::docfs::PathError>::new( + return Err(<$crate::error::Error as $crate::docfs::PathError>::new( io::Error::new(io::ErrorKind::Other, "not found"), $file, )); diff --git a/src/librustdoc/formats/cache.rs b/src/librustdoc/formats/cache.rs index 947bae99305..90942d87f72 100644 --- a/src/librustdoc/formats/cache.rs +++ b/src/librustdoc/formats/cache.rs @@ -274,7 +274,7 @@ impl<'a, 'tcx> DocFolder for CacheBuilder<'a, 'tcx> { None }; if let Some(name) = search_name { - add_item_to_search_index(self.tcx, &mut self.cache, &item, name) + add_item_to_search_index(self.tcx, self.cache, &item, name) } // Keep track of the fully qualified path for this item. @@ -452,7 +452,7 @@ fn add_item_to_search_index(tcx: TyCtxt<'_>, cache: &mut Cache, item: &clean::It // or if item is tuple struct/variant field (name is a number -> not useful for search). if cache.stripped_mod || item.type_() == ItemType::StructField - && name.as_str().chars().all(|c| c.is_digit(10)) + && name.as_str().chars().all(|c| c.is_ascii_digit()) { return; } @@ -463,7 +463,7 @@ fn add_item_to_search_index(tcx: TyCtxt<'_>, cache: &mut Cache, item: &clean::It } clean::MethodItem(..) | clean::AssocConstItem(..) | clean::AssocTypeItem(..) => { let last = cache.parent_stack.last().expect("parent_stack is empty 2"); - let parent_did = match &*last { + let parent_did = match last { // impl Trait for &T { fn method(self); } // // When generating a function index with the above shape, we want it @@ -471,9 +471,9 @@ fn add_item_to_search_index(tcx: TyCtxt<'_>, cache: &mut Cache, item: &clean::It // show up as `T::method`, rather than `reference::method`, in the search // results page. ParentStackItem::Impl { for_: clean::Type::BorrowedRef { type_, .. }, .. } => { - type_.def_id(&cache) + type_.def_id(cache) } - ParentStackItem::Impl { for_, .. } => for_.def_id(&cache), + ParentStackItem::Impl { for_, .. } => for_.def_id(cache), ParentStackItem::Type(item_id) => item_id.as_def_id(), }; let Some(parent_did) = parent_did else { return }; @@ -538,7 +538,7 @@ fn add_item_to_search_index(tcx: TyCtxt<'_>, cache: &mut Cache, item: &clean::It None }; let search_type = get_function_type_for_search( - &item, + item, tcx, clean_impl_generics(cache.parent_stack.last()).as_ref(), parent_did, diff --git a/src/librustdoc/formats/item_type.rs b/src/librustdoc/formats/item_type.rs index 3dcef15b552..9754e1e6f74 100644 --- a/src/librustdoc/formats/item_type.rs +++ b/src/librustdoc/formats/item_type.rs @@ -162,7 +162,8 @@ impl ItemType { | DefKind::LifetimeParam | DefKind::GlobalAsm | DefKind::Impl { .. } - | DefKind::Closure => Self::ForeignType, + | DefKind::Closure + | DefKind::SyntheticCoroutineBody => Self::ForeignType, } } diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 5cbf8c5e19f..530241f9a13 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -633,7 +633,7 @@ fn generate_item_def_id_path( let module_fqp = to_module_fqp(shortty, &fqp); let mut is_remote = false; - let url_parts = url_parts(cx.cache(), def_id, &module_fqp, &cx.current, &mut is_remote)?; + let url_parts = url_parts(cx.cache(), def_id, module_fqp, &cx.current, &mut is_remote)?; let (url_parts, shortty, fqp) = make_href(root_path, shortty, url_parts, &fqp, is_remote)?; if def_id == original_def_id { return Ok((url_parts, shortty, fqp)); @@ -811,7 +811,7 @@ pub(crate) fn link_tooltip(did: DefId, fragment: &Option<UrlFragment>, cx: &Cont // primitives are documented in a crate, but not actually part of it &fqp[fqp.len() - 1..] } else { - &fqp + fqp }; if let &Some(UrlFragment::Item(id)) = fragment { write!(buf, "{} ", cx.tcx().def_descr(id)); @@ -820,7 +820,7 @@ pub(crate) fn link_tooltip(did: DefId, fragment: &Option<UrlFragment>, cx: &Cont } write!(buf, "{}", cx.tcx().item_name(id)); } else if !fqp.is_empty() { - let mut fqp_it = fqp.into_iter(); + let mut fqp_it = fqp.iter(); write!(buf, "{shortty} {}", fqp_it.next().unwrap()); for component in fqp_it { write!(buf, "::{component}"); @@ -830,13 +830,13 @@ pub(crate) fn link_tooltip(did: DefId, fragment: &Option<UrlFragment>, cx: &Cont } /// Used to render a [`clean::Path`]. -fn resolved_path<'cx>( +fn resolved_path( w: &mut fmt::Formatter<'_>, did: DefId, path: &clean::Path, print_all: bool, use_absolute: bool, - cx: &'cx Context<'_>, + cx: &Context<'_>, ) -> fmt::Result { let last = path.segments.last().unwrap(); @@ -996,11 +996,11 @@ pub(crate) fn anchor<'a, 'cx: 'a>( }) } -fn fmt_type<'cx>( +fn fmt_type( t: &clean::Type, f: &mut fmt::Formatter<'_>, use_absolute: bool, - cx: &'cx Context<'_>, + cx: &Context<'_>, ) -> fmt::Result { trace!("fmt_type(t = {t:?})"); @@ -1493,9 +1493,8 @@ impl clean::FnDecl { } clean::BorrowedRef { lifetime, mutability, type_: box clean::SelfTy } => { write!(f, "{amp}")?; - match lifetime { - Some(lt) => write!(f, "{lt} ", lt = lt.print())?, - None => {} + if let Some(lt) = lifetime { + write!(f, "{lt} ", lt = lt.print())?; } write!(f, "{mutability}self", mutability = mutability.print_with_space())?; } diff --git a/src/librustdoc/html/render/write_shared.rs b/src/librustdoc/html/render/write_shared.rs index a18b7a252a4..60dc142b9ff 100644 --- a/src/librustdoc/html/render/write_shared.rs +++ b/src/librustdoc/html/render/write_shared.rs @@ -75,11 +75,11 @@ pub(crate) fn write_shared( let crate_name = krate.name(cx.tcx()); let crate_name = crate_name.as_str(); // rand let crate_name_json = OrderedJson::serialize(crate_name).unwrap(); // "rand" - let external_crates = hack_get_external_crate_names(&cx.dst)?; + let external_crates = hack_get_external_crate_names(&cx.dst, &cx.shared.resource_suffix)?; let info = CrateInfo { src_files_js: SourcesPart::get(cx, &crate_name_json)?, search_index_js: SearchIndexPart::get(index, &cx.shared.resource_suffix)?, - all_crates: AllCratesPart::get(crate_name_json.clone())?, + all_crates: AllCratesPart::get(crate_name_json.clone(), &cx.shared.resource_suffix)?, crates_index: CratesIndexPart::get(&crate_name, &external_crates)?, trait_impl: TraitAliasPart::get(cx, &crate_name_json)?, type_impl: TypeAliasPart::get(cx, krate, &crate_name_json)?, @@ -291,10 +291,13 @@ impl AllCratesPart { SortedTemplate::from_before_after("window.ALL_CRATES = [", "];") } - fn get(crate_name_json: OrderedJson) -> Result<PartsAndLocations<Self>, Error> { + fn get( + crate_name_json: OrderedJson, + resource_suffix: &str, + ) -> Result<PartsAndLocations<Self>, Error> { // external hack_get_external_crate_names not needed here, because // there's no way that we write the search index but not crates.js - let path = PathBuf::from("crates.js"); + let path = suffix_path("crates.js", resource_suffix); Ok(PartsAndLocations::with(path, crate_name_json)) } } @@ -305,8 +308,11 @@ impl AllCratesPart { /// /// This is to match the current behavior of rustdoc, which allows you to get all crates /// on the index page, even if --enable-index-page is only passed to the last crate. -fn hack_get_external_crate_names(doc_root: &Path) -> Result<Vec<String>, Error> { - let path = doc_root.join("crates.js"); +fn hack_get_external_crate_names( + doc_root: &Path, + resource_suffix: &str, +) -> Result<Vec<String>, Error> { + let path = doc_root.join(suffix_path("crates.js", resource_suffix)); let Ok(content) = fs::read_to_string(&path) else { // they didn't emit invocation specific, so we just say there were no crates return Ok(Vec::default()); diff --git a/src/librustdoc/html/render/write_shared/tests.rs b/src/librustdoc/html/render/write_shared/tests.rs index 4d1874b7df5..e282cd99e43 100644 --- a/src/librustdoc/html/render/write_shared/tests.rs +++ b/src/librustdoc/html/render/write_shared/tests.rs @@ -6,10 +6,10 @@ use crate::html::render::write_shared::*; fn hack_external_crate_names() { let path = tempfile::TempDir::new().unwrap(); let path = path.path(); - let crates = hack_get_external_crate_names(&path).unwrap(); + let crates = hack_get_external_crate_names(&path, "").unwrap(); assert!(crates.is_empty()); fs::write(path.join("crates.js"), r#"window.ALL_CRATES = ["a","b","c"];"#).unwrap(); - let crates = hack_get_external_crate_names(&path).unwrap(); + let crates = hack_get_external_crate_names(&path, "").unwrap(); assert_eq!(crates, ["a".to_string(), "b".to_string(), "c".to_string()]); } @@ -60,7 +60,7 @@ fn all_crates_template() { #[test] fn all_crates_parts() { - let parts = AllCratesPart::get(OrderedJson::serialize("crate").unwrap()).unwrap(); + let parts = AllCratesPart::get(OrderedJson::serialize("crate").unwrap(), "").unwrap(); assert_eq!(&parts.parts[0].0, Path::new("crates.js")); assert_eq!(&parts.parts[0].1.to_string(), r#""crate""#); } diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs index ab03f620230..eae12b84839 100644 --- a/src/librustdoc/passes/collect_intra_doc_links.rs +++ b/src/librustdoc/passes/collect_intra_doc_links.rs @@ -1950,7 +1950,9 @@ fn resolution_failure( | TraitAlias | TyParam | Static { .. } => "associated item", - Impl { .. } | GlobalAsm => unreachable!("not a path"), + Impl { .. } | GlobalAsm | SyntheticCoroutineBody => { + unreachable!("not a path") + } } } else { "associated item" diff --git a/src/tools/miri/src/machine.rs b/src/tools/miri/src/machine.rs index a7493d48d6a..264b7b269de 100644 --- a/src/tools/miri/src/machine.rs +++ b/src/tools/miri/src/machine.rs @@ -947,15 +947,47 @@ impl<'tcx> Machine<'tcx> for MiriMachine<'tcx> { } #[inline(always)] - fn enforce_abi(_ecx: &MiriInterpCx<'tcx>) -> bool { - true - } - - #[inline(always)] fn ignore_optional_overflow_checks(ecx: &MiriInterpCx<'tcx>) -> bool { !ecx.tcx.sess.overflow_checks() } + fn check_fn_target_features( + ecx: &MiriInterpCx<'tcx>, + instance: ty::Instance<'tcx>, + ) -> InterpResult<'tcx> { + let attrs = ecx.tcx.codegen_fn_attrs(instance.def_id()); + if attrs + .target_features + .iter() + .any(|feature| !ecx.tcx.sess.target_features.contains(&feature.name)) + { + let unavailable = attrs + .target_features + .iter() + .filter(|&feature| { + !feature.implied && !ecx.tcx.sess.target_features.contains(&feature.name) + }) + .fold(String::new(), |mut s, feature| { + if !s.is_empty() { + s.push_str(", "); + } + s.push_str(feature.name.as_str()); + s + }); + let msg = format!( + "calling a function that requires unavailable target features: {unavailable}" + ); + // On WASM, this is not UB, but instead gets rejected during validation of the module + // (see #84988). + if ecx.tcx.sess.target.is_like_wasm { + throw_machine_stop!(TerminationInfo::Abort(msg)); + } else { + throw_ub_format!("{msg}"); + } + } + Ok(()) + } + #[inline(always)] fn find_mir_or_eval_fn( ecx: &mut MiriInterpCx<'tcx>, @@ -1060,6 +1092,10 @@ impl<'tcx> Machine<'tcx> for MiriMachine<'tcx> { ecx.generate_nan(inputs) } + fn ub_checks(ecx: &InterpCx<'tcx, Self>) -> InterpResult<'tcx, bool> { + Ok(ecx.tcx.sess.ub_checks()) + } + fn thread_local_static_pointer( ecx: &mut MiriInterpCx<'tcx>, def_id: DefId, diff --git a/src/tools/miri/tests/fail/data_race/alloc_read_race.rs b/src/tools/miri/tests/fail/data_race/alloc_read_race.rs index c85c0ebe244..312b7ba05d3 100644 --- a/src/tools/miri/tests/fail/data_race/alloc_read_race.rs +++ b/src/tools/miri/tests/fail/data_race/alloc_read_race.rs @@ -1,7 +1,6 @@ //@compile-flags: -Zmiri-disable-weak-memory-emulation -Zmiri-preemption-rate=0 -Zmiri-disable-stacked-borrows // Avoid accidental synchronization via address reuse inside `thread::spawn`. //@compile-flags: -Zmiri-address-reuse-cross-thread-rate=0 -#![feature(new_uninit)] use std::mem::MaybeUninit; use std::ptr::null_mut; diff --git a/src/tools/miri/tests/fail/data_race/alloc_write_race.rs b/src/tools/miri/tests/fail/data_race/alloc_write_race.rs index 9e2a430dd94..f1f308b37e7 100644 --- a/src/tools/miri/tests/fail/data_race/alloc_write_race.rs +++ b/src/tools/miri/tests/fail/data_race/alloc_write_race.rs @@ -1,7 +1,6 @@ //@compile-flags: -Zmiri-disable-weak-memory-emulation -Zmiri-preemption-rate=0 -Zmiri-disable-stacked-borrows // Avoid accidental synchronization via address reuse inside `thread::spawn`. //@compile-flags: -Zmiri-address-reuse-cross-thread-rate=0 -#![feature(new_uninit)] use std::ptr::null_mut; use std::sync::atomic::{AtomicPtr, Ordering}; diff --git a/src/tools/miri/tests/fail/weak_memory/weak_uninit.rs b/src/tools/miri/tests/fail/weak_memory/weak_uninit.rs index 54bea6c6908..79c97a5b752 100644 --- a/src/tools/miri/tests/fail/weak_memory/weak_uninit.rs +++ b/src/tools/miri/tests/fail/weak_memory/weak_uninit.rs @@ -6,7 +6,6 @@ // run multiple times until one try returns true. // Spurious failure is possible, if you are really unlucky with // the RNG and always read the latest value from the store buffer. -#![feature(new_uninit)] use std::sync::atomic::*; use std::thread::spawn; diff --git a/src/tools/miri/tests/pass/function_calls/target_feature_wasm.rs b/src/tools/miri/tests/panic/target_feature_wasm.rs index 5056f32de44..c67d2983f78 100644 --- a/src/tools/miri/tests/pass/function_calls/target_feature_wasm.rs +++ b/src/tools/miri/tests/panic/target_feature_wasm.rs @@ -2,7 +2,9 @@ //@compile-flags: -C target-feature=-simd128 fn main() { - // Calling functions with `#[target_feature]` is not unsound on WASM, see #84988 + // Calling functions with `#[target_feature]` is not unsound on WASM, see #84988. + // But if the compiler actually uses the target feature, it will lead to an error when the module is loaded. + // We emulate this with an "unsupported" error. assert!(!cfg!(target_feature = "simd128")); simd128_fn(); } diff --git a/src/tools/miri/tests/pass/rc.rs b/src/tools/miri/tests/pass/rc.rs index b1470dabc26..ce01e611b2c 100644 --- a/src/tools/miri/tests/pass/rc.rs +++ b/src/tools/miri/tests/pass/rc.rs @@ -1,7 +1,6 @@ //@revisions: stack tree //@[tree]compile-flags: -Zmiri-tree-borrows //@compile-flags: -Zmiri-strict-provenance -#![feature(new_uninit)] #![feature(get_mut_unchecked)] #![allow(ambiguous_wide_pointer_comparisons)] diff --git a/src/tools/miri/tests/pass/slices.rs b/src/tools/miri/tests/pass/slices.rs index 0b9805681b4..459d04d6761 100644 --- a/src/tools/miri/tests/pass/slices.rs +++ b/src/tools/miri/tests/pass/slices.rs @@ -1,7 +1,6 @@ //@revisions: stack tree //@[tree]compile-flags: -Zmiri-tree-borrows //@compile-flags: -Zmiri-strict-provenance -#![feature(new_uninit)] #![feature(slice_as_chunks)] #![feature(slice_partition_dedup)] #![feature(layout_for_ptr)] diff --git a/src/tools/rustbook/Cargo.lock b/src/tools/rustbook/Cargo.lock index 3b859fe98c5..1394675a9dc 100644 --- a/src/tools/rustbook/Cargo.lock +++ b/src/tools/rustbook/Cargo.lock @@ -690,6 +690,7 @@ dependencies = [ "mdbook", "once_cell", "pathdiff", + "pulldown-cmark", "regex", "semver", "serde_json", diff --git a/src/tools/tidy/src/edition.rs b/src/tools/tidy/src/edition.rs index 6a58d58dbde..08f6a3909f8 100644 --- a/src/tools/tidy/src/edition.rs +++ b/src/tools/tidy/src/edition.rs @@ -1,4 +1,4 @@ -//! Tidy check to ensure that crate `edition` is '2018' or '2021'. +//! Tidy check to ensure that crate `edition` is '2021' or '2024'. use std::path::Path; @@ -12,7 +12,9 @@ pub fn check(path: &Path, bad: &mut bool) { return; } - let is_2021 = contents.lines().any(|line| line.trim() == "edition = \"2021\""); + let is_current_edition = contents + .lines() + .any(|line| line.trim() == "edition = \"2021\"" || line.trim() == "edition = \"2024\""); let is_workspace = contents.lines().any(|line| line.trim() == "[workspace]"); let is_package = contents.lines().any(|line| line.trim() == "[package]"); @@ -20,10 +22,10 @@ pub fn check(path: &Path, bad: &mut bool) { // Check that all packages use the 2021 edition. Virtual workspaces don't allow setting an // edition, so these shouldn't be checked. - if is_package && !is_2021 { + if is_package && !is_current_edition { tidy_error!( bad, - "{} doesn't have `edition = \"2021\"` on a separate line", + "{} doesn't have `edition = \"2021\"` or `edition = \"2024\"` on a separate line", file.display() ); } diff --git a/tests/assembly/struct-target-features.rs b/tests/assembly/struct-target-features.rs new file mode 100644 index 00000000000..cc86fbaa840 --- /dev/null +++ b/tests/assembly/struct-target-features.rs @@ -0,0 +1,37 @@ +//@ compile-flags: -O +//@ assembly-output: emit-asm +//@ only-x86_64 + +#![crate_type = "lib"] +#![feature(struct_target_features)] + +// Check that a struct_target_features type causes the compiler to effectively inline intrinsics. + +use std::arch::x86_64::*; + +#[target_feature(enable = "avx")] +struct Avx {} + +#[target_feature(enable = "fma")] +struct Fma {} + +pub fn add_simple(_: Avx, v: __m256) -> __m256 { + // CHECK-NOT: call + // CHECK: vaddps + unsafe { _mm256_add_ps(v, v) } +} + +pub fn add_complex_type(_: (&Avx, ()), v: __m256) -> __m256 { + // CHECK-NOT: call + // CHECK: vaddps + unsafe { _mm256_add_ps(v, v) } +} + +pub fn add_fma_combined(_: (&Avx, &Fma), v: __m256) -> (__m256, __m256) { + // CHECK-NOT: call + // CHECK-DAG: vaddps + let r1 = unsafe { _mm256_add_ps(v, v) }; + // CHECK-DAG: vfmadd213ps + let r2 = unsafe { _mm256_fmadd_ps(v, v, v) }; + (r1, r2) +} diff --git a/tests/codegen/cast-target-abi.rs b/tests/codegen/cast-target-abi.rs index 34e52d38bbe..db76aae3dd0 100644 --- a/tests/codegen/cast-target-abi.rs +++ b/tests/codegen/cast-target-abi.rs @@ -1,7 +1,7 @@ // ignore-tidy-linelength //@ revisions:aarch64 loongarch64 powerpc64 sparc64 x86_64 -// FIXME: Add `-Cllvm-args=--lint-abort-on-error` after LLVM 19 -//@ compile-flags: -O -C no-prepopulate-passes -C passes=lint +//@ min-llvm-version: 19 +//@ compile-flags: -O -Cno-prepopulate-passes -Zlint-llvm-ir -Cllvm-args=-lint-abort-on-error //@[aarch64] compile-flags: --target aarch64-unknown-linux-gnu //@[aarch64] needs-llvm-components: arm diff --git a/tests/codegen/cffi/ffi-out-of-bounds-loads.rs b/tests/codegen/cffi/ffi-out-of-bounds-loads.rs index a4b7c0caa6d..ae8d8383f5b 100644 --- a/tests/codegen/cffi/ffi-out-of-bounds-loads.rs +++ b/tests/codegen/cffi/ffi-out-of-bounds-loads.rs @@ -1,5 +1,6 @@ //@ revisions: linux apple -//@ compile-flags: -C opt-level=0 -C no-prepopulate-passes -C passes=lint +//@ min-llvm-version: 19 +//@ compile-flags: -Copt-level=0 -Cno-prepopulate-passes -Zlint-llvm-ir -Cllvm-args=-lint-abort-on-error //@[linux] compile-flags: --target x86_64-unknown-linux-gnu //@[linux] needs-llvm-components: x86 diff --git a/tests/codegen/naked-fn/aligned.rs b/tests/codegen/naked-fn/aligned.rs new file mode 100644 index 00000000000..d5faac44836 --- /dev/null +++ b/tests/codegen/naked-fn/aligned.rs @@ -0,0 +1,20 @@ +//@ compile-flags: -C no-prepopulate-passes -Copt-level=0 +//@ needs-asm-support +//@ ignore-arm no "ret" mnemonic + +#![crate_type = "lib"] +#![feature(naked_functions, fn_align)] +use std::arch::asm; + +// CHECK: Function Attrs: naked +// CHECK-NEXT: define{{.*}}void @naked_empty() +// CHECK: align 16 +#[repr(align(16))] +#[no_mangle] +#[naked] +pub unsafe extern "C" fn naked_empty() { + // CHECK-NEXT: start: + // CHECK-NEXT: call void asm + // CHECK-NEXT: unreachable + asm!("ret", options(noreturn)); +} diff --git a/tests/codegen/sanitizer/riscv64-shadow-call-stack.rs b/tests/codegen/sanitizer/riscv64-shadow-call-stack.rs new file mode 100644 index 00000000000..5833b832ba4 --- /dev/null +++ b/tests/codegen/sanitizer/riscv64-shadow-call-stack.rs @@ -0,0 +1,17 @@ +//@ compile-flags: --target riscv64imac-unknown-none-elf -Zsanitizer=shadow-call-stack +//@ needs-llvm-components: riscv + +#![allow(internal_features)] +#![crate_type = "rlib"] +#![feature(no_core, lang_items)] +#![no_core] + +#[lang = "sized"] +trait Sized {} + +// CHECK: ; Function Attrs:{{.*}}shadowcallstack +// CHECK: define dso_local void @foo() unnamed_addr #0 +#[no_mangle] +pub fn foo() {} + +// CHECK: attributes #0 = {{.*}}shadowcallstack{{.*}} diff --git a/tests/codegen/tied-features-strength.rs b/tests/codegen/tied-features-strength.rs index 1b4596ae2cb..1b2b63c3d1a 100644 --- a/tests/codegen/tied-features-strength.rs +++ b/tests/codegen/tied-features-strength.rs @@ -3,21 +3,21 @@ //@ compile-flags: --crate-type=rlib --target=aarch64-unknown-linux-gnu //@ needs-llvm-components: aarch64 -// The "+v8a" feature is matched as optional as it isn't added when we -// are targeting older LLVM versions. Once the min supported version -// is LLVM-14 we can remove the optional regex matching for this feature. +// The "+fpmr" feature is matched as optional as it is only an explicit +// feature in LLVM 18. Once the min supported version is LLVM-19 the optional +// regex matching for this feature can be removed. //@ [ENABLE_SVE] compile-flags: -C target-feature=+sve -Copt-level=0 -// ENABLE_SVE: attributes #0 = { {{.*}} "target-features"="{{((\+outline-atomics,?)|(\+v8a,?)?|(\+sve,?)|(\+neon,?)|(\+fp-armv8,?))*}}" } +// ENABLE_SVE: attributes #0 = { {{.*}} "target-features"="{{((\+outline-atomics,?)|(\+v8a,?)|(\+fpmr,?)?|(\+sve,?)|(\+neon,?)|(\+fp-armv8,?))*}}" } //@ [DISABLE_SVE] compile-flags: -C target-feature=-sve -Copt-level=0 -// DISABLE_SVE: attributes #0 = { {{.*}} "target-features"="{{((\+outline-atomics,?)|(\+v8a,?)?|(-sve,?)|(\+neon,?))*}}" } +// DISABLE_SVE: attributes #0 = { {{.*}} "target-features"="{{((\+outline-atomics,?)|(\+v8a,?)|(\+fpmr,?)?|(-sve,?)|(\+neon,?))*}}" } //@ [DISABLE_NEON] compile-flags: -C target-feature=-neon -Copt-level=0 -// DISABLE_NEON: attributes #0 = { {{.*}} "target-features"="{{((\+outline-atomics,?)|(\+v8a,?)?|(-fp-armv8,?)|(-neon,?))*}}" } +// DISABLE_NEON: attributes #0 = { {{.*}} "target-features"="{{((\+outline-atomics,?)|(\+v8a,?)|(\+fpmr,?)?|(-fp-armv8,?)|(-neon,?))*}}" } //@ [ENABLE_NEON] compile-flags: -C target-feature=+neon -Copt-level=0 -// ENABLE_NEON: attributes #0 = { {{.*}} "target-features"="{{((\+outline-atomics,?)|(\+v8a,?)?|(\+fp-armv8,?)|(\+neon,?))*}}" } +// ENABLE_NEON: attributes #0 = { {{.*}} "target-features"="{{((\+outline-atomics,?)|(\+v8a,?)|(\+fpmr,?)?|(\+fp-armv8,?)|(\+neon,?))*}}" } #![feature(no_core, lang_items)] #![no_core] diff --git a/tests/crashes/123693.rs b/tests/crashes/123693.rs index c2e192092be..c3236322c6e 100644 --- a/tests/crashes/123693.rs +++ b/tests/crashes/123693.rs @@ -3,11 +3,11 @@ #![feature(transmutability)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { Assume::NOTHING }>, + Dst: TransmuteFrom<Src, { Assume::NOTHING }>, { } } diff --git a/tests/crashes/124207.rs b/tests/crashes/124207.rs index a4e1c551890..a11eedb140a 100644 --- a/tests/crashes/124207.rs +++ b/tests/crashes/124207.rs @@ -4,6 +4,6 @@ trait OpaqueTrait {} type OpaqueType = impl OpaqueTrait; trait AnotherTrait {} -impl<T: std::mem::BikeshedIntrinsicFrom<(), ()>> AnotherTrait for T {} +impl<T: std::mem::TransmuteFrom<(), ()>> AnotherTrait for T {} impl AnotherTrait for OpaqueType {} pub fn main() {} diff --git a/tests/crashes/125881.rs b/tests/crashes/125881.rs index 98331d3c974..a38f1891b61 100644 --- a/tests/crashes/125881.rs +++ b/tests/crashes/125881.rs @@ -3,6 +3,6 @@ #![feature(transmutability)] #![feature(unboxed_closures,effects)] -const fn test() -> impl std::mem::BikeshedIntrinsicFrom() { +const fn test() -> impl std::mem::TransmuteFrom() { || {} } diff --git a/tests/crashes/126267.rs b/tests/crashes/126267.rs index c0604b90a67..728578179ed 100644 --- a/tests/crashes/126267.rs +++ b/tests/crashes/126267.rs @@ -14,11 +14,11 @@ pub enum Error { } mod assert { - use std::mem::BikeshedIntrinsicFrom; + use std::mem::TransmuteFrom; pub fn is_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src>, // safety is NOT assumed + Dst: TransmuteFrom<Src>, // safety is NOT assumed { } } diff --git a/tests/crashes/126377.rs b/tests/crashes/126377.rs index f8b9b693b65..f6727bcc0a4 100644 --- a/tests/crashes/126377.rs +++ b/tests/crashes/126377.rs @@ -4,7 +4,7 @@ #![feature(generic_const_exprs)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_transmutable< Src, @@ -15,7 +15,7 @@ mod assert { const ASSUME_VALIDITY: bool, >() where - Dst: BikeshedIntrinsicFrom< + Dst: TransmuteFrom< Src, { } >, diff --git a/tests/crashes/126966.rs b/tests/crashes/126966.rs index edeedc68c40..2c9f1a70f4f 100644 --- a/tests/crashes/126966.rs +++ b/tests/crashes/126966.rs @@ -1,10 +1,10 @@ //@ known-bug: rust-lang/rust#126966 mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src>, + Dst: TransmuteFrom<Src>, { } } diff --git a/tests/run-make/dos-device-input/rmake.rs b/tests/run-make/dos-device-input/rmake.rs index dee3b86f095..f5911d78fd9 100644 --- a/tests/run-make/dos-device-input/rmake.rs +++ b/tests/run-make/dos-device-input/rmake.rs @@ -1,13 +1,11 @@ //@ only-windows // Reason: dos devices are a Windows thing -use std::path::Path; - -use run_make_support::{rustc, static_lib_name}; +use run_make_support::{path, rustc, static_lib_name}; fn main() { rustc().input(r"\\.\NUL").crate_type("staticlib").run(); rustc().input(r"\\?\NUL").crate_type("staticlib").run(); - assert!(Path::new(&static_lib_name("rust_out")).exists()); + assert!(path(&static_lib_name("rust_out")).exists()); } diff --git a/tests/run-make/emit-shared-files/rmake.rs b/tests/run-make/emit-shared-files/rmake.rs index e5482af10bb..c8c113ce944 100644 --- a/tests/run-make/emit-shared-files/rmake.rs +++ b/tests/run-make/emit-shared-files/rmake.rs @@ -5,9 +5,7 @@ // `all-shared` should only emit files that can be shared between crates. // See https://github.com/rust-lang/rust/pull/83478 -use std::path::Path; - -use run_make_support::{has_extension, has_prefix, rustdoc, shallow_find_files}; +use run_make_support::{has_extension, has_prefix, path, rustdoc, shallow_find_files}; fn main() { rustdoc() @@ -19,17 +17,18 @@ fn main() { .args(&["--extend-css", "z.css"]) .input("x.rs") .run(); - assert!(Path::new("invocation-only/search-index-xxx.js").exists()); - assert!(Path::new("invocation-only/settings.html").exists()); - assert!(Path::new("invocation-only/x/all.html").exists()); - assert!(Path::new("invocation-only/x/index.html").exists()); - assert!(Path::new("invocation-only/theme-xxx.css").exists()); // generated from z.css - assert!(!Path::new("invocation-only/storage-xxx.js").exists()); - assert!(!Path::new("invocation-only/SourceSerif4-It.ttf.woff2").exists()); + assert!(path("invocation-only/search-index-xxx.js").exists()); + assert!(path("invocation-only/crates-xxx.js").exists()); + assert!(path("invocation-only/settings.html").exists()); + assert!(path("invocation-only/x/all.html").exists()); + assert!(path("invocation-only/x/index.html").exists()); + assert!(path("invocation-only/theme-xxx.css").exists()); // generated from z.css + assert!(!path("invocation-only/storage-xxx.js").exists()); + assert!(!path("invocation-only/SourceSerif4-It.ttf.woff2").exists()); // FIXME: this probably shouldn't have a suffix - assert!(Path::new("invocation-only/y-xxx.css").exists()); + assert!(path("invocation-only/y-xxx.css").exists()); // FIXME: this is technically incorrect (see `write_shared`) - assert!(!Path::new("invocation-only/main-xxx.js").exists()); + assert!(!path("invocation-only/main-xxx.js").exists()); rustdoc() .arg("-Zunstable-options") @@ -60,10 +59,10 @@ fn main() { .len(), 1 ); - assert!(!Path::new("toolchain-only/search-index-xxx.js").exists()); - assert!(!Path::new("toolchain-only/x/index.html").exists()); - assert!(!Path::new("toolchain-only/theme.css").exists()); - assert!(!Path::new("toolchain-only/y-xxx.css").exists()); + assert!(!path("toolchain-only/search-index-xxx.js").exists()); + assert!(!path("toolchain-only/x/index.html").exists()); + assert!(!path("toolchain-only/theme.css").exists()); + assert!(!path("toolchain-only/y-xxx.css").exists()); rustdoc() .arg("-Zunstable-options") @@ -87,11 +86,11 @@ fn main() { .len(), 1 ); - assert!(!Path::new("all-shared/search-index-xxx.js").exists()); - assert!(!Path::new("all-shared/settings.html").exists()); - assert!(!Path::new("all-shared/x").exists()); - assert!(!Path::new("all-shared/src").exists()); - assert!(!Path::new("all-shared/theme.css").exists()); + assert!(!path("all-shared/search-index-xxx.js").exists()); + assert!(!path("all-shared/settings.html").exists()); + assert!(!path("all-shared/x").exists()); + assert!(!path("all-shared/src").exists()); + assert!(!path("all-shared/theme.css").exists()); assert_eq!( shallow_find_files("all-shared/static.files", |path| { has_prefix(path, "main-") && has_extension(path, "js") @@ -99,5 +98,5 @@ fn main() { .len(), 1 ); - assert!(!Path::new("all-shared/y-xxx.css").exists()); + assert!(!path("all-shared/y-xxx.css").exists()); } diff --git a/tests/run-make/libtest-thread-limit/rmake.rs b/tests/run-make/libtest-thread-limit/rmake.rs index be0eeaf1717..5decd802b34 100644 --- a/tests/run-make/libtest-thread-limit/rmake.rs +++ b/tests/run-make/libtest-thread-limit/rmake.rs @@ -11,6 +11,9 @@ // Reason: thread limit modification //@ ignore-cross-compile // Reason: this test fails armhf-gnu, reasons unknown +//@ needs-unwind +// Reason: this should be ignored in cg_clif (Cranelift) CI and anywhere +// else that uses panic=abort. use std::ffi::{self, CStr, CString}; use std::path::PathBuf; diff --git a/tests/run-make/manual-crate-name/rmake.rs b/tests/run-make/manual-crate-name/rmake.rs index 9085b6c7bc2..9f480ec6b6a 100644 --- a/tests/run-make/manual-crate-name/rmake.rs +++ b/tests/run-make/manual-crate-name/rmake.rs @@ -1,8 +1,6 @@ -use std::path::Path; - -use run_make_support::rustc; +use run_make_support::{path, rustc}; fn main() { rustc().input("bar.rs").crate_name("foo").run(); - assert!(Path::new("libfoo.rlib").is_file()); + assert!(path("libfoo.rlib").is_file()); } diff --git a/tests/run-make/pretty-print-with-dep-file/rmake.rs b/tests/run-make/pretty-print-with-dep-file/rmake.rs index 5d422085834..24ae6bc2456 100644 --- a/tests/run-make/pretty-print-with-dep-file/rmake.rs +++ b/tests/run-make/pretty-print-with-dep-file/rmake.rs @@ -5,14 +5,12 @@ // does not get an unexpected dep-info file. // See https://github.com/rust-lang/rust/issues/112898 -use std::path::Path; - -use run_make_support::{invalid_utf8_contains, rfs, rustc}; +use run_make_support::{invalid_utf8_contains, path, rfs, rustc}; fn main() { rustc().emit("dep-info").arg("-Zunpretty=expanded").input("with-dep.rs").run(); invalid_utf8_contains("with-dep.d", "with-dep.rs"); rfs::remove_file("with-dep.d"); rustc().emit("dep-info").arg("-Zunpretty=normal").input("with-dep.rs").run(); - assert!(!Path::new("with-dep.d").exists()); + assert!(!path("with-dep.d").exists()); } diff --git a/tests/run-make/profile/rmake.rs b/tests/run-make/profile/rmake.rs index 4c6f9c19091..4287ab0a931 100644 --- a/tests/run-make/profile/rmake.rs +++ b/tests/run-make/profile/rmake.rs @@ -8,16 +8,14 @@ //@ ignore-cross-compile //@ needs-profiler-support -use std::path::Path; - -use run_make_support::{run, rustc}; +use run_make_support::{path, run, rustc}; fn main() { rustc().arg("-g").arg("-Zprofile").input("test.rs").run(); run("test"); - assert!(Path::new("test.gcno").exists(), "no .gcno file"); - assert!(Path::new("test.gcda").exists(), "no .gcda file"); + assert!(path("test.gcno").exists(), "no .gcno file"); + assert!(path("test.gcda").exists(), "no .gcda file"); rustc().arg("-g").arg("-Zprofile").arg("-Zprofile-emit=abc/abc.gcda").input("test.rs").run(); run("test"); - assert!(Path::new("abc/abc.gcda").exists(), "gcda file not emitted to defined path"); + assert!(path("abc/abc.gcda").exists(), "gcda file not emitted to defined path"); } diff --git a/tests/run-make/reset-codegen-1/rmake.rs b/tests/run-make/reset-codegen-1/rmake.rs index 118b3a666ad..bdc90e39f9e 100644 --- a/tests/run-make/reset-codegen-1/rmake.rs +++ b/tests/run-make/reset-codegen-1/rmake.rs @@ -7,9 +7,7 @@ //@ ignore-cross-compile -use std::path::Path; - -use run_make_support::{bin_name, rustc}; +use run_make_support::{bin_name, path, rustc}; fn compile(output_file: &str, emit: Option<&str>) { let mut rustc = rustc(); @@ -34,10 +32,10 @@ fn main() { // In the None case, bin_name is required for successful Windows compilation. let output_file = &bin_name(output_file); compile(output_file, emit); - assert!(Path::new(output_file).is_file()); + assert!(path(output_file).is_file()); } compile("multi-output", Some("asm,obj")); - assert!(Path::new("multi-output.s").is_file()); - assert!(Path::new("multi-output.o").is_file()); + assert!(path("multi-output.s").is_file()); + assert!(path("multi-output.o").is_file()); } diff --git a/tests/run-make/rustdoc-determinism/rmake.rs b/tests/run-make/rustdoc-determinism/rmake.rs index ce088508178..5a030c6f496 100644 --- a/tests/run-make/rustdoc-determinism/rmake.rs +++ b/tests/run-make/rustdoc-determinism/rmake.rs @@ -1,16 +1,14 @@ // Assert that the search index is generated deterministically, regardless of the // order that crates are documented in. -use std::path::Path; - -use run_make_support::{diff, rustdoc}; +use run_make_support::{diff, path, rustdoc}; fn main() { - let foo_first = Path::new("foo_first"); + let foo_first = path("foo_first"); rustdoc().input("foo.rs").out_dir(&foo_first).run(); rustdoc().input("bar.rs").out_dir(&foo_first).run(); - let bar_first = Path::new("bar_first"); + let bar_first = path("bar_first"); rustdoc().input("bar.rs").out_dir(&bar_first).run(); rustdoc().input("foo.rs").out_dir(&bar_first).run(); diff --git a/tests/run-make/rustdoc-output-path/rmake.rs b/tests/run-make/rustdoc-output-path/rmake.rs index 181239eac4d..7f6accf26c2 100644 --- a/tests/run-make/rustdoc-output-path/rmake.rs +++ b/tests/run-make/rustdoc-output-path/rmake.rs @@ -1,11 +1,9 @@ // Checks that if the output folder doesn't exist, rustdoc will create it. -use std::path::Path; - -use run_make_support::rustdoc; +use run_make_support::{path, rustdoc}; fn main() { - let out_dir = Path::new("foo/bar/doc"); + let out_dir = path("foo/bar/doc"); rustdoc().input("foo.rs").out_dir(&out_dir).run(); assert!(out_dir.exists()); } diff --git a/tests/ui/abi/compatibility.rs b/tests/ui/abi/compatibility.rs index ca78604edd8..d37e793d989 100644 --- a/tests/ui/abi/compatibility.rs +++ b/tests/ui/abi/compatibility.rs @@ -40,9 +40,10 @@ //@[loongarch64] compile-flags: --target loongarch64-unknown-linux-gnu //@[loongarch64] needs-llvm-components: loongarch //@[loongarch64] min-llvm-version: 18 -//@ revisions: wasm -//@[wasm] compile-flags: --target wasm32-unknown-unknown -//@[wasm] needs-llvm-components: webassembly +//FIXME: wasm is disabled due to <https://github.com/rust-lang/rust/issues/115666>. +//FIXME @ revisions: wasm +//FIXME @[wasm] compile-flags: --target wasm32-unknown-unknown +//FIXME @[wasm] needs-llvm-components: webassembly //@ revisions: wasip1 //@[wasip1] compile-flags: --target wasm32-wasip1 //@[wasip1] needs-llvm-components: webassembly diff --git a/tests/ui/asm/naked-with-invalid-repr-attr.rs b/tests/ui/asm/naked-with-invalid-repr-attr.rs new file mode 100644 index 00000000000..687fe1ad73d --- /dev/null +++ b/tests/ui/asm/naked-with-invalid-repr-attr.rs @@ -0,0 +1,48 @@ +//@ needs-asm-support +#![feature(naked_functions)] +#![feature(fn_align)] +#![crate_type = "lib"] +use std::arch::asm; + +#[repr(C)] +//~^ ERROR attribute should be applied to a struct, enum, or union [E0517] +#[naked] +extern "C" fn example1() { + //~^ NOTE not a struct, enum, or union + unsafe { asm!("", options(noreturn)) } +} + +#[repr(transparent)] +//~^ ERROR attribute should be applied to a struct, enum, or union [E0517] +#[naked] +extern "C" fn example2() { + //~^ NOTE not a struct, enum, or union + unsafe { asm!("", options(noreturn)) } +} + +#[repr(align(16), C)] +//~^ ERROR attribute should be applied to a struct, enum, or union [E0517] +#[naked] +extern "C" fn example3() { + //~^ NOTE not a struct, enum, or union + unsafe { asm!("", options(noreturn)) } +} + +// note: two errors because of packed and C +#[repr(C, packed)] +//~^ ERROR attribute should be applied to a struct or union [E0517] +//~| ERROR attribute should be applied to a struct, enum, or union [E0517] +#[naked] +extern "C" fn example4() { + //~^ NOTE not a struct, enum, or union + //~| NOTE not a struct or union + unsafe { asm!("", options(noreturn)) } +} + +#[repr(u8)] +//~^ ERROR attribute should be applied to an enum [E0517] +#[naked] +extern "C" fn example5() { + //~^ NOTE not an enum + unsafe { asm!("", options(noreturn)) } +} diff --git a/tests/ui/asm/naked-with-invalid-repr-attr.stderr b/tests/ui/asm/naked-with-invalid-repr-attr.stderr new file mode 100644 index 00000000000..3740f17a9dc --- /dev/null +++ b/tests/ui/asm/naked-with-invalid-repr-attr.stderr @@ -0,0 +1,77 @@ +error[E0517]: attribute should be applied to a struct, enum, or union + --> $DIR/naked-with-invalid-repr-attr.rs:7:8 + | +LL | #[repr(C)] + | ^ +... +LL | / extern "C" fn example1() { +LL | | +LL | | unsafe { asm!("", options(noreturn)) } +LL | | } + | |_- not a struct, enum, or union + +error[E0517]: attribute should be applied to a struct, enum, or union + --> $DIR/naked-with-invalid-repr-attr.rs:15:8 + | +LL | #[repr(transparent)] + | ^^^^^^^^^^^ +... +LL | / extern "C" fn example2() { +LL | | +LL | | unsafe { asm!("", options(noreturn)) } +LL | | } + | |_- not a struct, enum, or union + +error[E0517]: attribute should be applied to a struct, enum, or union + --> $DIR/naked-with-invalid-repr-attr.rs:23:19 + | +LL | #[repr(align(16), C)] + | ^ +... +LL | / extern "C" fn example3() { +LL | | +LL | | unsafe { asm!("", options(noreturn)) } +LL | | } + | |_- not a struct, enum, or union + +error[E0517]: attribute should be applied to a struct, enum, or union + --> $DIR/naked-with-invalid-repr-attr.rs:32:8 + | +LL | #[repr(C, packed)] + | ^ +... +LL | / extern "C" fn example4() { +LL | | +LL | | +LL | | unsafe { asm!("", options(noreturn)) } +LL | | } + | |_- not a struct, enum, or union + +error[E0517]: attribute should be applied to a struct or union + --> $DIR/naked-with-invalid-repr-attr.rs:32:11 + | +LL | #[repr(C, packed)] + | ^^^^^^ +... +LL | / extern "C" fn example4() { +LL | | +LL | | +LL | | unsafe { asm!("", options(noreturn)) } +LL | | } + | |_- not a struct or union + +error[E0517]: attribute should be applied to an enum + --> $DIR/naked-with-invalid-repr-attr.rs:42:8 + | +LL | #[repr(u8)] + | ^^ +... +LL | / extern "C" fn example5() { +LL | | +LL | | unsafe { asm!("", options(noreturn)) } +LL | | } + | |_- not an enum + +error: aborting due to 6 previous errors + +For more information about this error, try `rustc --explain E0517`. diff --git a/tests/ui/associated-inherent-types/bugs/cycle-iat-inside-of-adt.stderr b/tests/ui/associated-inherent-types/bugs/cycle-iat-inside-of-adt.stderr index a495e94bd9a..cf5d8f614dd 100644 --- a/tests/ui/associated-inherent-types/bugs/cycle-iat-inside-of-adt.stderr +++ b/tests/ui/associated-inherent-types/bugs/cycle-iat-inside-of-adt.stderr @@ -4,11 +4,6 @@ error[E0391]: cycle detected when computing predicates of `Foo` LL | struct Foo { | ^^^^^^^^^^ | -note: ...which requires computing predicates of `Foo`... - --> $DIR/cycle-iat-inside-of-adt.rs:7:1 - | -LL | struct Foo { - | ^^^^^^^^^^ note: ...which requires computing inferred outlives predicates of `Foo`... --> $DIR/cycle-iat-inside-of-adt.rs:7:1 | diff --git a/tests/ui/associated-inherent-types/bugs/cycle-iat-inside-of-where-predicate.stderr b/tests/ui/associated-inherent-types/bugs/cycle-iat-inside-of-where-predicate.stderr index e7292c08ebd..e97a5df9d49 100644 --- a/tests/ui/associated-inherent-types/bugs/cycle-iat-inside-of-where-predicate.stderr +++ b/tests/ui/associated-inherent-types/bugs/cycle-iat-inside-of-where-predicate.stderr @@ -4,11 +4,6 @@ error[E0391]: cycle detected when computing predicates of `user` LL | fn user<T>() where S<T>::P: std::fmt::Debug {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | -note: ...which requires computing predicates of `user`... - --> $DIR/cycle-iat-inside-of-where-predicate.rs:8:1 - | -LL | fn user<T>() where S<T>::P: std::fmt::Debug {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ note: ...which requires computing explicit predicates of `user`... --> $DIR/cycle-iat-inside-of-where-predicate.rs:8:1 | diff --git a/tests/ui/cfg/disallowed-cli-cfgs.fmt_debug_.stderr b/tests/ui/cfg/disallowed-cli-cfgs.fmt_debug_.stderr new file mode 100644 index 00000000000..a0d7fa5c3c9 --- /dev/null +++ b/tests/ui/cfg/disallowed-cli-cfgs.fmt_debug_.stderr @@ -0,0 +1,8 @@ +error: unexpected `--cfg fmt_debug="shallow"` flag + | + = note: config `fmt_debug` is only supposed to be controlled by `-Z fmt-debug` + = note: manually setting a built-in cfg can and does create incoherent behaviors + = note: `#[deny(explicit_builtin_cfgs_in_flags)]` on by default + +error: aborting due to 1 previous error + diff --git a/tests/ui/cfg/disallowed-cli-cfgs.rs b/tests/ui/cfg/disallowed-cli-cfgs.rs index 714c01f4bc6..3c9ee87f28a 100644 --- a/tests/ui/cfg/disallowed-cli-cfgs.rs +++ b/tests/ui/cfg/disallowed-cli-cfgs.rs @@ -6,6 +6,7 @@ //@ revisions: target_pointer_width_ target_vendor_ target_has_atomic_ //@ revisions: target_has_atomic_equal_alignment_ target_has_atomic_load_store_ //@ revisions: target_thread_local_ relocation_model_ +//@ revisions: fmt_debug_ //@ [overflow_checks_]compile-flags: --cfg overflow_checks //@ [debug_assertions_]compile-flags: --cfg debug_assertions @@ -31,5 +32,6 @@ //@ [target_has_atomic_load_store_]compile-flags: --cfg target_has_atomic_load_store="32" //@ [target_thread_local_]compile-flags: --cfg target_thread_local //@ [relocation_model_]compile-flags: --cfg relocation_model="a" +//@ [fmt_debug_]compile-flags: --cfg fmt_debug="shallow" fn main() {} diff --git a/tests/ui/check-cfg/allow-same-level.stderr b/tests/ui/check-cfg/allow-same-level.stderr index b311a80c8fd..b1a9c5810d8 100644 --- a/tests/ui/check-cfg/allow-same-level.stderr +++ b/tests/ui/check-cfg/allow-same-level.stderr @@ -4,7 +4,7 @@ warning: unexpected `cfg` condition name: `FALSE` LL | #[cfg(FALSE)] | ^^^^^ | - = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, and `windows` + = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `fmt_debug`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, and `windows` = help: to expect this configuration use `--check-cfg=cfg(FALSE)` = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration = note: `#[warn(unexpected_cfgs)]` on by default diff --git a/tests/ui/check-cfg/cargo-build-script.stderr b/tests/ui/check-cfg/cargo-build-script.stderr index 9ab3290ef22..0b01b1da5a7 100644 --- a/tests/ui/check-cfg/cargo-build-script.stderr +++ b/tests/ui/check-cfg/cargo-build-script.stderr @@ -4,7 +4,7 @@ warning: unexpected `cfg` condition name: `has_foo` LL | #[cfg(has_foo)] | ^^^^^^^ | - = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `has_bar`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, and `windows` + = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `fmt_debug`, `has_bar`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, and `windows` = help: consider using a Cargo feature instead = help: or consider adding in `Cargo.toml` the `check-cfg` lint config for the lint: [lints.rust] diff --git a/tests/ui/check-cfg/cargo-feature.none.stderr b/tests/ui/check-cfg/cargo-feature.none.stderr index 9d3117ed54d..6de6e9a6851 100644 --- a/tests/ui/check-cfg/cargo-feature.none.stderr +++ b/tests/ui/check-cfg/cargo-feature.none.stderr @@ -25,7 +25,7 @@ warning: unexpected `cfg` condition name: `tokio_unstable` LL | #[cfg(tokio_unstable)] | ^^^^^^^^^^^^^^ | - = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `feature`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, and `windows` + = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `feature`, `fmt_debug`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, and `windows` = help: consider using a Cargo feature instead = help: or consider adding in `Cargo.toml` the `check-cfg` lint config for the lint: [lints.rust] diff --git a/tests/ui/check-cfg/cargo-feature.some.stderr b/tests/ui/check-cfg/cargo-feature.some.stderr index 14e24cb1429..d4a7f6defb2 100644 --- a/tests/ui/check-cfg/cargo-feature.some.stderr +++ b/tests/ui/check-cfg/cargo-feature.some.stderr @@ -25,7 +25,7 @@ warning: unexpected `cfg` condition name: `tokio_unstable` LL | #[cfg(tokio_unstable)] | ^^^^^^^^^^^^^^ | - = help: expected names are: `CONFIG_NVME`, `clippy`, `debug_assertions`, `doc`, `doctest`, `feature`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, and `windows` + = help: expected names are: `CONFIG_NVME`, `clippy`, `debug_assertions`, `doc`, `doctest`, `feature`, `fmt_debug`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, and `windows` = help: consider using a Cargo feature instead = help: or consider adding in `Cargo.toml` the `check-cfg` lint config for the lint: [lints.rust] diff --git a/tests/ui/check-cfg/cfg-value-for-cfg-name-duplicate.stderr b/tests/ui/check-cfg/cfg-value-for-cfg-name-duplicate.stderr index 08bd43832ea..831722a12e2 100644 --- a/tests/ui/check-cfg/cfg-value-for-cfg-name-duplicate.stderr +++ b/tests/ui/check-cfg/cfg-value-for-cfg-name-duplicate.stderr @@ -4,7 +4,7 @@ warning: unexpected `cfg` condition name: `value` LL | #[cfg(value)] | ^^^^^ | - = help: expected names are: `bar`, `bee`, `clippy`, `cow`, `debug_assertions`, `doc`, `doctest`, `foo`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, and `windows` + = help: expected names are: `bar`, `bee`, `clippy`, `cow`, `debug_assertions`, `doc`, `doctest`, `fmt_debug`, `foo`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, and `windows` = help: to expect this configuration use `--check-cfg=cfg(value)` = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration = note: `#[warn(unexpected_cfgs)]` on by default diff --git a/tests/ui/check-cfg/cfg-value-for-cfg-name-multiple.stderr b/tests/ui/check-cfg/cfg-value-for-cfg-name-multiple.stderr index 6db1144eada..a35a8d68def 100644 --- a/tests/ui/check-cfg/cfg-value-for-cfg-name-multiple.stderr +++ b/tests/ui/check-cfg/cfg-value-for-cfg-name-multiple.stderr @@ -4,7 +4,7 @@ warning: unexpected `cfg` condition name: `my_value` LL | #[cfg(my_value)] | ^^^^^^^^ | - = help: expected names are: `bar`, `clippy`, `debug_assertions`, `doc`, `doctest`, `foo`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, and `windows` + = help: expected names are: `bar`, `clippy`, `debug_assertions`, `doc`, `doctest`, `fmt_debug`, `foo`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, and `windows` = help: to expect this configuration use `--check-cfg=cfg(my_value)` = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration = note: `#[warn(unexpected_cfgs)]` on by default diff --git a/tests/ui/check-cfg/cfg-value-for-cfg-name.stderr b/tests/ui/check-cfg/cfg-value-for-cfg-name.stderr index a5f8176343a..65a73ffcd1d 100644 --- a/tests/ui/check-cfg/cfg-value-for-cfg-name.stderr +++ b/tests/ui/check-cfg/cfg-value-for-cfg-name.stderr @@ -4,7 +4,7 @@ warning: unexpected `cfg` condition name: `linux` LL | #[cfg(linux)] | ^^^^^ help: found config with similar value: `target_os = "linux"` | - = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, and `windows` + = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `fmt_debug`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, and `windows` = help: to expect this configuration use `--check-cfg=cfg(linux)` = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration = note: `#[warn(unexpected_cfgs)]` on by default diff --git a/tests/ui/check-cfg/compact-names.stderr b/tests/ui/check-cfg/compact-names.stderr index 6fecdb52362..536c992ee92 100644 --- a/tests/ui/check-cfg/compact-names.stderr +++ b/tests/ui/check-cfg/compact-names.stderr @@ -4,7 +4,7 @@ warning: unexpected `cfg` condition name: `target_architecture` LL | #[cfg(target(os = "linux", architecture = "arm"))] | ^^^^^^^^^^^^^^^^^^^^ | - = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, and `windows` + = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `fmt_debug`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, and `windows` = help: to expect this configuration use `--check-cfg=cfg(target_architecture, values("arm"))` = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration = note: `#[warn(unexpected_cfgs)]` on by default diff --git a/tests/ui/check-cfg/exhaustive-names-values.empty_cfg.stderr b/tests/ui/check-cfg/exhaustive-names-values.empty_cfg.stderr index 2497864e87e..6c26a8b11d9 100644 --- a/tests/ui/check-cfg/exhaustive-names-values.empty_cfg.stderr +++ b/tests/ui/check-cfg/exhaustive-names-values.empty_cfg.stderr @@ -4,7 +4,7 @@ warning: unexpected `cfg` condition name: `unknown_key` LL | #[cfg(unknown_key = "value")] | ^^^^^^^^^^^^^^^^^^^^^ | - = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, and `windows` + = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `fmt_debug`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, and `windows` = help: to expect this configuration use `--check-cfg=cfg(unknown_key, values("value"))` = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration = note: `#[warn(unexpected_cfgs)]` on by default diff --git a/tests/ui/check-cfg/exhaustive-names-values.feature.stderr b/tests/ui/check-cfg/exhaustive-names-values.feature.stderr index a7d4c6d4df6..b7ccf5e5f83 100644 --- a/tests/ui/check-cfg/exhaustive-names-values.feature.stderr +++ b/tests/ui/check-cfg/exhaustive-names-values.feature.stderr @@ -4,7 +4,7 @@ warning: unexpected `cfg` condition name: `unknown_key` LL | #[cfg(unknown_key = "value")] | ^^^^^^^^^^^^^^^^^^^^^ | - = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `feature`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, and `windows` + = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `feature`, `fmt_debug`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, and `windows` = help: to expect this configuration use `--check-cfg=cfg(unknown_key, values("value"))` = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration = note: `#[warn(unexpected_cfgs)]` on by default diff --git a/tests/ui/check-cfg/exhaustive-names-values.full.stderr b/tests/ui/check-cfg/exhaustive-names-values.full.stderr index a7d4c6d4df6..b7ccf5e5f83 100644 --- a/tests/ui/check-cfg/exhaustive-names-values.full.stderr +++ b/tests/ui/check-cfg/exhaustive-names-values.full.stderr @@ -4,7 +4,7 @@ warning: unexpected `cfg` condition name: `unknown_key` LL | #[cfg(unknown_key = "value")] | ^^^^^^^^^^^^^^^^^^^^^ | - = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `feature`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, and `windows` + = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `feature`, `fmt_debug`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, and `windows` = help: to expect this configuration use `--check-cfg=cfg(unknown_key, values("value"))` = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration = note: `#[warn(unexpected_cfgs)]` on by default diff --git a/tests/ui/check-cfg/exhaustive-names.stderr b/tests/ui/check-cfg/exhaustive-names.stderr index 7ac3241db5f..5350534f3e8 100644 --- a/tests/ui/check-cfg/exhaustive-names.stderr +++ b/tests/ui/check-cfg/exhaustive-names.stderr @@ -4,7 +4,7 @@ warning: unexpected `cfg` condition name: `unknown_key` LL | #[cfg(unknown_key = "value")] | ^^^^^^^^^^^^^^^^^^^^^ | - = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, and `windows` + = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `fmt_debug`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, and `windows` = help: to expect this configuration use `--check-cfg=cfg(unknown_key, values("value"))` = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration = note: `#[warn(unexpected_cfgs)]` on by default diff --git a/tests/ui/check-cfg/mix.stderr b/tests/ui/check-cfg/mix.stderr index 520cffc4b02..a163728b51d 100644 --- a/tests/ui/check-cfg/mix.stderr +++ b/tests/ui/check-cfg/mix.stderr @@ -44,7 +44,7 @@ warning: unexpected `cfg` condition name: `uu` LL | #[cfg_attr(uu, test)] | ^^ | - = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `feature`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, and `windows` + = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `feature`, `fmt_debug`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, and `windows` = help: to expect this configuration use `--check-cfg=cfg(uu)` = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration @@ -251,7 +251,7 @@ warning: unexpected `cfg` condition value: `zebra` LL | cfg!(target_feature = "zebra"); | ^^^^^^^^^^^^^^^^^^^^^^^^ | - = note: expected values for `target_feature` are: `10e60`, `2e3`, `3e3r1`, `3e3r2`, `3e3r3`, `3e7`, `7e10`, `a`, `aclass`, `adx`, `aes`, `altivec`, `alu32`, `amx-bf16`, `amx-complex`, `amx-fp16`, `amx-int8`, `amx-tile`, `atomics`, `avx`, `avx2`, `avx512bf16`, `avx512bitalg`, `avx512bw`, `avx512cd`, `avx512dq`, `avx512f`, `avx512fp16`, `avx512ifma`, `avx512vbmi`, `avx512vbmi2`, `avx512vl`, `avx512vnni`, `avx512vp2intersect`, and `avx512vpopcntdq` and 201 more + = note: expected values for `target_feature` are: `10e60`, `2e3`, `3e3r1`, `3e3r2`, `3e3r3`, `3e7`, `7e10`, `a`, `aclass`, `adx`, `aes`, `altivec`, `alu32`, `amx-bf16`, `amx-complex`, `amx-fp16`, `amx-int8`, `amx-tile`, `atomics`, `avx`, `avx2`, `avx512bf16`, `avx512bitalg`, `avx512bw`, `avx512cd`, `avx512dq`, `avx512f`, `avx512fp16`, `avx512ifma`, `avx512vbmi`, `avx512vbmi2`, `avx512vl`, `avx512vnni`, `avx512vp2intersect`, and `avx512vpopcntdq` and 239 more = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration warning: 27 warnings emitted diff --git a/tests/ui/check-cfg/stmt-no-ice.stderr b/tests/ui/check-cfg/stmt-no-ice.stderr index e8b61d808fe..98f09a648bc 100644 --- a/tests/ui/check-cfg/stmt-no-ice.stderr +++ b/tests/ui/check-cfg/stmt-no-ice.stderr @@ -4,7 +4,7 @@ warning: unexpected `cfg` condition name: `crossbeam_loom` LL | #[cfg(crossbeam_loom)] | ^^^^^^^^^^^^^^ | - = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, and `windows` + = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `fmt_debug`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, and `windows` = help: to expect this configuration use `--check-cfg=cfg(crossbeam_loom)` = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration = note: `#[warn(unexpected_cfgs)]` on by default diff --git a/tests/ui/check-cfg/well-known-names.stderr b/tests/ui/check-cfg/well-known-names.stderr index 41130210df1..abcf53cfe30 100644 --- a/tests/ui/check-cfg/well-known-names.stderr +++ b/tests/ui/check-cfg/well-known-names.stderr @@ -18,7 +18,7 @@ warning: unexpected `cfg` condition name: `features` LL | #[cfg(features = "foo")] | ^^^^^^^^^^^^^^^^ | - = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, and `windows` + = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `fmt_debug`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, and `windows` = help: to expect this configuration use `--check-cfg=cfg(features, values("foo"))` = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration diff --git a/tests/ui/check-cfg/well-known-values.rs b/tests/ui/check-cfg/well-known-values.rs index d5fe7464792..1fda4b2089e 100644 --- a/tests/ui/check-cfg/well-known-values.rs +++ b/tests/ui/check-cfg/well-known-values.rs @@ -16,6 +16,7 @@ #![feature(cfg_target_has_atomic_equal_alignment)] #![feature(cfg_target_thread_local)] #![feature(cfg_ub_checks)] +#![feature(fmt_debug)] // This part makes sure that none of the well known names are // unexpected. @@ -33,6 +34,8 @@ //~^ WARN unexpected `cfg` condition value doctest = "_UNEXPECTED_VALUE", //~^ WARN unexpected `cfg` condition value + fmt_debug = "_UNEXPECTED_VALUE", + //~^ WARN unexpected `cfg` condition value miri = "_UNEXPECTED_VALUE", //~^ WARN unexpected `cfg` condition value overflow_checks = "_UNEXPECTED_VALUE", diff --git a/tests/ui/check-cfg/well-known-values.stderr b/tests/ui/check-cfg/well-known-values.stderr index 103a7564a0f..0530e1c34c9 100644 --- a/tests/ui/check-cfg/well-known-values.stderr +++ b/tests/ui/check-cfg/well-known-values.stderr @@ -1,5 +1,5 @@ warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:28:5 + --> $DIR/well-known-values.rs:29:5 | LL | clippy = "_UNEXPECTED_VALUE", | ^^^^^^---------------------- @@ -11,7 +11,7 @@ LL | clippy = "_UNEXPECTED_VALUE", = note: `#[warn(unexpected_cfgs)]` on by default warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:30:5 + --> $DIR/well-known-values.rs:31:5 | LL | debug_assertions = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^---------------------- @@ -22,7 +22,7 @@ LL | debug_assertions = "_UNEXPECTED_VALUE", = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:32:5 + --> $DIR/well-known-values.rs:33:5 | LL | doc = "_UNEXPECTED_VALUE", | ^^^---------------------- @@ -33,7 +33,7 @@ LL | doc = "_UNEXPECTED_VALUE", = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:34:5 + --> $DIR/well-known-values.rs:35:5 | LL | doctest = "_UNEXPECTED_VALUE", | ^^^^^^^---------------------- @@ -44,7 +44,16 @@ LL | doctest = "_UNEXPECTED_VALUE", = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:36:5 + --> $DIR/well-known-values.rs:37:5 + | +LL | fmt_debug = "_UNEXPECTED_VALUE", + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: expected values for `fmt_debug` are: `full`, `none`, and `shallow` + = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration + +warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` + --> $DIR/well-known-values.rs:39:5 | LL | miri = "_UNEXPECTED_VALUE", | ^^^^---------------------- @@ -55,7 +64,7 @@ LL | miri = "_UNEXPECTED_VALUE", = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:38:5 + --> $DIR/well-known-values.rs:41:5 | LL | overflow_checks = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^---------------------- @@ -66,7 +75,7 @@ LL | overflow_checks = "_UNEXPECTED_VALUE", = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:40:5 + --> $DIR/well-known-values.rs:43:5 | LL | panic = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -75,7 +84,7 @@ LL | panic = "_UNEXPECTED_VALUE", = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:42:5 + --> $DIR/well-known-values.rs:45:5 | LL | proc_macro = "_UNEXPECTED_VALUE", | ^^^^^^^^^^---------------------- @@ -86,7 +95,7 @@ LL | proc_macro = "_UNEXPECTED_VALUE", = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:44:5 + --> $DIR/well-known-values.rs:47:5 | LL | relocation_model = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -95,7 +104,7 @@ LL | relocation_model = "_UNEXPECTED_VALUE", = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:46:5 + --> $DIR/well-known-values.rs:49:5 | LL | rustfmt = "_UNEXPECTED_VALUE", | ^^^^^^^---------------------- @@ -106,7 +115,7 @@ LL | rustfmt = "_UNEXPECTED_VALUE", = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:48:5 + --> $DIR/well-known-values.rs:51:5 | LL | sanitize = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -115,7 +124,7 @@ LL | sanitize = "_UNEXPECTED_VALUE", = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:50:5 + --> $DIR/well-known-values.rs:53:5 | LL | target_abi = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -124,7 +133,7 @@ LL | target_abi = "_UNEXPECTED_VALUE", = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:52:5 + --> $DIR/well-known-values.rs:55:5 | LL | target_arch = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -133,7 +142,7 @@ LL | target_arch = "_UNEXPECTED_VALUE", = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:54:5 + --> $DIR/well-known-values.rs:57:5 | LL | target_endian = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -142,7 +151,7 @@ LL | target_endian = "_UNEXPECTED_VALUE", = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:56:5 + --> $DIR/well-known-values.rs:59:5 | LL | target_env = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -151,7 +160,7 @@ LL | target_env = "_UNEXPECTED_VALUE", = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:58:5 + --> $DIR/well-known-values.rs:61:5 | LL | target_family = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -160,16 +169,16 @@ LL | target_family = "_UNEXPECTED_VALUE", = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:60:5 + --> $DIR/well-known-values.rs:63:5 | LL | target_feature = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | - = note: expected values for `target_feature` are: `10e60`, `2e3`, `3e3r1`, `3e3r2`, `3e3r3`, `3e7`, `7e10`, `a`, `aclass`, `adx`, `aes`, `altivec`, `alu32`, `amx-bf16`, `amx-complex`, `amx-fp16`, `amx-int8`, `amx-tile`, `atomics`, `avx`, `avx2`, `avx512bf16`, `avx512bitalg`, `avx512bw`, `avx512cd`, `avx512dq`, `avx512f`, `avx512fp16`, `avx512ifma`, `avx512vbmi`, `avx512vbmi2`, `avx512vl`, `avx512vnni`, `avx512vp2intersect`, `avx512vpopcntdq`, `avxifma`, `avxneconvert`, `avxvnni`, `avxvnniint16`, `avxvnniint8`, `backchain`, `bf16`, `bmi1`, `bmi2`, `bti`, `bulk-memory`, `c`, `cache`, `cmpxchg16b`, `crc`, `crt-static`, `d`, `d32`, `dit`, `doloop`, `dotprod`, `dpb`, `dpb2`, `dsp`, `dsp1e2`, `dspe60`, `e`, `e1`, `e2`, `edsp`, `elrw`, `ermsb`, `exception-handling`, `extended-const`, `f`, `f16c`, `f32mm`, `f64mm`, `fcma`, `fdivdu`, `fhm`, `flagm`, `float1e2`, `float1e3`, `float3e4`, `float7e60`, `floate1`, `fma`, `fp-armv8`, `fp16`, `fp64`, `fpuv2_df`, `fpuv2_sf`, `fpuv3_df`, `fpuv3_hf`, `fpuv3_hi`, `fpuv3_sf`, `frecipe`, `frintts`, `fxsr`, `gfni`, `hard-float`, `hard-float-abi`, `hard-tp`, `high-registers`, `hvx`, `hvx-length128b`, `hwdiv`, `i8mm`, `jsconv`, `lahfsahf`, `lasx`, `lbt`, `lor`, `lse`, `lsx`, `lvz`, `lzcnt`, `m`, `mclass`, `movbe`, `mp`, `mp1e2`, `msa`, `mte`, `multivalue`, `mutable-globals`, `neon`, `nontrapping-fptoint`, `nvic`, `paca`, `pacg`, `pan`, `pclmulqdq`, `pmuv3`, `popcnt`, `power10-vector`, `power8-altivec`, `power8-vector`, `power9-altivec`, `power9-vector`, `prfchw`, `rand`, `ras`, `rclass`, `rcpc`, `rcpc2`, `rdm`, `rdrand`, `rdseed`, `reference-types`, `relax`, `relaxed-simd`, `rtm`, `sb`, `sha`, `sha2`, `sha3`, `sha512`, `sign-ext`, `simd128`, `sm3`, `sm4`, `spe`, `ssbs`, `sse`, `sse2`, `sse3`, `sse4.1`, `sse4.2`, `sse4a`, `ssse3`, `sve`, `sve2`, `sve2-aes`, `sve2-bitperm`, `sve2-sha3`, `sve2-sm4`, `tbm`, `thumb-mode`, `thumb2`, `tme`, `trust`, `trustzone`, `ual`, `unaligned-scalar-mem`, `v`, `v5te`, `v6`, `v6k`, `v6t2`, `v7`, `v8`, `v8.1a`, `v8.2a`, `v8.3a`, `v8.4a`, `v8.5a`, `v8.6a`, `v8.7a`, `vaes`, `vdsp2e60f`, `vdspv1`, `vdspv2`, `vector`, `vfp2`, `vfp3`, `vfp4`, `vh`, `virt`, `virtualization`, `vpclmulqdq`, `vsx`, `xop`, `xsave`, `xsavec`, `xsaveopt`, `xsaves`, `zba`, `zbb`, `zbc`, `zbkb`, `zbkc`, `zbkx`, `zbs`, `zdinx`, `zfh`, `zfhmin`, `zfinx`, `zhinx`, `zhinxmin`, `zk`, `zkn`, `zknd`, `zkne`, `zknh`, `zkr`, `zks`, `zksed`, `zksh`, and `zkt` + = note: expected values for `target_feature` are: `10e60`, `2e3`, `3e3r1`, `3e3r2`, `3e3r3`, `3e7`, `7e10`, `a`, `aclass`, `adx`, `aes`, `altivec`, `alu32`, `amx-bf16`, `amx-complex`, `amx-fp16`, `amx-int8`, `amx-tile`, `atomics`, `avx`, `avx2`, `avx512bf16`, `avx512bitalg`, `avx512bw`, `avx512cd`, `avx512dq`, `avx512f`, `avx512fp16`, `avx512ifma`, `avx512vbmi`, `avx512vbmi2`, `avx512vl`, `avx512vnni`, `avx512vp2intersect`, `avx512vpopcntdq`, `avxifma`, `avxneconvert`, `avxvnni`, `avxvnniint16`, `avxvnniint8`, `backchain`, `bf16`, `bmi1`, `bmi2`, `bti`, `bulk-memory`, `c`, `cache`, `cmpxchg16b`, `crc`, `crt-static`, `cssc`, `d`, `d32`, `dit`, `doloop`, `dotprod`, `dpb`, `dpb2`, `dsp`, `dsp1e2`, `dspe60`, `e`, `e1`, `e2`, `ecv`, `edsp`, `elrw`, `ermsb`, `exception-handling`, `extended-const`, `f`, `f16c`, `f32mm`, `f64mm`, `faminmax`, `fcma`, `fdivdu`, `fhm`, `flagm`, `flagm2`, `float1e2`, `float1e3`, `float3e4`, `float7e60`, `floate1`, `fma`, `fp-armv8`, `fp16`, `fp64`, `fp8`, `fp8dot2`, `fp8dot4`, `fp8fma`, `fpuv2_df`, `fpuv2_sf`, `fpuv3_df`, `fpuv3_hf`, `fpuv3_hi`, `fpuv3_sf`, `frecipe`, `frintts`, `fxsr`, `gfni`, `hard-float`, `hard-float-abi`, `hard-tp`, `hbc`, `high-registers`, `hvx`, `hvx-length128b`, `hwdiv`, `i8mm`, `jsconv`, `lahfsahf`, `lasx`, `lbt`, `lor`, `lse`, `lse128`, `lse2`, `lsx`, `lut`, `lvz`, `lzcnt`, `m`, `mclass`, `mops`, `movbe`, `mp`, `mp1e2`, `msa`, `mte`, `multivalue`, `mutable-globals`, `neon`, `nontrapping-fptoint`, `nvic`, `paca`, `pacg`, `pan`, `pclmulqdq`, `pmuv3`, `popcnt`, `power10-vector`, `power8-altivec`, `power8-vector`, `power9-altivec`, `power9-vector`, `prfchw`, `rand`, `ras`, `rclass`, `rcpc`, `rcpc2`, `rcpc3`, `rdm`, `rdrand`, `rdseed`, `reference-types`, `relax`, `relaxed-simd`, `rtm`, `sb`, `sha`, `sha2`, `sha3`, `sha512`, `sign-ext`, `simd128`, `sm3`, `sm4`, `sme`, `sme-f16f16`, `sme-f64f64`, `sme-f8f16`, `sme-f8f32`, `sme-fa64`, `sme-i16i64`, `sme-lutv2`, `sme2`, `sme2p1`, `spe`, `ssbs`, `sse`, `sse2`, `sse3`, `sse4.1`, `sse4.2`, `sse4a`, `ssse3`, `ssve-fp8dot2`, `ssve-fp8dot4`, `ssve-fp8fma`, `sve`, `sve-b16b16`, `sve2`, `sve2-aes`, `sve2-bitperm`, `sve2-sha3`, `sve2-sm4`, `sve2p1`, `tbm`, `thumb-mode`, `thumb2`, `tme`, `trust`, `trustzone`, `ual`, `unaligned-scalar-mem`, `v`, `v5te`, `v6`, `v6k`, `v6t2`, `v7`, `v8`, `v8.1a`, `v8.2a`, `v8.3a`, `v8.4a`, `v8.5a`, `v8.6a`, `v8.7a`, `v8.8a`, `v8.9a`, `v9.1a`, `v9.2a`, `v9.3a`, `v9.4a`, `v9.5a`, `v9a`, `vaes`, `vdsp2e60f`, `vdspv1`, `vdspv2`, `vector`, `vfp2`, `vfp3`, `vfp4`, `vh`, `virt`, `virtualization`, `vpclmulqdq`, `vsx`, `wfxt`, `xop`, `xsave`, `xsavec`, `xsaveopt`, `xsaves`, `zba`, `zbb`, `zbc`, `zbkb`, `zbkc`, `zbkx`, `zbs`, `zdinx`, `zfh`, `zfhmin`, `zfinx`, `zhinx`, `zhinxmin`, `zk`, `zkn`, `zknd`, `zkne`, `zknh`, `zkr`, `zks`, `zksed`, `zksh`, and `zkt` = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:62:5 + --> $DIR/well-known-values.rs:65:5 | LL | target_has_atomic = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -178,7 +187,7 @@ LL | target_has_atomic = "_UNEXPECTED_VALUE", = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:64:5 + --> $DIR/well-known-values.rs:67:5 | LL | target_has_atomic_equal_alignment = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -187,7 +196,7 @@ LL | target_has_atomic_equal_alignment = "_UNEXPECTED_VALUE", = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:66:5 + --> $DIR/well-known-values.rs:69:5 | LL | target_has_atomic_load_store = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -196,7 +205,7 @@ LL | target_has_atomic_load_store = "_UNEXPECTED_VALUE", = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:68:5 + --> $DIR/well-known-values.rs:71:5 | LL | target_os = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -205,7 +214,7 @@ LL | target_os = "_UNEXPECTED_VALUE", = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:70:5 + --> $DIR/well-known-values.rs:73:5 | LL | target_pointer_width = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -214,7 +223,7 @@ LL | target_pointer_width = "_UNEXPECTED_VALUE", = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:72:5 + --> $DIR/well-known-values.rs:75:5 | LL | target_thread_local = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^---------------------- @@ -225,7 +234,7 @@ LL | target_thread_local = "_UNEXPECTED_VALUE", = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:74:5 + --> $DIR/well-known-values.rs:77:5 | LL | target_vendor = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -234,7 +243,7 @@ LL | target_vendor = "_UNEXPECTED_VALUE", = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:76:5 + --> $DIR/well-known-values.rs:79:5 | LL | test = "_UNEXPECTED_VALUE", | ^^^^---------------------- @@ -245,7 +254,7 @@ LL | test = "_UNEXPECTED_VALUE", = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:78:5 + --> $DIR/well-known-values.rs:81:5 | LL | ub_checks = "_UNEXPECTED_VALUE", | ^^^^^^^^^---------------------- @@ -256,7 +265,7 @@ LL | ub_checks = "_UNEXPECTED_VALUE", = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:80:5 + --> $DIR/well-known-values.rs:83:5 | LL | unix = "_UNEXPECTED_VALUE", | ^^^^---------------------- @@ -267,7 +276,7 @@ LL | unix = "_UNEXPECTED_VALUE", = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:82:5 + --> $DIR/well-known-values.rs:85:5 | LL | windows = "_UNEXPECTED_VALUE", | ^^^^^^^---------------------- @@ -278,7 +287,7 @@ LL | windows = "_UNEXPECTED_VALUE", = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration warning: unexpected `cfg` condition value: `linuz` - --> $DIR/well-known-values.rs:88:7 + --> $DIR/well-known-values.rs:91:7 | LL | #[cfg(target_os = "linuz")] // testing that we suggest `linux` | ^^^^^^^^^^^^------- @@ -288,5 +297,5 @@ LL | #[cfg(target_os = "linuz")] // testing that we suggest `linux` = note: expected values for `target_os` are: `aix`, `android`, `cuda`, `dragonfly`, `emscripten`, `espidf`, `freebsd`, `fuchsia`, `haiku`, `hermit`, `horizon`, `hurd`, `illumos`, `ios`, `l4re`, `linux`, `macos`, `netbsd`, `none`, `nto`, `nuttx`, `openbsd`, `psp`, `redox`, `solaris`, `solid_asp3`, `teeos`, `trusty`, `tvos`, `uefi`, `unknown`, `visionos`, `vita`, `vxworks`, `wasi`, `watchos`, `windows`, `xous`, and `zkvm` = note: see <https://doc.rust-lang.org/nightly/rustc/check-cfg.html> for more information about checking conditional configuration -warning: 29 warnings emitted +warning: 30 warnings emitted diff --git a/tests/ui/const-generics/adt_const_params/transmutable-ice-110969.rs b/tests/ui/const-generics/adt_const_params/transmutable-ice-110969.rs index 569e57fa326..401267a0f16 100644 --- a/tests/ui/const-generics/adt_const_params/transmutable-ice-110969.rs +++ b/tests/ui/const-generics/adt_const_params/transmutable-ice-110969.rs @@ -4,11 +4,11 @@ #![allow(incomplete_features, unstable_features)] mod assert { - use std::mem::BikeshedIntrinsicFrom; + use std::mem::TransmuteFrom; pub fn is_transmutable<Src, Dst, Context, const ASSUME: std::mem::Assume>() where - Dst: BikeshedIntrinsicFrom<Src, Context, ASSUME>, + Dst: TransmuteFrom<Src, Context, ASSUME>, //~^ ERROR trait takes at most 2 generic arguments but 3 generic arguments were supplied { } diff --git a/tests/ui/const-generics/adt_const_params/transmutable-ice-110969.stderr b/tests/ui/const-generics/adt_const_params/transmutable-ice-110969.stderr index 5c04c4c9d5b..96716685614 100644 --- a/tests/ui/const-generics/adt_const_params/transmutable-ice-110969.stderr +++ b/tests/ui/const-generics/adt_const_params/transmutable-ice-110969.stderr @@ -1,8 +1,8 @@ error[E0107]: trait takes at most 2 generic arguments but 3 generic arguments were supplied --> $DIR/transmutable-ice-110969.rs:11:14 | -LL | Dst: BikeshedIntrinsicFrom<Src, Context, ASSUME>, - | ^^^^^^^^^^^^^^^^^^^^^ -------- help: remove the unnecessary generic argument +LL | Dst: TransmuteFrom<Src, Context, ASSUME>, + | ^^^^^^^^^^^^^ -------- help: remove the unnecessary generic argument | | | expected at most 2 generic arguments diff --git a/tests/ui/consts/const-eval/const_fn_target_feature.rs b/tests/ui/consts/const-eval/const_fn_target_feature.rs index ee669abb51e..8db41ba11c0 100644 --- a/tests/ui/consts/const-eval/const_fn_target_feature.rs +++ b/tests/ui/consts/const-eval/const_fn_target_feature.rs @@ -1,6 +1,7 @@ //@ only-x86_64 // Set the base cpu explicitly, in case the default has been changed. //@ compile-flags: -C target-cpu=x86-64 -C target-feature=+ssse3 +//@ check-pass #![crate_type = "lib"] @@ -9,7 +10,8 @@ const A: () = unsafe { ssse3_fn() }; // error (avx2 not enabled at compile time) const B: () = unsafe { avx2_fn() }; -//~^ ERROR evaluation of constant value failed +// FIXME: currently we do not detect this UB, since we don't want the result of const-eval +// to depend on `tcx.sess` which can differ between crates in a crate graph. #[target_feature(enable = "ssse3")] const unsafe fn ssse3_fn() {} diff --git a/tests/ui/consts/const-eval/const_fn_target_feature.stderr b/tests/ui/consts/const-eval/const_fn_target_feature.stderr deleted file mode 100644 index d3a00b57ebb..00000000000 --- a/tests/ui/consts/const-eval/const_fn_target_feature.stderr +++ /dev/null @@ -1,9 +0,0 @@ -error[E0080]: evaluation of constant value failed - --> $DIR/const_fn_target_feature.rs:11:24 - | -LL | const B: () = unsafe { avx2_fn() }; - | ^^^^^^^^^ calling a function that requires unavailable target features: avx2 - -error: aborting due to 1 previous error - -For more information about this error, try `rustc --explain E0080`. diff --git a/tests/ui/consts/const-eval/const_fn_target_feature_wasm.rs b/tests/ui/consts/const-eval/const_fn_target_feature_wasm.rs index deed09e4b2a..8ddfe61943c 100644 --- a/tests/ui/consts/const-eval/const_fn_target_feature_wasm.rs +++ b/tests/ui/consts/const-eval/const_fn_target_feature_wasm.rs @@ -7,7 +7,9 @@ #[cfg(target_feature = "simd128")] compile_error!("simd128 target feature should be disabled"); -// Calling functions with `#[target_feature]` is not unsound on WASM, see #84988 +// Calling functions with `#[target_feature]` is not unsound on WASM, see #84988. +// (It can still lead to a runtime error though so we'd be in our right to abort execution, +// just not to declare it UB.) const A: () = simd128_fn(); #[target_feature(enable = "simd128")] diff --git a/tests/ui/consts/precise-drop-allow-const-fn-unstable.not_allow.stderr b/tests/ui/consts/precise-drop-allow-const-fn-unstable.not_allow.stderr new file mode 100644 index 00000000000..6038c6d332f --- /dev/null +++ b/tests/ui/consts/precise-drop-allow-const-fn-unstable.not_allow.stderr @@ -0,0 +1,12 @@ +error[E0493]: destructor of `Option<T>` cannot be evaluated at compile-time + --> $DIR/precise-drop-allow-const-fn-unstable.rs:11:24 + | +LL | pub const fn unwrap<T>(this: Option<T>) -> T { + | ^^^^ the destructor for this type cannot be evaluated in constant functions +... +LL | } + | - value is dropped here + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0493`. diff --git a/tests/ui/consts/precise-drop-allow-const-fn-unstable.rs b/tests/ui/consts/precise-drop-allow-const-fn-unstable.rs new file mode 100644 index 00000000000..56155e519dc --- /dev/null +++ b/tests/ui/consts/precise-drop-allow-const-fn-unstable.rs @@ -0,0 +1,17 @@ +//@ revisions: allow not_allow +//@ compile-flags: --crate-type=lib -Cinstrument-coverage -Zno-profiler-runtime +//@[allow] check-pass + +#![feature(staged_api, rustc_allow_const_fn_unstable)] +#![stable(feature = "rust_test", since = "1.0.0")] + +#[stable(feature = "rust_test", since = "1.0.0")] +#[rustc_const_stable(feature = "rust_test", since = "1.0.0")] +#[cfg_attr(allow, rustc_allow_const_fn_unstable(const_precise_live_drops))] +pub const fn unwrap<T>(this: Option<T>) -> T { +//[not_allow]~^ ERROR: cannot be evaluated + match this { + Some(x) => x, + None => panic!(), + } +} diff --git a/tests/ui/deriving/deriving-smart-pointer-expanded.rs b/tests/ui/deriving/deriving-smart-pointer-expanded.rs index b78258c2529..e48ad3dd4bc 100644 --- a/tests/ui/deriving/deriving-smart-pointer-expanded.rs +++ b/tests/ui/deriving/deriving-smart-pointer-expanded.rs @@ -20,3 +20,9 @@ where data: &'a mut T, x: core::marker::PhantomData<X>, } + +#[derive(SmartPointer)] +#[repr(transparent)] +struct MyPointerWithoutPointee<'a, T: ?Sized> { + ptr: &'a T, +} diff --git a/tests/ui/deriving/deriving-smart-pointer-expanded.stdout b/tests/ui/deriving/deriving-smart-pointer-expanded.stdout index 3c7e7198180..68ef17f2b05 100644 --- a/tests/ui/deriving/deriving-smart-pointer-expanded.stdout +++ b/tests/ui/deriving/deriving-smart-pointer-expanded.stdout @@ -42,3 +42,18 @@ impl<'a, Y, Z: MyTrait<T> + MyTrait<__S>, T: ?Sized + MyTrait<T> + MyTrait<__S>> ::core::ops::CoerceUnsized<MyPointer2<'a, Y, Z, __S, X>> for MyPointer2<'a, Y, Z, T, X> where Y: MyTrait<T>, Y: MyTrait<__S> { } + +#[repr(transparent)] +struct MyPointerWithoutPointee<'a, T: ?Sized> { + ptr: &'a T, +} +#[automatically_derived] +impl<'a, T: ?Sized + ::core::marker::Unsize<__S>, __S: ?Sized> + ::core::ops::DispatchFromDyn<MyPointerWithoutPointee<'a, __S>> for + MyPointerWithoutPointee<'a, T> { +} +#[automatically_derived] +impl<'a, T: ?Sized + ::core::marker::Unsize<__S>, __S: ?Sized> + ::core::ops::CoerceUnsized<MyPointerWithoutPointee<'a, __S>> for + MyPointerWithoutPointee<'a, T> { +} diff --git a/tests/ui/deriving/deriving-smart-pointer-neg.rs b/tests/ui/deriving/deriving-smart-pointer-neg.rs index 04f52a154fe..f02fb56130f 100644 --- a/tests/ui/deriving/deriving-smart-pointer-neg.rs +++ b/tests/ui/deriving/deriving-smart-pointer-neg.rs @@ -10,13 +10,6 @@ enum NotStruct<'a, T: ?Sized> { } #[derive(SmartPointer)] -//~^ ERROR: At least one generic type should be designated as `#[pointee]` in order to derive `SmartPointer` traits -#[repr(transparent)] -struct NoPointee<'a, T: ?Sized> { - ptr: &'a T, -} - -#[derive(SmartPointer)] //~^ ERROR: `SmartPointer` can only be derived on `struct`s with at least one field #[repr(transparent)] struct NoField<'a, #[pointee] T: ?Sized> {} @@ -31,6 +24,23 @@ struct NoFieldUnit<'a, #[pointee] T: ?Sized>(); //~| ERROR: type parameter `T` is never used #[derive(SmartPointer)] +//~^ ERROR: `SmartPointer` can only be derived on `struct`s that are generic over at least one type +#[repr(transparent)] +struct NoGeneric<'a>(&'a u8); + +#[derive(SmartPointer)] +//~^ ERROR: exactly one generic type parameter must be marked as #[pointee] to derive SmartPointer traits +#[repr(transparent)] +struct AmbiguousPointee<'a, T1: ?Sized, T2: ?Sized> { + a: (&'a T1, &'a T2), +} + +#[derive(SmartPointer)] +#[repr(transparent)] +struct TooManyPointees<'a, #[pointee] A: ?Sized, #[pointee] B: ?Sized>((&'a A, &'a B)); +//~^ ERROR: only one type parameter can be marked as `#[pointee]` when deriving SmartPointer traits + +#[derive(SmartPointer)] //~^ ERROR: `SmartPointer` can only be derived on `struct`s with `#[repr(transparent)]` struct NotTransparent<'a, #[pointee] T: ?Sized> { ptr: &'a T, diff --git a/tests/ui/deriving/deriving-smart-pointer-neg.stderr b/tests/ui/deriving/deriving-smart-pointer-neg.stderr index 8b0f91d41fb..e7c2afc8b00 100644 --- a/tests/ui/deriving/deriving-smart-pointer-neg.stderr +++ b/tests/ui/deriving/deriving-smart-pointer-neg.stderr @@ -6,7 +6,7 @@ LL | #[derive(SmartPointer)] | = note: this error originates in the derive macro `SmartPointer` (in Nightly builds, run with -Z macro-backtrace for more info) -error: At least one generic type should be designated as `#[pointee]` in order to derive `SmartPointer` traits +error: `SmartPointer` can only be derived on `struct`s with at least one field --> $DIR/deriving-smart-pointer-neg.rs:12:10 | LL | #[derive(SmartPointer)] @@ -22,7 +22,7 @@ LL | #[derive(SmartPointer)] | = note: this error originates in the derive macro `SmartPointer` (in Nightly builds, run with -Z macro-backtrace for more info) -error: `SmartPointer` can only be derived on `struct`s with at least one field +error: `SmartPointer` can only be derived on `struct`s that are generic over at least one type --> $DIR/deriving-smart-pointer-neg.rs:26:10 | LL | #[derive(SmartPointer)] @@ -30,8 +30,22 @@ LL | #[derive(SmartPointer)] | = note: this error originates in the derive macro `SmartPointer` (in Nightly builds, run with -Z macro-backtrace for more info) +error: exactly one generic type parameter must be marked as #[pointee] to derive SmartPointer traits + --> $DIR/deriving-smart-pointer-neg.rs:31:10 + | +LL | #[derive(SmartPointer)] + | ^^^^^^^^^^^^ + | + = note: this error originates in the derive macro `SmartPointer` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: only one type parameter can be marked as `#[pointee]` when deriving SmartPointer traits + --> $DIR/deriving-smart-pointer-neg.rs:40:39 + | +LL | struct TooManyPointees<'a, #[pointee] A: ?Sized, #[pointee] B: ?Sized>((&'a A, &'a B)); + | ^ ^ + error: `SmartPointer` can only be derived on `struct`s with `#[repr(transparent)]` - --> $DIR/deriving-smart-pointer-neg.rs:33:10 + --> $DIR/deriving-smart-pointer-neg.rs:43:10 | LL | #[derive(SmartPointer)] | ^^^^^^^^^^^^ @@ -39,13 +53,13 @@ LL | #[derive(SmartPointer)] = note: this error originates in the derive macro `SmartPointer` (in Nightly builds, run with -Z macro-backtrace for more info) error: `derive(SmartPointer)` requires T to be marked `?Sized` - --> $DIR/deriving-smart-pointer-neg.rs:41:36 + --> $DIR/deriving-smart-pointer-neg.rs:51:36 | LL | struct NoMaybeSized<'a, #[pointee] T> { | ^ error[E0392]: lifetime parameter `'a` is never used - --> $DIR/deriving-smart-pointer-neg.rs:22:16 + --> $DIR/deriving-smart-pointer-neg.rs:15:16 | LL | struct NoField<'a, #[pointee] T: ?Sized> {} | ^^ unused lifetime parameter @@ -53,7 +67,7 @@ LL | struct NoField<'a, #[pointee] T: ?Sized> {} = help: consider removing `'a`, referring to it in a field, or using a marker such as `PhantomData` error[E0392]: type parameter `T` is never used - --> $DIR/deriving-smart-pointer-neg.rs:22:31 + --> $DIR/deriving-smart-pointer-neg.rs:15:31 | LL | struct NoField<'a, #[pointee] T: ?Sized> {} | ^ unused type parameter @@ -61,7 +75,7 @@ LL | struct NoField<'a, #[pointee] T: ?Sized> {} = help: consider removing `T`, referring to it in a field, or using a marker such as `PhantomData` error[E0392]: lifetime parameter `'a` is never used - --> $DIR/deriving-smart-pointer-neg.rs:29:20 + --> $DIR/deriving-smart-pointer-neg.rs:22:20 | LL | struct NoFieldUnit<'a, #[pointee] T: ?Sized>(); | ^^ unused lifetime parameter @@ -69,13 +83,13 @@ LL | struct NoFieldUnit<'a, #[pointee] T: ?Sized>(); = help: consider removing `'a`, referring to it in a field, or using a marker such as `PhantomData` error[E0392]: type parameter `T` is never used - --> $DIR/deriving-smart-pointer-neg.rs:29:35 + --> $DIR/deriving-smart-pointer-neg.rs:22:35 | LL | struct NoFieldUnit<'a, #[pointee] T: ?Sized>(); | ^ unused type parameter | = help: consider removing `T`, referring to it in a field, or using a marker such as `PhantomData` -error: aborting due to 10 previous errors +error: aborting due to 12 previous errors For more information about this error, try `rustc --explain E0392`. diff --git a/tests/ui/feature-gates/feature-gate-fmt-debug.rs b/tests/ui/feature-gates/feature-gate-fmt-debug.rs new file mode 100644 index 00000000000..f30befbd19c --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-fmt-debug.rs @@ -0,0 +1,5 @@ +#[cfg(fmt_debug = "full")] +//~^ ERROR is experimental +fn main() { + +} diff --git a/tests/ui/feature-gates/feature-gate-fmt-debug.stderr b/tests/ui/feature-gates/feature-gate-fmt-debug.stderr new file mode 100644 index 00000000000..9ced0b8facf --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-fmt-debug.stderr @@ -0,0 +1,13 @@ +error[E0658]: `cfg(fmt_debug)` is experimental and subject to change + --> $DIR/feature-gate-fmt-debug.rs:1:7 + | +LL | #[cfg(fmt_debug = "full")] + | ^^^^^^^^^^^^^^^^^^ + | + = note: see issue #129709 <https://github.com/rust-lang/rust/issues/129709> for more information + = help: add `#![feature(fmt_debug)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/feature-gates/feature-gate-struct-target-features.rs b/tests/ui/feature-gates/feature-gate-struct-target-features.rs new file mode 100644 index 00000000000..85494881146 --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-struct-target-features.rs @@ -0,0 +1,4 @@ +#[target_feature(enable = "avx")] //~ ERROR attribute should be applied to a function definition +struct Avx {} + +fn main() {} diff --git a/tests/ui/feature-gates/feature-gate-struct-target-features.stderr b/tests/ui/feature-gates/feature-gate-struct-target-features.stderr new file mode 100644 index 00000000000..1e18d3ee1e1 --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-struct-target-features.stderr @@ -0,0 +1,10 @@ +error: attribute should be applied to a function definition + --> $DIR/feature-gate-struct-target-features.rs:1:1 + | +LL | #[target_feature(enable = "avx")] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | struct Avx {} + | ------------- not a function definition + +error: aborting due to 1 previous error + diff --git a/tests/ui/fmt/fmt_debug/full.rs b/tests/ui/fmt/fmt_debug/full.rs new file mode 100644 index 00000000000..4e9384d2c52 --- /dev/null +++ b/tests/ui/fmt/fmt_debug/full.rs @@ -0,0 +1,15 @@ +//@ compile-flags: -Zfmt-debug=full +//@ run-pass +#![feature(fmt_debug)] +#![allow(dead_code)] +#![allow(unused)] + +#[derive(Debug)] +struct Foo { + bar: u32, +} + +fn main() { + let s = format!("Still works: {:?} '{:?}'", cfg!(fmt_debug = "full"), Foo { bar: 1 }); + assert_eq!("Still works: true 'Foo { bar: 1 }'", s); +} diff --git a/tests/ui/fmt/fmt_debug/invalid.rs b/tests/ui/fmt/fmt_debug/invalid.rs new file mode 100644 index 00000000000..09cb46f1ea6 --- /dev/null +++ b/tests/ui/fmt/fmt_debug/invalid.rs @@ -0,0 +1,4 @@ +//@ compile-flags: -Zfmt-debug=invalid-value +//@ failure-status: 1 +fn main() { +} diff --git a/tests/ui/fmt/fmt_debug/invalid.stderr b/tests/ui/fmt/fmt_debug/invalid.stderr new file mode 100644 index 00000000000..fa6c9380744 --- /dev/null +++ b/tests/ui/fmt/fmt_debug/invalid.stderr @@ -0,0 +1,2 @@ +error: incorrect value `invalid-value` for unstable option `fmt-debug` - either `full`, `shallow`, or `none` was expected + diff --git a/tests/ui/fmt/fmt_debug/none.rs b/tests/ui/fmt/fmt_debug/none.rs new file mode 100644 index 00000000000..f45d37d9da2 --- /dev/null +++ b/tests/ui/fmt/fmt_debug/none.rs @@ -0,0 +1,37 @@ +//@ compile-flags: -Zfmt-debug=none +//@ run-pass +#![feature(fmt_debug)] +#![allow(dead_code)] +#![allow(unused)] + +#[derive(Debug)] +struct Foo { + bar: u32, +} + +#[derive(Debug)] +enum Baz { + Quz, +} + +#[cfg(fmt_debug = "full")] +compile_error!("nope"); + +#[cfg(fmt_debug = "none")] +struct Custom; + +impl std::fmt::Debug for Custom { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("custom_fmt") + } +} + +fn main() { + let c = Custom; + let s = format!("Debug is '{:?}', '{:#?}', and '{c:?}'", Foo { bar: 1 }, Baz::Quz); + assert_eq!("Debug is '', '', and ''", s); + + let f = 3.0; + let s = format_args!("{:?}x{:#?}y{f:?}", 1234, "can't debug this").to_string(); + assert_eq!("xy", s); +} diff --git a/tests/ui/fmt/fmt_debug/shallow.rs b/tests/ui/fmt/fmt_debug/shallow.rs new file mode 100644 index 00000000000..479cd1b8875 --- /dev/null +++ b/tests/ui/fmt/fmt_debug/shallow.rs @@ -0,0 +1,33 @@ +//@ compile-flags: -Zfmt-debug=shallow +//@ run-pass +#![feature(fmt_debug)] +#![allow(dead_code)] +#![allow(unused)] + +#[derive(Debug)] +struct Foo { + bar: u32, + bomb: Bomb, +} + +#[derive(Debug)] +enum Baz { + Quz, +} + +struct Bomb; + +impl std::fmt::Debug for Bomb { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + panic!() + } +} + +fn main() { + let s = format!("Debug is '{:?}' and '{:#?}'", Foo { bar: 1, bomb: Bomb }, Baz::Quz); + assert_eq!("Debug is 'Foo' and 'Quz'", s); + + let f = 3.0; + let s = format_args!("{:?}{:#?}{f:?}", 1234, cfg!(fmt_debug = "shallow")).to_string(); + assert_eq!("1234true3.0", s); +} diff --git a/tests/ui/inference/detect-old-time-version-format_description-parse.rs b/tests/ui/inference/detect-old-time-version-format_description-parse.rs new file mode 100644 index 00000000000..453a795e768 --- /dev/null +++ b/tests/ui/inference/detect-old-time-version-format_description-parse.rs @@ -0,0 +1,8 @@ +#![crate_name = "time"] + +fn main() { + let items = Box::new(vec![]); //~ ERROR E0282 + //~^ NOTE type must be known at this point + //~| NOTE this is an inference error on crate `time` caused by an API change in Rust 1.80.0; update `time` to version `>=0.3.35` + items.into(); +} diff --git a/tests/ui/inference/detect-old-time-version-format_description-parse.stderr b/tests/ui/inference/detect-old-time-version-format_description-parse.stderr new file mode 100644 index 00000000000..2949a5dcfec --- /dev/null +++ b/tests/ui/inference/detect-old-time-version-format_description-parse.stderr @@ -0,0 +1,11 @@ +error[E0282]: type annotations needed for `Box<Vec<_>>` + --> $DIR/detect-old-time-version-format_description-parse.rs:4:9 + | +LL | let items = Box::new(vec![]); + | ^^^^^ ---------------- type must be known at this point + | + = note: this is an inference error on crate `time` caused by an API change in Rust 1.80.0; update `time` to version `>=0.3.35` by calling `cargo update` + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0282`. diff --git a/tests/ui/intrinsics/intrinsic-raw_eq-const-bad.rs b/tests/ui/intrinsics/intrinsic-raw_eq-const-bad.rs index ab46fd796c5..99f98c3f27a 100644 --- a/tests/ui/intrinsics/intrinsic-raw_eq-const-bad.rs +++ b/tests/ui/intrinsics/intrinsic-raw_eq-const-bad.rs @@ -13,5 +13,13 @@ const RAW_EQ_PTR: bool = unsafe { //~| unable to turn pointer into integer }; +const RAW_EQ_NOT_ALIGNED: bool = unsafe { + let arr = [0u8; 4]; + let aref = &*arr.as_ptr().cast::<i32>(); + std::intrinsics::raw_eq(aref, aref) +//~^ ERROR evaluation of constant value failed +//~| alignment +}; + pub fn main() { } diff --git a/tests/ui/intrinsics/intrinsic-raw_eq-const-bad.stderr b/tests/ui/intrinsics/intrinsic-raw_eq-const-bad.stderr index af16c2bc64a..bedfc8283ea 100644 --- a/tests/ui/intrinsics/intrinsic-raw_eq-const-bad.stderr +++ b/tests/ui/intrinsics/intrinsic-raw_eq-const-bad.stderr @@ -13,6 +13,12 @@ LL | std::intrinsics::raw_eq(&(&0), &(&1)) = help: this code performed an operation that depends on the underlying bytes representing a pointer = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported -error: aborting due to 2 previous errors +error[E0080]: evaluation of constant value failed + --> $DIR/intrinsic-raw_eq-const-bad.rs:19:5 + | +LL | std::intrinsics::raw_eq(aref, aref) + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ accessing memory with alignment 1, but alignment 4 is required + +error: aborting due to 3 previous errors For more information about this error, try `rustc --explain E0080`. diff --git a/tests/ui/lint/unused/lint-unused-variables.stderr b/tests/ui/lint/unused/lint-unused-variables.stderr index 09729eeba79..ef590d85aef 100644 --- a/tests/ui/lint/unused/lint-unused-variables.stderr +++ b/tests/ui/lint/unused/lint-unused-variables.stderr @@ -16,6 +16,12 @@ error: unused variable: `a` LL | a: i32, | ^ help: if this is intentional, prefix it with an underscore: `_a` +error: unused variable: `a` + --> $DIR/lint-unused-variables.rs:68:9 + | +LL | a: i32, + | ^ help: if this is intentional, prefix it with an underscore: `_a` + error: unused variable: `b` --> $DIR/lint-unused-variables.rs:14:5 | @@ -58,12 +64,6 @@ error: unused variable: `b` LL | b: i32, | ^ help: if this is intentional, prefix it with an underscore: `_b` -error: unused variable: `a` - --> $DIR/lint-unused-variables.rs:68:9 - | -LL | a: i32, - | ^ help: if this is intentional, prefix it with an underscore: `_a` - error: unused variable: `b` --> $DIR/lint-unused-variables.rs:74:9 | diff --git a/tests/ui/rfcs/rfc-2565-param-attrs/param-attrs-cfg.stderr b/tests/ui/rfcs/rfc-2565-param-attrs/param-attrs-cfg.stderr index 16e1af46059..9b92166bcb7 100644 --- a/tests/ui/rfcs/rfc-2565-param-attrs/param-attrs-cfg.stderr +++ b/tests/ui/rfcs/rfc-2565-param-attrs/param-attrs-cfg.stderr @@ -16,6 +16,12 @@ error: unused variable: `a` LL | #[cfg(something)] a: i32, | ^ help: if this is intentional, prefix it with an underscore: `_a` +error: unused variable: `a` + --> $DIR/param-attrs-cfg.rs:107:27 + | +LL | #[cfg(something)] a: i32, + | ^ help: if this is intentional, prefix it with an underscore: `_a` + error: unused variable: `b` --> $DIR/param-attrs-cfg.rs:30:23 | @@ -100,12 +106,6 @@ error: unused variable: `c` LL | #[cfg_attr(nothing, cfg(nothing))] c: i32, | ^ help: if this is intentional, prefix it with an underscore: `_c` -error: unused variable: `a` - --> $DIR/param-attrs-cfg.rs:107:27 - | -LL | #[cfg(something)] a: i32, - | ^ help: if this is intentional, prefix it with an underscore: `_a` - error: unused variable: `b` --> $DIR/param-attrs-cfg.rs:113:27 | diff --git a/tests/ui/target-feature/gate.rs b/tests/ui/target-feature/gate.rs index 94d79d56c59..5c4fb847932 100644 --- a/tests/ui/target-feature/gate.rs +++ b/tests/ui/target-feature/gate.rs @@ -17,6 +17,7 @@ // gate-test-ermsb_target_feature // gate-test-bpf_target_feature // gate-test-aarch64_ver_target_feature +// gate-test-aarch64_unstable_target_feature // gate-test-csky_target_feature // gate-test-loongarch_target_feature // gate-test-lahfsahf_target_feature diff --git a/tests/ui/target-feature/gate.stderr b/tests/ui/target-feature/gate.stderr index a69020e6864..37c5ed01688 100644 --- a/tests/ui/target-feature/gate.stderr +++ b/tests/ui/target-feature/gate.stderr @@ -1,5 +1,5 @@ error[E0658]: the target feature `avx512bw` is currently unstable - --> $DIR/gate.rs:26:18 + --> $DIR/gate.rs:27:18 | LL | #[target_feature(enable = "avx512bw")] | ^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/target-feature/struct-target-features.rs b/tests/ui/target-feature/struct-target-features.rs new file mode 100644 index 00000000000..feb479b6dc8 --- /dev/null +++ b/tests/ui/target-feature/struct-target-features.rs @@ -0,0 +1,98 @@ +//@ only-x86_64 +#![feature(struct_target_features)] +//~^ WARNING the feature `struct_target_features` is incomplete and may not be safe to use and/or cause compiler crashes +#![feature(target_feature_11)] + +use std::arch::x86_64::*; + +#[target_feature(enable = "avx")] +//~^ ERROR attribute should be applied to a function definition or unit struct +struct Invalid(u32); + +#[target_feature(enable = "avx")] +struct Avx {} + +#[target_feature(enable = "sse")] +struct Sse(); + +#[target_feature(enable = "avx")] +fn avx() {} + +trait TFAssociatedType { + type Assoc; +} + +impl TFAssociatedType for () { + type Assoc = Avx; +} + +fn avx_self(_: <() as TFAssociatedType>::Assoc) { + avx(); +} + +fn avx_avx(_: Avx) { + avx(); +} + +extern "C" fn bad_fun(_: Avx) {} +//~^ ERROR cannot use a struct with target features in a function with non-Rust ABI + +#[inline(always)] +//~^ ERROR cannot use `#[inline(always)]` with `#[target_feature]` +fn inline_fun(_: Avx) {} +//~^ ERROR cannot use a struct with target features in a #[inline(always)] function + +trait Simd { + fn do_something(&self); +} + +impl Simd for Avx { + fn do_something(&self) { + unsafe { + println!("{:?}", _mm256_setzero_ps()); + } + } +} + +impl Simd for Sse { + fn do_something(&self) { + unsafe { + println!("{:?}", _mm_setzero_ps()); + } + } +} + +struct WithAvx { + #[allow(dead_code)] + avx: Avx, +} + +impl Simd for WithAvx { + fn do_something(&self) { + unsafe { + println!("{:?}", _mm256_setzero_ps()); + } + } +} + +#[inline(never)] +fn dosomething<S: Simd>(simd: &S) { + simd.do_something(); +} + +fn avxfn(_: &Avx) {} + +fn main() { + Avx {}; + //~^ ERROR initializing type with `target_feature` attr is unsafe and requires unsafe function or block [E0133] + + if is_x86_feature_detected!("avx") { + let avx = unsafe { Avx {} }; + avxfn(&avx); + dosomething(&avx); + dosomething(&WithAvx { avx }); + } + if is_x86_feature_detected!("sse") { + dosomething(&unsafe { Sse {} }) + } +} diff --git a/tests/ui/target-feature/struct-target-features.stderr b/tests/ui/target-feature/struct-target-features.stderr new file mode 100644 index 00000000000..5ef863f504e --- /dev/null +++ b/tests/ui/target-feature/struct-target-features.stderr @@ -0,0 +1,47 @@ +warning: the feature `struct_target_features` is incomplete and may not be safe to use and/or cause compiler crashes + --> $DIR/struct-target-features.rs:2:12 + | +LL | #![feature(struct_target_features)] + | ^^^^^^^^^^^^^^^^^^^^^^ + | + = note: see issue #129107 <https://github.com/rust-lang/rust/issues/129107> for more information + = note: `#[warn(incomplete_features)]` on by default + +error: attribute should be applied to a function definition or unit struct + --> $DIR/struct-target-features.rs:8:1 + | +LL | #[target_feature(enable = "avx")] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | +LL | struct Invalid(u32); + | -------------------- not a function definition or a unit struct + +error: cannot use a struct with target features in a function with non-Rust ABI + --> $DIR/struct-target-features.rs:37:1 + | +LL | extern "C" fn bad_fun(_: Avx) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: cannot use a struct with target features in a #[inline(always)] function + --> $DIR/struct-target-features.rs:42:1 + | +LL | fn inline_fun(_: Avx) {} + | ^^^^^^^^^^^^^^^^^^^^^ + +error: cannot use `#[inline(always)]` with `#[target_feature]` + --> $DIR/struct-target-features.rs:40:1 + | +LL | #[inline(always)] + | ^^^^^^^^^^^^^^^^^ + +error[E0133]: initializing type with `target_feature` attr is unsafe and requires unsafe function or block + --> $DIR/struct-target-features.rs:86:5 + | +LL | Avx {}; + | ^^^^^^ initializing type with `target_feature` attr + | + = note: this struct can only be constructed if the corresponding `target_feature`s are available + +error: aborting due to 5 previous errors; 1 warning emitted + +For more information about this error, try `rustc --explain E0133`. diff --git a/tests/ui/threads-sendsync/child-outlives-parent.rs b/tests/ui/threads-sendsync/child-outlives-parent.rs index 213fd008cd3..e965bac5713 100644 --- a/tests/ui/threads-sendsync/child-outlives-parent.rs +++ b/tests/ui/threads-sendsync/child-outlives-parent.rs @@ -6,8 +6,8 @@ use std::thread; -fn child2(_s: String) { } +fn child2(_s: String) {} pub fn main() { - let _x = thread::spawn(move|| child2("hi".to_string())); + let _x = thread::spawn(move || child2("hi".to_string())); } diff --git a/tests/ui/threads-sendsync/clone-with-exterior.rs b/tests/ui/threads-sendsync/clone-with-exterior.rs index 67790367e27..9d5ac4b16aa 100644 --- a/tests/ui/threads-sendsync/clone-with-exterior.rs +++ b/tests/ui/threads-sendsync/clone-with-exterior.rs @@ -7,14 +7,15 @@ use std::thread; struct Pair { a: isize, - b: isize + b: isize, } pub fn main() { - let z: Box<_> = Box::new(Pair { a : 10, b : 12}); + let z: Box<_> = Box::new(Pair { a: 10, b: 12 }); - thread::spawn(move|| { + thread::spawn(move || { assert_eq!(z.a, 10); assert_eq!(z.b, 12); - }).join(); + }) + .join(); } diff --git a/tests/ui/threads-sendsync/comm.rs b/tests/ui/threads-sendsync/comm.rs index 0c37fda8a39..3eb68707e78 100644 --- a/tests/ui/threads-sendsync/comm.rs +++ b/tests/ui/threads-sendsync/comm.rs @@ -2,12 +2,12 @@ #![allow(unused_must_use)] //@ needs-threads -use std::thread; use std::sync::mpsc::{channel, Sender}; +use std::thread; pub fn main() { let (tx, rx) = channel(); - let t = thread::spawn(move || { child(&tx) }); + let t = thread::spawn(move || child(&tx)); let y = rx.recv().unwrap(); println!("received"); println!("{}", y); diff --git a/tests/ui/threads-sendsync/issue-24313.rs b/tests/ui/threads-sendsync/issue-24313.rs index 1ea862f1e7d..99c6c4a5e12 100644 --- a/tests/ui/threads-sendsync/issue-24313.rs +++ b/tests/ui/threads-sendsync/issue-24313.rs @@ -2,14 +2,15 @@ //@ needs-threads //@ ignore-sgx no processes -use std::thread; -use std::env; use std::process::Command; +use std::{env, thread}; struct Handle(i32); impl Drop for Handle { - fn drop(&mut self) { panic!(); } + fn drop(&mut self) { + panic!(); + } } thread_local!(static HANDLE: Handle = Handle(0)); @@ -19,14 +20,15 @@ fn main() { if args.len() == 1 { let out = Command::new(&args[0]).arg("test").output().unwrap(); let stderr = std::str::from_utf8(&out.stderr).unwrap(); - assert!(stderr.contains("explicit panic"), - "bad failure message:\n{}\n", stderr); + assert!(stderr.contains("explicit panic"), "bad failure message:\n{}\n", stderr); } else { // TLS dtors are not always run on process exit thread::spawn(|| { HANDLE.with(|h| { println!("{}", h.0); }); - }).join().unwrap(); + }) + .join() + .unwrap(); } } diff --git a/tests/ui/threads-sendsync/issue-29488.rs b/tests/ui/threads-sendsync/issue-29488.rs index fbbd6b02a06..5ce27faed76 100644 --- a/tests/ui/threads-sendsync/issue-29488.rs +++ b/tests/ui/threads-sendsync/issue-29488.rs @@ -19,5 +19,7 @@ fn main() { thread::spawn(|| { FOO.with(|_| {}); println!("test1"); - }).join().unwrap(); + }) + .join() + .unwrap(); } diff --git a/tests/ui/threads-sendsync/issue-4446.rs b/tests/ui/threads-sendsync/issue-4446.rs index aa2de51974b..5652ad7de55 100644 --- a/tests/ui/threads-sendsync/issue-4446.rs +++ b/tests/ui/threads-sendsync/issue-4446.rs @@ -9,7 +9,10 @@ pub fn main() { tx.send("hello, world").unwrap(); - thread::spawn(move|| { + thread::spawn(move || { println!("{}", rx.recv().unwrap()); - }).join().ok().unwrap(); + }) + .join() + .ok() + .unwrap(); } diff --git a/tests/ui/threads-sendsync/issue-4448.rs b/tests/ui/threads-sendsync/issue-4448.rs index b8324a8c43f..1adebd1e252 100644 --- a/tests/ui/threads-sendsync/issue-4448.rs +++ b/tests/ui/threads-sendsync/issue-4448.rs @@ -7,7 +7,7 @@ use std::thread; pub fn main() { let (tx, rx) = channel::<&'static str>(); - let t = thread::spawn(move|| { + let t = thread::spawn(move || { assert_eq!(rx.recv().unwrap(), "hello, world"); }); diff --git a/tests/ui/threads-sendsync/issue-8827.rs b/tests/ui/threads-sendsync/issue-8827.rs index fa07a4ebc7d..57fc87db768 100644 --- a/tests/ui/threads-sendsync/issue-8827.rs +++ b/tests/ui/threads-sendsync/issue-8827.rs @@ -1,12 +1,12 @@ //@ run-pass //@ needs-threads -use std::thread; use std::sync::mpsc::{channel, Receiver}; +use std::thread; fn periodical(n: isize) -> Receiver<bool> { let (chan, port) = channel(); - thread::spawn(move|| { + thread::spawn(move || { loop { for _ in 1..n { match chan.send(false) { @@ -16,7 +16,7 @@ fn periodical(n: isize) -> Receiver<bool> { } match chan.send(true) { Ok(()) => {} - Err(..) => break + Err(..) => break, } } }); @@ -25,7 +25,7 @@ fn periodical(n: isize) -> Receiver<bool> { fn integers() -> Receiver<isize> { let (chan, port) = channel(); - thread::spawn(move|| { + thread::spawn(move || { let mut i = 1; loop { match chan.send(i) { @@ -47,7 +47,7 @@ fn main() { (_, true, true) => println!("FizzBuzz"), (_, true, false) => println!("Fizz"), (_, false, true) => println!("Buzz"), - (i, false, false) => println!("{}", i) + (i, false, false) => println!("{}", i), } } } diff --git a/tests/ui/threads-sendsync/issue-9396.rs b/tests/ui/threads-sendsync/issue-9396.rs index 6b5907e5c1d..b532ddf104d 100644 --- a/tests/ui/threads-sendsync/issue-9396.rs +++ b/tests/ui/threads-sendsync/issue-9396.rs @@ -3,12 +3,12 @@ #![allow(deprecated)] //@ needs-threads -use std::sync::mpsc::{TryRecvError, channel}; +use std::sync::mpsc::{channel, TryRecvError}; use std::thread; pub fn main() { let (tx, rx) = channel(); - let t = thread::spawn(move||{ + let t = thread::spawn(move || { thread::sleep_ms(10); tx.send(()).unwrap(); }); @@ -16,7 +16,7 @@ pub fn main() { match rx.try_recv() { Ok(()) => break, Err(TryRecvError::Empty) => {} - Err(TryRecvError::Disconnected) => unreachable!() + Err(TryRecvError::Disconnected) => unreachable!(), } } t.join(); diff --git a/tests/ui/threads-sendsync/mpsc_stress.rs b/tests/ui/threads-sendsync/mpsc_stress.rs index f5354c60bfc..fe0b47f3a84 100644 --- a/tests/ui/threads-sendsync/mpsc_stress.rs +++ b/tests/ui/threads-sendsync/mpsc_stress.rs @@ -2,18 +2,12 @@ //@ compile-flags:--test //@ needs-threads -use std::sync::mpsc::channel; -use std::sync::mpsc::TryRecvError; -use std::sync::mpsc::RecvError; -use std::sync::mpsc::RecvTimeoutError; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::mpsc::{channel, RecvError, RecvTimeoutError, TryRecvError}; use std::sync::Arc; -use std::sync::atomic::AtomicUsize; -use std::sync::atomic::Ordering; - use std::thread; use std::time::Duration; - /// Simple thread synchronization utility struct Barrier { // Not using mutex/condvar for precision @@ -42,7 +36,6 @@ impl Barrier { } } - fn shared_close_sender_does_not_lose_messages_iter() { let (tb, rb) = Barrier::new2(); @@ -71,7 +64,6 @@ fn shared_close_sender_does_not_lose_messages() { }); } - // https://github.com/rust-lang/rust/issues/39364 fn concurrent_recv_timeout_and_upgrade_iter() { // 1 us @@ -85,8 +77,8 @@ fn concurrent_recv_timeout_and_upgrade_iter() { match rx.recv_timeout(sleep) { Ok(_) => { break; - }, - Err(_) => {}, + } + Err(_) => {} } } }); @@ -105,7 +97,6 @@ fn concurrent_recv_timeout_and_upgrade() { }); } - fn concurrent_writes_iter() { const THREADS: usize = 4; const PER_THR: usize = 100; diff --git a/tests/ui/threads-sendsync/send-is-not-static-par-for.rs b/tests/ui/threads-sendsync/send-is-not-static-par-for.rs index b943b0c433d..dd02166c0fa 100644 --- a/tests/ui/threads-sendsync/send-is-not-static-par-for.rs +++ b/tests/ui/threads-sendsync/send-is-not-static-par-for.rs @@ -1,12 +1,13 @@ //@ run-pass #![allow(unused_imports)] -use std::thread; use std::sync::Mutex; +use std::thread; fn par_for<I, F>(iter: I, f: F) - where I: Iterator, - I::Item: Send, - F: Fn(I::Item) + Sync +where + I: Iterator, + I::Item: Send, + F: Fn(I::Item) + Sync, { for item in iter { f(item) @@ -15,9 +16,7 @@ fn par_for<I, F>(iter: I, f: F) fn sum(x: &[i32]) { let sum_lengths = Mutex::new(0); - par_for(x.windows(4), |x| { - *sum_lengths.lock().unwrap() += x.len() - }); + par_for(x.windows(4), |x| *sum_lengths.lock().unwrap() += x.len()); assert_eq!(*sum_lengths.lock().unwrap(), (x.len() - 3) * 4); } @@ -26,9 +25,7 @@ fn main() { let mut elements = [0; 20]; // iterators over references into this stack frame - par_for(elements.iter_mut().enumerate(), |(i, x)| { - *x = i as i32 - }); + par_for(elements.iter_mut().enumerate(), |(i, x)| *x = i as i32); sum(&elements) } diff --git a/tests/ui/threads-sendsync/send-resource.rs b/tests/ui/threads-sendsync/send-resource.rs index 3e1532b3132..c02a3717d3d 100644 --- a/tests/ui/threads-sendsync/send-resource.rs +++ b/tests/ui/threads-sendsync/send-resource.rs @@ -6,11 +6,11 @@ //@ pretty-expanded FIXME #23616 //@ needs-threads -use std::thread; use std::sync::mpsc::channel; +use std::thread; struct test { - f: isize, + f: isize, } impl Drop for test { @@ -18,15 +18,13 @@ impl Drop for test { } fn test(f: isize) -> test { - test { - f: f - } + test { f: f } } pub fn main() { let (tx, rx) = channel(); - let t = thread::spawn(move|| { + let t = thread::spawn(move || { let (tx2, rx2) = channel(); tx.send(tx2).unwrap(); diff --git a/tests/ui/threads-sendsync/send-type-inference.rs b/tests/ui/threads-sendsync/send-type-inference.rs index 287b3d567ae..7608c19b575 100644 --- a/tests/ui/threads-sendsync/send-type-inference.rs +++ b/tests/ui/threads-sendsync/send-type-inference.rs @@ -9,11 +9,11 @@ use std::sync::mpsc::{channel, Sender}; // tests that ctrl's type gets inferred properly struct Command<K, V> { key: K, - val: V + val: V, } -fn cache_server<K:Send+'static,V:Send+'static>(mut tx: Sender<Sender<Command<K, V>>>) { +fn cache_server<K: Send + 'static, V: Send + 'static>(mut tx: Sender<Sender<Command<K, V>>>) { let (tx1, _rx) = channel(); tx.send(tx1); } -pub fn main() { } +pub fn main() {} diff --git a/tests/ui/threads-sendsync/send_str_hashmap.rs b/tests/ui/threads-sendsync/send_str_hashmap.rs index 9cbb0bed447..2675b162190 100644 --- a/tests/ui/threads-sendsync/send_str_hashmap.rs +++ b/tests/ui/threads-sendsync/send_str_hashmap.rs @@ -1,9 +1,7 @@ //@ run-pass -use std::collections::HashMap; use std::borrow::Cow; - -use std::borrow::Cow::Borrowed as B; -use std::borrow::Cow::Owned as O; +use std::borrow::Cow::{Borrowed as B, Owned as O}; +use std::collections::HashMap; type SendStr = Cow<'static, str>; diff --git a/tests/ui/threads-sendsync/send_str_treemap.rs b/tests/ui/threads-sendsync/send_str_treemap.rs index cc1f560f69b..3e0eace3399 100644 --- a/tests/ui/threads-sendsync/send_str_treemap.rs +++ b/tests/ui/threads-sendsync/send_str_treemap.rs @@ -1,8 +1,7 @@ //@ run-pass -use std::collections::BTreeMap; use std::borrow::Cow; - -use std::borrow::Cow::{Owned as O, Borrowed as B}; +use std::borrow::Cow::{Borrowed as B, Owned as O}; +use std::collections::BTreeMap; type SendStr = Cow<'static, str>; @@ -51,8 +50,8 @@ fn main() { assert_eq!(map.get(&O("def".to_string())), Some(&d)); assert!(map.remove(&B("foo")).is_some()); - assert_eq!(map.into_iter().map(|(k, v)| format!("{}{}", k, v)) - .collect::<Vec<String>>() - .concat(), - "abc50bcd51cde52def53".to_string()); + assert_eq!( + map.into_iter().map(|(k, v)| format!("{}{}", k, v)).collect::<Vec<String>>().concat(), + "abc50bcd51cde52def53".to_string() + ); } diff --git a/tests/ui/threads-sendsync/sendable-class.rs b/tests/ui/threads-sendsync/sendable-class.rs index 3ee1b60a04a..8e5e76d826a 100644 --- a/tests/ui/threads-sendsync/sendable-class.rs +++ b/tests/ui/threads-sendsync/sendable-class.rs @@ -11,15 +11,12 @@ use std::sync::mpsc::channel; struct foo { - i: isize, - j: char, + i: isize, + j: char, } -fn foo(i:isize, j: char) -> foo { - foo { - i: i, - j: j - } +fn foo(i: isize, j: char) -> foo { + foo { i: i, j: j } } pub fn main() { diff --git a/tests/ui/threads-sendsync/sendfn-is-a-block.rs b/tests/ui/threads-sendsync/sendfn-is-a-block.rs index f01b440424a..9afa1c47b65 100644 --- a/tests/ui/threads-sendsync/sendfn-is-a-block.rs +++ b/tests/ui/threads-sendsync/sendfn-is-a-block.rs @@ -1,7 +1,9 @@ //@ run-pass - -fn test<F>(f: F) -> usize where F: FnOnce(usize) -> usize { +fn test<F>(f: F) -> usize +where + F: FnOnce(usize) -> usize, +{ return f(22); } diff --git a/tests/ui/threads-sendsync/sendfn-spawn-with-fn-arg.rs b/tests/ui/threads-sendsync/sendfn-spawn-with-fn-arg.rs index 63cf3ff4049..79a71e968f9 100644 --- a/tests/ui/threads-sendsync/sendfn-spawn-with-fn-arg.rs +++ b/tests/ui/threads-sendsync/sendfn-spawn-with-fn-arg.rs @@ -3,19 +3,24 @@ use std::thread; -pub fn main() { test05(); } +pub fn main() { + test05(); +} -fn test05_start<F:FnOnce(isize)>(f: F) { +fn test05_start<F: FnOnce(isize)>(f: F) { f(22); } fn test05() { let three: Box<_> = Box::new(3); - let fn_to_send = move|n:isize| { + let fn_to_send = move |n: isize| { println!("{}", *three + n); // will copy x into the closure assert_eq!(*three, 3); }; - thread::spawn(move|| { + thread::spawn(move || { test05_start(fn_to_send); - }).join().ok().unwrap(); + }) + .join() + .ok() + .unwrap(); } diff --git a/tests/ui/threads-sendsync/spawn-fn.rs b/tests/ui/threads-sendsync/spawn-fn.rs index e4d83b53f3c..558c2d515aa 100644 --- a/tests/ui/threads-sendsync/spawn-fn.rs +++ b/tests/ui/threads-sendsync/spawn-fn.rs @@ -10,9 +10,9 @@ fn x(s: String, n: isize) { } pub fn main() { - let t1 = thread::spawn(|| x("hello from first spawned fn".to_string(), 65) ); - let t2 = thread::spawn(|| x("hello from second spawned fn".to_string(), 66) ); - let t3 = thread::spawn(|| x("hello from third spawned fn".to_string(), 67) ); + let t1 = thread::spawn(|| x("hello from first spawned fn".to_string(), 65)); + let t2 = thread::spawn(|| x("hello from second spawned fn".to_string(), 66)); + let t3 = thread::spawn(|| x("hello from third spawned fn".to_string(), 67)); let mut i = 30; while i > 0 { i = i - 1; diff --git a/tests/ui/threads-sendsync/spawn-types.rs b/tests/ui/threads-sendsync/spawn-types.rs index 2a7a9e2f497..e53385aa714 100644 --- a/tests/ui/threads-sendsync/spawn-types.rs +++ b/tests/ui/threads-sendsync/spawn-types.rs @@ -4,13 +4,13 @@ //@ needs-threads /* - Make sure we can spawn tasks that take different types of - parameters. This is based on a test case for #520 provided by Rob - Arnold. - */ + Make sure we can spawn tasks that take different types of + parameters. This is based on a test case for #520 provided by Rob + Arnold. +*/ -use std::thread; use std::sync::mpsc::{channel, Sender}; +use std::thread; type ctx = Sender<isize>; @@ -20,6 +20,6 @@ fn iotask(_tx: &ctx, ip: String) { pub fn main() { let (tx, _rx) = channel::<isize>(); - let t = thread::spawn(move|| iotask(&tx, "localhost".to_string()) ); + let t = thread::spawn(move || iotask(&tx, "localhost".to_string())); t.join().ok().unwrap(); } diff --git a/tests/ui/threads-sendsync/spawn.rs b/tests/ui/threads-sendsync/spawn.rs index c7b344b9f75..c9f7c40ddb8 100644 --- a/tests/ui/threads-sendsync/spawn.rs +++ b/tests/ui/threads-sendsync/spawn.rs @@ -4,7 +4,10 @@ use std::thread; pub fn main() { - thread::spawn(move|| child(10)).join().ok().unwrap(); + thread::spawn(move || child(10)).join().ok().unwrap(); } -fn child(i: isize) { println!("{}", i); assert_eq!(i, 10); } +fn child(i: isize) { + println!("{}", i); + assert_eq!(i, 10); +} diff --git a/tests/ui/threads-sendsync/spawn2.rs b/tests/ui/threads-sendsync/spawn2.rs index 8278fec1885..02dff2a3483 100644 --- a/tests/ui/threads-sendsync/spawn2.rs +++ b/tests/ui/threads-sendsync/spawn2.rs @@ -4,7 +4,7 @@ use std::thread; pub fn main() { - let t = thread::spawn(move|| child((10, 20, 30, 40, 50, 60, 70, 80, 90)) ); + let t = thread::spawn(move || child((10, 20, 30, 40, 50, 60, 70, 80, 90))); t.join().ok().unwrap(); // forget Err value, since it doesn't implement Debug } diff --git a/tests/ui/threads-sendsync/sync-send-in-std.rs b/tests/ui/threads-sendsync/sync-send-in-std.rs index 3a97cbb0c68..ddf026236a8 100644 --- a/tests/ui/threads-sendsync/sync-send-in-std.rs +++ b/tests/ui/threads-sendsync/sync-send-in-std.rs @@ -6,8 +6,16 @@ use std::net::ToSocketAddrs; -fn is_sync<T>(_: T) where T: Sync {} -fn is_send<T>(_: T) where T: Send {} +fn is_sync<T>(_: T) +where + T: Sync, +{ +} +fn is_send<T>(_: T) +where + T: Send, +{ +} macro_rules! all_sync_send { ($ctor:expr, $($iter:ident),+) => ({ diff --git a/tests/ui/threads-sendsync/sync-send-iterators-in-libcollections.rs b/tests/ui/threads-sendsync/sync-send-iterators-in-libcollections.rs index 3b8fdb60acf..51d5e294b38 100644 --- a/tests/ui/threads-sendsync/sync-send-iterators-in-libcollections.rs +++ b/tests/ui/threads-sendsync/sync-send-iterators-in-libcollections.rs @@ -3,18 +3,20 @@ #![allow(warnings)] #![feature(drain, collections_bound, btree_range)] -use std::collections::BinaryHeap; -use std::collections::{BTreeMap, BTreeSet}; -use std::collections::LinkedList; -use std::collections::VecDeque; -use std::collections::HashMap; -use std::collections::HashSet; - +use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, LinkedList, VecDeque}; use std::mem; use std::ops::Bound::Included; -fn is_sync<T>(_: T) where T: Sync {} -fn is_send<T>(_: T) where T: Send {} +fn is_sync<T>(_: T) +where + T: Sync, +{ +} +fn is_send<T>(_: T) +where + T: Send, +{ +} macro_rules! all_sync_send { ($ctor:expr, $($iter:ident),+) => ({ diff --git a/tests/ui/threads-sendsync/sync-send-iterators-in-libcore.rs b/tests/ui/threads-sendsync/sync-send-iterators-in-libcore.rs index 4c77b5d2ad8..512c81a85fc 100644 --- a/tests/ui/threads-sendsync/sync-send-iterators-in-libcore.rs +++ b/tests/ui/threads-sendsync/sync-send-iterators-in-libcore.rs @@ -5,8 +5,16 @@ use std::iter::{empty, once, repeat}; -fn is_sync<T>(_: T) where T: Sync {} -fn is_send<T>(_: T) where T: Send {} +fn is_sync<T>(_: T) +where + T: Sync, +{ +} +fn is_send<T>(_: T) +where + T: Send, +{ +} macro_rules! all_sync_send { ($ctor:expr, $iter:ident) => ({ @@ -43,12 +51,12 @@ macro_rules! all_sync_send_mutable_ref { } macro_rules! is_sync_send { - ($ctor:expr) => ({ + ($ctor:expr) => {{ let x = $ctor; is_sync(x); let y = $ctor; is_send(y); - }) + }}; } fn main() { @@ -63,24 +71,26 @@ fn main() { let a = [1]; let b = [2]; - all_sync_send!(a.iter(), - cloned, - cycle, - chain([2].iter()), - zip([2].iter()), - map(|_| 1), - filter(|_| true), - filter_map(|_| Some(1)), - enumerate, - peekable, - skip_while(|_| true), - take_while(|_| true), - skip(1), - take(1), - scan(1, |_, _| Some(1)), - flat_map(|_| b.iter()), - fuse, - inspect(|_| ())); + all_sync_send!( + a.iter(), + cloned, + cycle, + chain([2].iter()), + zip([2].iter()), + map(|_| 1), + filter(|_| true), + filter_map(|_| Some(1)), + enumerate, + peekable, + skip_while(|_| true), + take_while(|_| true), + skip(1), + take(1), + scan(1, |_, _| Some(1)), + flat_map(|_| b.iter()), + fuse, + inspect(|_| ()) + ); is_sync_send!((1..).step_by(2)); is_sync_send!((1..2).step_by(2)); diff --git a/tests/ui/threads-sendsync/task-comm-0.rs b/tests/ui/threads-sendsync/task-comm-0.rs index 50f2b591894..c4fe36e770d 100644 --- a/tests/ui/threads-sendsync/task-comm-0.rs +++ b/tests/ui/threads-sendsync/task-comm-0.rs @@ -2,12 +2,14 @@ #![allow(unused_must_use)] //@ needs-threads -use std::thread; use std::sync::mpsc::{channel, Sender}; +use std::thread; -pub fn main() { test05(); } +pub fn main() { + test05(); +} -fn test05_start(tx : &Sender<isize>) { +fn test05_start(tx: &Sender<isize>) { tx.send(10).unwrap(); println!("sent 10"); tx.send(20).unwrap(); @@ -18,7 +20,7 @@ fn test05_start(tx : &Sender<isize>) { fn test05() { let (tx, rx) = channel(); - let t = thread::spawn(move|| { test05_start(&tx) }); + let t = thread::spawn(move || test05_start(&tx)); let mut value: isize = rx.recv().unwrap(); println!("{}", value); value = rx.recv().unwrap(); diff --git a/tests/ui/threads-sendsync/task-comm-1.rs b/tests/ui/threads-sendsync/task-comm-1.rs index 41592bd916b..75d9e887cd1 100644 --- a/tests/ui/threads-sendsync/task-comm-1.rs +++ b/tests/ui/threads-sendsync/task-comm-1.rs @@ -4,11 +4,15 @@ use std::thread; -pub fn main() { test00(); } +pub fn main() { + test00(); +} -fn start() { println!("Started / Finished task."); } +fn start() { + println!("Started / Finished task."); +} fn test00() { - thread::spawn(move|| start() ).join(); + thread::spawn(move || start()).join(); println!("Completing."); } diff --git a/tests/ui/threads-sendsync/task-comm-10.rs b/tests/ui/threads-sendsync/task-comm-10.rs index 844652c0dde..44c31aeed77 100644 --- a/tests/ui/threads-sendsync/task-comm-10.rs +++ b/tests/ui/threads-sendsync/task-comm-10.rs @@ -3,8 +3,8 @@ #![allow(unused_mut)] //@ needs-threads -use std::thread; use std::sync::mpsc::{channel, Sender}; +use std::thread; fn start(tx: &Sender<Sender<String>>) { let (tx2, rx) = channel(); @@ -22,7 +22,7 @@ fn start(tx: &Sender<Sender<String>>) { pub fn main() { let (tx, rx) = channel(); - let child = thread::spawn(move|| { start(&tx) }); + let child = thread::spawn(move || start(&tx)); let mut c = rx.recv().unwrap(); c.send("A".to_string()).unwrap(); diff --git a/tests/ui/threads-sendsync/task-comm-11.rs b/tests/ui/threads-sendsync/task-comm-11.rs index 199082fda96..7c349c716fa 100644 --- a/tests/ui/threads-sendsync/task-comm-11.rs +++ b/tests/ui/threads-sendsync/task-comm-11.rs @@ -13,9 +13,7 @@ fn start(tx: &Sender<Sender<isize>>) { pub fn main() { let (tx, rx) = channel(); - let child = thread::spawn(move|| { - start(&tx) - }); + let child = thread::spawn(move || start(&tx)); let _tx = rx.recv().unwrap(); child.join(); } diff --git a/tests/ui/threads-sendsync/task-comm-12.rs b/tests/ui/threads-sendsync/task-comm-12.rs index 7be7ec4c988..95c5d5c45ef 100644 --- a/tests/ui/threads-sendsync/task-comm-12.rs +++ b/tests/ui/threads-sendsync/task-comm-12.rs @@ -5,15 +5,17 @@ use std::thread; -pub fn main() { test00(); } +pub fn main() { + test00(); +} -fn start(_task_number: isize) { println!("Started / Finished task."); } +fn start(_task_number: isize) { + println!("Started / Finished task."); +} fn test00() { let i: isize = 0; - let mut result = thread::spawn(move|| { - start(i) - }); + let mut result = thread::spawn(move || start(i)); // Sleep long enough for the thread to finish. let mut i = 0_usize; diff --git a/tests/ui/threads-sendsync/task-comm-13.rs b/tests/ui/threads-sendsync/task-comm-13.rs index 414e6e0db76..88ea3cbff08 100644 --- a/tests/ui/threads-sendsync/task-comm-13.rs +++ b/tests/ui/threads-sendsync/task-comm-13.rs @@ -7,12 +7,15 @@ use std::thread; fn start(tx: &Sender<isize>, start: isize, number_of_messages: isize) { let mut i: isize = 0; - while i< number_of_messages { tx.send(start + i).unwrap(); i += 1; } + while i < number_of_messages { + tx.send(start + i).unwrap(); + i += 1; + } } pub fn main() { println!("Check that we don't deadlock."); let (tx, rx) = channel(); - let _ = thread::spawn(move|| { start(&tx, 0, 10) }).join(); + let _ = thread::spawn(move || start(&tx, 0, 10)).join(); println!("Joined task"); } diff --git a/tests/ui/threads-sendsync/task-comm-14.rs b/tests/ui/threads-sendsync/task-comm-14.rs index 54deb221294..ff4ffd2968d 100644 --- a/tests/ui/threads-sendsync/task-comm-14.rs +++ b/tests/ui/threads-sendsync/task-comm-14.rs @@ -13,7 +13,10 @@ pub fn main() { while (i > 0) { println!("{}", i); let tx = tx.clone(); - thread::spawn({let i = i; move|| { child(i, &tx) }}); + thread::spawn({ + let i = i; + move || child(i, &tx) + }); i = i - 1; } diff --git a/tests/ui/threads-sendsync/task-comm-15.rs b/tests/ui/threads-sendsync/task-comm-15.rs index f487bf3cc84..1308446893b 100644 --- a/tests/ui/threads-sendsync/task-comm-15.rs +++ b/tests/ui/threads-sendsync/task-comm-15.rs @@ -20,9 +20,7 @@ pub fn main() { // the child's point of view the receiver may die. We should // drop messages on the floor in this case, and not crash! let (tx, rx) = channel(); - let t = thread::spawn(move|| { - start(&tx, 10) - }); + let t = thread::spawn(move || start(&tx, 10)); rx.recv(); t.join(); } diff --git a/tests/ui/threads-sendsync/task-comm-16.rs b/tests/ui/threads-sendsync/task-comm-16.rs index 3b0fec11acd..e76f7bedc93 100644 --- a/tests/ui/threads-sendsync/task-comm-16.rs +++ b/tests/ui/threads-sendsync/task-comm-16.rs @@ -3,15 +3,19 @@ #![allow(unused_parens)] #![allow(non_camel_case_types)] -use std::sync::mpsc::channel; use std::cmp; +use std::sync::mpsc::channel; // Tests of ports and channels on various types fn test_rec() { - struct R {val0: isize, val1: u8, val2: char} + struct R { + val0: isize, + val1: u8, + val2: char, + } let (tx, rx) = channel(); - let r0: R = R {val0: 0, val1: 1, val2: '2'}; + let r0: R = R { val0: 0, val1: 1, val2: '2' }; tx.send(r0).unwrap(); let mut r1: R; r1 = rx.recv().unwrap(); @@ -45,34 +49,29 @@ fn test_str() { enum t { tag1, tag2(isize), - tag3(isize, u8, char) + tag3(isize, u8, char), } impl cmp::PartialEq for t { fn eq(&self, other: &t) -> bool { match *self { - t::tag1 => { - match (*other) { - t::tag1 => true, - _ => false - } - } - t::tag2(e0a) => { - match (*other) { - t::tag2(e0b) => e0a == e0b, - _ => false - } - } - t::tag3(e0a, e1a, e2a) => { - match (*other) { - t::tag3(e0b, e1b, e2b) => - e0a == e0b && e1a == e1b && e2a == e2b, - _ => false - } - } + t::tag1 => match (*other) { + t::tag1 => true, + _ => false, + }, + t::tag2(e0a) => match (*other) { + t::tag2(e0b) => e0a == e0b, + _ => false, + }, + t::tag3(e0a, e1a, e2a) => match (*other) { + t::tag3(e0b, e1b, e2b) => e0a == e0b && e1a == e1b && e2a == e2b, + _ => false, + }, } } - fn ne(&self, other: &t) -> bool { !(*self).eq(other) } + fn ne(&self, other: &t) -> bool { + !(*self).eq(other) + } } fn test_tag() { diff --git a/tests/ui/threads-sendsync/task-comm-17.rs b/tests/ui/threads-sendsync/task-comm-17.rs index 687322d4dc9..a545beee599 100644 --- a/tests/ui/threads-sendsync/task-comm-17.rs +++ b/tests/ui/threads-sendsync/task-comm-17.rs @@ -9,9 +9,8 @@ use std::thread; -fn f() { -} +fn f() {} pub fn main() { - thread::spawn(move|| f() ).join(); + thread::spawn(move || f()).join(); } diff --git a/tests/ui/threads-sendsync/task-comm-3.rs b/tests/ui/threads-sendsync/task-comm-3.rs index 26f3eaf9dc6..565d97596c7 100644 --- a/tests/ui/threads-sendsync/task-comm-3.rs +++ b/tests/ui/threads-sendsync/task-comm-3.rs @@ -2,10 +2,13 @@ #![allow(unused_must_use)] //@ needs-threads -use std::thread; use std::sync::mpsc::{channel, Sender}; +use std::thread; -pub fn main() { println!("===== WITHOUT THREADS ====="); test00(); } +pub fn main() { + println!("===== WITHOUT THREADS ====="); + test00(); +} fn test00_start(ch: &Sender<isize>, message: isize, count: isize) { println!("Starting test00_start"); @@ -34,9 +37,7 @@ fn test00() { let tx = tx.clone(); results.push(thread::spawn({ let i = i; - move|| { - test00_start(&tx, i, number_of_messages) - } + move || test00_start(&tx, i, number_of_messages) })); i = i + 1; } @@ -53,7 +54,9 @@ fn test00() { } // Join spawned threads... - for r in results { r.join(); } + for r in results { + r.join(); + } println!("Completed: Final number is: "); println!("{}", sum); diff --git a/tests/ui/threads-sendsync/task-comm-4.rs b/tests/ui/threads-sendsync/task-comm-4.rs index 1210cee5582..6223f6a1ded 100644 --- a/tests/ui/threads-sendsync/task-comm-4.rs +++ b/tests/ui/threads-sendsync/task-comm-4.rs @@ -3,7 +3,9 @@ use std::sync::mpsc::channel; -pub fn main() { test00(); } +pub fn main() { + test00(); +} fn test00() { let mut r: isize = 0; diff --git a/tests/ui/threads-sendsync/task-comm-5.rs b/tests/ui/threads-sendsync/task-comm-5.rs index e07aa18c24d..e008b28f56c 100644 --- a/tests/ui/threads-sendsync/task-comm-5.rs +++ b/tests/ui/threads-sendsync/task-comm-5.rs @@ -2,7 +2,9 @@ use std::sync::mpsc::channel; -pub fn main() { test00(); } +pub fn main() { + test00(); +} fn test00() { let _r: isize = 0; @@ -10,8 +12,14 @@ fn test00() { let (tx, rx) = channel(); let number_of_messages: isize = 1000; let mut i: isize = 0; - while i < number_of_messages { tx.send(i + 0).unwrap(); i += 1; } + while i < number_of_messages { + tx.send(i + 0).unwrap(); + i += 1; + } i = 0; - while i < number_of_messages { sum += rx.recv().unwrap(); i += 1; } + while i < number_of_messages { + sum += rx.recv().unwrap(); + i += 1; + } assert_eq!(sum, number_of_messages * (number_of_messages - 1) / 2); } diff --git a/tests/ui/threads-sendsync/task-comm-6.rs b/tests/ui/threads-sendsync/task-comm-6.rs index 6a7dea63993..60697c908af 100644 --- a/tests/ui/threads-sendsync/task-comm-6.rs +++ b/tests/ui/threads-sendsync/task-comm-6.rs @@ -4,7 +4,9 @@ use std::sync::mpsc::channel; -pub fn main() { test00(); } +pub fn main() { + test00(); +} fn test00() { let mut r: isize = 0; @@ -38,5 +40,4 @@ fn test00() { assert_eq!(sum, 1998000); // assert (sum == 4 * ((number_of_messages * // (number_of_messages - 1)) / 2)); - } diff --git a/tests/ui/threads-sendsync/task-comm-7.rs b/tests/ui/threads-sendsync/task-comm-7.rs index d9b322daa66..bb59e4b4a72 100644 --- a/tests/ui/threads-sendsync/task-comm-7.rs +++ b/tests/ui/threads-sendsync/task-comm-7.rs @@ -6,12 +6,16 @@ use std::sync::mpsc::{channel, Sender}; use std::thread; -pub fn main() { test00(); } +pub fn main() { + test00(); +} -fn test00_start(c: &Sender<isize>, start: isize, - number_of_messages: isize) { +fn test00_start(c: &Sender<isize>, start: isize, number_of_messages: isize) { let mut i: isize = 0; - while i < number_of_messages { c.send(start + i).unwrap(); i += 1; } + while i < number_of_messages { + c.send(start + i).unwrap(); + i += 1; + } } fn test00() { @@ -21,19 +25,19 @@ fn test00() { let number_of_messages: isize = 10; let tx2 = tx.clone(); - let t1 = thread::spawn(move|| { + let t1 = thread::spawn(move || { test00_start(&tx2, number_of_messages * 0, number_of_messages); }); let tx2 = tx.clone(); - let t2 = thread::spawn(move|| { + let t2 = thread::spawn(move || { test00_start(&tx2, number_of_messages * 1, number_of_messages); }); let tx2 = tx.clone(); - let t3 = thread::spawn(move|| { + let t3 = thread::spawn(move || { test00_start(&tx2, number_of_messages * 2, number_of_messages); }); let tx2 = tx.clone(); - let t4 = thread::spawn(move|| { + let t4 = thread::spawn(move || { test00_start(&tx2, number_of_messages * 3, number_of_messages); }); diff --git a/tests/ui/threads-sendsync/task-comm-9.rs b/tests/ui/threads-sendsync/task-comm-9.rs index 3e617e4a40c..2e1f3cb673a 100644 --- a/tests/ui/threads-sendsync/task-comm-9.rs +++ b/tests/ui/threads-sendsync/task-comm-9.rs @@ -2,14 +2,19 @@ #![allow(unused_must_use)] //@ needs-threads -use std::thread; use std::sync::mpsc::{channel, Sender}; +use std::thread; -pub fn main() { test00(); } +pub fn main() { + test00(); +} fn test00_start(c: &Sender<isize>, number_of_messages: isize) { let mut i: isize = 0; - while i < number_of_messages { c.send(i + 0).unwrap(); i += 1; } + while i < number_of_messages { + c.send(i + 0).unwrap(); + i += 1; + } } fn test00() { @@ -18,7 +23,7 @@ fn test00() { let (tx, rx) = channel(); let number_of_messages: isize = 10; - let result = thread::spawn(move|| { + let result = thread::spawn(move || { test00_start(&tx, number_of_messages); }); diff --git a/tests/ui/threads-sendsync/task-life-0.rs b/tests/ui/threads-sendsync/task-life-0.rs index d3eca5d371f..f08a281e76c 100644 --- a/tests/ui/threads-sendsync/task-life-0.rs +++ b/tests/ui/threads-sendsync/task-life-0.rs @@ -6,9 +6,7 @@ use std::thread; pub fn main() { - thread::spawn(move|| child("Hello".to_string()) ).join(); + thread::spawn(move || child("Hello".to_string())).join(); } -fn child(_s: String) { - -} +fn child(_s: String) {} diff --git a/tests/ui/threads-sendsync/task-spawn-move-and-copy.rs b/tests/ui/threads-sendsync/task-spawn-move-and-copy.rs index ea1c6a9b108..07d1a3d5c36 100644 --- a/tests/ui/threads-sendsync/task-spawn-move-and-copy.rs +++ b/tests/ui/threads-sendsync/task-spawn-move-and-copy.rs @@ -2,8 +2,8 @@ #![allow(unused_must_use)] //@ needs-threads -use std::thread; use std::sync::mpsc::channel; +use std::thread; pub fn main() { let (tx, rx) = channel::<usize>(); diff --git a/tests/ui/threads-sendsync/task-stderr.rs b/tests/ui/threads-sendsync/task-stderr.rs index cad10c7a792..3934084e02a 100644 --- a/tests/ui/threads-sendsync/task-stderr.rs +++ b/tests/ui/threads-sendsync/task-stderr.rs @@ -4,20 +4,21 @@ #![feature(internal_output_capture)] -use std::io; -use std::str; use std::sync::{Arc, Mutex}; -use std::thread; +use std::{io, str, thread}; fn main() { let data = Arc::new(Mutex::new(Vec::new())); - let res = thread::Builder::new().spawn({ - let data = data.clone(); - move || { - io::set_output_capture(Some(data)); - panic!("Hello, world!") - } - }).unwrap().join(); + let res = thread::Builder::new() + .spawn({ + let data = data.clone(); + move || { + io::set_output_capture(Some(data)); + panic!("Hello, world!") + } + }) + .unwrap() + .join(); assert!(res.is_err()); let output = data.lock().unwrap(); diff --git a/tests/ui/threads-sendsync/tcp-stress.rs b/tests/ui/threads-sendsync/tcp-stress.rs index 429a4657314..b2f76a55fb9 100644 --- a/tests/ui/threads-sendsync/tcp-stress.rs +++ b/tests/ui/threads-sendsync/tcp-stress.rs @@ -8,14 +8,14 @@ use std::io::prelude::*; use std::net::{TcpListener, TcpStream}; use std::process; use std::sync::mpsc::channel; -use std::time::Duration; use std::thread::{self, Builder}; +use std::time::Duration; const TARGET_CNT: usize = 200; fn main() { // This test has a chance to time out, try to not let it time out - thread::spawn(move|| -> () { + thread::spawn(move || -> () { thread::sleep(Duration::from_secs(30)); process::exit(1); }); @@ -38,12 +38,12 @@ fn main() { let mut spawned_cnt = 0; for _ in 0..TARGET_CNT { let tx = tx.clone(); - let res = Builder::new().stack_size(64 * 1024).spawn(move|| { + let res = Builder::new().stack_size(64 * 1024).spawn(move || { match TcpStream::connect(addr) { Ok(mut stream) => { let _ = stream.write(&[1]); let _ = stream.read(&mut [0]); - }, + } Err(..) => {} } tx.send(()).unwrap(); diff --git a/tests/ui/threads-sendsync/threads.rs b/tests/ui/threads-sendsync/threads.rs index f3ed7890364..ad4e4774ea0 100644 --- a/tests/ui/threads-sendsync/threads.rs +++ b/tests/ui/threads-sendsync/threads.rs @@ -7,10 +7,16 @@ use std::thread; pub fn main() { let mut i = 10; while i > 0 { - thread::spawn({let i = i; move|| child(i)}).join(); + thread::spawn({ + let i = i; + move || child(i) + }) + .join(); i = i - 1; } println!("main thread exiting"); } -fn child(x: isize) { println!("{}", x); } +fn child(x: isize) { + println!("{}", x); +} diff --git a/tests/ui/threads-sendsync/tls-dtors-are-run-in-a-static-binary.rs b/tests/ui/threads-sendsync/tls-dtors-are-run-in-a-static-binary.rs index 84176659412..983028681cd 100644 --- a/tests/ui/threads-sendsync/tls-dtors-are-run-in-a-static-binary.rs +++ b/tests/ui/threads-sendsync/tls-dtors-are-run-in-a-static-binary.rs @@ -8,7 +8,9 @@ struct Foo; impl Drop for Foo { fn drop(&mut self) { - unsafe { HIT = true; } + unsafe { + HIT = true; + } } } @@ -17,6 +19,8 @@ thread_local!(static FOO: Foo = Foo); fn main() { std::thread::spawn(|| { FOO.with(|_| {}); - }).join().unwrap(); + }) + .join() + .unwrap(); assert!(unsafe { HIT }); } diff --git a/tests/ui/threads-sendsync/tls-init-on-init.rs b/tests/ui/threads-sendsync/tls-init-on-init.rs index fd764669e7f..1cae19aae86 100644 --- a/tests/ui/threads-sendsync/tls-init-on-init.rs +++ b/tests/ui/threads-sendsync/tls-init-on-init.rs @@ -1,14 +1,14 @@ //@ run-pass #![allow(stable_features)] - //@ needs-threads - #![feature(thread_local_try_with)] -use std::thread; use std::sync::atomic::{AtomicUsize, Ordering}; +use std::thread; -struct Foo { cnt: usize } +struct Foo { + cnt: usize, +} thread_local!(static FOO: Foo = Foo::init()); @@ -40,5 +40,7 @@ impl Drop for Foo { fn main() { thread::spawn(|| { FOO.with(|_| {}); - }).join().unwrap(); + }) + .join() + .unwrap(); } diff --git a/tests/ui/threads-sendsync/tls-try-with.rs b/tests/ui/threads-sendsync/tls-try-with.rs index 72cee219a0a..04071e77daa 100644 --- a/tests/ui/threads-sendsync/tls-try-with.rs +++ b/tests/ui/threads-sendsync/tls-try-with.rs @@ -1,8 +1,6 @@ //@ run-pass #![allow(stable_features)] - //@ needs-threads - #![feature(thread_local_try_with)] use std::thread; @@ -16,15 +14,17 @@ thread_local!(static FOO: Foo = Foo {}); impl Drop for Foo { fn drop(&mut self) { assert!(FOO.try_with(|_| panic!("`try_with` closure run")).is_err()); - unsafe { DROP_RUN = true; } + unsafe { + DROP_RUN = true; + } } } fn main() { thread::spawn(|| { - assert_eq!(FOO.try_with(|_| { - 132 - }).expect("`try_with` failed"), 132); - }).join().unwrap(); + assert_eq!(FOO.try_with(|_| { 132 }).expect("`try_with` failed"), 132); + }) + .join() + .unwrap(); assert!(unsafe { DROP_RUN }); } diff --git a/tests/ui/threads-sendsync/trivial-message.rs b/tests/ui/threads-sendsync/trivial-message.rs index 81657373643..d76ba0009dc 100644 --- a/tests/ui/threads-sendsync/trivial-message.rs +++ b/tests/ui/threads-sendsync/trivial-message.rs @@ -2,9 +2,9 @@ #![allow(unused_must_use)] /* - This is about the simplest program that can successfully send a - message. - */ + This is about the simplest program that can successfully send a + message. +*/ use std::sync::mpsc::channel; diff --git a/tests/ui/threads-sendsync/unwind-resource.rs b/tests/ui/threads-sendsync/unwind-resource.rs index 3b1ab57b46e..ec27a1846fe 100644 --- a/tests/ui/threads-sendsync/unwind-resource.rs +++ b/tests/ui/threads-sendsync/unwind-resource.rs @@ -21,9 +21,7 @@ impl Drop for complainer { fn complainer(tx: Sender<bool>) -> complainer { println!("Hello!"); - complainer { - tx: tx - } + complainer { tx: tx } } fn f(tx: Sender<bool>) { @@ -33,7 +31,7 @@ fn f(tx: Sender<bool>) { pub fn main() { let (tx, rx) = channel(); - let t = thread::spawn(move|| f(tx.clone())); + let t = thread::spawn(move || f(tx.clone())); println!("hiiiiiiiii"); assert!(rx.recv().unwrap()); drop(t.join()); diff --git a/tests/ui/threads-sendsync/yield.rs b/tests/ui/threads-sendsync/yield.rs index 99d14bd92ea..c2b10b901cf 100644 --- a/tests/ui/threads-sendsync/yield.rs +++ b/tests/ui/threads-sendsync/yield.rs @@ -17,5 +17,9 @@ pub fn main() { } fn child() { - println!("4"); thread::yield_now(); println!("5"); thread::yield_now(); println!("6"); + println!("4"); + thread::yield_now(); + println!("5"); + thread::yield_now(); + println!("6"); } diff --git a/tests/ui/threads-sendsync/yield1.rs b/tests/ui/threads-sendsync/yield1.rs index c965d2fc303..441e93ecf90 100644 --- a/tests/ui/threads-sendsync/yield1.rs +++ b/tests/ui/threads-sendsync/yield1.rs @@ -13,4 +13,6 @@ pub fn main() { result.join(); } -fn child() { println!("2"); } +fn child() { + println!("2"); +} diff --git a/tests/ui/threads-sendsync/yield2.rs b/tests/ui/threads-sendsync/yield2.rs index 9502f0d33da..2c24df44af2 100644 --- a/tests/ui/threads-sendsync/yield2.rs +++ b/tests/ui/threads-sendsync/yield2.rs @@ -4,5 +4,9 @@ use std::thread; pub fn main() { let mut i: isize = 0; - while i < 100 { i = i + 1; println!("{}", i); thread::yield_now(); } + while i < 100 { + i = i + 1; + println!("{}", i); + thread::yield_now(); + } } diff --git a/tests/ui/transmutability/abstraction/abstracted_assume.rs b/tests/ui/transmutability/abstraction/abstracted_assume.rs index 897e1b4b50a..7fd91e31a04 100644 --- a/tests/ui/transmutability/abstraction/abstracted_assume.rs +++ b/tests/ui/transmutability/abstraction/abstracted_assume.rs @@ -8,7 +8,7 @@ #![allow(dead_code, incomplete_features, non_camel_case_types)] mod assert { - use std::mem::BikeshedIntrinsicFrom; + use std::mem::TransmuteFrom; pub fn is_transmutable< Src, @@ -16,7 +16,7 @@ mod assert { const ASSUME: std::mem::Assume, >() where - Dst: BikeshedIntrinsicFrom< + Dst: TransmuteFrom< Src, ASSUME, >, diff --git a/tests/ui/transmutability/abstraction/const_generic_fn.rs b/tests/ui/transmutability/abstraction/const_generic_fn.rs index 0a5f0de0214..1ea978ce1ba 100644 --- a/tests/ui/transmutability/abstraction/const_generic_fn.rs +++ b/tests/ui/transmutability/abstraction/const_generic_fn.rs @@ -6,12 +6,12 @@ #![allow(dead_code, incomplete_features, non_camel_case_types)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn array_like<T, E, const N: usize>() where - T: BikeshedIntrinsicFrom<[E; N], { Assume::SAFETY }>, - [E; N]: BikeshedIntrinsicFrom<T, { Assume::SAFETY }> + T: TransmuteFrom<[E; N], { Assume::SAFETY }>, + [E; N]: TransmuteFrom<T, { Assume::SAFETY }> {} } diff --git a/tests/ui/transmutability/alignment/align-fail.rs b/tests/ui/transmutability/alignment/align-fail.rs index d88f1285c11..4c1a69b0128 100644 --- a/tests/ui/transmutability/alignment/align-fail.rs +++ b/tests/ui/transmutability/alignment/align-fail.rs @@ -2,11 +2,11 @@ #![feature(transmutability)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_maybe_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { + Dst: TransmuteFrom<Src, { Assume { alignment: false, lifetimes: true, diff --git a/tests/ui/transmutability/alignment/align-fail.stderr b/tests/ui/transmutability/alignment/align-fail.stderr index f05e55fb024..b9801e511b2 100644 --- a/tests/ui/transmutability/alignment/align-fail.stderr +++ b/tests/ui/transmutability/alignment/align-fail.stderr @@ -10,7 +10,7 @@ note: required by a bound in `is_maybe_transmutable` LL | pub fn is_maybe_transmutable<Src, Dst>() | --------------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume { LL | | alignment: false, diff --git a/tests/ui/transmutability/alignment/align-pass.rs b/tests/ui/transmutability/alignment/align-pass.rs index aecf7b02d62..feecf5edaa1 100644 --- a/tests/ui/transmutability/alignment/align-pass.rs +++ b/tests/ui/transmutability/alignment/align-pass.rs @@ -2,11 +2,11 @@ #![feature(transmutability)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_maybe_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { + Dst: TransmuteFrom<Src, { Assume { alignment: false, lifetimes: false, diff --git a/tests/ui/transmutability/arrays/huge-len.rs b/tests/ui/transmutability/arrays/huge-len.rs index 3fe254ebef4..dec24a559d3 100644 --- a/tests/ui/transmutability/arrays/huge-len.rs +++ b/tests/ui/transmutability/arrays/huge-len.rs @@ -1,11 +1,11 @@ #![crate_type = "lib"] #![feature(transmutability)] mod assert { - use std::mem::BikeshedIntrinsicFrom; + use std::mem::TransmuteFrom; pub fn is_maybe_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src>, + Dst: TransmuteFrom<Src>, { } } diff --git a/tests/ui/transmutability/arrays/huge-len.stderr b/tests/ui/transmutability/arrays/huge-len.stderr index 37160c5c959..1fa16c649d4 100644 --- a/tests/ui/transmutability/arrays/huge-len.stderr +++ b/tests/ui/transmutability/arrays/huge-len.stderr @@ -10,8 +10,8 @@ note: required by a bound in `is_maybe_transmutable` LL | pub fn is_maybe_transmutable<Src, Dst>() | --------------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src>, - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_maybe_transmutable` +LL | Dst: TransmuteFrom<Src>, + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_maybe_transmutable` error[E0277]: `ExplicitlyPadded` cannot be safely transmuted into `()` --> $DIR/huge-len.rs:24:55 @@ -25,8 +25,8 @@ note: required by a bound in `is_maybe_transmutable` LL | pub fn is_maybe_transmutable<Src, Dst>() | --------------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src>, - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_maybe_transmutable` +LL | Dst: TransmuteFrom<Src>, + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_maybe_transmutable` error: aborting due to 2 previous errors diff --git a/tests/ui/transmutability/arrays/issue-103783-array-length.rs b/tests/ui/transmutability/arrays/issue-103783-array-length.rs index 7fcbcc01075..3537a39259c 100644 --- a/tests/ui/transmutability/arrays/issue-103783-array-length.rs +++ b/tests/ui/transmutability/arrays/issue-103783-array-length.rs @@ -3,11 +3,11 @@ #![allow(dead_code)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_maybe_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom< + Dst: TransmuteFrom< Src, { Assume { alignment: true, lifetimes: true, safety: true, validity: true } }, >, diff --git a/tests/ui/transmutability/arrays/should_have_correct_length.rs b/tests/ui/transmutability/arrays/should_have_correct_length.rs index 747897d49d7..00c0c1122ef 100644 --- a/tests/ui/transmutability/arrays/should_have_correct_length.rs +++ b/tests/ui/transmutability/arrays/should_have_correct_length.rs @@ -6,11 +6,11 @@ #![allow(dead_code, incomplete_features, non_camel_case_types)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_maybe_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { Assume::SAFETY.and(Assume::VALIDITY) }> + Dst: TransmuteFrom<Src, { Assume::SAFETY.and(Assume::VALIDITY) }> {} } diff --git a/tests/ui/transmutability/arrays/should_inherit_alignment.rs b/tests/ui/transmutability/arrays/should_inherit_alignment.rs index d95c51e3361..70d2f07c449 100644 --- a/tests/ui/transmutability/arrays/should_inherit_alignment.rs +++ b/tests/ui/transmutability/arrays/should_inherit_alignment.rs @@ -6,11 +6,11 @@ #![allow(dead_code, incomplete_features, non_camel_case_types)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_maybe_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { + Dst: TransmuteFrom<Src, { Assume::ALIGNMENT .and(Assume::LIFETIMES) .and(Assume::SAFETY) diff --git a/tests/ui/transmutability/arrays/should_require_well_defined_layout.rs b/tests/ui/transmutability/arrays/should_require_well_defined_layout.rs index 5345b199f6e..29e8ad136ee 100644 --- a/tests/ui/transmutability/arrays/should_require_well_defined_layout.rs +++ b/tests/ui/transmutability/arrays/should_require_well_defined_layout.rs @@ -5,11 +5,11 @@ #![allow(dead_code, incomplete_features, non_camel_case_types)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_maybe_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { + Dst: TransmuteFrom<Src, { Assume::ALIGNMENT .and(Assume::LIFETIMES) .and(Assume::SAFETY) diff --git a/tests/ui/transmutability/arrays/should_require_well_defined_layout.stderr b/tests/ui/transmutability/arrays/should_require_well_defined_layout.stderr index b4cd70142c4..e9420cd393e 100644 --- a/tests/ui/transmutability/arrays/should_require_well_defined_layout.stderr +++ b/tests/ui/transmutability/arrays/should_require_well_defined_layout.stderr @@ -10,7 +10,7 @@ note: required by a bound in `is_maybe_transmutable` LL | pub fn is_maybe_transmutable<Src, Dst>() | --------------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume::ALIGNMENT LL | | .and(Assume::LIFETIMES) @@ -31,7 +31,7 @@ note: required by a bound in `is_maybe_transmutable` LL | pub fn is_maybe_transmutable<Src, Dst>() | --------------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume::ALIGNMENT LL | | .and(Assume::LIFETIMES) @@ -52,7 +52,7 @@ note: required by a bound in `is_maybe_transmutable` LL | pub fn is_maybe_transmutable<Src, Dst>() | --------------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume::ALIGNMENT LL | | .and(Assume::LIFETIMES) @@ -73,7 +73,7 @@ note: required by a bound in `is_maybe_transmutable` LL | pub fn is_maybe_transmutable<Src, Dst>() | --------------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume::ALIGNMENT LL | | .and(Assume::LIFETIMES) @@ -94,7 +94,7 @@ note: required by a bound in `is_maybe_transmutable` LL | pub fn is_maybe_transmutable<Src, Dst>() | --------------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume::ALIGNMENT LL | | .and(Assume::LIFETIMES) @@ -115,7 +115,7 @@ note: required by a bound in `is_maybe_transmutable` LL | pub fn is_maybe_transmutable<Src, Dst>() | --------------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume::ALIGNMENT LL | | .and(Assume::LIFETIMES) diff --git a/tests/ui/transmutability/enums/niche_optimization.rs b/tests/ui/transmutability/enums/niche_optimization.rs index 23f57ecad75..802d1747568 100644 --- a/tests/ui/transmutability/enums/niche_optimization.rs +++ b/tests/ui/transmutability/enums/niche_optimization.rs @@ -5,11 +5,11 @@ #![allow(dead_code, incomplete_features, non_camel_case_types)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { + Dst: TransmuteFrom<Src, { Assume { alignment: false, lifetimes: false, @@ -21,7 +21,7 @@ mod assert { pub fn is_maybe_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { + Dst: TransmuteFrom<Src, { Assume { alignment: false, lifetimes: false, diff --git a/tests/ui/transmutability/enums/repr/padding_differences.rs b/tests/ui/transmutability/enums/repr/padding_differences.rs index d0e1502b5e2..9d2380c613e 100644 --- a/tests/ui/transmutability/enums/repr/padding_differences.rs +++ b/tests/ui/transmutability/enums/repr/padding_differences.rs @@ -7,11 +7,11 @@ use std::mem::MaybeUninit; mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { + Dst: TransmuteFrom<Src, { Assume { alignment: false, lifetimes: false, @@ -23,7 +23,7 @@ mod assert { pub fn is_maybe_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { + Dst: TransmuteFrom<Src, { Assume { alignment: false, lifetimes: false, diff --git a/tests/ui/transmutability/enums/repr/primitive_reprs_should_have_correct_length.rs b/tests/ui/transmutability/enums/repr/primitive_reprs_should_have_correct_length.rs index d3d463e7929..a8f4cccc73e 100644 --- a/tests/ui/transmutability/enums/repr/primitive_reprs_should_have_correct_length.rs +++ b/tests/ui/transmutability/enums/repr/primitive_reprs_should_have_correct_length.rs @@ -5,11 +5,11 @@ #![allow(dead_code)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { + Dst: TransmuteFrom<Src, { Assume { alignment: true, lifetimes: true, diff --git a/tests/ui/transmutability/enums/repr/primitive_reprs_should_have_correct_length.stderr b/tests/ui/transmutability/enums/repr/primitive_reprs_should_have_correct_length.stderr index 6c88bf4ff96..c975ff276c8 100644 --- a/tests/ui/transmutability/enums/repr/primitive_reprs_should_have_correct_length.stderr +++ b/tests/ui/transmutability/enums/repr/primitive_reprs_should_have_correct_length.stderr @@ -10,7 +10,7 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume { LL | | alignment: true, @@ -32,7 +32,7 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume { LL | | alignment: true, @@ -54,7 +54,7 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume { LL | | alignment: true, @@ -76,7 +76,7 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume { LL | | alignment: true, @@ -98,7 +98,7 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume { LL | | alignment: true, @@ -120,7 +120,7 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume { LL | | alignment: true, @@ -142,7 +142,7 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume { LL | | alignment: true, @@ -164,7 +164,7 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume { LL | | alignment: true, @@ -186,7 +186,7 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume { LL | | alignment: true, @@ -208,7 +208,7 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume { LL | | alignment: true, @@ -230,7 +230,7 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume { LL | | alignment: true, @@ -252,7 +252,7 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume { LL | | alignment: true, @@ -274,7 +274,7 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume { LL | | alignment: true, @@ -296,7 +296,7 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume { LL | | alignment: true, @@ -318,7 +318,7 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume { LL | | alignment: true, @@ -340,7 +340,7 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume { LL | | alignment: true, @@ -362,7 +362,7 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume { LL | | alignment: true, @@ -384,7 +384,7 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume { LL | | alignment: true, @@ -406,7 +406,7 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume { LL | | alignment: true, @@ -428,7 +428,7 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume { LL | | alignment: true, diff --git a/tests/ui/transmutability/enums/repr/should_handle_all.rs b/tests/ui/transmutability/enums/repr/should_handle_all.rs index a8ec86fa40d..dec0126f22d 100644 --- a/tests/ui/transmutability/enums/repr/should_handle_all.rs +++ b/tests/ui/transmutability/enums/repr/should_handle_all.rs @@ -5,11 +5,11 @@ #![allow(dead_code, incomplete_features, non_camel_case_types)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_maybe_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { + Dst: TransmuteFrom<Src, { Assume { alignment: true, lifetimes: true, diff --git a/tests/ui/transmutability/enums/should_order_correctly.rs b/tests/ui/transmutability/enums/should_order_correctly.rs index d51a033f1a6..cea2055e148 100644 --- a/tests/ui/transmutability/enums/should_order_correctly.rs +++ b/tests/ui/transmutability/enums/should_order_correctly.rs @@ -6,11 +6,11 @@ #![allow(dead_code)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { + Dst: TransmuteFrom<Src, { Assume::ALIGNMENT .and(Assume::LIFETIMES) .and(Assume::SAFETY) diff --git a/tests/ui/transmutability/enums/should_pad_variants.rs b/tests/ui/transmutability/enums/should_pad_variants.rs index 81ef9e8a567..82bafe85415 100644 --- a/tests/ui/transmutability/enums/should_pad_variants.rs +++ b/tests/ui/transmutability/enums/should_pad_variants.rs @@ -6,11 +6,11 @@ #![allow(dead_code)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { + Dst: TransmuteFrom<Src, { Assume::ALIGNMENT .and(Assume::LIFETIMES) .and(Assume::SAFETY) diff --git a/tests/ui/transmutability/enums/should_pad_variants.stderr b/tests/ui/transmutability/enums/should_pad_variants.stderr index da4294bdbce..bb26281c2f0 100644 --- a/tests/ui/transmutability/enums/should_pad_variants.stderr +++ b/tests/ui/transmutability/enums/should_pad_variants.stderr @@ -10,7 +10,7 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume::ALIGNMENT LL | | .and(Assume::LIFETIMES) diff --git a/tests/ui/transmutability/enums/should_respect_endianness.rs b/tests/ui/transmutability/enums/should_respect_endianness.rs index 8e52274710a..9cf4de06ad2 100644 --- a/tests/ui/transmutability/enums/should_respect_endianness.rs +++ b/tests/ui/transmutability/enums/should_respect_endianness.rs @@ -6,11 +6,11 @@ #![allow(dead_code)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { + Dst: TransmuteFrom<Src, { Assume::ALIGNMENT .and(Assume::LIFETIMES) .and(Assume::SAFETY) diff --git a/tests/ui/transmutability/enums/should_respect_endianness.stderr b/tests/ui/transmutability/enums/should_respect_endianness.stderr index 9f88bb06813..1b9099b297b 100644 --- a/tests/ui/transmutability/enums/should_respect_endianness.stderr +++ b/tests/ui/transmutability/enums/should_respect_endianness.stderr @@ -10,7 +10,7 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume::ALIGNMENT LL | | .and(Assume::LIFETIMES) diff --git a/tests/ui/transmutability/enums/uninhabited_optimization.rs b/tests/ui/transmutability/enums/uninhabited_optimization.rs index c2d5b67ab2c..5b9de3a3963 100644 --- a/tests/ui/transmutability/enums/uninhabited_optimization.rs +++ b/tests/ui/transmutability/enums/uninhabited_optimization.rs @@ -4,7 +4,7 @@ fn assert_transmutable<T>() where - (): std::mem::BikeshedIntrinsicFrom<T> + (): std::mem::TransmuteFrom<T> {} enum Uninhabited {} diff --git a/tests/ui/transmutability/issue-101739-1.rs b/tests/ui/transmutability/issue-101739-1.rs index 81a9038fdb5..fcc1db073ee 100644 --- a/tests/ui/transmutability/issue-101739-1.rs +++ b/tests/ui/transmutability/issue-101739-1.rs @@ -1,11 +1,11 @@ #![feature(transmutability)] mod assert { - use std::mem::BikeshedIntrinsicFrom; + use std::mem::TransmuteFrom; pub fn is_transmutable<Src, const ASSUME_ALIGNMENT: bool>() where - Dst: BikeshedIntrinsicFrom<Src, ASSUME_ALIGNMENT>, //~ ERROR cannot find type `Dst` in this scope + Dst: TransmuteFrom<Src, ASSUME_ALIGNMENT>, //~ ERROR cannot find type `Dst` in this scope //~| the constant `ASSUME_ALIGNMENT` is not of type `Assume` //~| ERROR: mismatched types { diff --git a/tests/ui/transmutability/issue-101739-1.stderr b/tests/ui/transmutability/issue-101739-1.stderr index 6f79bf7b424..3687631dc51 100644 --- a/tests/ui/transmutability/issue-101739-1.stderr +++ b/tests/ui/transmutability/issue-101739-1.stderr @@ -1,23 +1,23 @@ error[E0412]: cannot find type `Dst` in this scope --> $DIR/issue-101739-1.rs:8:9 | -LL | Dst: BikeshedIntrinsicFrom<Src, ASSUME_ALIGNMENT>, +LL | Dst: TransmuteFrom<Src, ASSUME_ALIGNMENT>, | ^^^ not found in this scope error: the constant `ASSUME_ALIGNMENT` is not of type `Assume` --> $DIR/issue-101739-1.rs:8:14 | -LL | Dst: BikeshedIntrinsicFrom<Src, ASSUME_ALIGNMENT>, - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `Assume`, found `bool` +LL | Dst: TransmuteFrom<Src, ASSUME_ALIGNMENT>, + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `Assume`, found `bool` | -note: required by a const generic parameter in `BikeshedIntrinsicFrom` +note: required by a const generic parameter in `TransmuteFrom` --> $SRC_DIR/core/src/mem/transmutability.rs:LL:COL error[E0308]: mismatched types - --> $DIR/issue-101739-1.rs:8:41 + --> $DIR/issue-101739-1.rs:8:33 | -LL | Dst: BikeshedIntrinsicFrom<Src, ASSUME_ALIGNMENT>, - | ^^^^^^^^^^^^^^^^ expected `Assume`, found `bool` +LL | Dst: TransmuteFrom<Src, ASSUME_ALIGNMENT>, + | ^^^^^^^^^^^^^^^^ expected `Assume`, found `bool` error: aborting due to 3 previous errors diff --git a/tests/ui/transmutability/issue-101739-2.rs b/tests/ui/transmutability/issue-101739-2.rs index 6dfde06d6b3..02aa4669e05 100644 --- a/tests/ui/transmutability/issue-101739-2.rs +++ b/tests/ui/transmutability/issue-101739-2.rs @@ -3,7 +3,7 @@ #![allow(dead_code, incomplete_features, non_camel_case_types)] mod assert { - use std::mem::BikeshedIntrinsicFrom; + use std::mem::TransmuteFrom; pub fn is_transmutable< Src, @@ -14,7 +14,7 @@ mod assert { const ASSUME_VISIBILITY: bool, >() where - Dst: BikeshedIntrinsicFrom< + Dst: TransmuteFrom< //~^ ERROR trait takes at most 2 generic arguments but 5 generic arguments were supplied Src, ASSUME_ALIGNMENT, //~ ERROR: mismatched types diff --git a/tests/ui/transmutability/issue-101739-2.stderr b/tests/ui/transmutability/issue-101739-2.stderr index 11e8fa1d8c5..526fcabe14e 100644 --- a/tests/ui/transmutability/issue-101739-2.stderr +++ b/tests/ui/transmutability/issue-101739-2.stderr @@ -1,8 +1,8 @@ error[E0107]: trait takes at most 2 generic arguments but 5 generic arguments were supplied --> $DIR/issue-101739-2.rs:17:14 | -LL | Dst: BikeshedIntrinsicFrom< - | ^^^^^^^^^^^^^^^^^^^^^ expected at most 2 generic arguments +LL | Dst: TransmuteFrom< + | ^^^^^^^^^^^^^ expected at most 2 generic arguments ... LL | ASSUME_ALIGNMENT, | _________________________________- diff --git a/tests/ui/transmutability/issue-110467.rs b/tests/ui/transmutability/issue-110467.rs index 1f9e521c24b..4acea5f766d 100644 --- a/tests/ui/transmutability/issue-110467.rs +++ b/tests/ui/transmutability/issue-110467.rs @@ -1,11 +1,11 @@ //@ check-pass #![crate_type = "lib"] #![feature(transmutability)] -use std::mem::BikeshedIntrinsicFrom; +use std::mem::TransmuteFrom; pub fn is_maybe_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src>, + Dst: TransmuteFrom<Src>, { } diff --git a/tests/ui/transmutability/issue-110892.rs b/tests/ui/transmutability/issue-110892.rs index 9713684c959..ad1b9e7af10 100644 --- a/tests/ui/transmutability/issue-110892.rs +++ b/tests/ui/transmutability/issue-110892.rs @@ -3,7 +3,7 @@ #![allow(incomplete_features)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_transmutable< Src, @@ -14,7 +14,7 @@ mod assert { const ASSUME_VALIDITY: bool, >() where - Dst: BikeshedIntrinsicFrom< + Dst: TransmuteFrom< Src, { from_options(ASSUME_ALIGNMENT, ASSUME_LIFETIMES, ASSUME_SAFETY, ASSUME_VALIDITY) } >, diff --git a/tests/ui/transmutability/malformed-program-gracefulness/feature-missing.rs b/tests/ui/transmutability/malformed-program-gracefulness/feature-missing.rs index 30c381745d0..07133aa5614 100644 --- a/tests/ui/transmutability/malformed-program-gracefulness/feature-missing.rs +++ b/tests/ui/transmutability/malformed-program-gracefulness/feature-missing.rs @@ -2,7 +2,7 @@ #![crate_type = "lib"] -use std::mem::BikeshedIntrinsicFrom; +use std::mem::TransmuteFrom; //~^ ERROR use of unstable library feature 'transmutability' [E0658] use std::mem::Assume; diff --git a/tests/ui/transmutability/malformed-program-gracefulness/feature-missing.stderr b/tests/ui/transmutability/malformed-program-gracefulness/feature-missing.stderr index 9f221907172..a2096cd53e5 100644 --- a/tests/ui/transmutability/malformed-program-gracefulness/feature-missing.stderr +++ b/tests/ui/transmutability/malformed-program-gracefulness/feature-missing.stderr @@ -1,8 +1,8 @@ error[E0658]: use of unstable library feature 'transmutability' --> $DIR/feature-missing.rs:5:5 | -LL | use std::mem::BikeshedIntrinsicFrom; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | use std::mem::TransmuteFrom; + | ^^^^^^^^^^^^^^^^^^^^^^^ | = note: see issue #99571 <https://github.com/rust-lang/rust/issues/99571> for more information = help: add `#![feature(transmutability)]` to the crate attributes to enable diff --git a/tests/ui/transmutability/malformed-program-gracefulness/unknown_dst.rs b/tests/ui/transmutability/malformed-program-gracefulness/unknown_dst.rs index bcfbc1430a8..b8828c59d35 100644 --- a/tests/ui/transmutability/malformed-program-gracefulness/unknown_dst.rs +++ b/tests/ui/transmutability/malformed-program-gracefulness/unknown_dst.rs @@ -5,11 +5,11 @@ #![allow(dead_code, incomplete_features, non_camel_case_types)] mod assert { - use std::mem::BikeshedIntrinsicFrom; + use std::mem::TransmuteFrom; pub fn is_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src> + Dst: TransmuteFrom<Src> {} } diff --git a/tests/ui/transmutability/malformed-program-gracefulness/unknown_dst_field.rs b/tests/ui/transmutability/malformed-program-gracefulness/unknown_dst_field.rs index 8c18de11196..2285d2f532e 100644 --- a/tests/ui/transmutability/malformed-program-gracefulness/unknown_dst_field.rs +++ b/tests/ui/transmutability/malformed-program-gracefulness/unknown_dst_field.rs @@ -5,11 +5,11 @@ #![allow(incomplete_features)] mod assert { - use std::mem::BikeshedIntrinsicFrom; + use std::mem::TransmuteFrom; pub fn is_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src> + Dst: TransmuteFrom<Src> {} } diff --git a/tests/ui/transmutability/malformed-program-gracefulness/unknown_dst_field.stderr b/tests/ui/transmutability/malformed-program-gracefulness/unknown_dst_field.stderr index df10919f6d3..564aee687a5 100644 --- a/tests/ui/transmutability/malformed-program-gracefulness/unknown_dst_field.stderr +++ b/tests/ui/transmutability/malformed-program-gracefulness/unknown_dst_field.stderr @@ -22,8 +22,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `should_gracefully_handle_unknown_dst_ref_field::Src` cannot be safely transmuted into `should_gracefully_handle_unknown_dst_ref_field::Dst` --> $DIR/unknown_dst_field.rs:25:36 @@ -37,8 +37,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error: aborting due to 4 previous errors diff --git a/tests/ui/transmutability/malformed-program-gracefulness/unknown_src.rs b/tests/ui/transmutability/malformed-program-gracefulness/unknown_src.rs index bd7c3fc7fb5..10ba7a61b87 100644 --- a/tests/ui/transmutability/malformed-program-gracefulness/unknown_src.rs +++ b/tests/ui/transmutability/malformed-program-gracefulness/unknown_src.rs @@ -5,11 +5,11 @@ #![allow(dead_code, incomplete_features, non_camel_case_types)] mod assert { - use std::mem::BikeshedIntrinsicFrom; + use std::mem::TransmuteFrom; pub fn is_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src> + Dst: TransmuteFrom<Src> {} } diff --git a/tests/ui/transmutability/malformed-program-gracefulness/unknown_src_field.rs b/tests/ui/transmutability/malformed-program-gracefulness/unknown_src_field.rs index 1da16e67223..598e04971e2 100644 --- a/tests/ui/transmutability/malformed-program-gracefulness/unknown_src_field.rs +++ b/tests/ui/transmutability/malformed-program-gracefulness/unknown_src_field.rs @@ -5,11 +5,11 @@ #![allow(dead_code, incomplete_features, non_camel_case_types)] mod assert { - use std::mem::BikeshedIntrinsicFrom; + use std::mem::TransmuteFrom; pub fn is_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src> + Dst: TransmuteFrom<Src> {} } diff --git a/tests/ui/transmutability/malformed-program-gracefulness/unknown_src_field.stderr b/tests/ui/transmutability/malformed-program-gracefulness/unknown_src_field.stderr index 6ec66e17061..1156391c301 100644 --- a/tests/ui/transmutability/malformed-program-gracefulness/unknown_src_field.stderr +++ b/tests/ui/transmutability/malformed-program-gracefulness/unknown_src_field.stderr @@ -22,8 +22,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `should_gracefully_handle_unknown_src_ref_field::Src` cannot be safely transmuted into `should_gracefully_handle_unknown_src_ref_field::Dst` --> $DIR/unknown_src_field.rs:25:36 @@ -37,8 +37,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error: aborting due to 4 previous errors diff --git a/tests/ui/transmutability/malformed-program-gracefulness/wrong-type-assume.rs b/tests/ui/transmutability/malformed-program-gracefulness/wrong-type-assume.rs index 608366fa089..df925975bad 100644 --- a/tests/ui/transmutability/malformed-program-gracefulness/wrong-type-assume.rs +++ b/tests/ui/transmutability/malformed-program-gracefulness/wrong-type-assume.rs @@ -8,7 +8,7 @@ #![allow(dead_code, incomplete_features, non_camel_case_types)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_transmutable< Src, @@ -19,7 +19,7 @@ mod assert { const ASSUME_VALIDITY: bool, >() where - Dst: BikeshedIntrinsicFrom< + Dst: TransmuteFrom< Src, { from_options(ASSUME_ALIGNMENT, ASSUME_LIFETIMES, ASSUME_SAFETY, ASSUME_VALIDITY) } >, diff --git a/tests/ui/transmutability/maybeuninit.rs b/tests/ui/transmutability/maybeuninit.rs index 77c3381c774..7b60785b7e0 100644 --- a/tests/ui/transmutability/maybeuninit.rs +++ b/tests/ui/transmutability/maybeuninit.rs @@ -5,11 +5,11 @@ use std::mem::MaybeUninit; mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_maybe_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { Assume::SAFETY }> + Dst: TransmuteFrom<Src, { Assume::SAFETY }> {} } diff --git a/tests/ui/transmutability/maybeuninit.stderr b/tests/ui/transmutability/maybeuninit.stderr index be7dcaf35ea..897c2df10a8 100644 --- a/tests/ui/transmutability/maybeuninit.stderr +++ b/tests/ui/transmutability/maybeuninit.stderr @@ -10,8 +10,8 @@ note: required by a bound in `is_maybe_transmutable` LL | pub fn is_maybe_transmutable<Src, Dst>() | --------------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { Assume::SAFETY }> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_maybe_transmutable` +LL | Dst: TransmuteFrom<Src, { Assume::SAFETY }> + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_maybe_transmutable` error: aborting due to 1 previous error diff --git a/tests/ui/transmutability/primitives/bool-mut.rs b/tests/ui/transmutability/primitives/bool-mut.rs index 09b6d582d87..0a7dad37aaf 100644 --- a/tests/ui/transmutability/primitives/bool-mut.rs +++ b/tests/ui/transmutability/primitives/bool-mut.rs @@ -2,11 +2,11 @@ #![feature(transmutability)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { Assume::SAFETY }> + Dst: TransmuteFrom<Src, { Assume::SAFETY }> {} } diff --git a/tests/ui/transmutability/primitives/bool-mut.stderr b/tests/ui/transmutability/primitives/bool-mut.stderr index a6cf146659e..fcf60bc979c 100644 --- a/tests/ui/transmutability/primitives/bool-mut.stderr +++ b/tests/ui/transmutability/primitives/bool-mut.stderr @@ -10,8 +10,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { Assume::SAFETY }> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src, { Assume::SAFETY }> + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error: aborting due to 1 previous error diff --git a/tests/ui/transmutability/primitives/bool.current.stderr b/tests/ui/transmutability/primitives/bool.current.stderr index da6a4a44e95..2945cdaad40 100644 --- a/tests/ui/transmutability/primitives/bool.current.stderr +++ b/tests/ui/transmutability/primitives/bool.current.stderr @@ -10,8 +10,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { Assume::SAFETY }> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src, { Assume::SAFETY }> + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error: aborting due to 1 previous error diff --git a/tests/ui/transmutability/primitives/bool.next.stderr b/tests/ui/transmutability/primitives/bool.next.stderr index da6a4a44e95..2945cdaad40 100644 --- a/tests/ui/transmutability/primitives/bool.next.stderr +++ b/tests/ui/transmutability/primitives/bool.next.stderr @@ -10,8 +10,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { Assume::SAFETY }> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src, { Assume::SAFETY }> + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error: aborting due to 1 previous error diff --git a/tests/ui/transmutability/primitives/bool.rs b/tests/ui/transmutability/primitives/bool.rs index 19236a1ae2e..6fac8ba1ad1 100644 --- a/tests/ui/transmutability/primitives/bool.rs +++ b/tests/ui/transmutability/primitives/bool.rs @@ -4,16 +4,16 @@ #![feature(transmutability)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { Assume::SAFETY }> + Dst: TransmuteFrom<Src, { Assume::SAFETY }> {} pub fn is_maybe_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { Assume::SAFETY.and(Assume::VALIDITY) }> + Dst: TransmuteFrom<Src, { Assume::SAFETY.and(Assume::VALIDITY) }> {} } diff --git a/tests/ui/transmutability/primitives/numbers.current.stderr b/tests/ui/transmutability/primitives/numbers.current.stderr index 0a9b9d182f8..efb2ce8c772 100644 --- a/tests/ui/transmutability/primitives/numbers.current.stderr +++ b/tests/ui/transmutability/primitives/numbers.current.stderr @@ -10,8 +10,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i8` cannot be safely transmuted into `u16` --> $DIR/numbers.rs:65:40 @@ -25,8 +25,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i8` cannot be safely transmuted into `i32` --> $DIR/numbers.rs:66:40 @@ -40,8 +40,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i8` cannot be safely transmuted into `f32` --> $DIR/numbers.rs:67:40 @@ -55,8 +55,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i8` cannot be safely transmuted into `u32` --> $DIR/numbers.rs:68:40 @@ -70,8 +70,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i8` cannot be safely transmuted into `u64` --> $DIR/numbers.rs:69:40 @@ -85,8 +85,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i8` cannot be safely transmuted into `i64` --> $DIR/numbers.rs:70:40 @@ -100,8 +100,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i8` cannot be safely transmuted into `f64` --> $DIR/numbers.rs:71:40 @@ -115,8 +115,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i8` cannot be safely transmuted into `u128` --> $DIR/numbers.rs:72:39 @@ -130,8 +130,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i8` cannot be safely transmuted into `i128` --> $DIR/numbers.rs:73:39 @@ -145,8 +145,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u8` cannot be safely transmuted into `i16` --> $DIR/numbers.rs:75:40 @@ -160,8 +160,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u8` cannot be safely transmuted into `u16` --> $DIR/numbers.rs:76:40 @@ -175,8 +175,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u8` cannot be safely transmuted into `i32` --> $DIR/numbers.rs:77:40 @@ -190,8 +190,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u8` cannot be safely transmuted into `f32` --> $DIR/numbers.rs:78:40 @@ -205,8 +205,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u8` cannot be safely transmuted into `u32` --> $DIR/numbers.rs:79:40 @@ -220,8 +220,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u8` cannot be safely transmuted into `u64` --> $DIR/numbers.rs:80:40 @@ -235,8 +235,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u8` cannot be safely transmuted into `i64` --> $DIR/numbers.rs:81:40 @@ -250,8 +250,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u8` cannot be safely transmuted into `f64` --> $DIR/numbers.rs:82:40 @@ -265,8 +265,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u8` cannot be safely transmuted into `u128` --> $DIR/numbers.rs:83:39 @@ -280,8 +280,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u8` cannot be safely transmuted into `i128` --> $DIR/numbers.rs:84:39 @@ -295,8 +295,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i16` cannot be safely transmuted into `i32` --> $DIR/numbers.rs:86:40 @@ -310,8 +310,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i16` cannot be safely transmuted into `f32` --> $DIR/numbers.rs:87:40 @@ -325,8 +325,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i16` cannot be safely transmuted into `u32` --> $DIR/numbers.rs:88:40 @@ -340,8 +340,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i16` cannot be safely transmuted into `u64` --> $DIR/numbers.rs:89:40 @@ -355,8 +355,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i16` cannot be safely transmuted into `i64` --> $DIR/numbers.rs:90:40 @@ -370,8 +370,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i16` cannot be safely transmuted into `f64` --> $DIR/numbers.rs:91:40 @@ -385,8 +385,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i16` cannot be safely transmuted into `u128` --> $DIR/numbers.rs:92:39 @@ -400,8 +400,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i16` cannot be safely transmuted into `i128` --> $DIR/numbers.rs:93:39 @@ -415,8 +415,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u16` cannot be safely transmuted into `i32` --> $DIR/numbers.rs:95:40 @@ -430,8 +430,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u16` cannot be safely transmuted into `f32` --> $DIR/numbers.rs:96:40 @@ -445,8 +445,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u16` cannot be safely transmuted into `u32` --> $DIR/numbers.rs:97:40 @@ -460,8 +460,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u16` cannot be safely transmuted into `u64` --> $DIR/numbers.rs:98:40 @@ -475,8 +475,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u16` cannot be safely transmuted into `i64` --> $DIR/numbers.rs:99:40 @@ -490,8 +490,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u16` cannot be safely transmuted into `f64` --> $DIR/numbers.rs:100:40 @@ -505,8 +505,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u16` cannot be safely transmuted into `u128` --> $DIR/numbers.rs:101:39 @@ -520,8 +520,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u16` cannot be safely transmuted into `i128` --> $DIR/numbers.rs:102:39 @@ -535,8 +535,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i32` cannot be safely transmuted into `u64` --> $DIR/numbers.rs:104:40 @@ -550,8 +550,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i32` cannot be safely transmuted into `i64` --> $DIR/numbers.rs:105:40 @@ -565,8 +565,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i32` cannot be safely transmuted into `f64` --> $DIR/numbers.rs:106:40 @@ -580,8 +580,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i32` cannot be safely transmuted into `u128` --> $DIR/numbers.rs:107:39 @@ -595,8 +595,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i32` cannot be safely transmuted into `i128` --> $DIR/numbers.rs:108:39 @@ -610,8 +610,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `f32` cannot be safely transmuted into `u64` --> $DIR/numbers.rs:110:40 @@ -625,8 +625,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `f32` cannot be safely transmuted into `i64` --> $DIR/numbers.rs:111:40 @@ -640,8 +640,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `f32` cannot be safely transmuted into `f64` --> $DIR/numbers.rs:112:40 @@ -655,8 +655,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `f32` cannot be safely transmuted into `u128` --> $DIR/numbers.rs:113:39 @@ -670,8 +670,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `f32` cannot be safely transmuted into `i128` --> $DIR/numbers.rs:114:39 @@ -685,8 +685,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u32` cannot be safely transmuted into `u64` --> $DIR/numbers.rs:116:40 @@ -700,8 +700,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u32` cannot be safely transmuted into `i64` --> $DIR/numbers.rs:117:40 @@ -715,8 +715,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u32` cannot be safely transmuted into `f64` --> $DIR/numbers.rs:118:40 @@ -730,8 +730,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u32` cannot be safely transmuted into `u128` --> $DIR/numbers.rs:119:39 @@ -745,8 +745,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u32` cannot be safely transmuted into `i128` --> $DIR/numbers.rs:120:39 @@ -760,8 +760,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u64` cannot be safely transmuted into `u128` --> $DIR/numbers.rs:122:39 @@ -775,8 +775,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u64` cannot be safely transmuted into `i128` --> $DIR/numbers.rs:123:39 @@ -790,8 +790,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i64` cannot be safely transmuted into `u128` --> $DIR/numbers.rs:125:39 @@ -805,8 +805,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i64` cannot be safely transmuted into `i128` --> $DIR/numbers.rs:126:39 @@ -820,8 +820,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `f64` cannot be safely transmuted into `u128` --> $DIR/numbers.rs:128:39 @@ -835,8 +835,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `f64` cannot be safely transmuted into `i128` --> $DIR/numbers.rs:129:39 @@ -850,8 +850,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error: aborting due to 57 previous errors diff --git a/tests/ui/transmutability/primitives/numbers.next.stderr b/tests/ui/transmutability/primitives/numbers.next.stderr index 0a9b9d182f8..efb2ce8c772 100644 --- a/tests/ui/transmutability/primitives/numbers.next.stderr +++ b/tests/ui/transmutability/primitives/numbers.next.stderr @@ -10,8 +10,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i8` cannot be safely transmuted into `u16` --> $DIR/numbers.rs:65:40 @@ -25,8 +25,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i8` cannot be safely transmuted into `i32` --> $DIR/numbers.rs:66:40 @@ -40,8 +40,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i8` cannot be safely transmuted into `f32` --> $DIR/numbers.rs:67:40 @@ -55,8 +55,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i8` cannot be safely transmuted into `u32` --> $DIR/numbers.rs:68:40 @@ -70,8 +70,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i8` cannot be safely transmuted into `u64` --> $DIR/numbers.rs:69:40 @@ -85,8 +85,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i8` cannot be safely transmuted into `i64` --> $DIR/numbers.rs:70:40 @@ -100,8 +100,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i8` cannot be safely transmuted into `f64` --> $DIR/numbers.rs:71:40 @@ -115,8 +115,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i8` cannot be safely transmuted into `u128` --> $DIR/numbers.rs:72:39 @@ -130,8 +130,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i8` cannot be safely transmuted into `i128` --> $DIR/numbers.rs:73:39 @@ -145,8 +145,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u8` cannot be safely transmuted into `i16` --> $DIR/numbers.rs:75:40 @@ -160,8 +160,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u8` cannot be safely transmuted into `u16` --> $DIR/numbers.rs:76:40 @@ -175,8 +175,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u8` cannot be safely transmuted into `i32` --> $DIR/numbers.rs:77:40 @@ -190,8 +190,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u8` cannot be safely transmuted into `f32` --> $DIR/numbers.rs:78:40 @@ -205,8 +205,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u8` cannot be safely transmuted into `u32` --> $DIR/numbers.rs:79:40 @@ -220,8 +220,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u8` cannot be safely transmuted into `u64` --> $DIR/numbers.rs:80:40 @@ -235,8 +235,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u8` cannot be safely transmuted into `i64` --> $DIR/numbers.rs:81:40 @@ -250,8 +250,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u8` cannot be safely transmuted into `f64` --> $DIR/numbers.rs:82:40 @@ -265,8 +265,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u8` cannot be safely transmuted into `u128` --> $DIR/numbers.rs:83:39 @@ -280,8 +280,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u8` cannot be safely transmuted into `i128` --> $DIR/numbers.rs:84:39 @@ -295,8 +295,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i16` cannot be safely transmuted into `i32` --> $DIR/numbers.rs:86:40 @@ -310,8 +310,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i16` cannot be safely transmuted into `f32` --> $DIR/numbers.rs:87:40 @@ -325,8 +325,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i16` cannot be safely transmuted into `u32` --> $DIR/numbers.rs:88:40 @@ -340,8 +340,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i16` cannot be safely transmuted into `u64` --> $DIR/numbers.rs:89:40 @@ -355,8 +355,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i16` cannot be safely transmuted into `i64` --> $DIR/numbers.rs:90:40 @@ -370,8 +370,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i16` cannot be safely transmuted into `f64` --> $DIR/numbers.rs:91:40 @@ -385,8 +385,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i16` cannot be safely transmuted into `u128` --> $DIR/numbers.rs:92:39 @@ -400,8 +400,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i16` cannot be safely transmuted into `i128` --> $DIR/numbers.rs:93:39 @@ -415,8 +415,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u16` cannot be safely transmuted into `i32` --> $DIR/numbers.rs:95:40 @@ -430,8 +430,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u16` cannot be safely transmuted into `f32` --> $DIR/numbers.rs:96:40 @@ -445,8 +445,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u16` cannot be safely transmuted into `u32` --> $DIR/numbers.rs:97:40 @@ -460,8 +460,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u16` cannot be safely transmuted into `u64` --> $DIR/numbers.rs:98:40 @@ -475,8 +475,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u16` cannot be safely transmuted into `i64` --> $DIR/numbers.rs:99:40 @@ -490,8 +490,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u16` cannot be safely transmuted into `f64` --> $DIR/numbers.rs:100:40 @@ -505,8 +505,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u16` cannot be safely transmuted into `u128` --> $DIR/numbers.rs:101:39 @@ -520,8 +520,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u16` cannot be safely transmuted into `i128` --> $DIR/numbers.rs:102:39 @@ -535,8 +535,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i32` cannot be safely transmuted into `u64` --> $DIR/numbers.rs:104:40 @@ -550,8 +550,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i32` cannot be safely transmuted into `i64` --> $DIR/numbers.rs:105:40 @@ -565,8 +565,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i32` cannot be safely transmuted into `f64` --> $DIR/numbers.rs:106:40 @@ -580,8 +580,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i32` cannot be safely transmuted into `u128` --> $DIR/numbers.rs:107:39 @@ -595,8 +595,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i32` cannot be safely transmuted into `i128` --> $DIR/numbers.rs:108:39 @@ -610,8 +610,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `f32` cannot be safely transmuted into `u64` --> $DIR/numbers.rs:110:40 @@ -625,8 +625,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `f32` cannot be safely transmuted into `i64` --> $DIR/numbers.rs:111:40 @@ -640,8 +640,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `f32` cannot be safely transmuted into `f64` --> $DIR/numbers.rs:112:40 @@ -655,8 +655,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `f32` cannot be safely transmuted into `u128` --> $DIR/numbers.rs:113:39 @@ -670,8 +670,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `f32` cannot be safely transmuted into `i128` --> $DIR/numbers.rs:114:39 @@ -685,8 +685,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u32` cannot be safely transmuted into `u64` --> $DIR/numbers.rs:116:40 @@ -700,8 +700,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u32` cannot be safely transmuted into `i64` --> $DIR/numbers.rs:117:40 @@ -715,8 +715,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u32` cannot be safely transmuted into `f64` --> $DIR/numbers.rs:118:40 @@ -730,8 +730,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u32` cannot be safely transmuted into `u128` --> $DIR/numbers.rs:119:39 @@ -745,8 +745,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u32` cannot be safely transmuted into `i128` --> $DIR/numbers.rs:120:39 @@ -760,8 +760,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u64` cannot be safely transmuted into `u128` --> $DIR/numbers.rs:122:39 @@ -775,8 +775,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `u64` cannot be safely transmuted into `i128` --> $DIR/numbers.rs:123:39 @@ -790,8 +790,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i64` cannot be safely transmuted into `u128` --> $DIR/numbers.rs:125:39 @@ -805,8 +805,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `i64` cannot be safely transmuted into `i128` --> $DIR/numbers.rs:126:39 @@ -820,8 +820,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `f64` cannot be safely transmuted into `u128` --> $DIR/numbers.rs:128:39 @@ -835,8 +835,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `f64` cannot be safely transmuted into `i128` --> $DIR/numbers.rs:129:39 @@ -850,8 +850,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error: aborting due to 57 previous errors diff --git a/tests/ui/transmutability/primitives/numbers.rs b/tests/ui/transmutability/primitives/numbers.rs index 401502474cf..b5c21c992b6 100644 --- a/tests/ui/transmutability/primitives/numbers.rs +++ b/tests/ui/transmutability/primitives/numbers.rs @@ -7,11 +7,11 @@ #![allow(dead_code)] mod assert { - use std::mem::BikeshedIntrinsicFrom; + use std::mem::TransmuteFrom; pub fn is_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src> + Dst: TransmuteFrom<Src> {} } diff --git a/tests/ui/transmutability/primitives/unit.current.stderr b/tests/ui/transmutability/primitives/unit.current.stderr index 52b708d680e..4bfb229832b 100644 --- a/tests/ui/transmutability/primitives/unit.current.stderr +++ b/tests/ui/transmutability/primitives/unit.current.stderr @@ -10,7 +10,7 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume::ALIGNMENT LL | | .and(Assume::LIFETIMES) diff --git a/tests/ui/transmutability/primitives/unit.next.stderr b/tests/ui/transmutability/primitives/unit.next.stderr index 52b708d680e..4bfb229832b 100644 --- a/tests/ui/transmutability/primitives/unit.next.stderr +++ b/tests/ui/transmutability/primitives/unit.next.stderr @@ -10,7 +10,7 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume::ALIGNMENT LL | | .and(Assume::LIFETIMES) diff --git a/tests/ui/transmutability/primitives/unit.rs b/tests/ui/transmutability/primitives/unit.rs index 44216950f55..93b21e0b586 100644 --- a/tests/ui/transmutability/primitives/unit.rs +++ b/tests/ui/transmutability/primitives/unit.rs @@ -9,11 +9,11 @@ #![allow(dead_code)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { + Dst: TransmuteFrom<Src, { Assume::ALIGNMENT .and(Assume::LIFETIMES) .and(Assume::SAFETY) diff --git a/tests/ui/transmutability/references/accept_assume_lifetime_extension.rs b/tests/ui/transmutability/references/accept_assume_lifetime_extension.rs index 3bdd7256791..edad02fc96d 100644 --- a/tests/ui/transmutability/references/accept_assume_lifetime_extension.rs +++ b/tests/ui/transmutability/references/accept_assume_lifetime_extension.rs @@ -4,11 +4,11 @@ #![feature(transmutability, core_intrinsics)] -use std::mem::{Assume, BikeshedIntrinsicFrom}; +use std::mem::{Assume, TransmuteFrom}; unsafe fn transmute<Src, Dst>(src: Src) -> Dst where - Dst: BikeshedIntrinsicFrom<Src, { Assume::SAFETY.and(Assume::LIFETIMES) }>, + Dst: TransmuteFrom<Src, { Assume::SAFETY.and(Assume::LIFETIMES) }>, { core::intrinsics::transmute_unchecked(src) } @@ -82,7 +82,7 @@ mod hrtb { unsafe fn extend_hrtb<'a>(src: &'a u8) -> &'static u8 where - for<'b> &'b u8: BikeshedIntrinsicFrom<&'a u8, { Assume::LIFETIMES }>, + for<'b> &'b u8: TransmuteFrom<&'a u8, { Assume::LIFETIMES }>, { core::intrinsics::transmute_unchecked(src) } diff --git a/tests/ui/transmutability/references/accept_unexercised_lifetime_extension.rs b/tests/ui/transmutability/references/accept_unexercised_lifetime_extension.rs index 559ee23a446..5734575e90b 100644 --- a/tests/ui/transmutability/references/accept_unexercised_lifetime_extension.rs +++ b/tests/ui/transmutability/references/accept_unexercised_lifetime_extension.rs @@ -4,11 +4,11 @@ #![feature(transmutability, core_intrinsics)] -use std::mem::{Assume, BikeshedIntrinsicFrom}; +use std::mem::{Assume, TransmuteFrom}; unsafe fn transmute<Src, Dst>(src: Src) -> Dst where - Dst: BikeshedIntrinsicFrom<Src, { Assume::SAFETY }>, + Dst: TransmuteFrom<Src, { Assume::SAFETY }>, { core::intrinsics::transmute_unchecked(src) } diff --git a/tests/ui/transmutability/references/recursive-wrapper-types-bit-compatible-mut.rs b/tests/ui/transmutability/references/recursive-wrapper-types-bit-compatible-mut.rs index ba2db755e3b..92068ee0d4f 100644 --- a/tests/ui/transmutability/references/recursive-wrapper-types-bit-compatible-mut.rs +++ b/tests/ui/transmutability/references/recursive-wrapper-types-bit-compatible-mut.rs @@ -2,11 +2,11 @@ #![feature(transmutability)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_maybe_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { + Dst: TransmuteFrom<Src, { Assume { alignment: true, lifetimes: false, diff --git a/tests/ui/transmutability/references/recursive-wrapper-types-bit-compatible-mut.stderr b/tests/ui/transmutability/references/recursive-wrapper-types-bit-compatible-mut.stderr index 4b2866dc4f0..1698021d554 100644 --- a/tests/ui/transmutability/references/recursive-wrapper-types-bit-compatible-mut.stderr +++ b/tests/ui/transmutability/references/recursive-wrapper-types-bit-compatible-mut.stderr @@ -10,7 +10,7 @@ note: required by a bound in `is_maybe_transmutable` LL | pub fn is_maybe_transmutable<Src, Dst>() | --------------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume { LL | | alignment: true, diff --git a/tests/ui/transmutability/references/recursive-wrapper-types-bit-compatible.rs b/tests/ui/transmutability/references/recursive-wrapper-types-bit-compatible.rs index cd70c278285..8e2da3518a9 100644 --- a/tests/ui/transmutability/references/recursive-wrapper-types-bit-compatible.rs +++ b/tests/ui/transmutability/references/recursive-wrapper-types-bit-compatible.rs @@ -2,11 +2,11 @@ #![feature(transmutability)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_maybe_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { + Dst: TransmuteFrom<Src, { Assume { alignment: true, lifetimes: false, diff --git a/tests/ui/transmutability/references/recursive-wrapper-types-bit-incompatible.rs b/tests/ui/transmutability/references/recursive-wrapper-types-bit-incompatible.rs index 2f264e8339e..01b176cc3c1 100644 --- a/tests/ui/transmutability/references/recursive-wrapper-types-bit-incompatible.rs +++ b/tests/ui/transmutability/references/recursive-wrapper-types-bit-incompatible.rs @@ -2,11 +2,11 @@ #![feature(transmutability)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_maybe_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { + Dst: TransmuteFrom<Src, { Assume { alignment: true, lifetimes: false, diff --git a/tests/ui/transmutability/references/recursive-wrapper-types-bit-incompatible.stderr b/tests/ui/transmutability/references/recursive-wrapper-types-bit-incompatible.stderr index 2b7cab1660d..dbd3e39b365 100644 --- a/tests/ui/transmutability/references/recursive-wrapper-types-bit-incompatible.stderr +++ b/tests/ui/transmutability/references/recursive-wrapper-types-bit-incompatible.stderr @@ -10,7 +10,7 @@ note: required by a bound in `is_maybe_transmutable` LL | pub fn is_maybe_transmutable<Src, Dst>() | --------------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume { LL | | alignment: true, diff --git a/tests/ui/transmutability/references/recursive-wrapper-types.rs b/tests/ui/transmutability/references/recursive-wrapper-types.rs index 28f4d6661cb..53dedeb6388 100644 --- a/tests/ui/transmutability/references/recursive-wrapper-types.rs +++ b/tests/ui/transmutability/references/recursive-wrapper-types.rs @@ -2,11 +2,11 @@ #![feature(transmutability)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_maybe_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { + Dst: TransmuteFrom<Src, { Assume { alignment: true, lifetimes: false, diff --git a/tests/ui/transmutability/references/reject_extension.rs b/tests/ui/transmutability/references/reject_extension.rs index 161da5772e8..dd02e5c01c4 100644 --- a/tests/ui/transmutability/references/reject_extension.rs +++ b/tests/ui/transmutability/references/reject_extension.rs @@ -6,11 +6,11 @@ #![feature(transmutability)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom< + Dst: TransmuteFrom< Src, { Assume { diff --git a/tests/ui/transmutability/references/reject_extension.stderr b/tests/ui/transmutability/references/reject_extension.stderr index 88dd0313e3c..182106acf12 100644 --- a/tests/ui/transmutability/references/reject_extension.stderr +++ b/tests/ui/transmutability/references/reject_extension.stderr @@ -10,7 +10,7 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom< +LL | Dst: TransmuteFrom< | ______________^ LL | | Src, LL | | { diff --git a/tests/ui/transmutability/references/reject_lifetime_extension.rs b/tests/ui/transmutability/references/reject_lifetime_extension.rs index 79bb4e1e556..ff9290c34af 100644 --- a/tests/ui/transmutability/references/reject_lifetime_extension.rs +++ b/tests/ui/transmutability/references/reject_lifetime_extension.rs @@ -4,11 +4,11 @@ #![feature(transmutability, core_intrinsics)] -use std::mem::{Assume, BikeshedIntrinsicFrom}; +use std::mem::{Assume, TransmuteFrom}; unsafe fn transmute<Src, Dst>(src: Src) -> Dst where - Dst: BikeshedIntrinsicFrom<Src, { Assume::SAFETY }>, + Dst: TransmuteFrom<Src, { Assume::SAFETY }>, { core::intrinsics::transmute_unchecked(src) } @@ -82,7 +82,7 @@ mod hrtb { unsafe fn extend_hrtb<'a>(src: &'a u8) -> &'static u8 where - for<'b> &'b u8: BikeshedIntrinsicFrom<&'a u8>, + for<'b> &'b u8: TransmuteFrom<&'a u8>, { core::intrinsics::transmute_unchecked(src) } diff --git a/tests/ui/transmutability/references/reject_lifetime_extension.stderr b/tests/ui/transmutability/references/reject_lifetime_extension.stderr index df1b81f26d2..a597041c6ca 100644 --- a/tests/ui/transmutability/references/reject_lifetime_extension.stderr +++ b/tests/ui/transmutability/references/reject_lifetime_extension.stderr @@ -70,8 +70,8 @@ LL | unsafe { extend_hrtb(src) } note: due to current limitations in the borrow checker, this implies a `'static` lifetime --> $DIR/reject_lifetime_extension.rs:85:25 | -LL | for<'b> &'b u8: BikeshedIntrinsicFrom<&'a u8>, - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | for<'b> &'b u8: TransmuteFrom<&'a u8>, + | ^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 8 previous errors diff --git a/tests/ui/transmutability/references/u8-to-unit.rs b/tests/ui/transmutability/references/u8-to-unit.rs index 017b73d9595..98deb6457cb 100644 --- a/tests/ui/transmutability/references/u8-to-unit.rs +++ b/tests/ui/transmutability/references/u8-to-unit.rs @@ -2,11 +2,11 @@ #![feature(transmutability)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_maybe_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { + Dst: TransmuteFrom<Src, { Assume { alignment: false, lifetimes: true, diff --git a/tests/ui/transmutability/references/unit-to-itself.rs b/tests/ui/transmutability/references/unit-to-itself.rs index 40aec8418fe..789455c03ea 100644 --- a/tests/ui/transmutability/references/unit-to-itself.rs +++ b/tests/ui/transmutability/references/unit-to-itself.rs @@ -2,11 +2,11 @@ #![feature(transmutability)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_maybe_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { + Dst: TransmuteFrom<Src, { Assume { alignment: true, lifetimes: false, diff --git a/tests/ui/transmutability/references/unit-to-u8.rs b/tests/ui/transmutability/references/unit-to-u8.rs index 973d3206c12..575a40e3622 100644 --- a/tests/ui/transmutability/references/unit-to-u8.rs +++ b/tests/ui/transmutability/references/unit-to-u8.rs @@ -2,11 +2,11 @@ #![feature(transmutability)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_maybe_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { + Dst: TransmuteFrom<Src, { Assume { alignment: true, lifetimes: true, diff --git a/tests/ui/transmutability/references/unit-to-u8.stderr b/tests/ui/transmutability/references/unit-to-u8.stderr index 5d73dfdc8eb..b5a79b1917f 100644 --- a/tests/ui/transmutability/references/unit-to-u8.stderr +++ b/tests/ui/transmutability/references/unit-to-u8.stderr @@ -10,7 +10,7 @@ note: required by a bound in `is_maybe_transmutable` LL | pub fn is_maybe_transmutable<Src, Dst>() | --------------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume { LL | | alignment: true, diff --git a/tests/ui/transmutability/references/unsafecell.rs b/tests/ui/transmutability/references/unsafecell.rs index a8a1f969fb4..4001f139770 100644 --- a/tests/ui/transmutability/references/unsafecell.rs +++ b/tests/ui/transmutability/references/unsafecell.rs @@ -5,11 +5,11 @@ use std::cell::UnsafeCell; mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_maybe_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { Assume::SAFETY }> + Dst: TransmuteFrom<Src, { Assume::SAFETY }> {} } diff --git a/tests/ui/transmutability/references/unsafecell.stderr b/tests/ui/transmutability/references/unsafecell.stderr index 8bb32359355..6664d8a7d6f 100644 --- a/tests/ui/transmutability/references/unsafecell.stderr +++ b/tests/ui/transmutability/references/unsafecell.stderr @@ -10,8 +10,8 @@ note: required by a bound in `is_maybe_transmutable` LL | pub fn is_maybe_transmutable<Src, Dst>() | --------------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { Assume::SAFETY }> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_maybe_transmutable` +LL | Dst: TransmuteFrom<Src, { Assume::SAFETY }> + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_maybe_transmutable` error[E0277]: `&UnsafeCell<u8>` cannot be safely transmuted into `&UnsafeCell<u8>` --> $DIR/unsafecell.rs:29:62 @@ -25,8 +25,8 @@ note: required by a bound in `is_maybe_transmutable` LL | pub fn is_maybe_transmutable<Src, Dst>() | --------------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { Assume::SAFETY }> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_maybe_transmutable` +LL | Dst: TransmuteFrom<Src, { Assume::SAFETY }> + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_maybe_transmutable` error: aborting due to 2 previous errors diff --git a/tests/ui/transmutability/region-infer.rs b/tests/ui/transmutability/region-infer.rs index 0632bc53176..c164f35c447 100644 --- a/tests/ui/transmutability/region-infer.rs +++ b/tests/ui/transmutability/region-infer.rs @@ -1,13 +1,13 @@ #![feature(transmutability)] -use std::mem::{Assume, BikeshedIntrinsicFrom}; +use std::mem::{Assume, TransmuteFrom}; #[repr(C)] struct W<'a>(&'a ()); fn test<'a>() where - W<'a>: BikeshedIntrinsicFrom< + W<'a>: TransmuteFrom< (), { Assume { alignment: true, lifetimes: true, safety: true, validity: true } }, >, diff --git a/tests/ui/transmutability/region-infer.stderr b/tests/ui/transmutability/region-infer.stderr index 03c46823838..09ecf484bc8 100644 --- a/tests/ui/transmutability/region-infer.stderr +++ b/tests/ui/transmutability/region-infer.stderr @@ -10,7 +10,7 @@ note: required by a bound in `test` LL | fn test<'a>() | ---- required by a bound in this function LL | where -LL | W<'a>: BikeshedIntrinsicFrom< +LL | W<'a>: TransmuteFrom< | ____________^ LL | | (), LL | | { Assume { alignment: true, lifetimes: true, safety: true, validity: true } }, diff --git a/tests/ui/transmutability/safety/assume/should_accept_if_dst_has_safety_invariant.rs b/tests/ui/transmutability/safety/assume/should_accept_if_dst_has_safety_invariant.rs index cb3c1cdf46c..0113049f51e 100644 --- a/tests/ui/transmutability/safety/assume/should_accept_if_dst_has_safety_invariant.rs +++ b/tests/ui/transmutability/safety/assume/should_accept_if_dst_has_safety_invariant.rs @@ -8,11 +8,11 @@ #![allow(dead_code)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { Assume::SAFETY }> + Dst: TransmuteFrom<Src, { Assume::SAFETY }> {} } diff --git a/tests/ui/transmutability/safety/assume/should_accept_if_ref_src_has_safety_invariant.rs b/tests/ui/transmutability/safety/assume/should_accept_if_ref_src_has_safety_invariant.rs index b12c4a10d12..eca7a06559d 100644 --- a/tests/ui/transmutability/safety/assume/should_accept_if_ref_src_has_safety_invariant.rs +++ b/tests/ui/transmutability/safety/assume/should_accept_if_ref_src_has_safety_invariant.rs @@ -8,11 +8,11 @@ #![allow(dead_code)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { Assume::SAFETY }> + Dst: TransmuteFrom<Src, { Assume::SAFETY }> {} } diff --git a/tests/ui/transmutability/safety/assume/should_accept_if_src_has_safety_invariant.rs b/tests/ui/transmutability/safety/assume/should_accept_if_src_has_safety_invariant.rs index ff01462ffec..46e84b48044 100644 --- a/tests/ui/transmutability/safety/assume/should_accept_if_src_has_safety_invariant.rs +++ b/tests/ui/transmutability/safety/assume/should_accept_if_src_has_safety_invariant.rs @@ -8,11 +8,11 @@ #![allow(dead_code)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { Assume::SAFETY }> + Dst: TransmuteFrom<Src, { Assume::SAFETY }> {} } diff --git a/tests/ui/transmutability/safety/should_accept_if_src_has_safety_invariant.rs b/tests/ui/transmutability/safety/should_accept_if_src_has_safety_invariant.rs index d516e9a7da5..aaba6febde4 100644 --- a/tests/ui/transmutability/safety/should_accept_if_src_has_safety_invariant.rs +++ b/tests/ui/transmutability/safety/should_accept_if_src_has_safety_invariant.rs @@ -8,11 +8,11 @@ #![allow(dead_code)] mod assert { - use std::mem::BikeshedIntrinsicFrom; + use std::mem::TransmuteFrom; pub fn is_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src> // safety is NOT assumed + Dst: TransmuteFrom<Src> // safety is NOT assumed {} } diff --git a/tests/ui/transmutability/safety/should_reject_if_dst_has_safety_invariant.rs b/tests/ui/transmutability/safety/should_reject_if_dst_has_safety_invariant.rs index 4f0aee31548..6f8e383db1f 100644 --- a/tests/ui/transmutability/safety/should_reject_if_dst_has_safety_invariant.rs +++ b/tests/ui/transmutability/safety/should_reject_if_dst_has_safety_invariant.rs @@ -6,11 +6,11 @@ #![allow(dead_code)] mod assert { - use std::mem::BikeshedIntrinsicFrom; + use std::mem::TransmuteFrom; pub fn is_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src> // safety is NOT assumed + Dst: TransmuteFrom<Src> // safety is NOT assumed {} } diff --git a/tests/ui/transmutability/safety/should_reject_if_dst_has_safety_invariant.stderr b/tests/ui/transmutability/safety/should_reject_if_dst_has_safety_invariant.stderr index 2339c268326..6445b1e146e 100644 --- a/tests/ui/transmutability/safety/should_reject_if_dst_has_safety_invariant.stderr +++ b/tests/ui/transmutability/safety/should_reject_if_dst_has_safety_invariant.stderr @@ -10,8 +10,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> // safety is NOT assumed - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> // safety is NOT assumed + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error: aborting due to 1 previous error diff --git a/tests/ui/transmutability/safety/should_reject_if_ref_src_has_safety_invariant.rs b/tests/ui/transmutability/safety/should_reject_if_ref_src_has_safety_invariant.rs index 126059dd7b7..16d163d5420 100644 --- a/tests/ui/transmutability/safety/should_reject_if_ref_src_has_safety_invariant.rs +++ b/tests/ui/transmutability/safety/should_reject_if_ref_src_has_safety_invariant.rs @@ -6,11 +6,11 @@ #![allow(dead_code)] mod assert { - use std::mem::BikeshedIntrinsicFrom; + use std::mem::TransmuteFrom; pub fn is_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src> // safety is NOT assumed + Dst: TransmuteFrom<Src> // safety is NOT assumed {} } diff --git a/tests/ui/transmutability/safety/should_reject_if_ref_src_has_safety_invariant.stderr b/tests/ui/transmutability/safety/should_reject_if_ref_src_has_safety_invariant.stderr index 99feebe9211..38ef829f064 100644 --- a/tests/ui/transmutability/safety/should_reject_if_ref_src_has_safety_invariant.stderr +++ b/tests/ui/transmutability/safety/should_reject_if_ref_src_has_safety_invariant.stderr @@ -10,8 +10,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src> // safety is NOT assumed - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src> // safety is NOT assumed + | ^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error: aborting due to 1 previous error diff --git a/tests/ui/transmutability/structs/repr/should_handle_align.rs b/tests/ui/transmutability/structs/repr/should_handle_align.rs index 0c207766045..03065298b50 100644 --- a/tests/ui/transmutability/structs/repr/should_handle_align.rs +++ b/tests/ui/transmutability/structs/repr/should_handle_align.rs @@ -6,11 +6,11 @@ #![allow(dead_code, incomplete_features, non_camel_case_types)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_maybe_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { + Dst: TransmuteFrom<Src, { Assume { alignment: true, lifetimes: true, diff --git a/tests/ui/transmutability/structs/repr/should_handle_all.rs b/tests/ui/transmutability/structs/repr/should_handle_all.rs index 52c24eecf12..e5ca37e68ec 100644 --- a/tests/ui/transmutability/structs/repr/should_handle_all.rs +++ b/tests/ui/transmutability/structs/repr/should_handle_all.rs @@ -6,11 +6,11 @@ #![allow(dead_code, incomplete_features, non_camel_case_types)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_maybe_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { + Dst: TransmuteFrom<Src, { Assume { alignment: true, lifetimes: true, diff --git a/tests/ui/transmutability/structs/repr/should_handle_packed.rs b/tests/ui/transmutability/structs/repr/should_handle_packed.rs index 4af32d6e84e..c9be32d7b2a 100644 --- a/tests/ui/transmutability/structs/repr/should_handle_packed.rs +++ b/tests/ui/transmutability/structs/repr/should_handle_packed.rs @@ -6,11 +6,11 @@ #![allow(dead_code, incomplete_features, non_camel_case_types)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_maybe_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { + Dst: TransmuteFrom<Src, { Assume { alignment: true, lifetimes: true, diff --git a/tests/ui/transmutability/structs/repr/transmute_infinitely_recursive_type.rs b/tests/ui/transmutability/structs/repr/transmute_infinitely_recursive_type.rs index 4c285a616b3..8d291054365 100644 --- a/tests/ui/transmutability/structs/repr/transmute_infinitely_recursive_type.rs +++ b/tests/ui/transmutability/structs/repr/transmute_infinitely_recursive_type.rs @@ -7,11 +7,11 @@ #![allow(dead_code, incomplete_features, non_camel_case_types)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_maybe_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src>, + Dst: TransmuteFrom<Src>, { } } diff --git a/tests/ui/transmutability/structs/repr/transmute_infinitely_recursive_type.stderr b/tests/ui/transmutability/structs/repr/transmute_infinitely_recursive_type.stderr index 7fb051f6625..bdf2d3b6a58 100644 --- a/tests/ui/transmutability/structs/repr/transmute_infinitely_recursive_type.stderr +++ b/tests/ui/transmutability/structs/repr/transmute_infinitely_recursive_type.stderr @@ -12,7 +12,7 @@ LL | struct ExplicitlyPadded(Box<ExplicitlyPadded>); error[E0391]: cycle detected when computing layout of `should_pad_explicitly_packed_field::ExplicitlyPadded` | = note: ...which immediately requires computing layout of `should_pad_explicitly_packed_field::ExplicitlyPadded` again - = note: cycle used when evaluating trait selection obligation `(): core::mem::transmutability::BikeshedIntrinsicFrom<should_pad_explicitly_packed_field::ExplicitlyPadded, core::mem::transmutability::Assume { alignment: false, lifetimes: false, safety: false, validity: false }>` + = note: cycle used when evaluating trait selection obligation `(): core::mem::transmutability::TransmuteFrom<should_pad_explicitly_packed_field::ExplicitlyPadded, core::mem::transmutability::Assume { alignment: false, lifetimes: false, safety: false, validity: false }>` = note: see https://rustc-dev-guide.rust-lang.org/overview.html#queries and https://rustc-dev-guide.rust-lang.org/query.html for more information error: aborting due to 2 previous errors diff --git a/tests/ui/transmutability/structs/should_order_fields_correctly.rs b/tests/ui/transmutability/structs/should_order_fields_correctly.rs index 3675e4330ec..aa9ca39eff2 100644 --- a/tests/ui/transmutability/structs/should_order_fields_correctly.rs +++ b/tests/ui/transmutability/structs/should_order_fields_correctly.rs @@ -6,11 +6,11 @@ #![allow(dead_code)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { + Dst: TransmuteFrom<Src, { Assume::ALIGNMENT .and(Assume::LIFETIMES) .and(Assume::SAFETY) diff --git a/tests/ui/transmutability/transmute-padding-ice.rs b/tests/ui/transmutability/transmute-padding-ice.rs index f5935a0009e..133241c89cb 100644 --- a/tests/ui/transmutability/transmute-padding-ice.rs +++ b/tests/ui/transmutability/transmute-padding-ice.rs @@ -9,11 +9,11 @@ use std::mem::size_of; mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_maybe_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom< + Dst: TransmuteFrom< Src, { Assume { alignment: true, lifetimes: true, safety: true, validity: true } }, >, diff --git a/tests/ui/transmutability/uninhabited.rs b/tests/ui/transmutability/uninhabited.rs index 7524922c16a..74f7a1a2e89 100644 --- a/tests/ui/transmutability/uninhabited.rs +++ b/tests/ui/transmutability/uninhabited.rs @@ -3,11 +3,11 @@ #![allow(dead_code, incomplete_features, non_camel_case_types)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_maybe_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { + Dst: TransmuteFrom<Src, { Assume { alignment: true, lifetimes: true, diff --git a/tests/ui/transmutability/uninhabited.stderr b/tests/ui/transmutability/uninhabited.stderr index 88a98c798fc..3fa02f0867c 100644 --- a/tests/ui/transmutability/uninhabited.stderr +++ b/tests/ui/transmutability/uninhabited.stderr @@ -34,7 +34,7 @@ note: required by a bound in `is_maybe_transmutable` LL | pub fn is_maybe_transmutable<Src, Dst>() | --------------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume { LL | | alignment: true, @@ -56,7 +56,7 @@ note: required by a bound in `is_maybe_transmutable` LL | pub fn is_maybe_transmutable<Src, Dst>() | --------------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume { LL | | alignment: true, @@ -78,7 +78,7 @@ note: required by a bound in `is_maybe_transmutable` LL | pub fn is_maybe_transmutable<Src, Dst>() | --------------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume { LL | | alignment: true, @@ -100,7 +100,7 @@ note: required by a bound in `is_maybe_transmutable` LL | pub fn is_maybe_transmutable<Src, Dst>() | --------------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume { LL | | alignment: true, diff --git a/tests/ui/transmutability/unions/boolish.rs b/tests/ui/transmutability/unions/boolish.rs index c829f83149e..838643defd5 100644 --- a/tests/ui/transmutability/unions/boolish.rs +++ b/tests/ui/transmutability/unions/boolish.rs @@ -6,11 +6,11 @@ #![allow(dead_code)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { Assume::SAFETY }> + Dst: TransmuteFrom<Src, { Assume::SAFETY }> {} } diff --git a/tests/ui/transmutability/unions/repr/should_handle_align.rs b/tests/ui/transmutability/unions/repr/should_handle_align.rs index ba4e904e161..0605651bd7b 100644 --- a/tests/ui/transmutability/unions/repr/should_handle_align.rs +++ b/tests/ui/transmutability/unions/repr/should_handle_align.rs @@ -6,11 +6,11 @@ #![allow(dead_code, incomplete_features, non_camel_case_types)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_maybe_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { + Dst: TransmuteFrom<Src, { Assume { alignment: true, lifetimes: true, diff --git a/tests/ui/transmutability/unions/repr/should_handle_all.rs b/tests/ui/transmutability/unions/repr/should_handle_all.rs index 85d48dd9b7f..8505c7f9123 100644 --- a/tests/ui/transmutability/unions/repr/should_handle_all.rs +++ b/tests/ui/transmutability/unions/repr/should_handle_all.rs @@ -5,11 +5,11 @@ #![allow(dead_code, incomplete_features, non_camel_case_types)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_maybe_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { + Dst: TransmuteFrom<Src, { Assume { alignment: true, lifetimes: true, diff --git a/tests/ui/transmutability/unions/repr/should_handle_packed.rs b/tests/ui/transmutability/unions/repr/should_handle_packed.rs index fc06eba4353..5e9851ab0c9 100644 --- a/tests/ui/transmutability/unions/repr/should_handle_packed.rs +++ b/tests/ui/transmutability/unions/repr/should_handle_packed.rs @@ -6,11 +6,11 @@ #![allow(dead_code, incomplete_features, non_camel_case_types)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_maybe_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { + Dst: TransmuteFrom<Src, { Assume { alignment: true, lifetimes: true, diff --git a/tests/ui/transmutability/unions/should_pad_variants.rs b/tests/ui/transmutability/unions/should_pad_variants.rs index 1e4d2db8f74..986c7fafb85 100644 --- a/tests/ui/transmutability/unions/should_pad_variants.rs +++ b/tests/ui/transmutability/unions/should_pad_variants.rs @@ -6,11 +6,11 @@ #![allow(dead_code)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { + Dst: TransmuteFrom<Src, { Assume::ALIGNMENT .and(Assume::LIFETIMES) .and(Assume::SAFETY) diff --git a/tests/ui/transmutability/unions/should_pad_variants.stderr b/tests/ui/transmutability/unions/should_pad_variants.stderr index da4294bdbce..bb26281c2f0 100644 --- a/tests/ui/transmutability/unions/should_pad_variants.stderr +++ b/tests/ui/transmutability/unions/should_pad_variants.stderr @@ -10,7 +10,7 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { +LL | Dst: TransmuteFrom<Src, { | ______________^ LL | | Assume::ALIGNMENT LL | | .and(Assume::LIFETIMES) diff --git a/tests/ui/transmutability/unions/should_permit_intersecting_if_validity_is_assumed.rs b/tests/ui/transmutability/unions/should_permit_intersecting_if_validity_is_assumed.rs index 7efe9ac70f1..359ba515439 100644 --- a/tests/ui/transmutability/unions/should_permit_intersecting_if_validity_is_assumed.rs +++ b/tests/ui/transmutability/unions/should_permit_intersecting_if_validity_is_assumed.rs @@ -7,11 +7,11 @@ #![allow(dead_code, incomplete_features, non_camel_case_types)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_maybe_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { Assume::SAFETY.and(Assume::VALIDITY) }> + Dst: TransmuteFrom<Src, { Assume::SAFETY.and(Assume::VALIDITY) }> {} } diff --git a/tests/ui/transmutability/unions/should_reject_contraction.rs b/tests/ui/transmutability/unions/should_reject_contraction.rs index 62a0ee92919..87398328fc7 100644 --- a/tests/ui/transmutability/unions/should_reject_contraction.rs +++ b/tests/ui/transmutability/unions/should_reject_contraction.rs @@ -5,11 +5,11 @@ #![allow(dead_code, incomplete_features, non_camel_case_types)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { Assume::SAFETY }> + Dst: TransmuteFrom<Src, { Assume::SAFETY }> {} } diff --git a/tests/ui/transmutability/unions/should_reject_contraction.stderr b/tests/ui/transmutability/unions/should_reject_contraction.stderr index 20eaa3a6b09..ea68de14efc 100644 --- a/tests/ui/transmutability/unions/should_reject_contraction.stderr +++ b/tests/ui/transmutability/unions/should_reject_contraction.stderr @@ -10,8 +10,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { Assume::SAFETY }> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src, { Assume::SAFETY }> + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error: aborting due to 1 previous error diff --git a/tests/ui/transmutability/unions/should_reject_disjoint.rs b/tests/ui/transmutability/unions/should_reject_disjoint.rs index 732f92e8160..0427e3c44a2 100644 --- a/tests/ui/transmutability/unions/should_reject_disjoint.rs +++ b/tests/ui/transmutability/unions/should_reject_disjoint.rs @@ -5,11 +5,11 @@ #![allow(dead_code, incomplete_features, non_camel_case_types)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_maybe_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { Assume::SAFETY.and(Assume::VALIDITY) }> + Dst: TransmuteFrom<Src, { Assume::SAFETY.and(Assume::VALIDITY) }> {} } diff --git a/tests/ui/transmutability/unions/should_reject_disjoint.stderr b/tests/ui/transmutability/unions/should_reject_disjoint.stderr index ea47797c970..d55abbe0817 100644 --- a/tests/ui/transmutability/unions/should_reject_disjoint.stderr +++ b/tests/ui/transmutability/unions/should_reject_disjoint.stderr @@ -10,8 +10,8 @@ note: required by a bound in `is_maybe_transmutable` LL | pub fn is_maybe_transmutable<Src, Dst>() | --------------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { Assume::SAFETY.and(Assume::VALIDITY) }> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_maybe_transmutable` +LL | Dst: TransmuteFrom<Src, { Assume::SAFETY.and(Assume::VALIDITY) }> + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_maybe_transmutable` error[E0277]: `B` cannot be safely transmuted into `A` --> $DIR/should_reject_disjoint.rs:33:40 @@ -25,8 +25,8 @@ note: required by a bound in `is_maybe_transmutable` LL | pub fn is_maybe_transmutable<Src, Dst>() | --------------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { Assume::SAFETY.and(Assume::VALIDITY) }> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_maybe_transmutable` +LL | Dst: TransmuteFrom<Src, { Assume::SAFETY.and(Assume::VALIDITY) }> + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_maybe_transmutable` error: aborting due to 2 previous errors diff --git a/tests/ui/transmutability/unions/should_reject_intersecting.rs b/tests/ui/transmutability/unions/should_reject_intersecting.rs index 752a606c861..9b3b18919f5 100644 --- a/tests/ui/transmutability/unions/should_reject_intersecting.rs +++ b/tests/ui/transmutability/unions/should_reject_intersecting.rs @@ -6,11 +6,11 @@ #![allow(dead_code, incomplete_features, non_camel_case_types)] mod assert { - use std::mem::{Assume, BikeshedIntrinsicFrom}; + use std::mem::{Assume, TransmuteFrom}; pub fn is_transmutable<Src, Dst>() where - Dst: BikeshedIntrinsicFrom<Src, { Assume::SAFETY }> + Dst: TransmuteFrom<Src, { Assume::SAFETY }> // validity is NOT assumed -----^^^^^^^^^^^^^^^^^^ {} } diff --git a/tests/ui/transmutability/unions/should_reject_intersecting.stderr b/tests/ui/transmutability/unions/should_reject_intersecting.stderr index 79dec659d9d..522681d7d15 100644 --- a/tests/ui/transmutability/unions/should_reject_intersecting.stderr +++ b/tests/ui/transmutability/unions/should_reject_intersecting.stderr @@ -10,8 +10,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { Assume::SAFETY }> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src, { Assume::SAFETY }> + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error[E0277]: `B` cannot be safely transmuted into `A` --> $DIR/should_reject_intersecting.rs:36:34 @@ -25,8 +25,8 @@ note: required by a bound in `is_transmutable` LL | pub fn is_transmutable<Src, Dst>() | --------------- required by a bound in this function LL | where -LL | Dst: BikeshedIntrinsicFrom<Src, { Assume::SAFETY }> - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` +LL | Dst: TransmuteFrom<Src, { Assume::SAFETY }> + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_transmutable` error: aborting due to 2 previous errors |
