diff options
616 files changed, 4382 insertions, 3387 deletions
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f166e0c0b41..96c0955e871 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -68,6 +68,7 @@ jobs: timeout-minutes: 360 env: CI_JOB_NAME: ${{ matrix.name }} + CI_JOB_DOC_URL: ${{ matrix.doc_url }} CARGO_REGISTRIES_CRATES_IO_PROTOCOL: sparse # commit of PR sha or commit sha. `GITHUB_SHA` is not accurate for PRs. HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} @@ -190,8 +191,20 @@ jobs: CARGO_INCREMENTAL=0 CARGO_TARGET_DIR=../../../build/citool cargo build - name: run the build - # Redirect stderr to stdout to avoid reordering the two streams in the GHA logs. - run: src/ci/scripts/run-build-from-ci.sh 2>&1 + run: | + set +e + # Redirect stderr to stdout to avoid reordering the two streams in the GHA logs. + src/ci/scripts/run-build-from-ci.sh 2>&1 + STATUS=$? + set -e + + if [[ "$STATUS" -ne 0 && -n "$CI_JOB_DOC_URL" ]]; then + echo "****************************************************************************" + echo "To find more information about this job, visit the following URL:" + echo "$CI_JOB_DOC_URL" + echo "****************************************************************************" + fi + exit ${STATUS} env: AWS_ACCESS_KEY_ID: ${{ env.CACHES_AWS_ACCESS_KEY_ID }} AWS_SECRET_ACCESS_KEY: ${{ secrets[format('AWS_SECRET_ACCESS_KEY_{0}', env.CACHES_AWS_ACCESS_KEY_ID)] }} diff --git a/.github/workflows/post-merge.yml b/.github/workflows/post-merge.yml index 31e075f45d6..de31c28cc90 100644 --- a/.github/workflows/post-merge.yml +++ b/.github/workflows/post-merge.yml @@ -35,8 +35,13 @@ jobs: cd src/ci/citool - echo "Post-merge analysis result" > output.log + printf "*This is an experimental post-merge analysis report. You can ignore it.*\n\n" > output.log + printf "<details>\n<summary>Post-merge report</summary>\n\n" >> output.log + cargo run --release post-merge-report ${PARENT_COMMIT} ${{ github.sha }} >> output.log + + printf "</details>\n" >> output.log + cat output.log gh pr comment ${HEAD_PR} -F output.log diff --git a/Cargo.lock b/Cargo.lock index 942f8f43935..85f588f8e8a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1548,16 +1548,14 @@ dependencies = [ [[package]] name = "html5ever" -version = "0.27.0" +version = "0.29.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c13771afe0e6e846f1e67d038d4cb29998a6779f93c809212e4e9c32efd244d4" +checksum = "9b958f80f0fde8601dc6c08685adc743eecaa046181cebd5a57551468dfc2ddc" dependencies = [ "log", "mac", "markup5ever", - "proc-macro2", - "quote", - "syn 2.0.96", + "match_token", ] [[package]] @@ -2023,7 +2021,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc2f4eb4bc735547cfed7c0a4922cbd04a4655978c09b54f1f7b228750664c34" dependencies = [ "cfg-if", - "windows-targets 0.52.6", + "windows-targets 0.48.5", ] [[package]] @@ -2134,9 +2132,9 @@ checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4" [[package]] name = "markup5ever" -version = "0.12.1" +version = "0.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16ce3abbeba692c8b8441d036ef91aea6df8da2c6b6e21c7e14d3c18e526be45" +checksum = "03a7b81dfb91586d0677086d40a6d755070e0799b71bb897485bac408dfd5c69" dependencies = [ "log", "phf", @@ -2147,6 +2145,17 @@ dependencies = [ ] [[package]] +name = "match_token" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88a9689d8d44bf9964484516275f5cd4c9b59457a6940c1d5d0ecbb94510a36b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.96", +] + +[[package]] name = "matchers" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -2628,7 +2637,7 @@ version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" dependencies = [ - "phf_shared 0.11.3", + "phf_shared", ] [[package]] @@ -2637,18 +2646,8 @@ version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aef8048c789fa5e851558d709946d6d79a8ff88c0440c587967f8e94bfb1216a" dependencies = [ - "phf_generator 0.11.3", - "phf_shared 0.11.3", -] - -[[package]] -name = "phf_generator" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d5285893bb5eb82e6aaf5d59ee909a06a16737a8970984dd7746ba9283498d6" -dependencies = [ - "phf_shared 0.10.0", - "rand 0.8.5", + "phf_generator", + "phf_shared", ] [[package]] @@ -2657,26 +2656,17 @@ version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" dependencies = [ - "phf_shared 0.11.3", + "phf_shared", "rand 0.8.5", ] [[package]] name = "phf_shared" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6796ad771acdc0123d2a88dc428b5e38ef24456743ddb1744ed628f9815c096" -dependencies = [ - "siphasher 0.3.11", -] - -[[package]] -name = "phf_shared" version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" dependencies = [ - "siphasher 1.0.1", + "siphasher", ] [[package]] @@ -3440,7 +3430,6 @@ dependencies = [ "rustc_symbol_mangling", "rustc_target", "rustc_trait_selection", - "rustc_type_ir", "serde_json", "smallvec", "tempfile", @@ -3473,7 +3462,6 @@ dependencies = [ "rustc_span", "rustc_target", "rustc_trait_selection", - "rustc_type_ir", "tracing", ] @@ -3736,7 +3724,6 @@ dependencies = [ "rustc_span", "rustc_target", "rustc_trait_selection", - "rustc_type_ir", "smallvec", "tracing", ] @@ -3775,7 +3762,6 @@ dependencies = [ "rustc_session", "rustc_span", "rustc_trait_selection", - "rustc_type_ir", "smallvec", "tracing", ] @@ -3922,7 +3908,6 @@ dependencies = [ "rustc_span", "rustc_target", "rustc_trait_selection", - "rustc_type_ir", "smallvec", "tracing", "unicode-security", @@ -3998,7 +3983,6 @@ dependencies = [ "rustc_session", "rustc_span", "rustc_target", - "rustc_type_ir", "tempfile", "tracing", ] @@ -4114,7 +4098,6 @@ dependencies = [ "rustc_span", "rustc_target", "rustc_trait_selection", - "rustc_type_ir", "smallvec", "tracing", ] @@ -4538,7 +4521,6 @@ dependencies = [ "rustc_span", "rustc_target", "rustc_trait_selection", - "rustc_type_ir", "tracing", ] @@ -4871,12 +4853,6 @@ checksum = "1de1d4f81173b03af4c0cbed3c898f6bff5b870e4a7f5d6f4057d62a7a4b686e" [[package]] name = "siphasher" -version = "0.3.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d" - -[[package]] -name = "siphasher" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "56199f7ddabf13fe5074ce809e7d3f42b42ae711800501b5b16ea82ad029c39d" @@ -4989,26 +4965,25 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "string_cache" -version = "0.8.7" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f91138e76242f575eb1d3b38b4f1362f10d3a43f47d182a5b359af488a02293b" +checksum = "938d512196766101d333398efde81bc1f37b00cb42c2f8350e5df639f040bbbe" dependencies = [ "new_debug_unreachable", - "once_cell", "parking_lot", - "phf_shared 0.10.0", + "phf_shared", "precomputed-hash", "serde", ] [[package]] name = "string_cache_codegen" -version = "0.5.2" +version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6bb30289b722be4ff74a408c3cc27edeaad656e06cb1fe8fa9231fa59c728988" +checksum = "c711928715f1fe0fe509c53b43e993a9a557babc2d0a3567d0a3006f1ac931a0" dependencies = [ - "phf_generator 0.10.0", - "phf_shared 0.10.0", + "phf_generator", + "phf_shared", "proc-macro2", "quote", ] @@ -6439,6 +6414,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e9df38ee2d2c3c5948ea468a8406ff0db0b29ae1ffde1bcf20ef305bcc95c51" [[package]] +name = "x" +version = "0.1.1" + +[[package]] name = "xattr" version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" diff --git a/Cargo.toml b/Cargo.toml index 915ec2e00ca..16ff0f61593 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,50 +1,53 @@ [workspace] resolver = "2" members = [ +# tidy-alphabetical-start "compiler/rustc", "src/build_helper", "src/etc/test-float-parse", - "src/rustc-std-workspace/rustc-std-workspace-core", "src/rustc-std-workspace/rustc-std-workspace-alloc", + "src/rustc-std-workspace/rustc-std-workspace-core", "src/rustc-std-workspace/rustc-std-workspace-std", "src/rustdoc-json-types", + "src/tools/build-manifest", + "src/tools/bump-stage0", "src/tools/cargotest", "src/tools/clippy", "src/tools/clippy/clippy_dev", + "src/tools/collect-license-metadata", "src/tools/compiletest", - "src/tools/run-make-support", + "src/tools/coverage-dump", + "src/tools/features-status-dump", + "src/tools/generate-copyright", + "src/tools/generate-windows-sys", + "src/tools/html-checker", + "src/tools/jsondocck", + "src/tools/jsondoclint", "src/tools/linkchecker", "src/tools/lint-docs", + "src/tools/lld-wrapper", + "src/tools/llvm-bitcode-linker", + "src/tools/miri", + "src/tools/miri/cargo-miri", "src/tools/miropt-test-tools", - "src/tools/unstable-book-gen", - "src/tools/tidy", - "src/tools/tier-check", - "src/tools/build-manifest", + "src/tools/opt-dist", "src/tools/remote-test-client", "src/tools/remote-test-server", + "src/tools/replace-version-placeholder", + "src/tools/run-make-support", "src/tools/rust-installer", "src/tools/rustdoc", - "src/tools/rustfmt", - "src/tools/miri", - "src/tools/miri/cargo-miri", + "src/tools/rustdoc-gui-test", "src/tools/rustdoc-themes", - "src/tools/unicode-table-generator", - "src/tools/jsondocck", - "src/tools/jsondoclint", - "src/tools/llvm-bitcode-linker", - "src/tools/html-checker", - "src/tools/bump-stage0", - "src/tools/replace-version-placeholder", - "src/tools/lld-wrapper", - "src/tools/collect-license-metadata", - "src/tools/generate-copyright", + "src/tools/rustfmt", "src/tools/suggest-tests", - "src/tools/generate-windows-sys", - "src/tools/rustdoc-gui-test", - "src/tools/opt-dist", - "src/tools/coverage-dump", + "src/tools/tidy", + "src/tools/tier-check", + "src/tools/unicode-table-generator", + "src/tools/unstable-book-gen", "src/tools/wasm-component-ld", - "src/tools/features-status-dump", + "src/tools/x", +# tidy-alphabetical-end ] exclude = [ @@ -55,11 +58,6 @@ exclude = [ "tests/rustdoc-gui", # HACK(eddyb) This hardcodes the fact that our CI uses `/checkout/obj`. "obj", - # The `x` binary is a thin wrapper that calls `x.py`, which initializes - # submodules, before which workspace members cannot be invoked because - # not all `Cargo.toml` files are available, so we exclude the `x` binary, - # so it can be invoked before the current checkout is set up. - "src/tools/x", ] [profile.release.package.rustc-rayon-core] diff --git a/compiler/rustc_abi/src/lib.rs b/compiler/rustc_abi/src/lib.rs index d2f663999ba..3f28dc7a1ef 100644 --- a/compiler/rustc_abi/src/lib.rs +++ b/compiler/rustc_abi/src/lib.rs @@ -52,7 +52,7 @@ use rustc_data_structures::stable_hasher::StableOrd; use rustc_hashes::Hash64; use rustc_index::{Idx, IndexSlice, IndexVec}; #[cfg(feature = "nightly")] -use rustc_macros::{Decodable_Generic, Encodable_Generic, HashStable_Generic}; +use rustc_macros::{Decodable_NoContext, Encodable_NoContext, HashStable_Generic}; mod callconv; mod layout; @@ -74,7 +74,10 @@ pub use layout::{LayoutCalculator, LayoutCalculatorError}; pub trait HashStableContext {} #[derive(Clone, Copy, PartialEq, Eq, Default)] -#[cfg_attr(feature = "nightly", derive(Encodable_Generic, Decodable_Generic, HashStable_Generic))] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_Generic) +)] pub struct ReprFlags(u8); bitflags! { @@ -106,7 +109,10 @@ impl std::fmt::Debug for ReprFlags { } #[derive(Copy, Clone, Debug, Eq, PartialEq)] -#[cfg_attr(feature = "nightly", derive(Encodable_Generic, Decodable_Generic, HashStable_Generic))] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_Generic) +)] pub enum IntegerType { /// Pointer-sized integer type, i.e. `isize` and `usize`. The field shows signedness, e.g. /// `Pointer(true)` means `isize`. @@ -127,7 +133,10 @@ impl IntegerType { /// Represents the repr options provided by the user. #[derive(Copy, Clone, Debug, Eq, PartialEq, Default)] -#[cfg_attr(feature = "nightly", derive(Encodable_Generic, Decodable_Generic, HashStable_Generic))] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_Generic) +)] pub struct ReprOptions { pub int: Option<IntegerType>, pub align: Option<Align>, @@ -487,7 +496,10 @@ impl FromStr for Endian { /// Size of a type in bytes. #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[cfg_attr(feature = "nightly", derive(Encodable_Generic, Decodable_Generic, HashStable_Generic))] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_Generic) +)] pub struct Size { raw: u64, } @@ -713,7 +725,10 @@ impl Step for Size { /// Alignment of a type in bytes (always a power of two). #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[cfg_attr(feature = "nightly", derive(Encodable_Generic, Decodable_Generic, HashStable_Generic))] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_Generic) +)] pub struct Align { pow2: u8, } @@ -872,7 +887,10 @@ impl AbiAndPrefAlign { /// Integers, also used for enum discriminants. #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] -#[cfg_attr(feature = "nightly", derive(Encodable_Generic, Decodable_Generic, HashStable_Generic))] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_Generic) +)] pub enum Integer { I8, I16, diff --git a/compiler/rustc_ast_ir/src/lib.rs b/compiler/rustc_ast_ir/src/lib.rs index 6d05cd18cec..0898433a74c 100644 --- a/compiler/rustc_ast_ir/src/lib.rs +++ b/compiler/rustc_ast_ir/src/lib.rs @@ -12,14 +12,17 @@ // tidy-alphabetical-end #[cfg(feature = "nightly")] -use rustc_macros::{Decodable, Encodable, HashStable_NoContext}; +use rustc_macros::{Decodable_NoContext, Encodable_NoContext, HashStable_NoContext}; pub mod visit; /// The movability of a coroutine / closure literal: /// whether a coroutine contains self-references, causing it to be `!Unpin`. #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy)] -#[cfg_attr(feature = "nightly", derive(Encodable, Decodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) +)] pub enum Movability { /// May contain self-references, `!Unpin`. Static, @@ -28,7 +31,10 @@ pub enum Movability { } #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy)] -#[cfg_attr(feature = "nightly", derive(Encodable, Decodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) +)] pub enum Mutability { // N.B. Order is deliberate, so that Not < Mut Not, @@ -87,7 +93,10 @@ impl Mutability { } #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy)] -#[cfg_attr(feature = "nightly", derive(Encodable, Decodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) +)] pub enum Pinnedness { Not, Pinned, diff --git a/compiler/rustc_ast_lowering/src/delegation.rs b/compiler/rustc_ast_lowering/src/delegation.rs index 946f2cafa15..efc1fa05c5f 100644 --- a/compiler/rustc_ast_lowering/src/delegation.rs +++ b/compiler/rustc_ast_lowering/src/delegation.rs @@ -190,14 +190,19 @@ impl<'hir> LoweringContext<'_, 'hir> { ) -> hir::FnSig<'hir> { let header = if let Some(local_sig_id) = sig_id.as_local() { match self.resolver.delegation_fn_sigs.get(&local_sig_id) { - Some(sig) => self.lower_fn_header( - sig.header, + Some(sig) => { + let parent = self.tcx.parent(sig_id); // HACK: we override the default safety instead of generating attributes from the ether. // We are not forwarding the attributes, as the delegation fn sigs are collected on the ast, // and here we need the hir attributes. - if sig.target_feature { hir::Safety::Unsafe } else { hir::Safety::Safe }, - &[], - ), + let default_safety = + if sig.target_feature || self.tcx.def_kind(parent) == DefKind::ForeignMod { + hir::Safety::Unsafe + } else { + hir::Safety::Safe + }; + self.lower_fn_header(sig.header, default_safety, &[]) + } None => self.generate_header_error(), } } else { diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index c7d37e2704d..df671cf4b86 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -1516,7 +1516,14 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { fn lower_fn_params_to_names(&mut self, decl: &FnDecl) -> &'hir [Ident] { self.arena.alloc_from_iter(decl.inputs.iter().map(|param| match param.pat.kind { PatKind::Ident(_, ident, _) => self.lower_ident(ident), - _ => Ident::new(kw::Empty, self.lower_span(param.pat.span)), + PatKind::Wild => Ident::new(kw::Underscore, self.lower_span(param.pat.span)), + _ => { + self.dcx().span_delayed_bug( + param.pat.span, + "non-ident/wild param pat must trigger an error", + ); + Ident::new(kw::Empty, self.lower_span(param.pat.span)) + } })) } diff --git a/compiler/rustc_borrowck/src/diagnostics/region_errors.rs b/compiler/rustc_borrowck/src/diagnostics/region_errors.rs index 55b6367f35f..6b11f1a3681 100644 --- a/compiler/rustc_borrowck/src/diagnostics/region_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/region_errors.rs @@ -14,9 +14,8 @@ use rustc_infer::infer::{NllRegionVariableOrigin, RelateParamBound}; use rustc_middle::bug; use rustc_middle::hir::place::PlaceBase; use rustc_middle::mir::{AnnotationSource, ConstraintCategory, ReturnConstraint}; -use rustc_middle::ty::fold::fold_regions; use rustc_middle::ty::{ - self, GenericArgs, Region, RegionVid, Ty, TyCtxt, TypeFoldable, TypeVisitor, + self, GenericArgs, Region, RegionVid, Ty, TyCtxt, TypeFoldable, TypeVisitor, fold_regions, }; use rustc_span::{Ident, Span, kw}; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs index 7ae7936a2a2..07b3f3477a8 100644 --- a/compiler/rustc_borrowck/src/lib.rs +++ b/compiler/rustc_borrowck/src/lib.rs @@ -35,8 +35,7 @@ use rustc_infer::infer::{ }; use rustc_middle::mir::*; use rustc_middle::query::Providers; -use rustc_middle::ty::fold::fold_regions; -use rustc_middle::ty::{self, ParamEnv, RegionVid, TyCtxt, TypingMode}; +use rustc_middle::ty::{self, ParamEnv, RegionVid, TyCtxt, TypingMode, fold_regions}; use rustc_middle::{bug, span_bug}; use rustc_mir_dataflow::impls::{ EverInitializedPlaces, MaybeInitializedPlaces, MaybeUninitializedPlaces, diff --git a/compiler/rustc_borrowck/src/region_infer/mod.rs b/compiler/rustc_borrowck/src/region_infer/mod.rs index bb209a95711..a80d74d9e37 100644 --- a/compiler/rustc_borrowck/src/region_infer/mod.rs +++ b/compiler/rustc_borrowck/src/region_infer/mod.rs @@ -18,8 +18,7 @@ use rustc_middle::mir::{ ReturnConstraint, TerminatorKind, }; use rustc_middle::traits::{ObligationCause, ObligationCauseCode}; -use rustc_middle::ty::fold::fold_regions; -use rustc_middle::ty::{self, RegionVid, Ty, TyCtxt, TypeFoldable, UniverseIndex}; +use rustc_middle::ty::{self, RegionVid, Ty, TyCtxt, TypeFoldable, UniverseIndex, fold_regions}; use rustc_mir_dataflow::points::DenseLocationMap; use rustc_span::hygiene::DesugaringKind; use rustc_span::{DUMMY_SP, Span}; diff --git a/compiler/rustc_borrowck/src/region_infer/opaque_types.rs b/compiler/rustc_borrowck/src/region_infer/opaque_types.rs index 54f9e82dbb8..04839448596 100644 --- a/compiler/rustc_borrowck/src/region_infer/opaque_types.rs +++ b/compiler/rustc_borrowck/src/region_infer/opaque_types.rs @@ -5,11 +5,9 @@ use rustc_hir::def_id::LocalDefId; use rustc_infer::infer::outlives::env::OutlivesEnvironment; use rustc_infer::infer::{InferCtxt, NllRegionVariableOrigin, TyCtxtInferExt as _}; use rustc_macros::extension; -use rustc_middle::ty::fold::fold_regions; -use rustc_middle::ty::visit::TypeVisitableExt; use rustc_middle::ty::{ self, GenericArgKind, GenericArgs, OpaqueHiddenType, OpaqueTypeKey, Ty, TyCtxt, TypeFoldable, - TypingMode, + TypeVisitableExt, TypingMode, fold_regions, }; use rustc_span::Span; use rustc_trait_selection::regions::OutlivesEnvironmentBuildExt; diff --git a/compiler/rustc_borrowck/src/renumber.rs b/compiler/rustc_borrowck/src/renumber.rs index e355d2b415b..ff92b4168a8 100644 --- a/compiler/rustc_borrowck/src/renumber.rs +++ b/compiler/rustc_borrowck/src/renumber.rs @@ -2,8 +2,7 @@ use rustc_index::IndexSlice; use rustc_infer::infer::NllRegionVariableOrigin; use rustc_middle::mir::visit::{MutVisitor, TyContext}; use rustc_middle::mir::{Body, ConstOperand, Location, Promoted}; -use rustc_middle::ty::fold::fold_regions; -use rustc_middle::ty::{self, GenericArgsRef, Ty, TyCtxt, TypeFoldable}; +use rustc_middle::ty::{self, GenericArgsRef, Ty, TyCtxt, TypeFoldable, fold_regions}; use rustc_span::Symbol; use tracing::{debug, instrument}; diff --git a/compiler/rustc_borrowck/src/type_check/constraint_conversion.rs b/compiler/rustc_borrowck/src/type_check/constraint_conversion.rs index 8dff40ba6ac..6fbe1db6330 100644 --- a/compiler/rustc_borrowck/src/type_check/constraint_conversion.rs +++ b/compiler/rustc_borrowck/src/type_check/constraint_conversion.rs @@ -7,8 +7,9 @@ use rustc_infer::infer::{self, InferCtxt, SubregionOrigin}; use rustc_infer::traits::query::type_op::DeeplyNormalize; use rustc_middle::bug; use rustc_middle::mir::{ClosureOutlivesSubject, ClosureRegionRequirements, ConstraintCategory}; -use rustc_middle::ty::fold::fold_regions; -use rustc_middle::ty::{self, GenericArgKind, Ty, TyCtxt, TypeFoldable, TypeVisitableExt}; +use rustc_middle::ty::{ + self, GenericArgKind, Ty, TyCtxt, TypeFoldable, TypeVisitableExt, fold_regions, +}; use rustc_span::Span; use rustc_trait_selection::traits::query::type_op::{TypeOp, TypeOpOutput}; use tracing::{debug, instrument}; diff --git a/compiler/rustc_borrowck/src/type_check/liveness/mod.rs b/compiler/rustc_borrowck/src/type_check/liveness/mod.rs index f17ad23f4bf..b7a21cf48c8 100644 --- a/compiler/rustc_borrowck/src/type_check/liveness/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/liveness/mod.rs @@ -4,8 +4,7 @@ use rustc_middle::mir::visit::{TyContext, Visitor}; use rustc_middle::mir::{Body, Local, Location, SourceInfo}; use rustc_middle::span_bug; use rustc_middle::ty::relate::Relate; -use rustc_middle::ty::visit::TypeVisitable; -use rustc_middle::ty::{GenericArgsRef, Region, RegionVid, Ty, TyCtxt}; +use rustc_middle::ty::{GenericArgsRef, Region, RegionVid, Ty, TyCtxt, TypeVisitable}; use rustc_mir_dataflow::ResultsCursor; use rustc_mir_dataflow::impls::MaybeInitializedPlaces; use rustc_mir_dataflow::move_paths::MoveData; diff --git a/compiler/rustc_borrowck/src/type_check/mod.rs b/compiler/rustc_borrowck/src/type_check/mod.rs index d2eb7a52f78..0fda3e31690 100644 --- a/compiler/rustc_borrowck/src/type_check/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/mod.rs @@ -24,12 +24,10 @@ use rustc_middle::mir::*; use rustc_middle::traits::query::NoSolution; use rustc_middle::ty::adjustment::PointerCoercion; use rustc_middle::ty::cast::CastTy; -use rustc_middle::ty::fold::fold_regions; -use rustc_middle::ty::visit::TypeVisitableExt; use rustc_middle::ty::{ self, Binder, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, CoroutineArgsExt, - Dynamic, GenericArgsRef, OpaqueHiddenType, OpaqueTypeKey, RegionVid, Ty, TyCtxt, UserArgs, - UserTypeAnnotationIndex, + Dynamic, GenericArgsRef, OpaqueHiddenType, OpaqueTypeKey, RegionVid, Ty, TyCtxt, + TypeVisitableExt, UserArgs, UserTypeAnnotationIndex, fold_regions, }; use rustc_middle::{bug, span_bug}; use rustc_mir_dataflow::ResultsCursor; @@ -1773,6 +1771,22 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { { span_mirbug!(self, constant, "bad static type {:?} ({:?})", constant, terr); } + } else if let Const::Ty(_, ct) = constant.const_ + && let ty::ConstKind::Param(p) = ct.kind() + { + let body_def_id = self.universal_regions.defining_ty.def_id(); + let const_param = tcx.generics_of(body_def_id).const_param(p, tcx); + self.ascribe_user_type( + constant.const_.ty(), + ty::UserType::new(ty::UserTypeKind::TypeOf( + const_param.def_id, + UserArgs { + args: self.universal_regions.defining_ty.args(), + user_self_ty: None, + }, + )), + locations.span(self.body), + ); } if let ty::FnDef(def_id, args) = *constant.const_.ty().kind() { diff --git a/compiler/rustc_borrowck/src/type_check/opaque_types.rs b/compiler/rustc_borrowck/src/type_check/opaque_types.rs index 94b3d0c2bbf..8bab979a724 100644 --- a/compiler/rustc_borrowck/src/type_check/opaque_types.rs +++ b/compiler/rustc_borrowck/src/type_check/opaque_types.rs @@ -2,10 +2,9 @@ use std::iter; use rustc_data_structures::fx::FxIndexMap; use rustc_middle::span_bug; -use rustc_middle::ty::fold::fold_regions; use rustc_middle::ty::{ self, GenericArgKind, OpaqueHiddenType, OpaqueTypeKey, Ty, TyCtxt, TypeSuperVisitable, - TypeVisitable, TypeVisitableExt, TypeVisitor, + TypeVisitable, TypeVisitableExt, TypeVisitor, fold_regions, }; use tracing::{debug, trace}; diff --git a/compiler/rustc_borrowck/src/type_check/relate_tys.rs b/compiler/rustc_borrowck/src/type_check/relate_tys.rs index 59e2eee41d3..02a41469c97 100644 --- a/compiler/rustc_borrowck/src/type_check/relate_tys.rs +++ b/compiler/rustc_borrowck/src/type_check/relate_tys.rs @@ -10,9 +10,8 @@ use rustc_middle::mir::ConstraintCategory; use rustc_middle::span_bug; use rustc_middle::traits::ObligationCause; use rustc_middle::traits::query::NoSolution; -use rustc_middle::ty::fold::FnMutDelegate; use rustc_middle::ty::relate::combine::{super_combine_consts, super_combine_tys}; -use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt}; +use rustc_middle::ty::{self, FnMutDelegate, Ty, TyCtxt, TypeVisitableExt}; use rustc_span::{Span, Symbol, sym}; use tracing::{debug, instrument}; diff --git a/compiler/rustc_borrowck/src/universal_regions.rs b/compiler/rustc_borrowck/src/universal_regions.rs index cfac9b36832..8f6b405fcef 100644 --- a/compiler/rustc_borrowck/src/universal_regions.rs +++ b/compiler/rustc_borrowck/src/universal_regions.rs @@ -27,11 +27,10 @@ use rustc_hir::lang_items::LangItem; use rustc_index::IndexVec; use rustc_infer::infer::NllRegionVariableOrigin; use rustc_macros::extension; -use rustc_middle::ty::fold::{TypeFoldable, fold_regions}; use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_middle::ty::{ self, GenericArgs, GenericArgsRef, InlineConstArgs, InlineConstArgsParts, RegionVid, Ty, - TyCtxt, TypeVisitableExt, + TyCtxt, TypeFoldable, TypeVisitableExt, fold_regions, }; use rustc_middle::{bug, span_bug}; use rustc_span::{ErrorGuaranteed, kw, sym}; @@ -184,6 +183,20 @@ impl<'tcx> DefiningTy<'tcx> { | DefiningTy::GlobalAsm(def_id) => def_id, } } + + /// Returns the args of the `DefiningTy`. These are equivalent to the identity + /// substs of the body, but replaced with region vids. + pub(crate) fn args(&self) -> ty::GenericArgsRef<'tcx> { + match *self { + DefiningTy::Closure(_, args) + | DefiningTy::Coroutine(_, args) + | DefiningTy::CoroutineClosure(_, args) + | DefiningTy::FnDef(_, args) + | DefiningTy::Const(_, args) + | DefiningTy::InlineConst(_, args) => args, + DefiningTy::GlobalAsm(_) => ty::List::empty(), + } + } } #[derive(Debug)] diff --git a/compiler/rustc_codegen_cranelift/patches/0027-stdlib-128bit-atomic-operations.patch b/compiler/rustc_codegen_cranelift/patches/0027-stdlib-128bit-atomic-operations.patch index 3c81b04c0ea..d7e3b11127c 100644 --- a/compiler/rustc_codegen_cranelift/patches/0027-stdlib-128bit-atomic-operations.patch +++ b/compiler/rustc_codegen_cranelift/patches/0027-stdlib-128bit-atomic-operations.patch @@ -1,4 +1,4 @@ -From ad7ffe71baba46865f2e65266ab025920dfdc20b Mon Sep 17 00:00:00 2001 +From 5d7c709608b01301d4628d2159265936d4440b67 Mon Sep 17 00:00:00 2001 From: bjorn3 <bjorn3@users.noreply.github.com> Date: Thu, 18 Feb 2021 18:45:28 +0100 Subject: [PATCH] Disable 128bit atomic operations @@ -7,11 +7,10 @@ Cranelift doesn't support them yet --- library/core/src/panic/unwind_safe.rs | 6 ----- library/core/src/sync/atomic.rs | 38 --------------------------- - library/core/tests/atomic.rs | 4 --- - 4 files changed, 4 insertions(+), 50 deletions(-) + 2 files changed, 44 deletions(-) diff --git a/library/core/src/panic/unwind_safe.rs b/library/core/src/panic/unwind_safe.rs -index 092b7cf..158cf71 100644 +index a60f0799c0e..af056fbf41f 100644 --- a/library/core/src/panic/unwind_safe.rs +++ b/library/core/src/panic/unwind_safe.rs @@ -216,9 +216,6 @@ impl RefUnwindSafe for crate::sync::atomic::AtomicI32 {} @@ -21,7 +20,7 @@ index 092b7cf..158cf71 100644 -#[cfg(target_has_atomic_load_store = "128")] -#[unstable(feature = "integer_atomics", issue = "99069")] -impl RefUnwindSafe for crate::sync::atomic::AtomicI128 {} - + #[cfg(target_has_atomic_load_store = "ptr")] #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")] @@ -235,9 +232,6 @@ impl RefUnwindSafe for crate::sync::atomic::AtomicU32 {} @@ -31,14 +30,14 @@ index 092b7cf..158cf71 100644 -#[cfg(target_has_atomic_load_store = "128")] -#[unstable(feature = "integer_atomics", issue = "99069")] -impl RefUnwindSafe for crate::sync::atomic::AtomicU128 {} - + #[cfg(target_has_atomic_load_store = "8")] #[stable(feature = "unwind_safe_atomic_refs", since = "1.14.0")] diff --git a/library/core/src/sync/atomic.rs b/library/core/src/sync/atomic.rs -index d9de37e..8293fce 100644 +index bf2b6d59f88..d5ccce03bbf 100644 --- a/library/core/src/sync/atomic.rs +++ b/library/core/src/sync/atomic.rs -@@ -2996,44 +2996,6 @@ atomic_int! { +@@ -3585,44 +3585,6 @@ pub const fn as_ptr(&self) -> *mut $int_type { 8, u64 AtomicU64 } @@ -54,7 +53,7 @@ index d9de37e..8293fce 100644 - unstable(feature = "integer_atomics", issue = "99069"), - rustc_const_unstable(feature = "integer_atomics", issue = "99069"), - rustc_const_unstable(feature = "integer_atomics", issue = "99069"), -- cfg_attr(not(test), rustc_diagnostic_item = "AtomicI128"), +- rustc_diagnostic_item = "AtomicI128", - "i128", - "#![feature(integer_atomics)]\n\n", - atomic_min, atomic_max, @@ -73,7 +72,7 @@ index d9de37e..8293fce 100644 - unstable(feature = "integer_atomics", issue = "99069"), - rustc_const_unstable(feature = "integer_atomics", issue = "99069"), - rustc_const_unstable(feature = "integer_atomics", issue = "99069"), -- cfg_attr(not(test), rustc_diagnostic_item = "AtomicU128"), +- rustc_diagnostic_item = "AtomicU128", - "u128", - "#![feature(integer_atomics)]\n\n", - atomic_umin, atomic_umax, @@ -83,7 +82,6 @@ index d9de37e..8293fce 100644 #[cfg(target_has_atomic_load_store = "ptr")] macro_rules! atomic_int_ptr_sized { - ( $($target_pointer_width:literal $align:literal)* ) => { $( --- -2.26.2.7.g19db9cfb68 +-- +2.48.1 diff --git a/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs b/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs index 6735ae024d1..75f3a3c1972 100644 --- a/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs +++ b/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs @@ -1031,7 +1031,7 @@ fn codegen_regular_intrinsic_call<'tcx>( let layout = src.layout(); match layout.ty.kind() { - ty::Uint(_) | ty::Int(_) | ty::RawPtr(..) => {} + ty::Int(_) => {} _ => { report_atomic_type_validation_error(fx, intrinsic, source_info.span, layout.ty); return Ok(()); @@ -1052,7 +1052,7 @@ fn codegen_regular_intrinsic_call<'tcx>( let layout = src.layout(); match layout.ty.kind() { - ty::Uint(_) | ty::Int(_) | ty::RawPtr(..) => {} + ty::Uint(_) => {} _ => { report_atomic_type_validation_error(fx, intrinsic, source_info.span, layout.ty); return Ok(()); @@ -1073,7 +1073,7 @@ fn codegen_regular_intrinsic_call<'tcx>( let layout = src.layout(); match layout.ty.kind() { - ty::Uint(_) | ty::Int(_) | ty::RawPtr(..) => {} + ty::Int(_) => {} _ => { report_atomic_type_validation_error(fx, intrinsic, source_info.span, layout.ty); return Ok(()); @@ -1094,7 +1094,7 @@ fn codegen_regular_intrinsic_call<'tcx>( let layout = src.layout(); match layout.ty.kind() { - ty::Uint(_) | ty::Int(_) | ty::RawPtr(..) => {} + ty::Uint(_) => {} _ => { report_atomic_type_validation_error(fx, intrinsic, source_info.span, layout.ty); return Ok(()); diff --git a/compiler/rustc_codegen_ssa/Cargo.toml b/compiler/rustc_codegen_ssa/Cargo.toml index 1346efcb87c..caa1db8274d 100644 --- a/compiler/rustc_codegen_ssa/Cargo.toml +++ b/compiler/rustc_codegen_ssa/Cargo.toml @@ -40,7 +40,6 @@ rustc_span = { path = "../rustc_span" } rustc_symbol_mangling = { path = "../rustc_symbol_mangling" } rustc_target = { path = "../rustc_target" } rustc_trait_selection = { path = "../rustc_trait_selection" } -rustc_type_ir = { path = "../rustc_type_ir" } serde_json = "1.0.59" smallvec = { version = "1.8.1", features = ["union", "may_dangle"] } tempfile = "3.2" diff --git a/compiler/rustc_codegen_ssa/src/back/command.rs b/compiler/rustc_codegen_ssa/src/back/command.rs index 63023fdba20..05351bd6ca3 100644 --- a/compiler/rustc_codegen_ssa/src/back/command.rs +++ b/compiler/rustc_codegen_ssa/src/back/command.rs @@ -137,17 +137,40 @@ impl Command { /// Returns a `true` if we're pretty sure that this'll blow OS spawn limits, /// or `false` if we should attempt to spawn and see what the OS says. pub(crate) fn very_likely_to_exceed_some_spawn_limit(&self) -> bool { - // We mostly only care about Windows in this method, on Unix the limits - // can be gargantuan anyway so we're pretty unlikely to hit them - if cfg!(unix) { + #[cfg(not(any(windows, unix)))] + { return false; } - // Right now LLD doesn't support the `@` syntax of passing an argument - // through files, so regardless of the platform we try to go to the OS - // on this one. - if let Program::Lld(..) = self.program { - return false; + // On Unix the limits can be gargantuan anyway so we're pretty + // unlikely to hit them, but might still exceed it. + // We consult ARG_MAX here to get an estimate. + #[cfg(unix)] + { + let ptr_size = mem::size_of::<usize>(); + // arg + \0 + pointer + let args_size = self.args.iter().fold(0usize, |acc, a| { + let arg = a.as_encoded_bytes().len(); + let nul = 1; + acc.saturating_add(arg).saturating_add(nul).saturating_add(ptr_size) + }); + // key + `=` + value + \0 + pointer + let envs_size = self.env.iter().fold(0usize, |acc, (k, v)| { + let k = k.as_encoded_bytes().len(); + let eq = 1; + let v = v.as_encoded_bytes().len(); + let nul = 1; + acc.saturating_add(k) + .saturating_add(eq) + .saturating_add(v) + .saturating_add(nul) + .saturating_add(ptr_size) + }); + let arg_max = match unsafe { libc::sysconf(libc::_SC_ARG_MAX) } { + -1 => return false, // Go to OS anyway. + max => max as usize, + }; + return args_size.saturating_add(envs_size) > arg_max; } // Ok so on Windows to spawn a process is 32,768 characters in its @@ -172,9 +195,14 @@ impl Command { // // [1]: https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessa // [2]: https://devblogs.microsoft.com/oldnewthing/?p=41553 - - let estimated_command_line_len = self.args.iter().map(|a| a.len()).sum::<usize>(); - estimated_command_line_len > 1024 * 6 + #[cfg(windows)] + { + let estimated_command_line_len = self + .args + .iter() + .fold(0usize, |acc, a| acc.saturating_add(a.as_encoded_bytes().len())); + return estimated_command_line_len > 1024 * 6; + } } } diff --git a/compiler/rustc_codegen_ssa/src/errors.rs b/compiler/rustc_codegen_ssa/src/errors.rs index 394c80fcfbd..0b7cad0c2fd 100644 --- a/compiler/rustc_codegen_ssa/src/errors.rs +++ b/compiler/rustc_codegen_ssa/src/errors.rs @@ -12,10 +12,9 @@ use rustc_errors::{ Diag, DiagArgValue, DiagCtxtHandle, Diagnostic, EmissionGuarantee, IntoDiagArg, Level, }; use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; -use rustc_middle::ty::Ty; use rustc_middle::ty::layout::LayoutError; +use rustc_middle::ty::{FloatTy, Ty}; use rustc_span::{Span, Symbol}; -use rustc_type_ir::FloatTy; use crate::assert_module_sources::CguReuse; use crate::back::command::Command; diff --git a/compiler/rustc_codegen_ssa/src/mir/analyze.rs b/compiler/rustc_codegen_ssa/src/mir/analyze.rs index 23baab3124e..99f35b79208 100644 --- a/compiler/rustc_codegen_ssa/src/mir/analyze.rs +++ b/compiler/rustc_codegen_ssa/src/mir/analyze.rs @@ -205,7 +205,12 @@ impl<'a, 'b, 'tcx, Bx: BuilderMethods<'b, 'tcx>> Visitor<'tcx> for LocalAnalyzer | PlaceContext::MutatingUse(MutatingUseContext::Retag) => {} PlaceContext::NonMutatingUse( - NonMutatingUseContext::Copy | NonMutatingUseContext::Move, + NonMutatingUseContext::Copy + | NonMutatingUseContext::Move + // Inspect covers things like `PtrMetadata` and `Discriminant` + // which we can treat similar to `Copy` use for the purpose of + // whether we can use SSA variables for things. + | NonMutatingUseContext::Inspect, ) => match &mut self.locals[local] { LocalKind::ZST => {} LocalKind::Memory => {} @@ -229,8 +234,7 @@ impl<'a, 'b, 'tcx, Bx: BuilderMethods<'b, 'tcx>> Visitor<'tcx> for LocalAnalyzer | MutatingUseContext::Projection, ) | PlaceContext::NonMutatingUse( - NonMutatingUseContext::Inspect - | NonMutatingUseContext::SharedBorrow + NonMutatingUseContext::SharedBorrow | NonMutatingUseContext::FakeBorrow | NonMutatingUseContext::RawBorrow | NonMutatingUseContext::Projection, diff --git a/compiler/rustc_codegen_ssa/src/mir/constant.rs b/compiler/rustc_codegen_ssa/src/mir/constant.rs index eafc551501c..68a56044a07 100644 --- a/compiler/rustc_codegen_ssa/src/mir/constant.rs +++ b/compiler/rustc_codegen_ssa/src/mir/constant.rs @@ -43,7 +43,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { mir::Const::Ty(_, c) => match c.kind() { // A constant that came from a const generic but was then used as an argument to // old-style simd_shuffle (passing as argument instead of as a generic param). - rustc_type_ir::ConstKind::Value(cv) => return Ok(Ok(cv.valtree)), + ty::ConstKind::Value(cv) => return Ok(Ok(cv.valtree)), other => span_bug!(constant.span, "{other:#?}"), }, // We should never encounter `Const::Val` unless MIR opts (like const prop) evaluate diff --git a/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs b/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs index b34e966ba6c..63025a4574f 100644 --- a/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs +++ b/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs @@ -62,7 +62,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { let callee_ty = instance.ty(bx.tcx(), bx.typing_env()); let ty::FnDef(def_id, fn_args) = *callee_ty.kind() else { - bug!("expected fn item type, found {}", callee_ty); + span_bug!(span, "expected fn item type, found {}", callee_ty); }; let sig = callee_ty.fn_sig(bx.tcx()); @@ -325,14 +325,6 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { } } - sym::discriminant_value => { - if ret_ty.is_integral() { - args[0].deref(bx.cx()).codegen_get_discr(bx, ret_ty) - } else { - span_bug!(span, "Invalid discriminant type for `{:?}`", arg_tys[0]) - } - } - // This requires that atomic intrinsics follow a specific naming pattern: // "atomic_<operation>[_<ordering>]" name if let Some(atomic) = name_str.strip_prefix("atomic_") => { @@ -441,6 +433,40 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { } // These are all AtomicRMW ops + "max" | "min" => { + let atom_op = if instruction == "max" { + AtomicRmwBinOp::AtomicMax + } else { + AtomicRmwBinOp::AtomicMin + }; + + let ty = fn_args.type_at(0); + if matches!(ty.kind(), ty::Int(_)) { + let ptr = args[0].immediate(); + let val = args[1].immediate(); + bx.atomic_rmw(atom_op, ptr, val, parse_ordering(bx, ordering)) + } else { + invalid_monomorphization(ty); + return Ok(()); + } + } + "umax" | "umin" => { + let atom_op = if instruction == "umax" { + AtomicRmwBinOp::AtomicUMax + } else { + AtomicRmwBinOp::AtomicUMin + }; + + let ty = fn_args.type_at(0); + if matches!(ty.kind(), ty::Uint(_)) { + let ptr = args[0].immediate(); + let val = args[1].immediate(); + bx.atomic_rmw(atom_op, ptr, val, parse_ordering(bx, ordering)) + } else { + invalid_monomorphization(ty); + return Ok(()); + } + } op => { let atom_op = match op { "xchg" => AtomicRmwBinOp::AtomicXchg, @@ -450,10 +476,6 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { "nand" => AtomicRmwBinOp::AtomicNand, "or" => AtomicRmwBinOp::AtomicOr, "xor" => AtomicRmwBinOp::AtomicXor, - "max" => AtomicRmwBinOp::AtomicMax, - "min" => AtomicRmwBinOp::AtomicMin, - "umax" => AtomicRmwBinOp::AtomicUMax, - "umin" => AtomicRmwBinOp::AtomicUMin, _ => bx.sess().dcx().emit_fatal(errors::UnknownAtomicOperation), }; diff --git a/compiler/rustc_codegen_ssa/src/mir/operand.rs b/compiler/rustc_codegen_ssa/src/mir/operand.rs index acae09b2c25..7e355b6406a 100644 --- a/compiler/rustc_codegen_ssa/src/mir/operand.rs +++ b/compiler/rustc_codegen_ssa/src/mir/operand.rs @@ -3,16 +3,17 @@ use std::fmt; use arrayvec::ArrayVec; use either::Either; use rustc_abi as abi; -use rustc_abi::{Align, BackendRepr, Size}; +use rustc_abi::{Align, BackendRepr, FIRST_VARIANT, Primitive, Size, TagEncoding, Variants}; use rustc_middle::mir::interpret::{Pointer, Scalar, alloc_range}; use rustc_middle::mir::{self, ConstValue}; use rustc_middle::ty::Ty; use rustc_middle::ty::layout::{LayoutOf, TyAndLayout}; use rustc_middle::{bug, span_bug}; -use tracing::debug; +use tracing::{debug, instrument}; use super::place::{PlaceRef, PlaceValue}; use super::{FunctionCx, LocalRef}; +use crate::common::IntPredicate; use crate::traits::*; use crate::{MemFlags, size_of_val}; @@ -415,6 +416,149 @@ impl<'a, 'tcx, V: CodegenObject> OperandRef<'tcx, V> { OperandRef { val, layout: field } } + + /// Obtain the actual discriminant of a value. + #[instrument(level = "trace", skip(fx, bx))] + pub fn codegen_get_discr<Bx: BuilderMethods<'a, 'tcx, Value = V>>( + self, + fx: &mut FunctionCx<'a, 'tcx, Bx>, + bx: &mut Bx, + cast_to: Ty<'tcx>, + ) -> V { + let dl = &bx.tcx().data_layout; + let cast_to_layout = bx.cx().layout_of(cast_to); + let cast_to = bx.cx().immediate_backend_type(cast_to_layout); + + // We check uninhabitedness separately because a type like + // `enum Foo { Bar(i32, !) }` is still reported as `Variants::Single`, + // *not* as `Variants::Empty`. + if self.layout.is_uninhabited() { + return bx.cx().const_poison(cast_to); + } + + let (tag_scalar, tag_encoding, tag_field) = match self.layout.variants { + Variants::Empty => unreachable!("we already handled uninhabited types"), + Variants::Single { index } => { + let discr_val = + if let Some(discr) = self.layout.ty.discriminant_for_variant(bx.tcx(), index) { + discr.val + } else { + // This arm is for types which are neither enums nor coroutines, + // and thus for which the only possible "variant" should be the first one. + assert_eq!(index, FIRST_VARIANT); + // There's thus no actual discriminant to return, so we return + // what it would have been if this was a single-variant enum. + 0 + }; + return bx.cx().const_uint_big(cast_to, discr_val); + } + Variants::Multiple { tag, ref tag_encoding, tag_field, .. } => { + (tag, tag_encoding, tag_field) + } + }; + + // Read the tag/niche-encoded discriminant from memory. + let tag_op = match self.val { + OperandValue::ZeroSized => bug!(), + OperandValue::Immediate(_) | OperandValue::Pair(_, _) => { + self.extract_field(fx, bx, tag_field) + } + OperandValue::Ref(place) => { + let tag = place.with_type(self.layout).project_field(bx, tag_field); + bx.load_operand(tag) + } + }; + let tag_imm = tag_op.immediate(); + + // Decode the discriminant (specifically if it's niche-encoded). + match *tag_encoding { + TagEncoding::Direct => { + let signed = match tag_scalar.primitive() { + // We use `i1` for bytes that are always `0` or `1`, + // e.g., `#[repr(i8)] enum E { A, B }`, but we can't + // let LLVM interpret the `i1` as signed, because + // then `i1 1` (i.e., `E::B`) is effectively `i8 -1`. + Primitive::Int(_, signed) => !tag_scalar.is_bool() && signed, + _ => false, + }; + bx.intcast(tag_imm, cast_to, signed) + } + TagEncoding::Niche { untagged_variant, ref niche_variants, niche_start } => { + // Cast to an integer so we don't have to treat a pointer as a + // special case. + let (tag, tag_llty) = match tag_scalar.primitive() { + // FIXME(erikdesjardins): handle non-default addrspace ptr sizes + Primitive::Pointer(_) => { + let t = bx.type_from_integer(dl.ptr_sized_integer()); + let tag = bx.ptrtoint(tag_imm, t); + (tag, t) + } + _ => (tag_imm, bx.cx().immediate_backend_type(tag_op.layout)), + }; + + let relative_max = niche_variants.end().as_u32() - niche_variants.start().as_u32(); + + // We have a subrange `niche_start..=niche_end` inside `range`. + // If the value of the tag is inside this subrange, it's a + // "niche value", an increment of the discriminant. Otherwise it + // indicates the untagged variant. + // A general algorithm to extract the discriminant from the tag + // is: + // relative_tag = tag - niche_start + // is_niche = relative_tag <= (ule) relative_max + // discr = if is_niche { + // cast(relative_tag) + niche_variants.start() + // } else { + // untagged_variant + // } + // However, we will likely be able to emit simpler code. + let (is_niche, tagged_discr, delta) = if relative_max == 0 { + // Best case scenario: only one tagged variant. This will + // likely become just a comparison and a jump. + // The algorithm is: + // is_niche = tag == niche_start + // discr = if is_niche { + // niche_start + // } else { + // untagged_variant + // } + let niche_start = bx.cx().const_uint_big(tag_llty, niche_start); + let is_niche = bx.icmp(IntPredicate::IntEQ, tag, niche_start); + let tagged_discr = + bx.cx().const_uint(cast_to, niche_variants.start().as_u32() as u64); + (is_niche, tagged_discr, 0) + } else { + // The special cases don't apply, so we'll have to go with + // the general algorithm. + let relative_discr = bx.sub(tag, bx.cx().const_uint_big(tag_llty, niche_start)); + let cast_tag = bx.intcast(relative_discr, cast_to, false); + let is_niche = bx.icmp( + IntPredicate::IntULE, + relative_discr, + bx.cx().const_uint(tag_llty, relative_max as u64), + ); + (is_niche, cast_tag, niche_variants.start().as_u32() as u128) + }; + + let tagged_discr = if delta == 0 { + tagged_discr + } else { + bx.add(tagged_discr, bx.cx().const_uint_big(cast_to, delta)) + }; + + let discr = bx.select( + is_niche, + tagged_discr, + bx.cx().const_uint(cast_to, untagged_variant.as_u32() as u64), + ); + + // In principle we could insert assumes on the possible range of `discr`, but + // currently in LLVM this seems to be a pessimization. + + discr + } + } + } } impl<'a, 'tcx, V: CodegenObject> OperandValue<V> { diff --git a/compiler/rustc_codegen_ssa/src/mir/place.rs b/compiler/rustc_codegen_ssa/src/mir/place.rs index 6988724b421..31db7fa9a18 100644 --- a/compiler/rustc_codegen_ssa/src/mir/place.rs +++ b/compiler/rustc_codegen_ssa/src/mir/place.rs @@ -1,4 +1,3 @@ -use rustc_abi::Primitive::{Int, Pointer}; use rustc_abi::{Align, BackendRepr, FieldsShape, Size, TagEncoding, VariantIdx, Variants}; use rustc_middle::mir::PlaceTy; use rustc_middle::mir::interpret::Scalar; @@ -233,129 +232,6 @@ impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> { val.with_type(field) } - /// Obtain the actual discriminant of a value. - #[instrument(level = "trace", skip(bx))] - pub fn codegen_get_discr<Bx: BuilderMethods<'a, 'tcx, Value = V>>( - self, - bx: &mut Bx, - cast_to: Ty<'tcx>, - ) -> V { - let dl = &bx.tcx().data_layout; - let cast_to_layout = bx.cx().layout_of(cast_to); - let cast_to = bx.cx().immediate_backend_type(cast_to_layout); - if self.layout.is_uninhabited() { - return bx.cx().const_poison(cast_to); - } - let (tag_scalar, tag_encoding, tag_field) = match self.layout.variants { - Variants::Empty => unreachable!("we already handled uninhabited types"), - Variants::Single { index } => { - let discr_val = self - .layout - .ty - .discriminant_for_variant(bx.cx().tcx(), index) - .map_or(index.as_u32() as u128, |discr| discr.val); - return bx.cx().const_uint_big(cast_to, discr_val); - } - Variants::Multiple { tag, ref tag_encoding, tag_field, .. } => { - (tag, tag_encoding, tag_field) - } - }; - - // Read the tag/niche-encoded discriminant from memory. - let tag = self.project_field(bx, tag_field); - let tag_op = bx.load_operand(tag); - let tag_imm = tag_op.immediate(); - - // Decode the discriminant (specifically if it's niche-encoded). - match *tag_encoding { - TagEncoding::Direct => { - let signed = match tag_scalar.primitive() { - // We use `i1` for bytes that are always `0` or `1`, - // e.g., `#[repr(i8)] enum E { A, B }`, but we can't - // let LLVM interpret the `i1` as signed, because - // then `i1 1` (i.e., `E::B`) is effectively `i8 -1`. - Int(_, signed) => !tag_scalar.is_bool() && signed, - _ => false, - }; - bx.intcast(tag_imm, cast_to, signed) - } - TagEncoding::Niche { untagged_variant, ref niche_variants, niche_start } => { - // Cast to an integer so we don't have to treat a pointer as a - // special case. - let (tag, tag_llty) = match tag_scalar.primitive() { - // FIXME(erikdesjardins): handle non-default addrspace ptr sizes - Pointer(_) => { - let t = bx.type_from_integer(dl.ptr_sized_integer()); - let tag = bx.ptrtoint(tag_imm, t); - (tag, t) - } - _ => (tag_imm, bx.cx().immediate_backend_type(tag_op.layout)), - }; - - let relative_max = niche_variants.end().as_u32() - niche_variants.start().as_u32(); - - // We have a subrange `niche_start..=niche_end` inside `range`. - // If the value of the tag is inside this subrange, it's a - // "niche value", an increment of the discriminant. Otherwise it - // indicates the untagged variant. - // A general algorithm to extract the discriminant from the tag - // is: - // relative_tag = tag - niche_start - // is_niche = relative_tag <= (ule) relative_max - // discr = if is_niche { - // cast(relative_tag) + niche_variants.start() - // } else { - // untagged_variant - // } - // However, we will likely be able to emit simpler code. - let (is_niche, tagged_discr, delta) = if relative_max == 0 { - // Best case scenario: only one tagged variant. This will - // likely become just a comparison and a jump. - // The algorithm is: - // is_niche = tag == niche_start - // discr = if is_niche { - // niche_start - // } else { - // untagged_variant - // } - let niche_start = bx.cx().const_uint_big(tag_llty, niche_start); - let is_niche = bx.icmp(IntPredicate::IntEQ, tag, niche_start); - let tagged_discr = - bx.cx().const_uint(cast_to, niche_variants.start().as_u32() as u64); - (is_niche, tagged_discr, 0) - } else { - // The special cases don't apply, so we'll have to go with - // the general algorithm. - let relative_discr = bx.sub(tag, bx.cx().const_uint_big(tag_llty, niche_start)); - let cast_tag = bx.intcast(relative_discr, cast_to, false); - let is_niche = bx.icmp( - IntPredicate::IntULE, - relative_discr, - bx.cx().const_uint(tag_llty, relative_max as u64), - ); - (is_niche, cast_tag, niche_variants.start().as_u32() as u128) - }; - - let tagged_discr = if delta == 0 { - tagged_discr - } else { - bx.add(tagged_discr, bx.cx().const_uint_big(cast_to, delta)) - }; - - let discr = bx.select( - is_niche, - tagged_discr, - bx.cx().const_uint(cast_to, untagged_variant.as_u32() as u64), - ); - - // In principle we could insert assumes on the possible range of `discr`, but - // currently in LLVM this seems to be a pessimization. - - discr - } - } - } - /// Sets the discriminant for a new value of the given case of the given /// representation. pub fn codegen_set_discr<Bx: BuilderMethods<'a, 'tcx, Value = V>>( diff --git a/compiler/rustc_codegen_ssa/src/mir/rvalue.rs b/compiler/rustc_codegen_ssa/src/mir/rvalue.rs index 95b108b1d33..96be44ee09f 100644 --- a/compiler/rustc_codegen_ssa/src/mir/rvalue.rs +++ b/compiler/rustc_codegen_ssa/src/mir/rvalue.rs @@ -706,7 +706,8 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { mir::Rvalue::Discriminant(ref place) => { let discr_ty = rvalue.ty(self.mir, bx.tcx()); let discr_ty = self.monomorphize(discr_ty); - let discr = self.codegen_place(bx, place.as_ref()).codegen_get_discr(bx, discr_ty); + let operand = self.codegen_consume(bx, place.as_ref()); + let discr = operand.codegen_get_discr(self, bx, discr_ty); OperandRef { val: OperandValue::Immediate(discr), layout: self.cx.layout_of(discr_ty), diff --git a/compiler/rustc_const_eval/Cargo.toml b/compiler/rustc_const_eval/Cargo.toml index a0cc2c65e6e..02be8762d6f 100644 --- a/compiler/rustc_const_eval/Cargo.toml +++ b/compiler/rustc_const_eval/Cargo.toml @@ -23,6 +23,5 @@ rustc_session = { path = "../rustc_session" } rustc_span = { path = "../rustc_span" } rustc_target = { path = "../rustc_target" } rustc_trait_selection = { path = "../rustc_trait_selection" } -rustc_type_ir = { path = "../rustc_type_ir" } tracing = "0.1" # tidy-alphabetical-end diff --git a/compiler/rustc_const_eval/src/interpret/cast.rs b/compiler/rustc_const_eval/src/interpret/cast.rs index 7b706334ed8..643a5805019 100644 --- a/compiler/rustc_const_eval/src/interpret/cast.rs +++ b/compiler/rustc_const_eval/src/interpret/cast.rs @@ -9,7 +9,6 @@ use rustc_middle::ty::adjustment::PointerCoercion; use rustc_middle::ty::layout::{IntegerExt, LayoutOf, TyAndLayout}; use rustc_middle::ty::{self, FloatTy, Ty}; use rustc_middle::{bug, span_bug}; -use rustc_type_ir::TyKind::*; use tracing::trace; use super::util::ensure_monomorphic_enough; @@ -182,9 +181,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { src: &ImmTy<'tcx, M::Provenance>, cast_to: TyAndLayout<'tcx>, ) -> InterpResult<'tcx, ImmTy<'tcx, M::Provenance>> { - use rustc_type_ir::TyKind::*; - - let Float(fty) = src.layout.ty.kind() else { + let ty::Float(fty) = src.layout.ty.kind() else { bug!("FloatToFloat/FloatToInt cast: source type {} is not a float type", src.layout.ty) }; let val = match fty { @@ -277,19 +274,19 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { let signed = src_layout.backend_repr.is_signed(); // Also asserts that abi is `Scalar`. let v = match src_layout.ty.kind() { - Uint(_) | RawPtr(..) | FnPtr(..) => scalar.to_uint(src_layout.size)?, - Int(_) => scalar.to_int(src_layout.size)? as u128, // we will cast back to `i128` below if the sign matters - Bool => scalar.to_bool()?.into(), - Char => scalar.to_char()?.into(), + ty::Uint(_) | ty::RawPtr(..) | ty::FnPtr(..) => scalar.to_uint(src_layout.size)?, + ty::Int(_) => scalar.to_int(src_layout.size)? as u128, // we will cast back to `i128` below if the sign matters + ty::Bool => scalar.to_bool()?.into(), + ty::Char => scalar.to_char()?.into(), _ => span_bug!(self.cur_span(), "invalid int-like cast from {}", src_layout.ty), }; interp_ok(match *cast_ty.kind() { // int -> int - Int(_) | Uint(_) => { + ty::Int(_) | ty::Uint(_) => { let size = match *cast_ty.kind() { - Int(t) => Integer::from_int_ty(self, t).size(), - Uint(t) => Integer::from_uint_ty(self, t).size(), + ty::Int(t) => Integer::from_int_ty(self, t).size(), + ty::Uint(t) => Integer::from_uint_ty(self, t).size(), _ => bug!(), }; let v = size.truncate(v); @@ -297,7 +294,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { } // signed int -> float - Float(fty) if signed => { + ty::Float(fty) if signed => { let v = v as i128; match fty { FloatTy::F16 => Scalar::from_f16(Half::from_i128(v).value), @@ -307,7 +304,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { } } // unsigned int -> float - Float(fty) => match fty { + ty::Float(fty) => match fty { FloatTy::F16 => Scalar::from_f16(Half::from_u128(v).value), FloatTy::F32 => Scalar::from_f32(Single::from_u128(v).value), FloatTy::F64 => Scalar::from_f64(Double::from_u128(v).value), @@ -315,7 +312,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { }, // u8 -> char - Char => Scalar::from_u32(u8::try_from(v).unwrap().into()), + ty::Char => Scalar::from_u32(u8::try_from(v).unwrap().into()), // Casts to bool are not permitted by rustc, no need to handle them here. _ => span_bug!(self.cur_span(), "invalid int to {} cast", cast_ty), @@ -332,11 +329,9 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { + FloatConvert<Double> + FloatConvert<Quad>, { - use rustc_type_ir::TyKind::*; - match *dest_ty.kind() { // float -> uint - Uint(t) => { + ty::Uint(t) => { let size = Integer::from_uint_ty(self, t).size(); // `to_u128` is a saturating cast, which is what we need // (https://doc.rust-lang.org/nightly/nightly-rustc/rustc_apfloat/trait.Float.html#method.to_i128_r). @@ -345,7 +340,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { Scalar::from_uint(v, size) } // float -> int - Int(t) => { + ty::Int(t) => { let size = Integer::from_int_ty(self, t).size(); // `to_i128` is a saturating cast, which is what we need // (https://doc.rust-lang.org/nightly/nightly-rustc/rustc_apfloat/trait.Float.html#method.to_i128_r). @@ -353,7 +348,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { Scalar::from_int(v, size) } // float -> float - Float(fty) => match fty { + ty::Float(fty) => match fty { FloatTy::F16 => { Scalar::from_f16(self.adjust_nan(f.convert(&mut false).value, &[f])) } diff --git a/compiler/rustc_const_eval/src/interpret/machine.rs b/compiler/rustc_const_eval/src/interpret/machine.rs index 1a799f5dea5..a21bf018d01 100644 --- a/compiler/rustc_const_eval/src/interpret/machine.rs +++ b/compiler/rustc_const_eval/src/interpret/machine.rs @@ -8,7 +8,6 @@ use std::hash::Hash; use rustc_abi::{Align, Size}; use rustc_apfloat::{Float, FloatConvert}; -use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece}; use rustc_middle::query::TyCtxtAt; use rustc_middle::ty::Ty; use rustc_middle::ty::layout::TyAndLayout; @@ -21,7 +20,6 @@ use super::{ AllocBytes, AllocId, AllocKind, AllocRange, Allocation, CTFE_ALLOC_SALT, ConstAllocation, CtfeProvenance, FnArg, Frame, ImmTy, InterpCx, InterpResult, MPlaceTy, MemoryKind, Misalignment, OpTy, PlaceTy, Pointer, Provenance, RangeSet, interp_ok, throw_unsup, - throw_unsup_format, }; /// Data returned by [`Machine::after_stack_pop`], and consumed by @@ -361,6 +359,19 @@ pub trait Machine<'tcx>: Sized { size: i64, ) -> Option<(AllocId, Size, Self::ProvenanceExtra)>; + /// Return a "root" pointer for the given allocation: the one that is used for direct + /// accesses to this static/const/fn allocation, or the one returned from the heap allocator. + /// + /// Not called on `extern` or thread-local statics (those use the methods above). + /// + /// `kind` is the kind of the allocation the pointer points to; it can be `None` when + /// it's a global and `GLOBAL_KIND` is `None`. + fn adjust_alloc_root_pointer( + ecx: &InterpCx<'tcx, Self>, + ptr: Pointer, + kind: Option<MemoryKind<Self::MemoryKind>>, + ) -> InterpResult<'tcx, Pointer<Self::Provenance>>; + /// Called to adjust global allocations to the Provenance and AllocExtra of this machine. /// /// If `alloc` contains pointers, then they are all pointing to globals. @@ -375,11 +386,12 @@ pub trait Machine<'tcx>: Sized { alloc: &'b Allocation, ) -> InterpResult<'tcx, Cow<'b, Allocation<Self::Provenance, Self::AllocExtra, Self::Bytes>>>; - /// Initialize the extra state of an allocation. + /// Initialize the extra state of an allocation local to this machine. /// - /// This is guaranteed to be called exactly once on all allocations that are accessed by the - /// program. - fn init_alloc_extra( + /// This is guaranteed to be called exactly once on all allocations local to this machine. + /// It will not be called automatically for global allocations; `adjust_global_allocation` + /// has to do that itself if that is desired. + fn init_local_allocation( ecx: &InterpCx<'tcx, Self>, id: AllocId, kind: MemoryKind<Self::MemoryKind>, @@ -387,34 +399,6 @@ pub trait Machine<'tcx>: Sized { align: Align, ) -> InterpResult<'tcx, Self::AllocExtra>; - /// Return a "root" pointer for the given allocation: the one that is used for direct - /// accesses to this static/const/fn allocation, or the one returned from the heap allocator. - /// - /// Not called on `extern` or thread-local statics (those use the methods above). - /// - /// `kind` is the kind of the allocation the pointer points to; it can be `None` when - /// it's a global and `GLOBAL_KIND` is `None`. - fn adjust_alloc_root_pointer( - ecx: &InterpCx<'tcx, Self>, - ptr: Pointer, - kind: Option<MemoryKind<Self::MemoryKind>>, - ) -> InterpResult<'tcx, Pointer<Self::Provenance>>; - - /// Evaluate the inline assembly. - /// - /// This should take care of jumping to the next block (one of `targets`) when asm goto - /// is triggered, `targets[0]` when the assembly falls through, or diverge in case of - /// naked_asm! or `InlineAsmOptions::NORETURN` being set. - fn eval_inline_asm( - _ecx: &mut InterpCx<'tcx, Self>, - _template: &'tcx [InlineAsmTemplatePiece], - _operands: &[mir::InlineAsmOperand<'tcx>], - _options: InlineAsmOptions, - _targets: &[mir::BasicBlock], - ) -> InterpResult<'tcx> { - throw_unsup_format!("inline assembly is not supported") - } - /// Hook for performing extra checks on a memory read access. /// /// This will *not* be called during validation! @@ -699,7 +683,7 @@ pub macro compile_time_machine(<$tcx: lifetime>) { interp_ok(Cow::Borrowed(alloc)) } - fn init_alloc_extra( + fn init_local_allocation( _ecx: &InterpCx<$tcx, Self>, _id: AllocId, _kind: MemoryKind<Self::MemoryKind>, diff --git a/compiler/rustc_const_eval/src/interpret/memory.rs b/compiler/rustc_const_eval/src/interpret/memory.rs index e5af0673629..75726269a86 100644 --- a/compiler/rustc_const_eval/src/interpret/memory.rs +++ b/compiler/rustc_const_eval/src/interpret/memory.rs @@ -263,9 +263,9 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { M::GLOBAL_KIND.map(MemoryKind::Machine), "dynamically allocating global memory" ); - // We have set things up so we don't need to call `adjust_from_tcx` here, - // so we avoid copying the entire allocation contents. - let extra = M::init_alloc_extra(self, id, kind, alloc.size(), alloc.align)?; + // This cannot be merged with the `adjust_global_allocation` code path + // since here we have an allocation that already uses `M::Bytes`. + let extra = M::init_local_allocation(self, id, kind, alloc.size(), alloc.align)?; let alloc = alloc.with_extra(extra); self.memory.alloc_map.insert(id, (kind, alloc)); M::adjust_alloc_root_pointer(self, Pointer::from(id), Some(kind)) diff --git a/compiler/rustc_const_eval/src/interpret/step.rs b/compiler/rustc_const_eval/src/interpret/step.rs index 6a17da61c8b..ddf2d65914f 100644 --- a/compiler/rustc_const_eval/src/interpret/step.rs +++ b/compiler/rustc_const_eval/src/interpret/step.rs @@ -14,7 +14,7 @@ use tracing::{info, instrument, trace}; use super::{ FnArg, FnVal, ImmTy, Immediate, InterpCx, InterpResult, Machine, MemPlaceMeta, PlaceTy, - Projectable, Scalar, interp_ok, throw_ub, + Projectable, Scalar, interp_ok, throw_ub, throw_unsup_format, }; use crate::util; @@ -590,8 +590,8 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { terminator.kind ), - InlineAsm { template, ref operands, options, ref targets, .. } => { - M::eval_inline_asm(self, template, operands, options, targets)?; + InlineAsm { .. } => { + throw_unsup_format!("inline assembly is not supported"); } } diff --git a/compiler/rustc_data_structures/src/sorted_map.rs b/compiler/rustc_data_structures/src/sorted_map.rs index a01a420dfbd..c002d47815b 100644 --- a/compiler/rustc_data_structures/src/sorted_map.rs +++ b/compiler/rustc_data_structures/src/sorted_map.rs @@ -4,7 +4,7 @@ use std::fmt::Debug; use std::mem; use std::ops::{Bound, Index, IndexMut, RangeBounds}; -use rustc_macros::{Decodable_Generic, Encodable_Generic}; +use rustc_macros::{Decodable_NoContext, Encodable_NoContext}; use crate::stable_hasher::{HashStable, StableHasher, StableOrd}; @@ -20,7 +20,7 @@ pub use index_map::SortedIndexMultiMap; /// stores data in a more compact way. It also supports accessing contiguous /// ranges of elements as a slice, and slices of already sorted elements can be /// inserted efficiently. -#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable_Generic, Decodable_Generic)] +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable_NoContext, Decodable_NoContext)] pub struct SortedMap<K, V> { data: Vec<(K, V)>, } diff --git a/compiler/rustc_data_structures/src/svh.rs b/compiler/rustc_data_structures/src/svh.rs index 391a7c9f30d..f51fcb8ed22 100644 --- a/compiler/rustc_data_structures/src/svh.rs +++ b/compiler/rustc_data_structures/src/svh.rs @@ -7,12 +7,12 @@ use std::fmt; -use rustc_macros::{Decodable_Generic, Encodable_Generic}; +use rustc_macros::{Decodable_NoContext, Encodable_NoContext}; use crate::fingerprint::Fingerprint; use crate::stable_hasher; -#[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable_Generic, Decodable_Generic, Hash)] +#[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable_NoContext, Decodable_NoContext, Hash)] pub struct Svh { hash: Fingerprint, } diff --git a/compiler/rustc_data_structures/src/unord.rs b/compiler/rustc_data_structures/src/unord.rs index 34895d3efe6..baa66cd7c85 100644 --- a/compiler/rustc_data_structures/src/unord.rs +++ b/compiler/rustc_data_structures/src/unord.rs @@ -9,7 +9,7 @@ use std::iter::{Product, Sum}; use std::ops::Index; use rustc_hash::{FxHashMap, FxHashSet}; -use rustc_macros::{Decodable_Generic, Encodable_Generic}; +use rustc_macros::{Decodable_NoContext, Encodable_NoContext}; use crate::fingerprint::Fingerprint; use crate::stable_hasher::{HashStable, StableCompare, StableHasher, ToStableHashKey}; @@ -224,7 +224,7 @@ trait UnordCollection {} /// /// See [MCP 533](https://github.com/rust-lang/compiler-team/issues/533) /// for more information. -#[derive(Debug, Eq, PartialEq, Clone, Encodable_Generic, Decodable_Generic)] +#[derive(Debug, Eq, PartialEq, Clone, Encodable_NoContext, Decodable_NoContext)] pub struct UnordSet<V: Eq + Hash> { inner: FxHashSet<V>, } @@ -259,6 +259,12 @@ impl<V: Eq + Hash> UnordSet<V> { self.inner.is_empty() } + /// If the set has only one element, returns it, otherwise returns `None`. + #[inline] + pub fn get_only(&self) -> Option<&V> { + if self.inner.len() == 1 { self.inner.iter().next() } else { None } + } + #[inline] pub fn insert(&mut self, v: V) -> bool { self.inner.insert(v) @@ -415,7 +421,7 @@ impl<HCX, V: Hash + Eq + HashStable<HCX>> HashStable<HCX> for UnordSet<V> { /// /// See [MCP 533](https://github.com/rust-lang/compiler-team/issues/533) /// for more information. -#[derive(Debug, Eq, PartialEq, Clone, Encodable_Generic, Decodable_Generic)] +#[derive(Debug, Eq, PartialEq, Clone, Encodable_NoContext, Decodable_NoContext)] pub struct UnordMap<K: Eq + Hash, V> { inner: FxHashMap<K, V>, } @@ -639,7 +645,7 @@ impl<HCX, K: Hash + Eq + HashStable<HCX>, V: HashStable<HCX>> HashStable<HCX> fo /// /// See [MCP 533](https://github.com/rust-lang/compiler-team/issues/533) /// for more information. -#[derive(Default, Debug, Eq, PartialEq, Clone, Encodable_Generic, Decodable_Generic)] +#[derive(Default, Debug, Eq, PartialEq, Clone, Encodable_NoContext, Decodable_NoContext)] pub struct UnordBag<V> { inner: Vec<V>, } diff --git a/compiler/rustc_errors/src/emitter.rs b/compiler/rustc_errors/src/emitter.rs index 21255fcca96..fe01e289334 100644 --- a/compiler/rustc_errors/src/emitter.rs +++ b/compiler/rustc_errors/src/emitter.rs @@ -297,7 +297,9 @@ pub trait Emitter: Translate { // are some which do actually involve macros. ExpnKind::Desugaring(..) | ExpnKind::AstPass(..) => None, - ExpnKind::Macro(macro_kind, name) => Some((macro_kind, name)), + ExpnKind::Macro(macro_kind, name) => { + Some((macro_kind, name, expn_data.hide_backtrace)) + } } }) .collect(); @@ -309,13 +311,17 @@ pub trait Emitter: Translate { self.render_multispans_macro_backtrace(span, children, backtrace); if !backtrace { - if let Some((macro_kind, name)) = has_macro_spans.first() { + // Skip builtin macros, as their expansion isn't relevant to the end user. This includes + // actual intrinsics, like `asm!`. + if let Some((macro_kind, name, _)) = has_macro_spans.first() + && let Some((_, _, false)) = has_macro_spans.last() + { // Mark the actual macro this originates from - let and_then = if let Some((macro_kind, last_name)) = has_macro_spans.last() + let and_then = if let Some((macro_kind, last_name, _)) = has_macro_spans.last() && last_name != name { let descr = macro_kind.descr(); - format!(" which comes from the expansion of the {descr} `{last_name}`",) + format!(" which comes from the expansion of the {descr} `{last_name}`") } else { "".to_string() }; diff --git a/compiler/rustc_expand/src/base.rs b/compiler/rustc_expand/src/base.rs index 895efe05e11..c4b53962584 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -889,16 +889,16 @@ impl SyntaxExtension { }) .unwrap_or_else(|| (None, helper_attrs)); - let stability = find_attr!(attrs, AttributeKind::Stability{stability, ..} => *stability); + let stability = find_attr!(attrs, AttributeKind::Stability { stability, .. } => *stability); // FIXME(jdonszelmann): make it impossible to miss the or_else in the typesystem - if let Some(sp) = find_attr!(attrs, AttributeKind::ConstStability{span, ..} => *span) { + if let Some(sp) = find_attr!(attrs, AttributeKind::ConstStability { span, .. } => *span) { sess.dcx().emit_err(errors::MacroConstStability { span: sp, head_span: sess.source_map().guess_head_span(span), }); } - if let Some(sp) = find_attr!(attrs, AttributeKind::BodyStability{span, ..} => *span) { + if let Some(sp) = find_attr!(attrs, AttributeKind::BodyStability{ span, .. } => *span) { sess.dcx().emit_err(errors::MacroBodyStability { span: sp, head_span: sess.source_map().guess_head_span(span), @@ -912,7 +912,10 @@ impl SyntaxExtension { // FIXME(jdonszelmann): avoid the into_iter/collect? .then(|| allow_internal_unstable.iter().map(|i| i.0).collect::<Vec<_>>().into()), stability, - deprecation: find_attr!(attrs, AttributeKind::Deprecation{deprecation, ..} => *deprecation), + deprecation: find_attr!( + attrs, + AttributeKind::Deprecation { deprecation, .. } => *deprecation + ), helper_attrs, edition, builtin_name, @@ -1000,6 +1003,7 @@ impl SyntaxExtension { self.allow_internal_unsafe, self.local_inner_macros, self.collapse_debuginfo, + self.builtin_name.is_some(), ) } } diff --git a/compiler/rustc_hir_analysis/Cargo.toml b/compiler/rustc_hir_analysis/Cargo.toml index 55a816a855a..e5017794d8f 100644 --- a/compiler/rustc_hir_analysis/Cargo.toml +++ b/compiler/rustc_hir_analysis/Cargo.toml @@ -28,7 +28,6 @@ rustc_session = { path = "../rustc_session" } rustc_span = { path = "../rustc_span" } rustc_target = { path = "../rustc_target" } rustc_trait_selection = { path = "../rustc_trait_selection" } -rustc_type_ir = { path = "../rustc_type_ir" } smallvec = { version = "1.8.1", features = ["union", "may_dangle"] } tracing = "0.1" # tidy-alphabetical-end diff --git a/compiler/rustc_hir_analysis/src/check/check.rs b/compiler/rustc_hir_analysis/src/check/check.rs index a266286664c..07b5837bd87 100644 --- a/compiler/rustc_hir_analysis/src/check/check.rs +++ b/compiler/rustc_hir_analysis/src/check/check.rs @@ -18,18 +18,17 @@ use rustc_middle::hir::nested_filter; use rustc_middle::middle::resolve_bound_vars::ResolvedArg; use rustc_middle::middle::stability::EvalResult; use rustc_middle::ty::error::TypeErrorToStringExt; -use rustc_middle::ty::fold::{BottomUpFolder, fold_regions}; use rustc_middle::ty::layout::{LayoutError, MAX_SIMD_LANES}; use rustc_middle::ty::util::{Discr, IntTypeExt}; use rustc_middle::ty::{ - AdtDef, GenericArgKind, RegionKind, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, + AdtDef, BottomUpFolder, GenericArgKind, RegionKind, TypeFoldable, TypeSuperVisitable, + TypeVisitable, TypeVisitableExt, fold_regions, }; use rustc_session::lint::builtin::UNINHABITED_STATIC; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::error_reporting::traits::on_unimplemented::OnUnimplementedDirective; use rustc_trait_selection::traits; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt; -use rustc_type_ir::fold::TypeFoldable; use tracing::{debug, instrument}; use ty::TypingMode; use {rustc_attr_parsing as attr, rustc_hir as hir}; @@ -1715,7 +1714,7 @@ fn opaque_type_cycle_error(tcx: TyCtxt<'_>, opaque_def_id: LocalDefId) -> ErrorG opaques: Vec<DefId>, closures: Vec<DefId>, } - impl<'tcx> ty::visit::TypeVisitor<TyCtxt<'tcx>> for OpaqueTypeCollector { + impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for OpaqueTypeCollector { fn visit_ty(&mut self, t: Ty<'tcx>) { match *t.kind() { ty::Alias(ty::Opaque, ty::AliasTy { def_id: def, .. }) => { diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs index 0a37a27b35b..ca820deebdf 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs @@ -12,10 +12,9 @@ use rustc_hir::{self as hir, AmbigArg, GenericParamKind, ImplItemKind, intravisi use rustc_infer::infer::{self, InferCtxt, TyCtxtInferExt}; use rustc_infer::traits::util; use rustc_middle::ty::error::{ExpectedFound, TypeError}; -use rustc_middle::ty::fold::BottomUpFolder; use rustc_middle::ty::util::ExplicitSelf; use rustc_middle::ty::{ - self, GenericArgs, GenericParamDefKind, Ty, TyCtxt, TypeFoldable, TypeFolder, + self, BottomUpFolder, GenericArgs, GenericParamDefKind, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt, TypingMode, Upcast, }; use rustc_middle::{bug, span_bug}; diff --git a/compiler/rustc_hir_analysis/src/check/mod.rs b/compiler/rustc_hir_analysis/src/check/mod.rs index 9c28fac809d..b4a16b2b805 100644 --- a/compiler/rustc_hir_analysis/src/check/mod.rs +++ b/compiler/rustc_hir_analysis/src/check/mod.rs @@ -84,6 +84,7 @@ use rustc_infer::infer::{self, TyCtxtInferExt as _}; use rustc_infer::traits::ObligationCause; use rustc_middle::query::Providers; use rustc_middle::ty::error::{ExpectedFound, TypeError}; +use rustc_middle::ty::print::with_types_for_signature; use rustc_middle::ty::{self, GenericArgs, GenericArgsRef, Ty, TyCtxt, TypingMode}; use rustc_middle::{bug, span_bug}; use rustc_session::parse::feature_err; @@ -240,11 +241,11 @@ fn missing_items_err( (Vec::new(), Vec::new(), Vec::new()); for &trait_item in missing_items { - let snippet = suggestion_signature( + let snippet = with_types_for_signature!(suggestion_signature( tcx, trait_item, tcx.impl_trait_ref(impl_def_id).unwrap().instantiate_identity(), - ); + )); let code = format!("{padding}{snippet}\n{padding}"); if let Some(span) = tcx.hir().span_if_local(trait_item.def_id) { missing_trait_item_label diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index fd5ffdc2d7a..4769153ff4d 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -16,10 +16,12 @@ use rustc_lint_defs::builtin::SUPERTRAIT_ITEM_SHADOWING_DEFINITION; use rustc_macros::LintDiagnostic; use rustc_middle::mir::interpret::ErrorHandled; use rustc_middle::query::Providers; +use rustc_middle::traits::solve::NoSolution; use rustc_middle::ty::trait_def::TraitSpecializationKind; use rustc_middle::ty::{ - self, AdtKind, GenericArgKind, GenericArgs, GenericParamDefKind, Ty, TyCtxt, TypeFoldable, - TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode, Upcast, + self, AdtKind, GenericArgKind, GenericArgs, GenericParamDefKind, Ty, TyCtxt, TypeFlags, + TypeFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode, + Upcast, }; use rustc_middle::{bug, span_bug}; use rustc_session::parse::feature_err; @@ -34,8 +36,6 @@ use rustc_trait_selection::traits::{ self, FulfillmentError, Obligation, ObligationCause, ObligationCauseCode, ObligationCtxt, WellFormedLoc, }; -use rustc_type_ir::TypeFlags; -use rustc_type_ir::solve::NoSolution; use tracing::{debug, instrument}; use {rustc_ast as ast, rustc_hir as hir}; @@ -1520,7 +1520,7 @@ fn check_where_clauses<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, span: Span, def_id struct CountParams { params: FxHashSet<u32>, } - impl<'tcx> ty::visit::TypeVisitor<TyCtxt<'tcx>> for CountParams { + impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for CountParams { type Result = ControlFlow<()>; fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result { if let ty::Param(param) = t.kind() { diff --git a/compiler/rustc_hir_analysis/src/coherence/builtin.rs b/compiler/rustc_hir_analysis/src/coherence/builtin.rs index c918abe4c07..1f3f0b754bb 100644 --- a/compiler/rustc_hir_analysis/src/coherence/builtin.rs +++ b/compiler/rustc_hir_analysis/src/coherence/builtin.rs @@ -250,13 +250,16 @@ fn visit_implementation_of_dispatch_from_dyn(checker: &Checker<'_>) -> Result<() // trait, they *do* satisfy the repr(transparent) rules, and then we assume that everything else // in the compiler (in particular, all the call ABI logic) will treat them as repr(transparent) // even if they do not carry that attribute. - use rustc_type_ir::TyKind::*; match (source.kind(), target.kind()) { - (&Ref(r_a, _, mutbl_a), Ref(r_b, _, mutbl_b)) if r_a == *r_b && mutbl_a == *mutbl_b => { + (&ty::Ref(r_a, _, mutbl_a), ty::Ref(r_b, _, mutbl_b)) + if r_a == *r_b && mutbl_a == *mutbl_b => + { Ok(()) } - (&RawPtr(_, a_mutbl), &RawPtr(_, b_mutbl)) if a_mutbl == b_mutbl => Ok(()), - (&Adt(def_a, args_a), &Adt(def_b, args_b)) if def_a.is_struct() && def_b.is_struct() => { + (&ty::RawPtr(_, a_mutbl), &ty::RawPtr(_, b_mutbl)) if a_mutbl == b_mutbl => Ok(()), + (&ty::Adt(def_a, args_a), &ty::Adt(def_b, args_b)) + if def_a.is_struct() && def_b.is_struct() => + { if def_a != def_b { let source_path = tcx.def_path_str(def_a.did()); let target_path = tcx.def_path_str(def_b.did()); diff --git a/compiler/rustc_hir_analysis/src/coherence/mod.rs b/compiler/rustc_hir_analysis/src/coherence/mod.rs index b5c6c2f3861..15e0a72fdcb 100644 --- a/compiler/rustc_hir_analysis/src/coherence/mod.rs +++ b/compiler/rustc_hir_analysis/src/coherence/mod.rs @@ -10,10 +10,9 @@ use rustc_errors::struct_span_code_err; use rustc_hir::LangItem; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_middle::query::Providers; -use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt}; +use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt, elaborate}; use rustc_session::parse::feature_err; use rustc_span::{ErrorGuaranteed, sym}; -use rustc_type_ir::elaborate; use tracing::debug; use crate::check::always_applicable; diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index e0e435dd6f0..54a630f5b00 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -33,9 +33,8 @@ use rustc_infer::infer::{InferCtxt, TyCtxtInferExt}; use rustc_infer::traits::ObligationCause; use rustc_middle::hir::nested_filter; use rustc_middle::query::Providers; -use rustc_middle::ty::fold::fold_regions; use rustc_middle::ty::util::{Discr, IntTypeExt}; -use rustc_middle::ty::{self, AdtKind, Const, IsSuggestable, Ty, TyCtxt, TypingMode}; +use rustc_middle::ty::{self, AdtKind, Const, IsSuggestable, Ty, TyCtxt, TypingMode, fold_regions}; use rustc_middle::{bug, span_bug}; use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym}; use rustc_trait_selection::error_reporting::traits::suggestions::NextTypeParamName; diff --git a/compiler/rustc_hir_analysis/src/collect/item_bounds.rs b/compiler/rustc_hir_analysis/src/collect/item_bounds.rs index 1c1a246cc15..6e07f0ff53c 100644 --- a/compiler/rustc_hir_analysis/src/collect/item_bounds.rs +++ b/compiler/rustc_hir_analysis/src/collect/item_bounds.rs @@ -1,14 +1,13 @@ use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_hir as hir; use rustc_infer::traits::util; -use rustc_middle::ty::fold::shift_vars; use rustc_middle::ty::{ self, GenericArgs, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt, + Upcast, shift_vars, }; use rustc_middle::{bug, span_bug}; use rustc_span::Span; use rustc_span::def_id::{DefId, LocalDefId}; -use rustc_type_ir::Upcast; use tracing::{debug, instrument}; use super::ItemCtxt; diff --git a/compiler/rustc_hir_analysis/src/collect/type_of.rs b/compiler/rustc_hir_analysis/src/collect/type_of.rs index 16caa4f6874..4e8f5ce3986 100644 --- a/compiler/rustc_hir_analysis/src/collect/type_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/type_of.rs @@ -5,10 +5,9 @@ use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::intravisit::VisitorExt; use rustc_hir::{self as hir, AmbigArg, HirId}; use rustc_middle::query::plumbing::CyclePlaceholder; -use rustc_middle::ty::fold::fold_regions; use rustc_middle::ty::print::with_forced_trimmed_paths; use rustc_middle::ty::util::IntTypeExt; -use rustc_middle::ty::{self, IsSuggestable, Ty, TyCtxt, TypeVisitableExt}; +use rustc_middle::ty::{self, IsSuggestable, Ty, TyCtxt, TypeVisitableExt, fold_regions}; use rustc_middle::{bug, span_bug}; use rustc_span::{DUMMY_SP, Ident, Span}; diff --git a/compiler/rustc_hir_analysis/src/constrained_generic_params.rs b/compiler/rustc_hir_analysis/src/constrained_generic_params.rs index 6a9ae0de1c1..53866aa27b1 100644 --- a/compiler/rustc_hir_analysis/src/constrained_generic_params.rs +++ b/compiler/rustc_hir_analysis/src/constrained_generic_params.rs @@ -1,9 +1,7 @@ use rustc_data_structures::fx::FxHashSet; use rustc_middle::bug; -use rustc_middle::ty::visit::{TypeSuperVisitable, TypeVisitor}; -use rustc_middle::ty::{self, Ty, TyCtxt}; +use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable, TypeSuperVisitable, TypeVisitor}; use rustc_span::Span; -use rustc_type_ir::fold::TypeFoldable; use tracing::debug; #[derive(Clone, PartialEq, Eq, Hash, Debug)] diff --git a/compiler/rustc_hir_analysis/src/delegation.rs b/compiler/rustc_hir_analysis/src/delegation.rs index 78b20f9897c..b907ec090e5 100644 --- a/compiler/rustc_hir_analysis/src/delegation.rs +++ b/compiler/rustc_hir_analysis/src/delegation.rs @@ -7,10 +7,10 @@ use std::assert_matches::debug_assert_matches; use rustc_data_structures::fx::FxHashMap; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LocalDefId}; -use rustc_middle::ty::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable}; -use rustc_middle::ty::{self, Ty, TyCtxt}; +use rustc_middle::ty::{ + self, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt, +}; use rustc_span::{ErrorGuaranteed, Span}; -use rustc_type_ir::visit::TypeVisitableExt; type RemapTable = FxHashMap<u32, u32>; diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs index 60af36da6e2..f0dffd780bc 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs @@ -8,10 +8,12 @@ use rustc_hir::HirId; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_middle::bug; -use rustc_middle::ty::{self as ty, IsSuggestable, Ty, TyCtxt, Upcast}; +use rustc_middle::ty::{ + self as ty, IsSuggestable, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, + TypeVisitor, Upcast, +}; use rustc_span::{ErrorGuaranteed, Ident, Span, Symbol, kw, sym}; use rustc_trait_selection::traits; -use rustc_type_ir::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor}; use smallvec::SmallVec; use tracing::{debug, instrument}; diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_compatibility.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_compatibility.rs index 3eb4945ebf8..7e1f35627e3 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_compatibility.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_compatibility.rs @@ -4,15 +4,14 @@ use rustc_errors::struct_span_code_err; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_lint_defs::builtin::UNUSED_ASSOCIATED_TYPE_BOUNDS; -use rustc_middle::ty::fold::BottomUpFolder; +use rustc_middle::ty::elaborate::ClauseWithSupertraitSpan; use rustc_middle::ty::{ - self, DynKind, ExistentialPredicateStableCmpExt as _, Ty, TyCtxt, TypeFoldable, + self, BottomUpFolder, DynKind, ExistentialPredicateStableCmpExt as _, Ty, TyCtxt, TypeFoldable, TypeVisitableExt, Upcast, }; use rustc_span::{ErrorGuaranteed, Span}; use rustc_trait_selection::error_reporting::traits::report_dyn_incompatibility; use rustc_trait_selection::traits::{self, hir_ty_lowering_dyn_compatibility_violations}; -use rustc_type_ir::elaborate::ClauseWithSupertraitSpan; use smallvec::{SmallVec, smallvec}; use tracing::{debug, instrument}; diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/lint.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/lint.rs index e78801dd601..be726c042da 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/lint.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/lint.rs @@ -411,14 +411,16 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { Applicability::MachineApplicable, ); if !is_dyn_compatible { - diag.note(format!("`{trait_name}` it is dyn-incompatible, so it can't be `dyn`")); + diag.note(format!( + "`{trait_name}` is dyn-incompatible, otherwise a trait object could be used" + )); } else { // No ampersand in suggestion if it's borrowed already let (dyn_str, paren_dyn_str) = if borrowed { ("dyn ", "(dyn ") } else { ("&dyn ", "&(dyn ") }; let sugg = if let hir::TyKind::TraitObject([_, _, ..], _) = self_ty.kind { - // There are more than one trait bound, we need surrounding parentheses. + // There is more than one trait bound, we need surrounding parentheses. vec![ (self_ty.span.shrink_to_lo(), paren_dyn_str.to_string()), (self_ty.span.shrink_to_hi(), ")".to_string()), diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs index 8fff6eb9f6e..76a880da418 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs @@ -36,11 +36,10 @@ use rustc_infer::infer::{InferCtxt, TyCtxtInferExt}; use rustc_infer::traits::ObligationCause; use rustc_middle::middle::stability::AllowUnstable; use rustc_middle::mir::interpret::LitToConstInput; -use rustc_middle::ty::fold::fold_regions; use rustc_middle::ty::print::PrintPolyTraitRefExt as _; use rustc_middle::ty::{ self, Const, GenericArgKind, GenericArgsRef, GenericParamDefKind, ParamEnv, Ty, TyCtxt, - TypeVisitableExt, TypingMode, + TypeVisitableExt, TypingMode, Upcast, fold_regions, }; use rustc_middle::{bug, span_bug}; use rustc_session::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS; @@ -50,7 +49,6 @@ use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym}; use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits::wf::object_region_bounds; use rustc_trait_selection::traits::{self, ObligationCtxt}; -use rustc_type_ir::Upcast; use tracing::{debug, instrument}; use self::errors::assoc_kind_str; diff --git a/compiler/rustc_hir_analysis/src/hir_wf_check.rs b/compiler/rustc_hir_analysis/src/hir_wf_check.rs index 0b1be8e4f7a..1f5d69bd1b3 100644 --- a/compiler/rustc_hir_analysis/src/hir_wf_check.rs +++ b/compiler/rustc_hir_analysis/src/hir_wf_check.rs @@ -4,8 +4,7 @@ use rustc_infer::infer::TyCtxtInferExt; use rustc_infer::traits::{ObligationCause, WellFormedLoc}; use rustc_middle::bug; use rustc_middle::query::Providers; -use rustc_middle::ty::fold::fold_regions; -use rustc_middle::ty::{self, TyCtxt, TypingMode}; +use rustc_middle::ty::{self, TyCtxt, TypingMode, fold_regions}; use rustc_span::def_id::LocalDefId; use rustc_trait_selection::traits::{self, ObligationCtxt}; use tracing::debug; diff --git a/compiler/rustc_hir_analysis/src/lib.rs b/compiler/rustc_hir_analysis/src/lib.rs index cb3cdc5e8d3..e7ecd727a85 100644 --- a/compiler/rustc_hir_analysis/src/lib.rs +++ b/compiler/rustc_hir_analysis/src/lib.rs @@ -252,7 +252,9 @@ pub fn lower_ty<'tcx>(tcx: TyCtxt<'tcx>, hir_ty: &hir::Ty<'tcx>) -> Ty<'tcx> { // def-ID that will be used to determine the traits/predicates in // scope. This is derived from the enclosing item-like thing. let env_def_id = tcx.hir_get_parent_item(hir_ty.hir_id); - collect::ItemCtxt::new(tcx, env_def_id.def_id).lower_ty(hir_ty) + collect::ItemCtxt::new(tcx, env_def_id.def_id) + .lowerer() + .lower_ty_maybe_return_type_notation(hir_ty) } /// This is for rustdoc. diff --git a/compiler/rustc_hir_analysis/src/outlives/utils.rs b/compiler/rustc_hir_analysis/src/outlives/utils.rs index 0c9f5ba8b6f..d0a2a2230ab 100644 --- a/compiler/rustc_hir_analysis/src/outlives/utils.rs +++ b/compiler/rustc_hir_analysis/src/outlives/utils.rs @@ -1,8 +1,8 @@ use rustc_data_structures::fx::FxIndexMap; +use rustc_middle::ty::outlives::{Component, push_outlives_components}; use rustc_middle::ty::{self, GenericArg, GenericArgKind, Region, Ty, TyCtxt}; use rustc_middle::{bug, span_bug}; use rustc_span::Span; -use rustc_type_ir::outlives::{Component, push_outlives_components}; use smallvec::smallvec; /// Tracks the `T: 'a` or `'a: 'a` predicates that we have inferred diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index 3067766fb4d..1409310339a 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -2148,9 +2148,11 @@ impl<'a> State<'a> { s.print_implicit_self(&decl.implicit_self); } else { if let Some(arg_name) = arg_names.get(i) { - s.word(arg_name.to_string()); - s.word(":"); - s.space(); + if arg_name.name != kw::Empty { + s.word(arg_name.to_string()); + s.word(":"); + s.space(); + } } else if let Some(body_id) = body_id { s.ann.nested(s, Nested::BodyParamPat(body_id, i)); s.word(":"); diff --git a/compiler/rustc_hir_typeck/Cargo.toml b/compiler/rustc_hir_typeck/Cargo.toml index f1afb7b712d..b2b90cb29e3 100644 --- a/compiler/rustc_hir_typeck/Cargo.toml +++ b/compiler/rustc_hir_typeck/Cargo.toml @@ -23,7 +23,6 @@ rustc_middle = { path = "../rustc_middle" } rustc_session = { path = "../rustc_session" } rustc_span = { path = "../rustc_span" } rustc_trait_selection = { path = "../rustc_trait_selection" } -rustc_type_ir = { path = "../rustc_type_ir" } smallvec = { version = "1.8.1", features = ["union", "may_dangle"] } tracing = "0.1" # tidy-alphabetical-end diff --git a/compiler/rustc_hir_typeck/src/cast.rs b/compiler/rustc_hir_typeck/src/cast.rs index 70b49fea34f..c85c3b90ce7 100644 --- a/compiler/rustc_hir_typeck/src/cast.rs +++ b/compiler/rustc_hir_typeck/src/cast.rs @@ -32,6 +32,7 @@ use rustc_ast::util::parser::ExprPrecedence; use rustc_data_structures::fx::FxHashSet; use rustc_errors::codes::*; use rustc_errors::{Applicability, Diag, ErrorGuaranteed}; +use rustc_hir::def_id::DefId; use rustc_hir::{self as hir, ExprKind}; use rustc_infer::infer::DefineOpaqueTypes; use rustc_macros::{TypeFoldable, TypeVisitable}; @@ -39,13 +40,12 @@ use rustc_middle::mir::Mutability; use rustc_middle::ty::adjustment::AllowTwoPhase; use rustc_middle::ty::cast::{CastKind, CastTy}; use rustc_middle::ty::error::TypeError; -use rustc_middle::ty::{self, Ty, TyCtxt, TypeAndMut, TypeVisitableExt, VariantDef}; +use rustc_middle::ty::{self, Ty, TyCtxt, TypeAndMut, TypeVisitableExt, VariantDef, elaborate}; use rustc_middle::{bug, span_bug}; use rustc_session::lint; use rustc_span::def_id::LOCAL_CRATE; use rustc_span::{DUMMY_SP, Span, sym}; use rustc_trait_selection::infer::InferCtxtExt; -use rustc_type_ir::elaborate; use tracing::{debug, instrument}; use super::FnCtxt; @@ -155,7 +155,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } -#[derive(Copy, Clone, Debug)] +#[derive(Debug)] enum CastError<'tcx> { ErrorGuaranteed(ErrorGuaranteed), @@ -182,6 +182,7 @@ enum CastError<'tcx> { /// when we're typechecking a type parameter with a ?Sized bound. IntToWideCast(Option<&'static str>), ForeignNonExhaustiveAdt, + PtrPtrAddingAutoTrait(Vec<DefId>), } impl From<ErrorGuaranteed> for CastError<'_> { @@ -596,6 +597,21 @@ impl<'a, 'tcx> CastCheck<'tcx> { .with_note("cannot cast an enum with a non-exhaustive variant when it's defined in another crate") .emit(); } + CastError::PtrPtrAddingAutoTrait(added) => { + fcx.dcx().emit_err(errors::PtrCastAddAutoToObject { + span: self.span, + traits_len: added.len(), + traits: { + let mut traits: Vec<_> = added + .into_iter() + .map(|trait_did| fcx.tcx.def_path_str(trait_did)) + .collect(); + + traits.sort(); + traits.into() + }, + }); + } } } @@ -940,19 +956,7 @@ impl<'a, 'tcx> CastCheck<'tcx> { .collect::<Vec<_>>(); if !added.is_empty() { - tcx.dcx().emit_err(errors::PtrCastAddAutoToObject { - span: self.span, - traits_len: added.len(), - traits: { - let mut traits: Vec<_> = added - .into_iter() - .map(|trait_did| tcx.def_path_str(trait_did)) - .collect(); - - traits.sort(); - traits.into() - }, - }); + return Err(CastError::PtrPtrAddingAutoTrait(added)); } Ok(CastKind::PtrPtrCast) diff --git a/compiler/rustc_hir_typeck/src/closure.rs b/compiler/rustc_hir_typeck/src/closure.rs index 71a0664bbdf..fc1f9a7f2e0 100644 --- a/compiler/rustc_hir_typeck/src/closure.rs +++ b/compiler/rustc_hir_typeck/src/closure.rs @@ -12,13 +12,14 @@ use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes, InferOk, use rustc_infer::traits::{ObligationCauseCode, PredicateObligations}; use rustc_macros::{TypeFoldable, TypeVisitable}; use rustc_middle::span_bug; -use rustc_middle::ty::visit::{TypeVisitable, TypeVisitableExt}; -use rustc_middle::ty::{self, GenericArgs, Ty, TyCtxt, TypeSuperVisitable, TypeVisitor}; +use rustc_middle::ty::{ + self, ClosureKind, GenericArgs, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, + TypeVisitableExt, TypeVisitor, +}; use rustc_span::def_id::LocalDefId; use rustc_span::{DUMMY_SP, Span}; use rustc_trait_selection::error_reporting::traits::ArgKind; use rustc_trait_selection::traits; -use rustc_type_ir::ClosureKind; use tracing::{debug, instrument, trace}; use super::{CoroutineTypes, Expectation, FnCtxt, check_fn}; diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index d7b5c1ed5e1..4cbc42b99ea 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -55,8 +55,7 @@ use rustc_middle::ty::adjustment::{ Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, PointerCoercion, }; use rustc_middle::ty::error::TypeError; -use rustc_middle::ty::visit::TypeVisitableExt; -use rustc_middle::ty::{self, AliasTy, GenericArgsRef, Ty, TyCtxt}; +use rustc_middle::ty::{self, AliasTy, GenericArgsRef, Ty, TyCtxt, TypeVisitableExt}; use rustc_span::{BytePos, DUMMY_SP, DesugaringKind, Span}; use rustc_trait_selection::infer::InferCtxtExt as _; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt; diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index aa917ee07ff..3eef32aa7c1 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -6,9 +6,8 @@ use rustc_infer::infer::DefineOpaqueTypes; use rustc_middle::bug; use rustc_middle::ty::adjustment::AllowTwoPhase; use rustc_middle::ty::error::{ExpectedFound, TypeError}; -use rustc_middle::ty::fold::BottomUpFolder; use rustc_middle::ty::print::with_no_trimmed_paths; -use rustc_middle::ty::{self, AssocItem, Ty, TypeFoldable, TypeVisitableExt}; +use rustc_middle::ty::{self, AssocItem, BottomUpFolder, Ty, TypeFoldable, TypeVisitableExt}; use rustc_span::{DUMMY_SP, Ident, Span, sym}; use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits::ObligationCause; diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 7c6bb495be3..7e8e4e3a561 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -2060,7 +2060,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // struct-like enums (yet...), but it's definitely not // a bug to have constructed one. if adt_kind != AdtKind::Enum { - tcx.check_stability(v_field.did, Some(expr.hir_id), field.span, None); + tcx.check_stability(v_field.did, Some(field.hir_id), field.span, None); } self.field_ty(field.span, v_field, args) diff --git a/compiler/rustc_hir_typeck/src/expr_use_visitor.rs b/compiler/rustc_hir_typeck/src/expr_use_visitor.rs index 63e4a8fb44b..35e687f2b0f 100644 --- a/compiler/rustc_hir_typeck/src/expr_use_visitor.rs +++ b/compiler/rustc_hir_typeck/src/expr_use_visitor.rs @@ -1840,7 +1840,8 @@ impl<'tcx, Cx: TypeInformationCtxt<'tcx>, D: Delegate<'tcx>> ExprUseVisitor<'tcx let ty = self.pat_ty_adjusted(subpat)?; let ty = Ty::new_ref(self.cx.tcx(), re_erased, ty, mutability); // A deref pattern generates a temporary. - let place = self.cat_rvalue(pat.hir_id, ty); + let base = self.cat_rvalue(pat.hir_id, ty); + let place = self.cat_deref(pat.hir_id, base)?; self.cat_pattern(place, subpat, op)?; } diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs index c82f7a91168..64886957ff3 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs @@ -21,11 +21,9 @@ use rustc_infer::infer::canonical::{Canonical, OriginalQueryValues, QueryRespons use rustc_infer::infer::{DefineOpaqueTypes, InferResult}; use rustc_lint::builtin::SELF_CONSTRUCTOR_FROM_OUTER_ITEM; use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow, AutoBorrowMutability}; -use rustc_middle::ty::fold::TypeFoldable; -use rustc_middle::ty::visit::{TypeVisitable, TypeVisitableExt}; use rustc_middle::ty::{ self, AdtKind, CanonicalUserType, GenericArgKind, GenericArgsRef, GenericParamDefKind, - IsIdentity, Ty, TyCtxt, UserArgs, UserSelfTy, + IsIdentity, Ty, TyCtxt, TypeFoldable, TypeVisitable, TypeVisitableExt, UserArgs, UserSelfTy, }; use rustc_middle::{bug, span_bug}; use rustc_session::lint; diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs index b8517701667..90bdb3c4b37 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs @@ -15,11 +15,10 @@ use rustc_index::IndexVec; use rustc_infer::infer::{DefineOpaqueTypes, InferOk, TypeTrace}; use rustc_middle::ty::adjustment::AllowTwoPhase; use rustc_middle::ty::error::TypeError; -use rustc_middle::ty::visit::TypeVisitableExt; -use rustc_middle::ty::{self, IsSuggestable, Ty, TyCtxt}; +use rustc_middle::ty::{self, IsSuggestable, Ty, TyCtxt, TypeVisitableExt}; use rustc_middle::{bug, span_bug}; use rustc_session::Session; -use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym}; +use rustc_span::{DUMMY_SP, Ident, Span, kw, sym}; use rustc_trait_selection::error_reporting::infer::{FailureCode, ObligationCauseExt}; use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits::{self, ObligationCauseCode, ObligationCtxt, SelectionContext}; @@ -2679,7 +2678,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { params.get(is_method as usize..params.len() - sig.decl.c_variadic as usize)?; debug_assert_eq!(params.len(), fn_inputs.len()); Some(( - fn_inputs.zip(params.iter().map(|param| FnParam::Name(param))).collect(), + fn_inputs.zip(params.iter().map(|¶m| FnParam::Name(param))).collect(), generics, )) } @@ -2710,23 +2709,14 @@ impl<'tcx> Visitor<'tcx> for FindClosureArg<'tcx> { #[derive(Clone, Copy)] enum FnParam<'hir> { Param(&'hir hir::Param<'hir>), - Name(&'hir Ident), + Name(Ident), } + impl FnParam<'_> { fn span(&self) -> Span { match self { - Self::Param(x) => x.span, - Self::Name(x) => x.span, - } - } - - fn name(&self) -> Option<Symbol> { - match self { - Self::Param(x) if let hir::PatKind::Binding(_, _, ident, _) = x.pat.kind => { - Some(ident.name) - } - Self::Name(x) if x.name != kw::Empty => Some(x.name), - _ => None, + Self::Param(param) => param.span, + Self::Name(ident) => ident.span, } } @@ -2734,8 +2724,23 @@ impl FnParam<'_> { struct D<'a>(FnParam<'a>, usize); impl fmt::Display for D<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - if let Some(name) = self.0.name() { - write!(f, "`{name}`") + // A "unique" param name is one that (a) exists, and (b) is guaranteed to be unique + // among the parameters, i.e. `_` does not count. + let unique_name = match self.0 { + FnParam::Param(param) + if let hir::PatKind::Binding(_, _, ident, _) = param.pat.kind => + { + Some(ident.name) + } + FnParam::Name(ident) + if ident.name != kw::Empty && ident.name != kw::Underscore => + { + Some(ident.name) + } + _ => None, + }; + if let Some(unique_name) = unique_name { + write!(f, "`{unique_name}`") } else { write!(f, "parameter #{}", self.1 + 1) } diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/inspect_obligations.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/inspect_obligations.rs index dc10b53fd83..95b9cb3be62 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/inspect_obligations.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/inspect_obligations.rs @@ -1,13 +1,12 @@ //! A utility module to inspect currently ambiguous obligations in the current context. use rustc_infer::traits::{self, ObligationCause, PredicateObligations}; -use rustc_middle::traits::solve::Goal; +use rustc_middle::traits::solve::{Goal, GoalSource}; use rustc_middle::ty::{self, Ty, TypeVisitableExt}; use rustc_span::Span; use rustc_trait_selection::solve::inspect::{ InspectConfig, InspectGoal, ProofTreeInferCtxtExt, ProofTreeVisitor, }; -use rustc_type_ir::solve::GoalSource; use tracing::{debug, instrument, trace}; use crate::FnCtxt; diff --git a/compiler/rustc_hir_typeck/src/method/confirm.rs b/compiler/rustc_hir_typeck/src/method/confirm.rs index 0483164ca03..a614b4f00ff 100644 --- a/compiler/rustc_hir_typeck/src/method/confirm.rs +++ b/compiler/rustc_hir_typeck/src/method/confirm.rs @@ -15,9 +15,9 @@ use rustc_middle::traits::ObligationCauseCode; use rustc_middle::ty::adjustment::{ Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, PointerCoercion, }; -use rustc_middle::ty::fold::TypeFoldable; use rustc_middle::ty::{ - self, GenericArgs, GenericArgsRef, GenericParamDefKind, Ty, TyCtxt, TypeVisitableExt, UserArgs, + self, GenericArgs, GenericArgsRef, GenericParamDefKind, Ty, TyCtxt, TypeFoldable, + TypeVisitableExt, UserArgs, }; use rustc_middle::{bug, span_bug}; use rustc_span::{DUMMY_SP, Span}; diff --git a/compiler/rustc_hir_typeck/src/method/probe.rs b/compiler/rustc_hir_typeck/src/method/probe.rs index ee01d78965d..0a01ec89a32 100644 --- a/compiler/rustc_hir_typeck/src/method/probe.rs +++ b/compiler/rustc_hir_typeck/src/method/probe.rs @@ -14,6 +14,7 @@ use rustc_infer::infer::{self, DefineOpaqueTypes, InferOk, TyCtxtInferExt}; use rustc_infer::traits::ObligationCauseCode; use rustc_middle::middle::stability; use rustc_middle::query::Providers; +use rustc_middle::ty::elaborate::supertrait_def_ids; use rustc_middle::ty::fast_reject::{TreatParams, simplify_type}; use rustc_middle::ty::{ self, AssocItem, AssocItemContainer, GenericArgs, GenericArgsRef, GenericParamDefKind, @@ -34,7 +35,6 @@ use rustc_trait_selection::traits::query::method_autoderef::{ CandidateStep, MethodAutoderefBadTy, MethodAutoderefStepsResult, }; use rustc_trait_selection::traits::{self, ObligationCause, ObligationCtxt}; -use rustc_type_ir::elaborate::supertrait_def_ids; use smallvec::{SmallVec, smallvec}; use tracing::{debug, instrument}; diff --git a/compiler/rustc_hir_typeck/src/op.rs b/compiler/rustc_hir_typeck/src/op.rs index 1750c2af1c7..a473e14b244 100644 --- a/compiler/rustc_hir_typeck/src/op.rs +++ b/compiler/rustc_hir_typeck/src/op.rs @@ -15,7 +15,6 @@ use rustc_span::source_map::Spanned; use rustc_span::{Ident, Span, sym}; use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits::{FulfillmentError, Obligation, ObligationCtxt}; -use rustc_type_ir::TyKind::*; use tracing::debug; use {rustc_ast as ast, rustc_hir as hir}; @@ -519,7 +518,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { { suggest_deref_binop(&mut err, lhs_deref_ty); } else if is_assign == IsAssign::No - && let Ref(region, lhs_deref_ty, mutbl) = lhs_ty.kind() + && let ty::Ref(region, lhs_deref_ty, mutbl) = lhs_ty.kind() { if self.type_is_copy_modulo_regions(self.param_env, *lhs_deref_ty) { suggest_deref_binop(&mut err, *lhs_deref_ty); @@ -536,7 +535,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { None, ); - if let Ref(region, rhs_deref_ty, mutbl) = rhs_ty.kind() { + if let ty::Ref(region, rhs_deref_ty, mutbl) = rhs_ty.kind() { let rhs_inv_mutbl = mutbl.invert(); let rhs_inv_mutbl_ty = Ty::new_ref(self.tcx, *region, *rhs_deref_ty, rhs_inv_mutbl); @@ -726,12 +725,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { |ty: Ty<'tcx>| ty.ty_adt_def().is_some_and(|ty_def| Some(ty_def.did()) == string_type); match (lhs_ty.kind(), rhs_ty.kind()) { - (&Ref(_, l_ty, _), &Ref(_, r_ty, _)) // &str or &String + &str, &String or &&str - if (*l_ty.kind() == Str || is_std_string(l_ty)) - && (*r_ty.kind() == Str + (&ty::Ref(_, l_ty, _), &ty::Ref(_, r_ty, _)) // &str or &String + &str, &String or &&str + if (*l_ty.kind() == ty::Str || is_std_string(l_ty)) + && (*r_ty.kind() == ty::Str || is_std_string(r_ty) || matches!( - r_ty.kind(), Ref(_, inner_ty, _) if *inner_ty.kind() == Str + r_ty.kind(), ty::Ref(_, inner_ty, _) if *inner_ty.kind() == ty::Str )) => { if let IsAssign::No = is_assign { // Do not supply this message if `&str += &str` @@ -755,8 +754,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } true } - (&Ref(_, l_ty, _), &Adt(..)) // Handle `&str` & `&String` + `String` - if (*l_ty.kind() == Str || is_std_string(l_ty)) && is_std_string(rhs_ty) => + (&ty::Ref(_, l_ty, _), &ty::Adt(..)) // Handle `&str` & `&String` + `String` + if (*l_ty.kind() == ty::Str || is_std_string(l_ty)) && is_std_string(rhs_ty) => { err.span_label( op.span, @@ -847,7 +846,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp)); } else { match actual.kind() { - Uint(_) if op == hir::UnOp::Neg => { + ty::Uint(_) if op == hir::UnOp::Neg => { err.note("unsigned values cannot be negated"); if let hir::ExprKind::Unary( @@ -881,8 +880,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ); } } - Str | Never | Char | Tuple(_) | Array(_, _) => {} - Ref(_, lty, _) if *lty.kind() == Str => {} + ty::Str | ty::Never | ty::Char | ty::Tuple(_) | ty::Array(_, _) => {} + ty::Ref(_, lty, _) if *lty.kind() == ty::Str => {} _ => { self.note_unmet_impls_on_type(&mut err, errors, true); } diff --git a/compiler/rustc_hir_typeck/src/pat.rs b/compiler/rustc_hir_typeck/src/pat.rs index 7e6973259fe..3d1c61a9c34 100644 --- a/compiler/rustc_hir_typeck/src/pat.rs +++ b/compiler/rustc_hir_typeck/src/pat.rs @@ -1422,7 +1422,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.tcx.check_stability( variant.fields[FieldIdx::from_usize(i)].did, - Some(pat.hir_id), + Some(subpat.hir_id), subpat.span, None, ); @@ -1686,7 +1686,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .get(&ident) .map(|(i, f)| { self.write_field_index(field.hir_id, *i); - self.tcx.check_stability(f.did, Some(pat.hir_id), span, None); + self.tcx.check_stability(f.did, Some(field.hir_id), span, None); self.field_ty(span, f, args) }) .unwrap_or_else(|| { diff --git a/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs b/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs index 381606a9fb0..88f4f7caa95 100644 --- a/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs +++ b/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs @@ -7,8 +7,7 @@ use rustc_hir::def_id::LocalDefId; use rustc_hir::{HirId, HirIdMap}; use rustc_infer::infer::{InferCtxt, InferOk, TyCtxtInferExt}; use rustc_middle::span_bug; -use rustc_middle::ty::visit::TypeVisitableExt; -use rustc_middle::ty::{self, Ty, TyCtxt, TypingMode}; +use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt, TypingMode}; use rustc_span::Span; use rustc_span::def_id::LocalDefIdMap; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt; diff --git a/compiler/rustc_hir_typeck/src/writeback.rs b/compiler/rustc_hir_typeck/src/writeback.rs index d7d7d6a20ac..6a3417ae5d6 100644 --- a/compiler/rustc_hir_typeck/src/writeback.rs +++ b/compiler/rustc_hir_typeck/src/writeback.rs @@ -11,9 +11,9 @@ use rustc_hir::{self as hir, AmbigArg, HirId}; use rustc_middle::span_bug; use rustc_middle::traits::ObligationCause; use rustc_middle::ty::adjustment::{Adjust, Adjustment, PointerCoercion}; -use rustc_middle::ty::fold::{TypeFoldable, TypeFolder, fold_regions}; -use rustc_middle::ty::visit::TypeVisitableExt; -use rustc_middle::ty::{self, Ty, TyCtxt, TypeSuperFoldable}; +use rustc_middle::ty::{ + self, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt, fold_regions, +}; use rustc_span::{Span, sym}; use rustc_trait_selection::error_reporting::infer::need_type_info::TypeAnnotationNeeded; use rustc_trait_selection::solve; diff --git a/compiler/rustc_index/src/bit_set.rs b/compiler/rustc_index/src/bit_set.rs index 598409c9051..07934389158 100644 --- a/compiler/rustc_index/src/bit_set.rs +++ b/compiler/rustc_index/src/bit_set.rs @@ -7,7 +7,7 @@ use std::{fmt, iter, slice}; use Chunk::*; #[cfg(feature = "nightly")] -use rustc_macros::{Decodable_Generic, Encodable_Generic}; +use rustc_macros::{Decodable_NoContext, Encodable_NoContext}; use smallvec::{SmallVec, smallvec}; use crate::{Idx, IndexVec}; @@ -114,7 +114,7 @@ macro_rules! bit_relations_inherent_impls { /// to or greater than the domain size. All operations that involve two bitsets /// will panic if the bitsets have differing domain sizes. /// -#[cfg_attr(feature = "nightly", derive(Decodable_Generic, Encodable_Generic))] +#[cfg_attr(feature = "nightly", derive(Decodable_NoContext, Encodable_NoContext))] #[derive(Eq, PartialEq, Hash)] pub struct DenseBitSet<T> { domain_size: usize, @@ -1392,7 +1392,7 @@ impl<T: Idx> From<DenseBitSet<T>> for GrowableBitSet<T> { /// /// All operations that involve a row and/or column index will panic if the /// index exceeds the relevant bound. -#[cfg_attr(feature = "nightly", derive(Decodable_Generic, Encodable_Generic))] +#[cfg_attr(feature = "nightly", derive(Decodable_NoContext, Encodable_NoContext))] #[derive(Clone, Eq, PartialEq, Hash)] pub struct BitMatrix<R: Idx, C: Idx> { num_rows: usize, @@ -1816,7 +1816,7 @@ impl std::fmt::Debug for FiniteBitSet<u32> { /// A fixed-sized bitset type represented by an integer type. Indices outwith than the range /// representable by `T` are considered set. -#[cfg_attr(feature = "nightly", derive(Decodable_Generic, Encodable_Generic))] +#[cfg_attr(feature = "nightly", derive(Decodable_NoContext, Encodable_NoContext))] #[derive(Copy, Clone, Eq, PartialEq)] pub struct FiniteBitSet<T: FiniteBitSetTy>(pub T); diff --git a/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs b/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs index c47f27e871f..307110d9fbc 100644 --- a/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs +++ b/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs @@ -8,9 +8,9 @@ use rustc_data_structures::fx::FxHashMap; use rustc_index::Idx; use rustc_middle::bug; -use rustc_middle::ty::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable}; use rustc_middle::ty::{ - self, BoundVar, GenericArg, InferConst, List, Ty, TyCtxt, TypeFlags, TypeVisitableExt, + self, BoundVar, GenericArg, InferConst, List, Ty, TyCtxt, TypeFlags, TypeFoldable, TypeFolder, + TypeSuperFoldable, TypeVisitableExt, }; use smallvec::SmallVec; use tracing::debug; diff --git a/compiler/rustc_infer/src/infer/canonical/instantiate.rs b/compiler/rustc_infer/src/infer/canonical/instantiate.rs index c10df2ec02e..f5ee5702d09 100644 --- a/compiler/rustc_infer/src/infer/canonical/instantiate.rs +++ b/compiler/rustc_infer/src/infer/canonical/instantiate.rs @@ -8,8 +8,7 @@ use rustc_macros::extension; use rustc_middle::bug; -use rustc_middle::ty::fold::{FnMutDelegate, TypeFoldable}; -use rustc_middle::ty::{self, GenericArgKind, TyCtxt}; +use rustc_middle::ty::{self, FnMutDelegate, GenericArgKind, TyCtxt, TypeFoldable}; use crate::infer::canonical::{Canonical, CanonicalVarValues}; diff --git a/compiler/rustc_infer/src/infer/canonical/mod.rs b/compiler/rustc_infer/src/infer/canonical/mod.rs index fb5fc3a53fe..3be07dbe208 100644 --- a/compiler/rustc_infer/src/infer/canonical/mod.rs +++ b/compiler/rustc_infer/src/infer/canonical/mod.rs @@ -24,8 +24,7 @@ pub use instantiate::CanonicalExt; use rustc_index::IndexVec; pub use rustc_middle::infer::canonical::*; -use rustc_middle::ty::fold::TypeFoldable; -use rustc_middle::ty::{self, GenericArg, List, Ty, TyCtxt}; +use rustc_middle::ty::{self, GenericArg, List, Ty, TyCtxt, TypeFoldable}; use rustc_span::Span; use crate::infer::{InferCtxt, RegionVariableOrigin}; diff --git a/compiler/rustc_infer/src/infer/canonical/query_response.rs b/compiler/rustc_infer/src/infer/canonical/query_response.rs index 8a61631c69c..d53f631cc07 100644 --- a/compiler/rustc_infer/src/infer/canonical/query_response.rs +++ b/compiler/rustc_infer/src/infer/canonical/query_response.rs @@ -13,8 +13,7 @@ use std::iter; use rustc_index::{Idx, IndexVec}; use rustc_middle::arena::ArenaAllocatable; use rustc_middle::mir::ConstraintCategory; -use rustc_middle::ty::fold::TypeFoldable; -use rustc_middle::ty::{self, BoundVar, GenericArg, GenericArgKind, Ty, TyCtxt}; +use rustc_middle::ty::{self, BoundVar, GenericArg, GenericArgKind, Ty, TyCtxt, TypeFoldable}; use rustc_middle::{bug, span_bug}; use tracing::{debug, instrument}; diff --git a/compiler/rustc_infer/src/infer/context.rs b/compiler/rustc_infer/src/infer/context.rs index eae69ec3e0f..75affa13977 100644 --- a/compiler/rustc_infer/src/infer/context.rs +++ b/compiler/rustc_infer/src/infer/context.rs @@ -1,10 +1,9 @@ ///! Definition of `InferCtxtLike` from the librarified type layer. use rustc_hir::def_id::DefId; use rustc_middle::traits::ObligationCause; -use rustc_middle::ty::fold::TypeFoldable; use rustc_middle::ty::relate::RelateResult; use rustc_middle::ty::relate::combine::PredicateEmittingRelation; -use rustc_middle::ty::{self, Ty, TyCtxt}; +use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable}; use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span}; use super::{BoundRegionConversionTime, InferCtxt, RegionVariableOrigin, SubregionOrigin}; diff --git a/compiler/rustc_infer/src/infer/freshen.rs b/compiler/rustc_infer/src/infer/freshen.rs index 74c8b463fc8..f2bb66ff736 100644 --- a/compiler/rustc_infer/src/infer/freshen.rs +++ b/compiler/rustc_infer/src/infer/freshen.rs @@ -35,8 +35,9 @@ use std::collections::hash_map::Entry; use rustc_data_structures::fx::FxHashMap; use rustc_middle::bug; -use rustc_middle::ty::fold::TypeFolder; -use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable, TypeSuperFoldable, TypeVisitableExt}; +use rustc_middle::ty::{ + self, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt, +}; use super::InferCtxt; 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 03c4614af13..91595de97f7 100644 --- a/compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs +++ b/compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs @@ -9,10 +9,9 @@ use rustc_data_structures::graph::implementation::{ use rustc_data_structures::intern::Interned; use rustc_data_structures::unord::UnordSet; use rustc_index::{IndexSlice, IndexVec}; -use rustc_middle::ty::fold::{TypeFoldable, fold_regions}; use rustc_middle::ty::{ self, ReBound, ReEarlyParam, ReErased, ReError, ReLateParam, RePlaceholder, ReStatic, ReVar, - Region, RegionVid, Ty, TyCtxt, + Region, RegionVid, Ty, TyCtxt, TypeFoldable, fold_regions, }; use rustc_middle::{bug, span_bug}; use rustc_span::Span; diff --git a/compiler/rustc_infer/src/infer/mod.rs b/compiler/rustc_infer/src/infer/mod.rs index 537e8119ada..fa8dea064da 100644 --- a/compiler/rustc_infer/src/infer/mod.rs +++ b/compiler/rustc_infer/src/infer/mod.rs @@ -28,14 +28,11 @@ use rustc_middle::infer::canonical::{CanonicalQueryInput, CanonicalVarValues}; use rustc_middle::mir::ConstraintCategory; use rustc_middle::traits::select; use rustc_middle::ty::error::{ExpectedFound, TypeError}; -use rustc_middle::ty::fold::{ - BoundVarReplacerDelegate, TypeFoldable, TypeFolder, TypeSuperFoldable, fold_regions, -}; -use rustc_middle::ty::visit::TypeVisitableExt; use rustc_middle::ty::{ - self, ConstVid, FloatVid, GenericArg, GenericArgKind, GenericArgs, GenericArgsRef, - GenericParamDefKind, InferConst, IntVid, PseudoCanonicalInput, Ty, TyCtxt, TyVid, - TypeVisitable, TypingEnv, TypingMode, + self, BoundVarReplacerDelegate, ConstVid, FloatVid, GenericArg, GenericArgKind, GenericArgs, + GenericArgsRef, GenericParamDefKind, InferConst, IntVid, PseudoCanonicalInput, Ty, TyCtxt, + TyVid, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitable, TypeVisitableExt, TypingEnv, + TypingMode, fold_regions, }; use rustc_span::{Span, Symbol}; use snapshot::undo_log::InferCtxtUndoLogs; diff --git a/compiler/rustc_infer/src/infer/opaque_types/mod.rs b/compiler/rustc_infer/src/infer/opaque_types/mod.rs index f6ef3f40e62..3fa1923121a 100644 --- a/compiler/rustc_infer/src/infer/opaque_types/mod.rs +++ b/compiler/rustc_infer/src/infer/opaque_types/mod.rs @@ -5,9 +5,9 @@ use rustc_middle::bug; use rustc_middle::traits::ObligationCause; use rustc_middle::traits::solve::Goal; use rustc_middle::ty::error::{ExpectedFound, TypeError}; -use rustc_middle::ty::fold::BottomUpFolder; use rustc_middle::ty::{ - self, OpaqueHiddenType, OpaqueTypeKey, Ty, TyCtxt, TypeFoldable, TypeVisitableExt, + self, BottomUpFolder, OpaqueHiddenType, OpaqueTypeKey, Ty, TyCtxt, TypeFoldable, + TypeVisitableExt, }; use rustc_span::Span; use tracing::{debug, instrument}; diff --git a/compiler/rustc_infer/src/infer/relate/generalize.rs b/compiler/rustc_infer/src/infer/relate/generalize.rs index ce2d07f4af9..e16212955ff 100644 --- a/compiler/rustc_infer/src/infer/relate/generalize.rs +++ b/compiler/rustc_infer/src/infer/relate/generalize.rs @@ -5,10 +5,9 @@ use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_hir::def_id::DefId; use rustc_middle::bug; use rustc_middle::ty::error::TypeError; -use rustc_middle::ty::visit::MaxUniverse; use rustc_middle::ty::{ - self, AliasRelationDirection, InferConst, Term, Ty, TyCtxt, TypeVisitable, TypeVisitableExt, - TypingMode, + self, AliasRelationDirection, InferConst, MaxUniverse, Term, Ty, TyCtxt, TypeVisitable, + TypeVisitableExt, TypingMode, }; use rustc_span::Span; use tracing::{debug, instrument, warn}; diff --git a/compiler/rustc_infer/src/infer/relate/higher_ranked.rs b/compiler/rustc_infer/src/infer/relate/higher_ranked.rs index a12d83db91f..2143f72a3b0 100644 --- a/compiler/rustc_infer/src/infer/relate/higher_ranked.rs +++ b/compiler/rustc_infer/src/infer/relate/higher_ranked.rs @@ -1,9 +1,7 @@ //! Helper routines for higher-ranked things. See the `doc` module at //! the end of the file for details. -use rustc_middle::ty::fold::FnMutDelegate; -use rustc_middle::ty::visit::TypeVisitableExt; -use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable}; +use rustc_middle::ty::{self, FnMutDelegate, Ty, TyCtxt, TypeFoldable, TypeVisitableExt}; use tracing::{debug, instrument}; use super::RelateResult; diff --git a/compiler/rustc_infer/src/infer/resolve.rs b/compiler/rustc_infer/src/infer/resolve.rs index 6ec2e0152f0..4a99c220975 100644 --- a/compiler/rustc_infer/src/infer/resolve.rs +++ b/compiler/rustc_infer/src/infer/resolve.rs @@ -1,7 +1,8 @@ use rustc_middle::bug; -use rustc_middle::ty::fold::{FallibleTypeFolder, TypeFolder, TypeSuperFoldable}; -use rustc_middle::ty::visit::TypeVisitableExt; -use rustc_middle::ty::{self, Const, InferConst, Ty, TyCtxt, TypeFoldable}; +use rustc_middle::ty::{ + self, Const, FallibleTypeFolder, InferConst, Ty, TyCtxt, TypeFoldable, TypeFolder, + TypeSuperFoldable, TypeVisitableExt, +}; use rustc_type_ir::data_structures::DelayedMap; use super::{FixupError, FixupResult, InferCtxt}; diff --git a/compiler/rustc_infer/src/infer/snapshot/fudge.rs b/compiler/rustc_infer/src/infer/snapshot/fudge.rs index 3a47b13665d..b5d3c26b05e 100644 --- a/compiler/rustc_infer/src/infer/snapshot/fudge.rs +++ b/compiler/rustc_infer/src/infer/snapshot/fudge.rs @@ -1,9 +1,11 @@ use std::ops::Range; use rustc_data_structures::{snapshot_vec as sv, unify as ut}; -use rustc_middle::ty::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable}; -use rustc_middle::ty::{self, ConstVid, FloatVid, IntVid, RegionVid, Ty, TyCtxt, TyVid}; -use rustc_type_ir::visit::TypeVisitableExt; +use rustc_middle::ty::{ + self, ConstVid, FloatVid, IntVid, RegionVid, Ty, TyCtxt, TyVid, TypeFoldable, TypeFolder, + TypeSuperFoldable, +}; +use rustc_type_ir::TypeVisitableExt; use tracing::instrument; use ut::UnifyKey; diff --git a/compiler/rustc_infer/src/traits/structural_impls.rs b/compiler/rustc_infer/src/traits/structural_impls.rs index b346e193d0b..4335073d9bc 100644 --- a/compiler/rustc_infer/src/traits/structural_impls.rs +++ b/compiler/rustc_infer/src/traits/structural_impls.rs @@ -1,8 +1,8 @@ use std::fmt; -use rustc_middle::ty::fold::{FallibleTypeFolder, TypeFoldable}; -use rustc_middle::ty::visit::{TypeVisitable, TypeVisitor, try_visit}; -use rustc_middle::ty::{self, TyCtxt}; +use rustc_middle::ty::{ + self, FallibleTypeFolder, TyCtxt, TypeFoldable, TypeVisitable, TypeVisitor, try_visit, +}; use crate::traits; use crate::traits::project::Normalized; diff --git a/compiler/rustc_lint/Cargo.toml b/compiler/rustc_lint/Cargo.toml index d6014f5006a..7718f16984d 100644 --- a/compiler/rustc_lint/Cargo.toml +++ b/compiler/rustc_lint/Cargo.toml @@ -23,7 +23,6 @@ rustc_session = { path = "../rustc_session" } rustc_span = { path = "../rustc_span" } rustc_target = { path = "../rustc_target" } rustc_trait_selection = { path = "../rustc_trait_selection" } -rustc_type_ir = { path = "../rustc_type_ir" } smallvec = { version = "1.8.1", features = ["union", "may_dangle"] } tracing = "0.1" unicode-security = "0.1.0" diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index 918a42f3047..b4892e73842 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -2582,34 +2582,35 @@ impl<'tcx> LateLintPass<'tcx> for InvalidValue { ) -> Option<InitError> { let ty = cx.tcx.try_normalize_erasing_regions(cx.typing_env(), ty).unwrap_or(ty); - use rustc_type_ir::TyKind::*; match ty.kind() { // Primitive types that don't like 0 as a value. - Ref(..) => Some("references must be non-null".into()), - Adt(..) if ty.is_box() => Some("`Box` must be non-null".into()), - FnPtr(..) => Some("function pointers must be non-null".into()), - Never => Some("the `!` type has no valid value".into()), - RawPtr(ty, _) if matches!(ty.kind(), Dynamic(..)) => + ty::Ref(..) => Some("references must be non-null".into()), + ty::Adt(..) if ty.is_box() => Some("`Box` must be non-null".into()), + ty::FnPtr(..) => Some("function pointers must be non-null".into()), + ty::Never => Some("the `!` type has no valid value".into()), + ty::RawPtr(ty, _) if matches!(ty.kind(), ty::Dynamic(..)) => // raw ptr to dyn Trait { Some("the vtable of a wide raw pointer must be non-null".into()) } // Primitive types with other constraints. - Bool if init == InitKind::Uninit => { + ty::Bool if init == InitKind::Uninit => { Some("booleans must be either `true` or `false`".into()) } - Char if init == InitKind::Uninit => { + ty::Char if init == InitKind::Uninit => { Some("characters must be a valid Unicode codepoint".into()) } - Int(_) | Uint(_) if init == InitKind::Uninit => { + ty::Int(_) | ty::Uint(_) if init == InitKind::Uninit => { Some("integers must be initialized".into()) } - Float(_) if init == InitKind::Uninit => Some("floats must be initialized".into()), - RawPtr(_, _) if init == InitKind::Uninit => { + ty::Float(_) if init == InitKind::Uninit => { + Some("floats must be initialized".into()) + } + ty::RawPtr(_, _) if init == InitKind::Uninit => { Some("raw pointers must be initialized".into()) } // Recurse and checks for some compound types. (but not unions) - Adt(adt_def, args) if !adt_def.is_union() => { + ty::Adt(adt_def, args) if !adt_def.is_union() => { // Handle structs. if adt_def.is_struct() { return variant_find_init_error( @@ -2675,11 +2676,11 @@ impl<'tcx> LateLintPass<'tcx> for InvalidValue { // We couldn't find anything wrong here. None } - Tuple(..) => { + ty::Tuple(..) => { // Proceed recursively, check all fields. ty.tuple_fields().iter().find_map(|field| ty_find_init_error(cx, field, init)) } - Array(ty, len) => { + ty::Array(ty, len) => { if matches!(len.try_to_target_usize(cx.tcx), Some(v) if v > 0) { // Array length known at array non-empty -- recurse. ty_find_init_error(cx, *ty, init) diff --git a/compiler/rustc_lint/src/enum_intrinsics_non_enums.rs b/compiler/rustc_lint/src/enum_intrinsics_non_enums.rs index 7ead8eafbd5..179f2bcf07f 100644 --- a/compiler/rustc_lint/src/enum_intrinsics_non_enums.rs +++ b/compiler/rustc_lint/src/enum_intrinsics_non_enums.rs @@ -1,6 +1,5 @@ use rustc_hir as hir; -use rustc_middle::ty::Ty; -use rustc_middle::ty::visit::TypeVisitableExt; +use rustc_middle::ty::{Ty, TypeVisitableExt}; use rustc_session::{declare_lint, declare_lint_pass}; use rustc_span::{Span, sym}; diff --git a/compiler/rustc_lint/src/foreign_modules.rs b/compiler/rustc_lint/src/foreign_modules.rs index 6175415c31f..0494c78a7a9 100644 --- a/compiler/rustc_lint/src/foreign_modules.rs +++ b/compiler/rustc_lint/src/foreign_modules.rs @@ -270,14 +270,12 @@ fn structurally_same_type_impl<'tcx>( true } else { // Do a full, depth-first comparison between the two. - use rustc_type_ir::TyKind::*; - let is_primitive_or_pointer = - |ty: Ty<'tcx>| ty.is_primitive() || matches!(ty.kind(), RawPtr(..) | Ref(..)); + |ty: Ty<'tcx>| ty.is_primitive() || matches!(ty.kind(), ty::RawPtr(..) | ty::Ref(..)); ensure_sufficient_stack(|| { match (a.kind(), b.kind()) { - (&Adt(a_def, a_gen_args), &Adt(b_def, b_gen_args)) => { + (&ty::Adt(a_def, a_gen_args), &ty::Adt(b_def, b_gen_args)) => { // Only `repr(C)` types can be compared structurally. if !(a_def.repr().c() && b_def.repr().c()) { return false; @@ -308,30 +306,30 @@ fn structurally_same_type_impl<'tcx>( }, ) } - (Array(a_ty, a_len), Array(b_ty, b_len)) => { + (ty::Array(a_ty, a_len), ty::Array(b_ty, b_len)) => { // For arrays, we also check the length. a_len == b_len && structurally_same_type_impl( seen_types, tcx, typing_env, *a_ty, *b_ty, ckind, ) } - (Slice(a_ty), Slice(b_ty)) => { + (ty::Slice(a_ty), ty::Slice(b_ty)) => { structurally_same_type_impl(seen_types, tcx, typing_env, *a_ty, *b_ty, ckind) } - (RawPtr(a_ty, a_mutbl), RawPtr(b_ty, b_mutbl)) => { + (ty::RawPtr(a_ty, a_mutbl), ty::RawPtr(b_ty, b_mutbl)) => { a_mutbl == b_mutbl && structurally_same_type_impl( seen_types, tcx, typing_env, *a_ty, *b_ty, ckind, ) } - (Ref(_a_region, a_ty, a_mut), Ref(_b_region, b_ty, b_mut)) => { + (ty::Ref(_a_region, a_ty, a_mut), ty::Ref(_b_region, b_ty, b_mut)) => { // For structural sameness, we don't need the region to be same. a_mut == b_mut && structurally_same_type_impl( seen_types, tcx, typing_env, *a_ty, *b_ty, ckind, ) } - (FnDef(..), FnDef(..)) => { + (ty::FnDef(..), ty::FnDef(..)) => { let a_poly_sig = a.fn_sig(tcx); let b_poly_sig = b.fn_sig(tcx); @@ -354,35 +352,38 @@ fn structurally_same_type_impl<'tcx>( ckind, ) } - (Tuple(..), Tuple(..)) => { + (ty::Tuple(..), ty::Tuple(..)) => { // Tuples are not `repr(C)` so these cannot be compared structurally. false } // For these, it's not quite as easy to define structural-sameness quite so easily. // For the purposes of this lint, take the conservative approach and mark them as // not structurally same. - (Dynamic(..), Dynamic(..)) - | (Error(..), Error(..)) - | (Closure(..), Closure(..)) - | (Coroutine(..), Coroutine(..)) - | (CoroutineWitness(..), CoroutineWitness(..)) - | (Alias(ty::Projection, ..), Alias(ty::Projection, ..)) - | (Alias(ty::Inherent, ..), Alias(ty::Inherent, ..)) - | (Alias(ty::Opaque, ..), Alias(ty::Opaque, ..)) => false, + (ty::Dynamic(..), ty::Dynamic(..)) + | (ty::Error(..), ty::Error(..)) + | (ty::Closure(..), ty::Closure(..)) + | (ty::Coroutine(..), ty::Coroutine(..)) + | (ty::CoroutineWitness(..), ty::CoroutineWitness(..)) + | (ty::Alias(ty::Projection, ..), ty::Alias(ty::Projection, ..)) + | (ty::Alias(ty::Inherent, ..), ty::Alias(ty::Inherent, ..)) + | (ty::Alias(ty::Opaque, ..), ty::Alias(ty::Opaque, ..)) => false, // These definitely should have been caught above. - (Bool, Bool) | (Char, Char) | (Never, Never) | (Str, Str) => unreachable!(), + (ty::Bool, ty::Bool) + | (ty::Char, ty::Char) + | (ty::Never, ty::Never) + | (ty::Str, ty::Str) => unreachable!(), // An Adt and a primitive or pointer type. This can be FFI-safe if non-null // enum layout optimisation is being applied. - (Adt(..) | Pat(..), _) if is_primitive_or_pointer(b) => { + (ty::Adt(..) | ty::Pat(..), _) if is_primitive_or_pointer(b) => { if let Some(a_inner) = types::repr_nullable_ptr(tcx, typing_env, a, ckind) { a_inner == b } else { false } } - (_, Adt(..) | Pat(..)) if is_primitive_or_pointer(a) => { + (_, ty::Adt(..) | ty::Pat(..)) if is_primitive_or_pointer(a) => { if let Some(b_inner) = types::repr_nullable_ptr(tcx, typing_env, b, ckind) { b_inner == a } else { diff --git a/compiler/rustc_lint/src/impl_trait_overcaptures.rs b/compiler/rustc_lint/src/impl_trait_overcaptures.rs index 0b3af7d6aba..c2404a7b843 100644 --- a/compiler/rustc_lint/src/impl_trait_overcaptures.rs +++ b/compiler/rustc_lint/src/impl_trait_overcaptures.rs @@ -506,9 +506,9 @@ impl<'tcx> TypeRelation<TyCtxt<'tcx>> for FunctionalVariances<'tcx> { self.tcx } - fn relate_with_variance<T: ty::relate::Relate<TyCtxt<'tcx>>>( + fn relate_with_variance<T: Relate<TyCtxt<'tcx>>>( &mut self, - variance: rustc_type_ir::Variance, + variance: ty::Variance, _: ty::VarianceDiagInfo<TyCtxt<'tcx>>, a: T, b: T, diff --git a/compiler/rustc_lint/src/levels.rs b/compiler/rustc_lint/src/levels.rs index aa6eef906ea..8718fb807ec 100644 --- a/compiler/rustc_lint/src/levels.rs +++ b/compiler/rustc_lint/src/levels.rs @@ -299,6 +299,11 @@ impl<'tcx> Visitor<'tcx> for LintLevelsBuilder<'_, LintLevelQueryMap<'tcx>> { intravisit::walk_expr(self, e); } + fn visit_pat_field(&mut self, f: &'tcx hir::PatField<'tcx>) -> Self::Result { + self.add_id(f.hir_id); + intravisit::walk_pat_field(self, f); + } + fn visit_expr_field(&mut self, f: &'tcx hir::ExprField<'tcx>) { self.add_id(f.hir_id); intravisit::walk_expr_field(self, f); diff --git a/compiler/rustc_lint/src/nonstandard_style.rs b/compiler/rustc_lint/src/nonstandard_style.rs index 722779d3268..9e4fdd2b3ce 100644 --- a/compiler/rustc_lint/src/nonstandard_style.rs +++ b/compiler/rustc_lint/src/nonstandard_style.rs @@ -274,18 +274,13 @@ impl NonSnakeCase { let ident = ident.trim_start_matches('\''); let ident = ident.trim_matches('_'); - let mut allow_underscore = true; - ident.chars().all(|c| { - allow_underscore = match c { - '_' if !allow_underscore => return false, - '_' => false, - // It would be more obvious to use `c.is_lowercase()`, - // but some characters do not have a lowercase form - c if !c.is_uppercase() => true, - _ => return false, - }; - true - }) + if ident.contains("__") { + return false; + } + + // This correctly handles letters in languages with and without + // cases, as well as numbers and underscores. + !ident.chars().any(char::is_uppercase) } let name = ident.name.as_str(); diff --git a/compiler/rustc_lint/src/opaque_hidden_inferred_bound.rs b/compiler/rustc_lint/src/opaque_hidden_inferred_bound.rs index 659f6d98f03..f836094191e 100644 --- a/compiler/rustc_lint/src/opaque_hidden_inferred_bound.rs +++ b/compiler/rustc_lint/src/opaque_hidden_inferred_bound.rs @@ -1,9 +1,8 @@ use rustc_hir::{self as hir, AmbigArg}; use rustc_infer::infer::TyCtxtInferExt; use rustc_macros::{LintDiagnostic, Subdiagnostic}; -use rustc_middle::ty::fold::BottomUpFolder; use rustc_middle::ty::print::{PrintTraitPredicateExt as _, TraitPredPrintModifiersAndPath}; -use rustc_middle::ty::{self, Ty, TypeFoldable}; +use rustc_middle::ty::{self, BottomUpFolder, Ty, TypeFoldable}; use rustc_session::{declare_lint, declare_lint_pass}; use rustc_span::{Span, kw}; use rustc_trait_selection::traits::{self, ObligationCtxt}; diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index 6f3c32af5ef..7be48a769fe 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -1422,7 +1422,7 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { fn check_for_opaque_ty(&mut self, sp: Span, ty: Ty<'tcx>) -> bool { struct ProhibitOpaqueTypes; - impl<'tcx> ty::visit::TypeVisitor<TyCtxt<'tcx>> for ProhibitOpaqueTypes { + impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for ProhibitOpaqueTypes { type Result = ControlFlow<Ty<'tcx>>; fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result { @@ -1564,7 +1564,7 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { } } - impl<'tcx> ty::visit::TypeVisitor<TyCtxt<'tcx>> for FnPtrFinder<'tcx> { + impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for FnPtrFinder<'tcx> { type Result = (); fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result { diff --git a/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp b/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp index bc3d4d6f83a..86f1bcc46ee 100644 --- a/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp +++ b/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp @@ -1682,12 +1682,21 @@ extern "C" void LLVMRustComputeLTOCacheKey(RustStringRef KeyOut, #endif // Based on the 'InProcessThinBackend' constructor in LLVM +#if LLVM_VERSION_GE(21, 0) + for (auto &Name : Data->Index.cfiFunctionDefs().symbols()) + CfiFunctionDefs.insert( + GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Name))); + for (auto &Name : Data->Index.cfiFunctionDecls().symbols()) + CfiFunctionDecls.insert( + GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Name))); +#else for (auto &Name : Data->Index.cfiFunctionDefs()) CfiFunctionDefs.insert( GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Name))); for (auto &Name : Data->Index.cfiFunctionDecls()) CfiFunctionDecls.insert( GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Name))); +#endif #if LLVM_VERSION_GE(20, 0) Key = llvm::computeLTOCacheKey(conf, Data->Index, ModId, ImportList, diff --git a/compiler/rustc_macros/src/lib.rs b/compiler/rustc_macros/src/lib.rs index 44ba064dd82..edb25e79904 100644 --- a/compiler/rustc_macros/src/lib.rs +++ b/compiler/rustc_macros/src/lib.rs @@ -74,8 +74,8 @@ decl_derive!( hash_stable::hash_stable_no_context_derive ); -decl_derive!([Decodable_Generic] => serialize::decodable_generic_derive); -decl_derive!([Encodable_Generic] => serialize::encodable_generic_derive); +decl_derive!([Decodable_NoContext] => serialize::decodable_nocontext_derive); +decl_derive!([Encodable_NoContext] => serialize::encodable_nocontext_derive); decl_derive!([Decodable] => serialize::decodable_derive); decl_derive!([Encodable] => serialize::encodable_derive); decl_derive!([TyDecodable] => serialize::type_decodable_derive); diff --git a/compiler/rustc_macros/src/serialize.rs b/compiler/rustc_macros/src/serialize.rs index 2c33a0ac0aa..673e6cd618f 100644 --- a/compiler/rustc_macros/src/serialize.rs +++ b/compiler/rustc_macros/src/serialize.rs @@ -6,16 +6,11 @@ use syn::spanned::Spanned; pub(super) fn type_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 }); + } 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>> } - } else if s.ast().generics.type_params().any(|ty| ty.ident == "I") { - quote! { <I = I> } - } else { - quote! {} - }; - - s.add_impl_generic(parse_quote! { #decoder_ty: ::rustc_type_ir::codec::TyDecoder #bound }); + s.add_impl_generic(parse_quote! { #decoder_ty: ::rustc_middle::ty::codec::TyDecoder<'tcx> }); s.add_bounds(synstructure::AddBounds::Fields); s.underscore_const(true); @@ -45,12 +40,12 @@ pub(super) fn decodable_derive(mut s: synstructure::Structure<'_>) -> proc_macro decodable_body(s, decoder_ty) } -pub(super) fn decodable_generic_derive( +pub(super) fn decodable_nocontext_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); + s.add_bounds(synstructure::AddBounds::Fields); s.underscore_const(true); decodable_body(s, decoder_ty) @@ -132,16 +127,11 @@ fn decode_field(field: &syn::Field) -> 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") { - quote! { <I = I> } - } else { - quote! {} - }; - let encoder_ty = quote! { __E }; - s.add_impl_generic(parse_quote! { #encoder_ty: ::rustc_type_ir::codec::TyEncoder #bound }); + if !s.ast().generics.lifetimes().any(|lt| lt.lifetime.ident == "tcx") { + s.add_impl_generic(parse_quote! { 'tcx }); + } + s.add_impl_generic(parse_quote! { #encoder_ty: ::rustc_middle::ty::codec::TyEncoder<'tcx> }); s.add_bounds(synstructure::AddBounds::Fields); s.underscore_const(true); @@ -171,12 +161,12 @@ pub(super) fn encodable_derive(mut s: synstructure::Structure<'_>) -> proc_macro encodable_body(s, encoder_ty, false) } -pub(super) fn encodable_generic_derive( +pub(super) fn encodable_nocontext_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); + s.add_bounds(synstructure::AddBounds::Fields); s.underscore_const(true); encodable_body(s, encoder_ty, false) diff --git a/compiler/rustc_macros/src/type_foldable.rs b/compiler/rustc_macros/src/type_foldable.rs index bc3b82c2893..c4f584dca43 100644 --- a/compiler/rustc_macros/src/type_foldable.rs +++ b/compiler/rustc_macros/src/type_foldable.rs @@ -38,16 +38,16 @@ pub(super) fn type_foldable_derive(mut s: synstructure::Structure<'_>) -> proc_m bind.to_token_stream() } else { quote! { - ::rustc_middle::ty::fold::TypeFoldable::try_fold_with(#bind, __folder)? + ::rustc_middle::ty::TypeFoldable::try_fold_with(#bind, __folder)? } } }) }); s.bound_impl( - quote!(::rustc_middle::ty::fold::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>), + quote!(::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>), quote! { - fn try_fold_with<__F: ::rustc_middle::ty::fold::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>( + fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>( self, __folder: &mut __F ) -> Result<Self, __F::Error> { diff --git a/compiler/rustc_macros/src/type_visitable.rs b/compiler/rustc_macros/src/type_visitable.rs index a7906d50d0f..fb37e1a39ed 100644 --- a/compiler/rustc_macros/src/type_visitable.rs +++ b/compiler/rustc_macros/src/type_visitable.rs @@ -36,12 +36,12 @@ pub(super) fn type_visitable_derive( s.add_bounds(synstructure::AddBounds::Generics); let body_visit = s.each(|bind| { quote! { - match ::rustc_middle::ty::visit::VisitorResult::branch( - ::rustc_middle::ty::visit::TypeVisitable::visit_with(#bind, __visitor) + match ::rustc_middle::ty::VisitorResult::branch( + ::rustc_middle::ty::TypeVisitable::visit_with(#bind, __visitor) ) { ::core::ops::ControlFlow::Continue(()) => {}, ::core::ops::ControlFlow::Break(r) => { - return ::rustc_middle::ty::visit::VisitorResult::from_residual(r); + return ::rustc_middle::ty::VisitorResult::from_residual(r); }, } } @@ -49,14 +49,14 @@ pub(super) fn type_visitable_derive( s.bind_with(|_| synstructure::BindStyle::Move); s.bound_impl( - quote!(::rustc_middle::ty::visit::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>), + quote!(::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>), quote! { - fn visit_with<__V: ::rustc_middle::ty::visit::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>( + fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>( &self, __visitor: &mut __V ) -> __V::Result { match *self { #body_visit } - <__V::Result as ::rustc_middle::ty::visit::VisitorResult>::output() + <__V::Result as ::rustc_middle::ty::VisitorResult>::output() } }, ) diff --git a/compiler/rustc_metadata/Cargo.toml b/compiler/rustc_metadata/Cargo.toml index a8821640f04..1f5d41014d4 100644 --- a/compiler/rustc_metadata/Cargo.toml +++ b/compiler/rustc_metadata/Cargo.toml @@ -27,7 +27,6 @@ rustc_serialize = { path = "../rustc_serialize" } rustc_session = { path = "../rustc_session" } rustc_span = { path = "../rustc_span" } rustc_target = { path = "../rustc_target" } -rustc_type_ir = { path = "../rustc_type_ir" } tempfile = "3.2" tracing = "0.1" # tidy-alphabetical-end diff --git a/compiler/rustc_metadata/src/rmeta/decoder.rs b/compiler/rustc_metadata/src/rmeta/decoder.rs index 6ffbebfffd5..e60904eebeb 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder.rs @@ -386,13 +386,11 @@ impl<'a, 'tcx> DecodeContext<'a, 'tcx> { } } -impl<'a, 'tcx> TyDecoder for DecodeContext<'a, 'tcx> { +impl<'a, 'tcx> TyDecoder<'tcx> for DecodeContext<'a, 'tcx> { const CLEAR_CROSS_CRATE: bool = true; - type I = TyCtxt<'tcx>; - #[inline] - fn interner(&self) -> Self::I { + fn interner(&self) -> TyCtxt<'tcx> { self.tcx() } diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 57c941976e4..2b9113242aa 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -378,11 +378,9 @@ impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for [u8] { } } -impl<'a, 'tcx> TyEncoder for EncodeContext<'a, 'tcx> { +impl<'a, 'tcx> TyEncoder<'tcx> for EncodeContext<'a, 'tcx> { const CLEAR_CROSS_CRATE: bool = true; - type I = TyCtxt<'tcx>; - fn position(&self) -> usize { self.opaque.position() } diff --git a/compiler/rustc_middle/src/hir/map.rs b/compiler/rustc_middle/src/hir/map.rs index 73c0af84a9f..c61c7a4fb02 100644 --- a/compiler/rustc_middle/src/hir/map.rs +++ b/compiler/rustc_middle/src/hir/map.rs @@ -281,8 +281,9 @@ impl<'tcx> TyCtxt<'tcx> { } pub fn hir_body_param_names(self, id: BodyId) -> impl Iterator<Item = Ident> { - self.hir_body(id).params.iter().map(|arg| match arg.pat.kind { + self.hir_body(id).params.iter().map(|param| match param.pat.kind { PatKind::Binding(_, _, ident, _) => ident, + PatKind::Wild => Ident::new(kw::Underscore, param.pat.span), _ => Ident::empty(), }) } diff --git a/compiler/rustc_middle/src/macros.rs b/compiler/rustc_middle/src/macros.rs index b5f3a0e1482..0ae774ebee7 100644 --- a/compiler/rustc_middle/src/macros.rs +++ b/compiler/rustc_middle/src/macros.rs @@ -59,8 +59,8 @@ macro_rules! TrivialLiftImpls { macro_rules! TrivialTypeTraversalImpls { ($($ty:ty),+ $(,)?) => { $( - impl<'tcx> $crate::ty::fold::TypeFoldable<$crate::ty::TyCtxt<'tcx>> for $ty { - fn try_fold_with<F: $crate::ty::fold::FallibleTypeFolder<$crate::ty::TyCtxt<'tcx>>>( + impl<'tcx> $crate::ty::TypeFoldable<$crate::ty::TyCtxt<'tcx>> for $ty { + fn try_fold_with<F: $crate::ty::FallibleTypeFolder<$crate::ty::TyCtxt<'tcx>>>( self, _: &mut F, ) -> ::std::result::Result<Self, F::Error> { @@ -68,7 +68,7 @@ macro_rules! TrivialTypeTraversalImpls { } #[inline] - fn fold_with<F: $crate::ty::fold::TypeFolder<$crate::ty::TyCtxt<'tcx>>>( + fn fold_with<F: $crate::ty::TypeFolder<$crate::ty::TyCtxt<'tcx>>>( self, _: &mut F, ) -> Self { @@ -76,14 +76,14 @@ macro_rules! TrivialTypeTraversalImpls { } } - impl<'tcx> $crate::ty::visit::TypeVisitable<$crate::ty::TyCtxt<'tcx>> for $ty { + impl<'tcx> $crate::ty::TypeVisitable<$crate::ty::TyCtxt<'tcx>> for $ty { #[inline] - fn visit_with<F: $crate::ty::visit::TypeVisitor<$crate::ty::TyCtxt<'tcx>>>( + fn visit_with<F: $crate::ty::TypeVisitor<$crate::ty::TyCtxt<'tcx>>>( &self, _: &mut F) -> F::Result { - <F::Result as ::rustc_middle::ty::visit::VisitorResult>::output() + <F::Result as ::rustc_middle::ty::VisitorResult>::output() } } )+ diff --git a/compiler/rustc_middle/src/mir/consts.rs b/compiler/rustc_middle/src/mir/consts.rs index 923160cc0cc..34b27c2e1cc 100644 --- a/compiler/rustc_middle/src/mir/consts.rs +++ b/compiler/rustc_middle/src/mir/consts.rs @@ -6,7 +6,7 @@ use rustc_macros::{HashStable, Lift, TyDecodable, TyEncodable, TypeFoldable, Typ use rustc_session::RemapFileNameExt; use rustc_session::config::RemapPathScopeComponents; use rustc_span::{DUMMY_SP, Span, Symbol}; -use rustc_type_ir::visit::TypeVisitableExt; +use rustc_type_ir::TypeVisitableExt; use super::interpret::ReportedErrorInfo; use crate::mir::interpret::{AllocId, ConstAllocation, ErrorHandled, Scalar, alloc_range}; diff --git a/compiler/rustc_middle/src/mir/interpret/allocation.rs b/compiler/rustc_middle/src/mir/interpret/allocation.rs index aed38414ab1..57aafbb26bc 100644 --- a/compiler/rustc_middle/src/mir/interpret/allocation.rs +++ b/compiler/rustc_middle/src/mir/interpret/allocation.rs @@ -16,8 +16,7 @@ use rustc_abi::{Align, HasDataLayout, Size}; use rustc_ast::Mutability; use rustc_data_structures::intern::Interned; use rustc_macros::HashStable; -use rustc_serialize::{Decodable, Encodable}; -use rustc_type_ir::{TyDecoder, TyEncoder}; +use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; use super::{ AllocId, BadBytesAccess, CtfeProvenance, InterpErrorKind, InterpResult, Pointer, @@ -112,7 +111,7 @@ struct AllocFlags { all_zero: bool, } -impl<E: TyEncoder> Encodable<E> for AllocFlags { +impl<E: Encoder> Encodable<E> for AllocFlags { fn encode(&self, encoder: &mut E) { // Make sure Align::MAX can be stored with the high 2 bits unset. const { @@ -131,7 +130,7 @@ impl<E: TyEncoder> Encodable<E> for AllocFlags { } } -impl<D: TyDecoder> Decodable<D> for AllocFlags { +impl<D: Decoder> Decodable<D> for AllocFlags { fn decode(decoder: &mut D) -> Self { let flags: u8 = Decodable::decode(decoder); let align = flags & 0b0011_1111; @@ -173,7 +172,7 @@ fn all_zero(buf: &[u8]) -> bool { } /// Custom encoder for [`Allocation`] to more efficiently represent the case where all bytes are 0. -impl<Prov: Provenance, Extra, Bytes, E: TyEncoder> Encodable<E> for Allocation<Prov, Extra, Bytes> +impl<Prov: Provenance, Extra, Bytes, E: Encoder> Encodable<E> for Allocation<Prov, Extra, Bytes> where Bytes: AllocBytes, ProvenanceMap<Prov>: Encodable<E>, @@ -193,7 +192,7 @@ where } } -impl<Prov: Provenance, Extra, Bytes, D: TyDecoder> Decodable<D> for Allocation<Prov, Extra, Bytes> +impl<Prov: Provenance, Extra, Bytes, D: Decoder> Decodable<D> for Allocation<Prov, Extra, Bytes> where Bytes: AllocBytes, ProvenanceMap<Prov>: Decodable<D>, 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 fea5038e6dd..20492cda4e2 100644 --- a/compiler/rustc_middle/src/mir/interpret/allocation/init_mask.rs +++ b/compiler/rustc_middle/src/mir/interpret/allocation/init_mask.rs @@ -5,9 +5,8 @@ use std::ops::Range; use std::{hash, iter}; use rustc_abi::Size; -use rustc_macros::{HashStable, TyDecodable, TyEncodable}; -use rustc_serialize::{Decodable, Encodable}; -use rustc_type_ir::{TyDecoder, TyEncoder}; +use rustc_macros::{Decodable_NoContext, Encodable_NoContext, HashStable}; +use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; use super::AllocRange; @@ -19,13 +18,13 @@ type Block = u64; /// possible. Currently, if all the blocks have the same value, then the mask represents either a /// fully initialized or fully uninitialized const allocation, so we can only store that single /// value. -#[derive(Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)] +#[derive(Clone, Debug, Eq, PartialEq, Encodable_NoContext, Decodable_NoContext, Hash, HashStable)] pub struct InitMask { blocks: InitMaskBlocks, len: Size, } -#[derive(Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)] +#[derive(Clone, Debug, Eq, PartialEq, Encodable_NoContext, Decodable_NoContext, Hash, HashStable)] enum InitMaskBlocks { Lazy { /// Whether the lazy init mask is fully initialized or uninitialized. @@ -194,7 +193,7 @@ struct InitMaskMaterialized { // and also produces more output when the high bits of each `u64` are occupied. // Note: There is probably a remaining optimization for masks that do not use an entire // `Block`. -impl<E: TyEncoder> Encodable<E> for InitMaskMaterialized { +impl<E: Encoder> Encodable<E> for InitMaskMaterialized { fn encode(&self, encoder: &mut E) { encoder.emit_usize(self.blocks.len()); for block in &self.blocks { @@ -204,7 +203,7 @@ impl<E: TyEncoder> Encodable<E> for InitMaskMaterialized { } // This implementation is deliberately not derived, see the matching `Encodable` impl. -impl<D: TyDecoder> Decodable<D> for InitMaskMaterialized { +impl<D: Decoder> Decodable<D> for InitMaskMaterialized { fn decode(decoder: &mut D) -> Self { let num_blocks = decoder.read_usize(); let mut blocks = Vec::with_capacity(num_blocks); diff --git a/compiler/rustc_middle/src/mir/interpret/mod.rs b/compiler/rustc_middle/src/mir/interpret/mod.rs index effedf854e4..c2438af6a1e 100644 --- a/compiler/rustc_middle/src/mir/interpret/mod.rs +++ b/compiler/rustc_middle/src/mir/interpret/mod.rs @@ -105,7 +105,7 @@ enum AllocDiscriminant { Static, } -pub fn specialized_encode_alloc_id<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>>( +pub fn specialized_encode_alloc_id<'tcx, E: TyEncoder<'tcx>>( encoder: &mut E, tcx: TyCtxt<'tcx>, alloc_id: AllocId, @@ -175,7 +175,7 @@ impl<'s> AllocDecodingSession<'s> { /// Decodes an `AllocId` in a thread-safe way. pub fn decode_alloc_id<'tcx, D>(&self, decoder: &mut D) -> AllocId where - D: TyDecoder<I = TyCtxt<'tcx>>, + D: TyDecoder<'tcx>, { // Read the index of the allocation. let idx = usize::try_from(decoder.read_u32()).unwrap(); diff --git a/compiler/rustc_middle/src/mir/interpret/queries.rs b/compiler/rustc_middle/src/mir/interpret/queries.rs index 78749428c6d..4222a68e544 100644 --- a/compiler/rustc_middle/src/mir/interpret/queries.rs +++ b/compiler/rustc_middle/src/mir/interpret/queries.rs @@ -10,8 +10,7 @@ use super::{ }; use crate::mir; use crate::query::TyCtxtEnsureOk; -use crate::ty::visit::TypeVisitableExt; -use crate::ty::{self, GenericArgs, TyCtxt}; +use crate::ty::{self, GenericArgs, TyCtxt, TypeVisitableExt}; impl<'tcx> TyCtxt<'tcx> { /// Evaluates a constant without providing any generic parameters. This is useful to evaluate consts diff --git a/compiler/rustc_middle/src/mir/mod.rs b/compiler/rustc_middle/src/mir/mod.rs index 83857ab6c5c..7090e93549e 100644 --- a/compiler/rustc_middle/src/mir/mod.rs +++ b/compiler/rustc_middle/src/mir/mod.rs @@ -32,10 +32,9 @@ pub use self::query::*; use crate::mir::interpret::{AllocRange, Scalar}; use crate::ty::codec::{TyDecoder, TyEncoder}; use crate::ty::print::{FmtPrinter, Printer, pretty_print_const, with_no_trimmed_paths}; -use crate::ty::visit::TypeVisitableExt; use crate::ty::{ - self, AdtDef, GenericArg, GenericArgsRef, Instance, InstanceKind, List, Ty, TyCtxt, TypingEnv, - UserTypeAnnotationIndex, + self, AdtDef, GenericArg, GenericArgsRef, Instance, InstanceKind, List, Ty, TyCtxt, + TypeVisitableExt, TypingEnv, UserTypeAnnotationIndex, }; mod basic_blocks; @@ -791,7 +790,7 @@ impl<T> ClearCrossCrate<T> { const TAG_CLEAR_CROSS_CRATE_CLEAR: u8 = 0; const TAG_CLEAR_CROSS_CRATE_SET: u8 = 1; -impl<E: TyEncoder, T: Encodable<E>> Encodable<E> for ClearCrossCrate<T> { +impl<'tcx, E: TyEncoder<'tcx>, T: Encodable<E>> Encodable<E> for ClearCrossCrate<T> { #[inline] fn encode(&self, e: &mut E) { if E::CLEAR_CROSS_CRATE { @@ -807,7 +806,7 @@ impl<E: TyEncoder, T: Encodable<E>> Encodable<E> for ClearCrossCrate<T> { } } } -impl<D: TyDecoder, T: Decodable<D>> Decodable<D> for ClearCrossCrate<T> { +impl<'tcx, D: TyDecoder<'tcx>, T: Decodable<D>> Decodable<D> for ClearCrossCrate<T> { #[inline] fn decode(d: &mut D) -> ClearCrossCrate<T> { if D::CLEAR_CROSS_CRATE { diff --git a/compiler/rustc_middle/src/mir/query.rs b/compiler/rustc_middle/src/mir/query.rs index 50494355e3e..5a9fe10938a 100644 --- a/compiler/rustc_middle/src/mir/query.rs +++ b/compiler/rustc_middle/src/mir/query.rs @@ -13,8 +13,7 @@ use rustc_span::{Span, Symbol}; use smallvec::SmallVec; use super::{ConstValue, SourceInfo}; -use crate::ty::fold::fold_regions; -use crate::ty::{self, CoroutineArgsExt, OpaqueHiddenType, Ty, TyCtxt}; +use crate::ty::{self, CoroutineArgsExt, OpaqueHiddenType, Ty, TyCtxt, fold_regions}; rustc_index::newtype_index! { #[derive(HashStable)] diff --git a/compiler/rustc_middle/src/query/on_disk_cache.rs b/compiler/rustc_middle/src/query/on_disk_cache.rs index d9035efaf56..e66958dfcb8 100644 --- a/compiler/rustc_middle/src/query/on_disk_cache.rs +++ b/compiler/rustc_middle/src/query/on_disk_cache.rs @@ -518,8 +518,7 @@ where value } -impl<'a, 'tcx> TyDecoder for CacheDecoder<'a, 'tcx> { - type I = TyCtxt<'tcx>; +impl<'a, 'tcx> TyDecoder<'tcx> for CacheDecoder<'a, 'tcx> { const CLEAR_CROSS_CRATE: bool = false; #[inline] @@ -943,8 +942,7 @@ impl<'a, 'tcx> SpanEncoder for CacheEncoder<'a, 'tcx> { } } -impl<'a, 'tcx> TyEncoder for CacheEncoder<'a, 'tcx> { - type I = TyCtxt<'tcx>; +impl<'a, 'tcx> TyEncoder<'tcx> for CacheEncoder<'a, 'tcx> { const CLEAR_CROSS_CRATE: bool = false; #[inline] diff --git a/compiler/rustc_middle/src/traits/solve.rs b/compiler/rustc_middle/src/traits/solve.rs index 9c74f6263b3..145561b76c4 100644 --- a/compiler/rustc_middle/src/traits/solve.rs +++ b/compiler/rustc_middle/src/traits/solve.rs @@ -3,9 +3,9 @@ use rustc_macros::HashStable; use rustc_type_ir as ir; pub use rustc_type_ir::solve::*; -use crate::ty::visit::try_visit; use crate::ty::{ self, FallibleTypeFolder, TyCtxt, TypeFoldable, TypeFolder, TypeVisitable, TypeVisitor, + try_visit, }; pub type Goal<'tcx, P> = ir::solve::Goal<TyCtxt<'tcx>, P>; diff --git a/compiler/rustc_middle/src/traits/specialization_graph.rs b/compiler/rustc_middle/src/traits/specialization_graph.rs index 8e54a9d487d..05c19db4caa 100644 --- a/compiler/rustc_middle/src/traits/specialization_graph.rs +++ b/compiler/rustc_middle/src/traits/specialization_graph.rs @@ -6,8 +6,7 @@ use rustc_span::sym; use crate::error::StrictCoherenceNeedsNegativeCoherence; use crate::ty::fast_reject::SimplifiedType; -use crate::ty::visit::TypeVisitableExt; -use crate::ty::{self, TyCtxt}; +use crate::ty::{self, TyCtxt, TypeVisitableExt}; /// A per-trait graph of impls in specialization order. At the moment, this /// graph forms a tree rooted with the trait itself, with all other nodes diff --git a/compiler/rustc_middle/src/ty/codec.rs b/compiler/rustc_middle/src/ty/codec.rs index fe42a224d9f..74b34afe616 100644 --- a/compiler/rustc_middle/src/ty/codec.rs +++ b/compiler/rustc_middle/src/ty/codec.rs @@ -14,9 +14,8 @@ use rustc_abi::{FieldIdx, VariantIdx}; use rustc_data_structures::fx::FxHashMap; use rustc_hir::def_id::LocalDefId; use rustc_serialize::{Decodable, Encodable}; -use rustc_span::Span; use rustc_span::source_map::Spanned; -pub use rustc_type_ir::{TyDecoder, TyEncoder}; +use rustc_span::{Span, SpanDecoder, SpanEncoder}; use crate::arena::ArenaAllocatable; use crate::infer::canonical::{CanonicalVarInfo, CanonicalVarInfos}; @@ -31,13 +30,45 @@ use crate::ty::{self, AdtDef, GenericArgsRef, Ty, TyCtxt}; /// This offset is also chosen so that the first byte is never < 0x80. pub const SHORTHAND_OFFSET: usize = 0x80; -pub trait EncodableWithShorthand<E: TyEncoder>: Copy + Eq + Hash { +pub trait TyEncoder<'tcx>: SpanEncoder { + const CLEAR_CROSS_CRATE: bool; + + fn position(&self) -> usize; + + fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize>; + + fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize>; + + fn encode_alloc_id(&mut self, alloc_id: &AllocId); +} + +pub trait TyDecoder<'tcx>: SpanDecoder { + const CLEAR_CROSS_CRATE: bool; + + fn interner(&self) -> TyCtxt<'tcx>; + + fn cached_ty_for_shorthand<F>(&mut self, shorthand: usize, or_insert_with: F) -> Ty<'tcx> + where + F: FnOnce(&mut Self) -> Ty<'tcx>; + + fn with_position<F, R>(&mut self, pos: usize, f: F) -> R + where + F: FnOnce(&mut Self) -> R; + + fn positioned_at_shorthand(&self) -> bool { + (self.peek_byte() & (SHORTHAND_OFFSET as u8)) != 0 + } + + fn decode_alloc_id(&mut self) -> AllocId; +} + +pub trait EncodableWithShorthand<'tcx, E: TyEncoder<'tcx>>: Copy + Eq + Hash { type Variant: Encodable<E>; fn variant(&self) -> &Self::Variant; } #[allow(rustc::usage_of_ty_tykind)] -impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> EncodableWithShorthand<E> for Ty<'tcx> { +impl<'tcx, E: TyEncoder<'tcx>> EncodableWithShorthand<'tcx, E> for Ty<'tcx> { type Variant = ty::TyKind<'tcx>; #[inline] @@ -46,7 +77,7 @@ impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> EncodableWithShorthand<E> for Ty<'tcx } } -impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> EncodableWithShorthand<E> for ty::PredicateKind<'tcx> { +impl<'tcx, E: TyEncoder<'tcx>> EncodableWithShorthand<'tcx, E> for ty::PredicateKind<'tcx> { type Variant = ty::PredicateKind<'tcx>; #[inline] @@ -65,16 +96,16 @@ impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> EncodableWithShorthand<E> for ty::Pre /// /// `Decodable` can still be implemented in cases where `Decodable` is required /// by a trait bound. -pub trait RefDecodable<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> { +pub trait RefDecodable<'tcx, D: TyDecoder<'tcx>> { fn decode(d: &mut D) -> &'tcx Self; } /// Encode the given value or a previously cached shorthand. pub fn encode_with_shorthand<'tcx, E, T, M>(encoder: &mut E, value: &T, cache: M) where - E: TyEncoder<I = TyCtxt<'tcx>>, + E: TyEncoder<'tcx>, M: for<'b> Fn(&'b mut E) -> &'b mut FxHashMap<T, usize>, - T: EncodableWithShorthand<E>, + T: EncodableWithShorthand<'tcx, E>, // The discriminant and shorthand must have the same size. T::Variant: DiscriminantKind<Discriminant = isize>, { @@ -108,13 +139,13 @@ where } } -impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for Ty<'tcx> { +impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for Ty<'tcx> { fn encode(&self, e: &mut E) { encode_with_shorthand(e, self, TyEncoder::type_shorthands); } } -impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for ty::Predicate<'tcx> { +impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for ty::Predicate<'tcx> { fn encode(&self, e: &mut E) { let kind = self.kind(); kind.bound_vars().encode(e); @@ -122,76 +153,72 @@ impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for ty::Predicate<'tcx> } } -impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for ty::Clause<'tcx> { +impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for ty::Clause<'tcx> { fn encode(&self, e: &mut E) { self.as_predicate().encode(e); } } -impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for ty::Region<'tcx> { +impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for ty::Region<'tcx> { fn encode(&self, e: &mut E) { self.kind().encode(e); } } -impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for ty::Const<'tcx> { +impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for ty::Const<'tcx> { fn encode(&self, e: &mut E) { self.0.0.encode(e); } } -impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for ty::Pattern<'tcx> { +impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for ty::Pattern<'tcx> { fn encode(&self, e: &mut E) { self.0.0.encode(e); } } -impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for ty::ValTree<'tcx> { +impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for ty::ValTree<'tcx> { fn encode(&self, e: &mut E) { self.0.0.encode(e); } } -impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for ConstAllocation<'tcx> { +impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for ConstAllocation<'tcx> { fn encode(&self, e: &mut E) { self.inner().encode(e) } } -impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for AdtDef<'tcx> { +impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for AdtDef<'tcx> { fn encode(&self, e: &mut E) { self.0.0.encode(e) } } -impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for AllocId { +impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for AllocId { fn encode(&self, e: &mut E) { e.encode_alloc_id(self) } } -impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for CtfeProvenance { +impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for CtfeProvenance { fn encode(&self, e: &mut E) { self.into_parts().encode(e); } } -impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for ty::ParamEnv<'tcx> { +impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for ty::ParamEnv<'tcx> { fn encode(&self, e: &mut E) { self.caller_bounds().encode(e); } } #[inline] -fn decode_arena_allocable< - 'tcx, - D: TyDecoder<I = TyCtxt<'tcx>>, - T: ArenaAllocatable<'tcx> + Decodable<D>, ->( +fn decode_arena_allocable<'tcx, D: TyDecoder<'tcx>, T: ArenaAllocatable<'tcx> + Decodable<D>>( decoder: &mut D, ) -> &'tcx T where - D: TyDecoder, + D: TyDecoder<'tcx>, { decoder.interner().arena.alloc(Decodable::decode(decoder)) } @@ -199,18 +226,18 @@ where #[inline] fn decode_arena_allocable_slice< 'tcx, - D: TyDecoder<I = TyCtxt<'tcx>>, + D: TyDecoder<'tcx>, T: ArenaAllocatable<'tcx> + Decodable<D>, >( decoder: &mut D, ) -> &'tcx [T] where - D: TyDecoder, + D: TyDecoder<'tcx>, { decoder.interner().arena.alloc_from_iter(<Vec<T> as Decodable<D>>::decode(decoder)) } -impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for Ty<'tcx> { +impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for Ty<'tcx> { #[allow(rustc::usage_of_ty_tykind)] fn decode(decoder: &mut D) -> Ty<'tcx> { // Handle shorthands first, if we have a usize > 0x80. @@ -229,7 +256,7 @@ impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for Ty<'tcx> { } } -impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for ty::Predicate<'tcx> { +impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Predicate<'tcx> { fn decode(decoder: &mut D) -> ty::Predicate<'tcx> { let bound_vars = Decodable::decode(decoder); // Handle shorthands first, if we have a usize > 0x80. @@ -249,14 +276,14 @@ impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for ty::Predicate<'tcx> } } -impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for ty::Clause<'tcx> { +impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Clause<'tcx> { fn decode(decoder: &mut D) -> ty::Clause<'tcx> { let pred: ty::Predicate<'tcx> = Decodable::decode(decoder); pred.expect_clause() } } -impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for GenericArgsRef<'tcx> { +impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for GenericArgsRef<'tcx> { fn decode(decoder: &mut D) -> Self { let len = decoder.read_usize(); let tcx = decoder.interner(); @@ -266,7 +293,7 @@ impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for GenericArgsRef<'tcx> } } -impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for mir::Place<'tcx> { +impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for mir::Place<'tcx> { fn decode(decoder: &mut D) -> Self { let local: mir::Local = Decodable::decode(decoder); let len = decoder.read_usize(); @@ -277,13 +304,13 @@ impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for mir::Place<'tcx> { } } -impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for ty::Region<'tcx> { +impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Region<'tcx> { fn decode(decoder: &mut D) -> Self { ty::Region::new_from_kind(decoder.interner(), Decodable::decode(decoder)) } } -impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for CanonicalVarInfos<'tcx> { +impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for CanonicalVarInfos<'tcx> { fn decode(decoder: &mut D) -> Self { let len = decoder.read_usize(); decoder.interner().mk_canonical_var_infos_from_iter( @@ -292,26 +319,26 @@ impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for CanonicalVarInfos<'t } } -impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for AllocId { +impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for AllocId { fn decode(decoder: &mut D) -> Self { decoder.decode_alloc_id() } } -impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for CtfeProvenance { +impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for CtfeProvenance { fn decode(decoder: &mut D) -> Self { let parts = Decodable::decode(decoder); CtfeProvenance::from_parts(parts) } } -impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for ty::SymbolName<'tcx> { +impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::SymbolName<'tcx> { fn decode(decoder: &mut D) -> Self { ty::SymbolName::new(decoder.interner(), decoder.read_str()) } } -impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for ty::ParamEnv<'tcx> { +impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::ParamEnv<'tcx> { fn decode(d: &mut D) -> Self { let caller_bounds = Decodable::decode(d); ty::ParamEnv::new(caller_bounds) @@ -320,7 +347,7 @@ impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for ty::ParamEnv<'tcx> { macro_rules! impl_decodable_via_ref { ($($t:ty,)+) => { - $(impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for $t { + $(impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for $t { fn decode(decoder: &mut D) -> Self { RefDecodable::decode(decoder) } @@ -328,7 +355,7 @@ macro_rules! impl_decodable_via_ref { } } -impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for ty::List<Ty<'tcx>> { +impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::List<Ty<'tcx>> { fn decode(decoder: &mut D) -> &'tcx Self { let len = decoder.read_usize(); decoder @@ -337,7 +364,7 @@ impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for ty::List<Ty } } -impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> +impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::List<ty::PolyExistentialPredicate<'tcx>> { fn decode(decoder: &mut D) -> &'tcx Self { @@ -348,38 +375,38 @@ impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> } } -impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for ty::Const<'tcx> { +impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Const<'tcx> { fn decode(decoder: &mut D) -> Self { let kind: ty::ConstKind<'tcx> = Decodable::decode(decoder); decoder.interner().mk_ct_from_kind(kind) } } -impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for ty::Pattern<'tcx> { +impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::Pattern<'tcx> { fn decode(decoder: &mut D) -> Self { decoder.interner().mk_pat(Decodable::decode(decoder)) } } -impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for ty::ValTree<'tcx> { +impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ty::ValTree<'tcx> { fn decode(decoder: &mut D) -> Self { decoder.interner().intern_valtree(Decodable::decode(decoder)) } } -impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for ConstAllocation<'tcx> { +impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for ConstAllocation<'tcx> { fn decode(decoder: &mut D) -> Self { decoder.interner().mk_const_alloc(Decodable::decode(decoder)) } } -impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for AdtDef<'tcx> { +impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for AdtDef<'tcx> { fn decode(decoder: &mut D) -> Self { decoder.interner().mk_adt_def_from_data(Decodable::decode(decoder)) } } -impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for [(ty::Clause<'tcx>, Span)] { +impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [(ty::Clause<'tcx>, Span)] { fn decode(decoder: &mut D) -> &'tcx Self { decoder .interner() @@ -388,9 +415,7 @@ impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for [(ty::Claus } } -impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> - for [(ty::PolyTraitRef<'tcx>, Span)] -{ +impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [(ty::PolyTraitRef<'tcx>, Span)] { fn decode(decoder: &mut D) -> &'tcx Self { decoder .interner() @@ -399,7 +424,7 @@ impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> } } -impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for [Spanned<MonoItem<'tcx>>] { +impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [Spanned<MonoItem<'tcx>>] { fn decode(decoder: &mut D) -> &'tcx Self { decoder .interner() @@ -408,9 +433,7 @@ impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for [Spanned<Mo } } -impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> - for ty::List<ty::BoundVariableKind> -{ +impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::List<ty::BoundVariableKind> { fn decode(decoder: &mut D) -> &'tcx Self { let len = decoder.read_usize(); decoder.interner().mk_bound_variable_kinds_from_iter( @@ -419,7 +442,7 @@ impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> } } -impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for ty::List<ty::Const<'tcx>> { +impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::List<ty::Const<'tcx>> { fn decode(decoder: &mut D) -> &'tcx Self { let len = decoder.read_usize(); decoder.interner().mk_const_list_from_iter( @@ -428,7 +451,7 @@ impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for ty::List<ty } } -impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> +impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::ListWithCachedTypeInfo<ty::Clause<'tcx>> { fn decode(decoder: &mut D) -> &'tcx Self { @@ -439,7 +462,7 @@ impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> } } -impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for ty::List<FieldIdx> { +impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::List<FieldIdx> { fn decode(decoder: &mut D) -> &'tcx Self { let len = decoder.read_usize(); decoder @@ -448,7 +471,7 @@ impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for ty::List<Fi } } -impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for ty::List<LocalDefId> { +impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::List<LocalDefId> { fn decode(decoder: &mut D) -> &'tcx Self { let len = decoder.read_usize(); decoder.interner().mk_local_def_ids_from_iter( @@ -457,15 +480,13 @@ impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for ty::List<Lo } } -impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for &'tcx ty::List<LocalDefId> { +impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for &'tcx ty::List<LocalDefId> { fn decode(d: &mut D) -> Self { RefDecodable::decode(d) } } -impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> - for ty::List<(VariantIdx, FieldIdx)> -{ +impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for ty::List<(VariantIdx, FieldIdx)> { fn decode(decoder: &mut D) -> &'tcx Self { let len = decoder.read_usize(); decoder.interner().mk_offset_of_from_iter( @@ -503,14 +524,14 @@ macro_rules! impl_arena_allocatable_decoder { ([]$args:tt) => {}; ([decode $(, $attrs:ident)*] [$name:ident: $ty:ty]) => { - impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for $ty { + impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for $ty { #[inline] fn decode(decoder: &mut D) -> &'tcx Self { decode_arena_allocable(decoder) } } - impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for [$ty] { + impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [$ty] { #[inline] fn decode(decoder: &mut D) -> &'tcx Self { decode_arena_allocable_slice(decoder) @@ -532,14 +553,14 @@ arena_types!(impl_arena_allocatable_decoders); macro_rules! impl_arena_copy_decoder { (<$tcx:tt> $($ty:ty,)*) => { - $(impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for $ty { + $(impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for $ty { #[inline] fn decode(decoder: &mut D) -> &'tcx Self { decoder.interner().arena.alloc(Decodable::decode(decoder)) } } - impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> RefDecodable<'tcx, D> for [$ty] { + impl<'tcx, D: TyDecoder<'tcx>> RefDecodable<'tcx, D> for [$ty] { #[inline] fn decode(decoder: &mut D) -> &'tcx Self { decoder.interner().arena.alloc_from_iter(<Vec<_> as Decodable<D>>::decode(decoder)) diff --git a/compiler/rustc_middle/src/ty/consts.rs b/compiler/rustc_middle/src/ty/consts.rs index d30520a0222..ae1c6c670cb 100644 --- a/compiler/rustc_middle/src/ty/consts.rs +++ b/compiler/rustc_middle/src/ty/consts.rs @@ -34,7 +34,7 @@ impl<'tcx> rustc_type_ir::inherent::IntoKind for Const<'tcx> { } } -impl<'tcx> rustc_type_ir::visit::Flags for Const<'tcx> { +impl<'tcx> rustc_type_ir::Flags for Const<'tcx> { fn flags(&self) -> TypeFlags { self.0.flags } diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index a2472157d0e..f54dd2b0040 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -49,11 +49,10 @@ use rustc_session::{Limit, MetadataKind, Session}; use rustc_span::def_id::{CRATE_DEF_ID, DefPathHash, StableCrateId}; use rustc_span::{DUMMY_SP, Ident, Span, Symbol, kw, sym}; use rustc_type_ir::TyKind::*; -use rustc_type_ir::fold::TypeFoldable; use rustc_type_ir::lang_items::TraitSolverLangItem; pub use rustc_type_ir::lift::Lift; use rustc_type_ir::{ - CollectAndApply, Interner, TypeFlags, WithCachedTypeInfo, elaborate, search_graph, + CollectAndApply, Interner, TypeFlags, TypeFoldable, WithCachedTypeInfo, elaborate, search_graph, }; use tracing::{debug, instrument}; diff --git a/compiler/rustc_middle/src/ty/erase_regions.rs b/compiler/rustc_middle/src/ty/erase_regions.rs index ecca1d44907..f25c48cf42a 100644 --- a/compiler/rustc_middle/src/ty/erase_regions.rs +++ b/compiler/rustc_middle/src/ty/erase_regions.rs @@ -1,8 +1,9 @@ use tracing::debug; use crate::query::Providers; -use crate::ty::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable}; -use crate::ty::{self, Ty, TyCtxt, TypeFlags, TypeVisitableExt}; +use crate::ty::{ + self, Ty, TyCtxt, TypeFlags, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt, +}; pub(super) fn provide(providers: &mut Providers) { *providers = Providers { erase_regions_ty, ..*providers }; diff --git a/compiler/rustc_middle/src/ty/fold.rs b/compiler/rustc_middle/src/ty/fold.rs index 4ea4050ed8b..dc2c9e3d9f1 100644 --- a/compiler/rustc_middle/src/ty/fold.rs +++ b/compiler/rustc_middle/src/ty/fold.rs @@ -1,12 +1,11 @@ use rustc_data_structures::fx::FxIndexMap; use rustc_hir::def_id::DefId; use rustc_type_ir::data_structures::DelayedMap; -pub use rustc_type_ir::fold::{ - FallibleTypeFolder, TypeFoldable, TypeFolder, TypeSuperFoldable, fold_regions, shift_region, - shift_vars, -}; -use crate::ty::{self, Binder, BoundTy, Ty, TyCtxt, TypeVisitableExt}; +use crate::ty::{ + self, Binder, BoundTy, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, + TypeVisitableExt, +}; /////////////////////////////////////////////////////////////////////////// // Some sample folders @@ -129,7 +128,7 @@ where ty::Bound(debruijn, bound_ty) if debruijn == self.current_index => { let ty = self.delegate.replace_ty(bound_ty); debug_assert!(!ty.has_vars_bound_above(ty::INNERMOST)); - ty::fold::shift_vars(self.tcx, ty, self.current_index.as_u32()) + ty::shift_vars(self.tcx, ty, self.current_index.as_u32()) } _ => { if !t.has_vars_bound_at_or_above(self.current_index) { @@ -169,7 +168,7 @@ where ty::ConstKind::Bound(debruijn, bound_const) if debruijn == self.current_index => { let ct = self.delegate.replace_const(bound_const); debug_assert!(!ct.has_vars_bound_above(ty::INNERMOST)); - ty::fold::shift_vars(self.tcx, ct, self.current_index.as_u32()) + ty::shift_vars(self.tcx, ct, self.current_index.as_u32()) } _ => ct.super_fold_with(self), } diff --git a/compiler/rustc_middle/src/ty/generic_args.rs b/compiler/rustc_middle/src/ty/generic_args.rs index f24910477dc..e87859a55ed 100644 --- a/compiler/rustc_middle/src/ty/generic_args.rs +++ b/compiler/rustc_middle/src/ty/generic_args.rs @@ -8,16 +8,16 @@ use std::ptr::NonNull; use rustc_data_structures::intern::Interned; use rustc_errors::{DiagArgValue, IntoDiagArg}; use rustc_hir::def_id::DefId; -use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable, extension}; +use rustc_macros::{HashStable, TyDecodable, TyEncodable, extension}; use rustc_serialize::{Decodable, Encodable}; use rustc_type_ir::WithCachedTypeInfo; use smallvec::SmallVec; use crate::ty::codec::{TyDecoder, TyEncoder}; -use crate::ty::fold::{FallibleTypeFolder, TypeFoldable}; -use crate::ty::visit::{TypeVisitable, TypeVisitor, VisitorResult, walk_visitable_list}; use crate::ty::{ - self, ClosureArgs, CoroutineArgs, CoroutineClosureArgs, InlineConstArgs, Lift, List, Ty, TyCtxt, + self, ClosureArgs, CoroutineArgs, CoroutineClosureArgs, FallibleTypeFolder, InlineConstArgs, + Lift, List, Ty, TyCtxt, TypeFoldable, TypeVisitable, TypeVisitor, VisitorResult, + walk_visitable_list, }; pub type GenericArgKind<'tcx> = rustc_type_ir::GenericArgKind<TyCtxt<'tcx>>; @@ -334,13 +334,13 @@ impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for GenericArg<'tcx> { } } -impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for GenericArg<'tcx> { +impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for GenericArg<'tcx> { fn encode(&self, e: &mut E) { self.unpack().encode(e) } } -impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for GenericArg<'tcx> { +impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for GenericArg<'tcx> { fn decode(d: &mut D) -> GenericArg<'tcx> { GenericArgKind::decode(d).pack() } diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index ad9d32fd6c1..a508487c796 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -33,6 +33,7 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet}; use rustc_data_structures::intern::Interned; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::steal::Steal; +use rustc_data_structures::unord::UnordMap; use rustc_errors::{Diag, ErrorGuaranteed}; use rustc_hir::LangItem; use rustc_hir::def::{CtorKind, CtorOf, DefKind, DocLinkResMap, LifetimeRes, Res}; @@ -68,7 +69,7 @@ pub use self::context::{ CtxtInterners, CurrentGcx, DeducedParamAttrs, Feed, FreeRegionInfo, GlobalCtxt, Lift, TyCtxt, TyCtxtFeed, tls, }; -pub use self::fold::{FallibleTypeFolder, TypeFoldable, TypeFolder, TypeSuperFoldable}; +pub use self::fold::*; pub use self::instance::{Instance, InstanceKind, ReifyReason, ShortInstance, UnusedGenericParams}; pub use self::list::{List, ListWithCachedTypeInfo}; pub use self::opaque_types::OpaqueTypeKey; @@ -98,13 +99,14 @@ pub use self::typeck_results::{ CanonicalUserType, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, IsIdentity, Rust2024IncompatiblePatInfo, TypeckResults, UserType, UserTypeAnnotationIndex, UserTypeKind, }; -pub use self::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor}; +pub use self::visit::*; use crate::error::{OpaqueHiddenTypeMismatch, TypeMismatchReason}; use crate::metadata::ModChild; use crate::middle::privacy::EffectiveVisibilities; use crate::mir::{Body, CoroutineLayout}; use crate::query::{IntoQueryParam, Providers}; use crate::ty; +use crate::ty::codec::{TyDecoder, TyEncoder}; pub use crate::ty::diagnostics::*; use crate::ty::fast_reject::SimplifiedType; use crate::ty::util::Discr; @@ -116,7 +118,6 @@ pub mod codec; pub mod error; pub mod fast_reject; pub mod flags; -pub mod fold; pub mod inhabitedness; pub mod layout; pub mod normalize_erasing_regions; @@ -126,7 +127,6 @@ pub mod relate; pub mod significant_drop_order; pub mod trait_def; pub mod util; -pub mod visit; pub mod vtable; pub mod walk; @@ -138,6 +138,7 @@ mod context; mod diagnostics; mod elaborate_impl; mod erase_regions; +mod fold; mod generic_args; mod generics; mod impls_ty; @@ -154,6 +155,7 @@ mod structural_impls; #[allow(hidden_glob_reexports)] mod sty; mod typeck_results; +mod visit; // Data types @@ -168,7 +170,7 @@ pub struct ResolverGlobalCtxt { /// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`. pub expn_that_defined: FxHashMap<LocalDefId, ExpnId>, pub effective_visibilities: EffectiveVisibilities, - pub extern_crate_map: FxHashMap<LocalDefId, CrateNum>, + pub extern_crate_map: UnordMap<LocalDefId, CrateNum>, pub maybe_unused_trait_imports: FxIndexSet<LocalDefId>, pub module_children: LocalDefIdMap<Vec<ModChild>>, pub glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>, @@ -442,7 +444,7 @@ impl<'tcx> rustc_type_ir::inherent::IntoKind for Ty<'tcx> { } } -impl<'tcx> rustc_type_ir::visit::Flags for Ty<'tcx> { +impl<'tcx> rustc_type_ir::Flags for Ty<'tcx> { fn flags(&self) -> TypeFlags { self.0.flags } @@ -549,13 +551,13 @@ impl<'tcx> TypeVisitable<TyCtxt<'tcx>> for Term<'tcx> { } } -impl<'tcx, E: TyEncoder<I = TyCtxt<'tcx>>> Encodable<E> for Term<'tcx> { +impl<'tcx, E: TyEncoder<'tcx>> Encodable<E> for Term<'tcx> { fn encode(&self, e: &mut E) { self.unpack().encode(e) } } -impl<'tcx, D: TyDecoder<I = TyCtxt<'tcx>>> Decodable<D> for Term<'tcx> { +impl<'tcx, D: TyDecoder<'tcx>> Decodable<D> for Term<'tcx> { fn decode(d: &mut D) -> Self { let res: TermKind<'tcx> = Decodable::decode(d); res.pack() @@ -938,7 +940,7 @@ impl rustc_type_ir::inherent::PlaceholderLike for PlaceholderConst { pub type Clauses<'tcx> = &'tcx ListWithCachedTypeInfo<Clause<'tcx>>; -impl<'tcx> rustc_type_ir::visit::Flags for Clauses<'tcx> { +impl<'tcx> rustc_type_ir::Flags for Clauses<'tcx> { fn flags(&self) -> TypeFlags { (**self).flags() } diff --git a/compiler/rustc_middle/src/ty/normalize_erasing_regions.rs b/compiler/rustc_middle/src/ty/normalize_erasing_regions.rs index e86e01451fe..f2a4a5a4ecf 100644 --- a/compiler/rustc_middle/src/ty/normalize_erasing_regions.rs +++ b/compiler/rustc_middle/src/ty/normalize_erasing_regions.rs @@ -11,8 +11,10 @@ use rustc_macros::{HashStable, TyDecodable, TyEncodable}; use tracing::{debug, instrument}; use crate::traits::query::NoSolution; -use crate::ty::fold::{FallibleTypeFolder, TypeFoldable, TypeFolder}; -use crate::ty::{self, EarlyBinder, GenericArgsRef, Ty, TyCtxt, TypeVisitableExt}; +use crate::ty::{ + self, EarlyBinder, FallibleTypeFolder, GenericArgsRef, Ty, TyCtxt, TypeFoldable, TypeFolder, + TypeVisitableExt, +}; #[derive(Debug, Copy, Clone, HashStable, TyEncodable, TyDecodable)] pub enum NormalizationError<'tcx> { diff --git a/compiler/rustc_middle/src/ty/opaque_types.rs b/compiler/rustc_middle/src/ty/opaque_types.rs index cf789807bb0..56c44c8a84c 100644 --- a/compiler/rustc_middle/src/ty/opaque_types.rs +++ b/compiler/rustc_middle/src/ty/opaque_types.rs @@ -4,8 +4,9 @@ use rustc_span::def_id::DefId; use tracing::{debug, instrument, trace}; use crate::error::ConstNotUsedTraitAlias; -use crate::ty::fold::{TypeFolder, TypeSuperFoldable}; -use crate::ty::{self, GenericArg, GenericArgKind, Ty, TyCtxt, TypeFoldable}; +use crate::ty::{ + self, GenericArg, GenericArgKind, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, +}; pub type OpaqueTypeKey<'tcx> = rustc_type_ir::OpaqueTypeKey<TyCtxt<'tcx>>; diff --git a/compiler/rustc_middle/src/ty/predicate.rs b/compiler/rustc_middle/src/ty/predicate.rs index 1674ca4cfc5..02e316dfc3d 100644 --- a/compiler/rustc_middle/src/ty/predicate.rs +++ b/compiler/rustc_middle/src/ty/predicate.rs @@ -63,7 +63,7 @@ impl<'tcx> rustc_type_ir::inherent::IntoKind for Predicate<'tcx> { } } -impl<'tcx> rustc_type_ir::visit::Flags for Predicate<'tcx> { +impl<'tcx> rustc_type_ir::Flags for Predicate<'tcx> { fn flags(&self) -> TypeFlags { self.0.flags } diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index 2a3a7705b7b..d200b1437c5 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -63,6 +63,18 @@ thread_local! { static FORCE_TRIMMED_PATH: Cell<bool> = const { Cell::new(false) }; static REDUCED_QUERIES: Cell<bool> = const { Cell::new(false) }; static NO_VISIBLE_PATH: Cell<bool> = const { Cell::new(false) }; + static RTN_MODE: Cell<RtnMode> = const { Cell::new(RtnMode::ForDiagnostic) }; +} + +/// Rendering style for RTN types. +#[derive(Copy, Clone, PartialEq, Eq, Debug)] +pub enum RtnMode { + /// Print the RTN type as an impl trait with its path, i.e.e `impl Sized { T::method(..) }`. + ForDiagnostic, + /// Print the RTN type as an impl trait, i.e. `impl Sized`. + ForSignature, + /// Print the RTN type as a value path, i.e. `T::method(..): ...`. + ForSuggestion, } macro_rules! define_helper { @@ -124,6 +136,38 @@ define_helper!( fn with_no_visible_paths(NoVisibleGuard, NO_VISIBLE_PATH); ); +#[must_use] +pub struct RtnModeHelper(RtnMode); + +impl RtnModeHelper { + pub fn with(mode: RtnMode) -> RtnModeHelper { + RtnModeHelper(RTN_MODE.with(|c| c.replace(mode))) + } +} + +impl Drop for RtnModeHelper { + fn drop(&mut self) { + RTN_MODE.with(|c| c.set(self.0)) + } +} + +/// Print types for the purposes of a suggestion. +/// +/// Specifically, this will render RPITITs as `T::method(..)` which is suitable for +/// things like where-clauses. +pub macro with_types_for_suggestion($e:expr) {{ + let _guard = $crate::ty::print::pretty::RtnModeHelper::with(RtnMode::ForSuggestion); + $e +}} + +/// Print types for the purposes of a signature suggestion. +/// +/// Specifically, this will render RPITITs as `impl Trait` rather than `T::method(..)`. +pub macro with_types_for_signature($e:expr) {{ + let _guard = $crate::ty::print::pretty::RtnModeHelper::with(RtnMode::ForSignature); + $e +}} + /// Avoids running any queries during prints. pub macro with_no_queries($e:expr) {{ $crate::ty::print::with_reduced_queries!($crate::ty::print::with_forced_impl_filename_line!( @@ -1223,22 +1267,6 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } } - if self.tcx().features().return_type_notation() - && let Some(ty::ImplTraitInTraitData::Trait { fn_def_id, .. }) = - self.tcx().opt_rpitit_info(def_id) - && let ty::Alias(_, alias_ty) = - self.tcx().fn_sig(fn_def_id).skip_binder().output().skip_binder().kind() - && alias_ty.def_id == def_id - && let generics = self.tcx().generics_of(fn_def_id) - // FIXME(return_type_notation): We only support lifetime params for now. - && generics.own_params.iter().all(|param| matches!(param.kind, ty::GenericParamDefKind::Lifetime)) - { - let num_args = generics.count(); - write!(self, " {{ ")?; - self.print_def_path(fn_def_id, &args[..num_args])?; - write!(self, "(..) }}")?; - } - Ok(()) } @@ -1306,6 +1334,46 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { ) } + fn pretty_print_rpitit( + &mut self, + def_id: DefId, + args: ty::GenericArgsRef<'tcx>, + ) -> Result<(), PrintError> { + let fn_args = if self.tcx().features().return_type_notation() + && let Some(ty::ImplTraitInTraitData::Trait { fn_def_id, .. }) = + self.tcx().opt_rpitit_info(def_id) + && let ty::Alias(_, alias_ty) = + self.tcx().fn_sig(fn_def_id).skip_binder().output().skip_binder().kind() + && alias_ty.def_id == def_id + && let generics = self.tcx().generics_of(fn_def_id) + // FIXME(return_type_notation): We only support lifetime params for now. + && generics.own_params.iter().all(|param| matches!(param.kind, ty::GenericParamDefKind::Lifetime)) + { + let num_args = generics.count(); + Some((fn_def_id, &args[..num_args])) + } else { + None + }; + + match (fn_args, RTN_MODE.with(|c| c.get())) { + (Some((fn_def_id, fn_args)), RtnMode::ForDiagnostic) => { + self.pretty_print_opaque_impl_type(def_id, args)?; + write!(self, " {{ ")?; + self.print_def_path(fn_def_id, fn_args)?; + write!(self, "(..) }}")?; + } + (Some((fn_def_id, fn_args)), RtnMode::ForSuggestion) => { + self.print_def_path(fn_def_id, fn_args)?; + write!(self, "(..)")?; + } + _ => { + self.pretty_print_opaque_impl_type(def_id, args)?; + } + } + + Ok(()) + } + fn ty_infer_name(&self, _: ty::TyVid) -> Option<Symbol> { None } @@ -2877,7 +2945,7 @@ impl<'tcx> FmtPrinter<'_, 'tcx> { } } - impl<'tcx> ty::visit::TypeVisitor<TyCtxt<'tcx>> for RegionNameCollector<'tcx> { + impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for RegionNameCollector<'tcx> { fn visit_region(&mut self, r: ty::Region<'tcx>) { trace!("address: {:p}", r.0.0); @@ -3123,22 +3191,21 @@ define_print! { ty::AliasTerm<'tcx> { match self.kind(cx.tcx()) { ty::AliasTermKind::InherentTy => p!(pretty_print_inherent_projection(*self)), - ty::AliasTermKind::ProjectionTy - | ty::AliasTermKind::WeakTy - | ty::AliasTermKind::OpaqueTy - | ty::AliasTermKind::UnevaluatedConst - | ty::AliasTermKind::ProjectionConst => { - // If we're printing verbosely, or don't want to invoke queries - // (`is_impl_trait_in_trait`), then fall back to printing the def path. - // This is likely what you want if you're debugging the compiler anyways. + ty::AliasTermKind::ProjectionTy => { if !(cx.should_print_verbose() || with_reduced_queries()) && cx.tcx().is_impl_trait_in_trait(self.def_id) { - return cx.pretty_print_opaque_impl_type(self.def_id, self.args); + p!(pretty_print_rpitit(self.def_id, self.args)) } else { p!(print_def_path(self.def_id, self.args)); } } + | ty::AliasTermKind::WeakTy + | ty::AliasTermKind::OpaqueTy + | ty::AliasTermKind::UnevaluatedConst + | ty::AliasTermKind::ProjectionConst => { + p!(print_def_path(self.def_id, self.args)); + } } } diff --git a/compiler/rustc_middle/src/ty/region.rs b/compiler/rustc_middle/src/ty/region.rs index 14a2e5befe6..fb52cf96b02 100644 --- a/compiler/rustc_middle/src/ty/region.rs +++ b/compiler/rustc_middle/src/ty/region.rs @@ -26,7 +26,7 @@ impl<'tcx> rustc_type_ir::inherent::IntoKind for Region<'tcx> { } } -impl<'tcx> rustc_type_ir::visit::Flags for Region<'tcx> { +impl<'tcx> rustc_type_ir::Flags for Region<'tcx> { fn flags(&self) -> TypeFlags { self.type_flags() } diff --git a/compiler/rustc_middle/src/ty/structural_impls.rs b/compiler/rustc_middle/src/ty/structural_impls.rs index f1d03d0a659..60fd531b4d0 100644 --- a/compiler/rustc_middle/src/ty/structural_impls.rs +++ b/compiler/rustc_middle/src/ty/structural_impls.rs @@ -11,16 +11,16 @@ use rustc_hir::def::Namespace; use rustc_hir::def_id::LocalDefId; use rustc_span::Span; use rustc_span::source_map::Spanned; -use rustc_type_ir::ConstKind; -use rustc_type_ir::visit::{VisitorResult, try_visit}; +use rustc_type_ir::{ConstKind, VisitorResult, try_visit}; use super::print::PrettyPrinter; use super::{GenericArg, GenericArgKind, Pattern, Region}; use crate::mir::PlaceElem; -use crate::ty::fold::{FallibleTypeFolder, TypeFoldable, TypeSuperFoldable}; use crate::ty::print::{FmtPrinter, Printer, with_no_trimmed_paths}; -use crate::ty::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitor}; -use crate::ty::{self, InferConst, Lift, Term, TermKind, Ty, TyCtxt}; +use crate::ty::{ + self, FallibleTypeFolder, InferConst, Lift, Term, TermKind, Ty, TyCtxt, TypeFoldable, + TypeSuperFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitor, +}; impl fmt::Debug for ty::TraitDef { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index ce563c59251..74a94d82784 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -16,8 +16,7 @@ use rustc_hir::def_id::DefId; use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, extension}; use rustc_span::{DUMMY_SP, Span, Symbol, sym}; use rustc_type_ir::TyKind::*; -use rustc_type_ir::visit::TypeVisitableExt; -use rustc_type_ir::{self as ir, BoundVar, CollectAndApply, DynKind, elaborate}; +use rustc_type_ir::{self as ir, BoundVar, CollectAndApply, DynKind, TypeVisitableExt, elaborate}; use tracing::instrument; use ty::util::{AsyncDropGlueMorphology, IntTypeExt}; diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index 0c68913904f..c0d4130336e 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -23,11 +23,10 @@ use super::TypingEnv; use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags; use crate::mir; use crate::query::Providers; -use crate::ty::fold::fold_regions; use crate::ty::layout::{FloatExt, IntegerExt}; use crate::ty::{ self, Asyncness, FallibleTypeFolder, GenericArgKind, GenericArgsRef, Ty, TyCtxt, TypeFoldable, - TypeFolder, TypeSuperFoldable, TypeVisitableExt, Upcast, + TypeFolder, TypeSuperFoldable, TypeVisitableExt, Upcast, fold_regions, }; #[derive(Copy, Clone, Debug)] diff --git a/compiler/rustc_middle/src/ty/visit.rs b/compiler/rustc_middle/src/ty/visit.rs index 95256b55bb4..e3b7a258c39 100644 --- a/compiler/rustc_middle/src/ty/visit.rs +++ b/compiler/rustc_middle/src/ty/visit.rs @@ -1,10 +1,11 @@ use std::ops::ControlFlow; use rustc_data_structures::fx::FxIndexSet; -use rustc_type_ir::fold::TypeFoldable; -pub use rustc_type_ir::visit::*; +use rustc_type_ir::TypeFoldable; -use crate::ty::{self, Binder, Ty, TyCtxt, TypeFlags}; +use crate::ty::{ + self, Binder, Ty, TyCtxt, TypeFlags, TypeSuperVisitable, TypeVisitable, TypeVisitor, +}; /////////////////////////////////////////////////////////////////////////// // Region folder diff --git a/compiler/rustc_mir_build/src/check_unsafety.rs b/compiler/rustc_mir_build/src/check_unsafety.rs index d78c874c766..7f2e7d5ca83 100644 --- a/compiler/rustc_mir_build/src/check_unsafety.rs +++ b/compiler/rustc_mir_build/src/check_unsafety.rs @@ -753,6 +753,11 @@ impl UnsafeOpKind { span: Span, suggest_unsafe_block: bool, ) { + if tcx.hir_opt_delegation_sig_id(hir_id.owner.def_id).is_some() { + // The body of the delegation item is synthesized, so it makes no sense + // to emit this lint. + return; + } let parent_id = tcx.hir_get_parent_item(hir_id); let parent_owner = tcx.hir_owner_node(parent_id); let should_suggest = parent_owner.fn_sig().is_some_and(|sig| { diff --git a/compiler/rustc_mir_transform/Cargo.toml b/compiler/rustc_mir_transform/Cargo.toml index fb8d0ac5e74..9e4b4534dcc 100644 --- a/compiler/rustc_mir_transform/Cargo.toml +++ b/compiler/rustc_mir_transform/Cargo.toml @@ -26,7 +26,6 @@ rustc_session = { path = "../rustc_session" } rustc_span = { path = "../rustc_span" } rustc_target = { path = "../rustc_target" } rustc_trait_selection = { path = "../rustc_trait_selection" } -rustc_type_ir = { path = "../rustc_type_ir" } smallvec = { version = "1.8.1", features = ["union", "may_dangle"] } tracing = "0.1" # tidy-alphabetical-end 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 9cd7045a0a2..89a306c6104 100644 --- a/compiler/rustc_mir_transform/src/coroutine/by_move_body.rs +++ b/compiler/rustc_mir_transform/src/coroutine/by_move_body.rs @@ -178,7 +178,7 @@ pub(crate) fn coroutine_by_move_body_def_id<'tcx>( ), }; - ( + Some(( FieldIdx::from_usize(child_field_idx + num_args), ( FieldIdx::from_usize(parent_field_idx + num_args), @@ -186,9 +186,10 @@ pub(crate) fn coroutine_by_move_body_def_id<'tcx>( peel_deref, child_precise_captures, ), - ) + )) }, ) + .flatten() .collect(); if coroutine_kind == ty::ClosureKind::FnOnce { @@ -312,10 +313,46 @@ impl<'tcx> MutVisitor<'tcx> for MakeByMoveBody<'tcx> { self.super_place(place, context, location); } + fn visit_statement(&mut self, statement: &mut mir::Statement<'tcx>, location: mir::Location) { + // Remove fake borrows of closure captures if that capture has been + // replaced with a by-move version of that capture. + // + // For example, imagine we capture `Foo` in the parent and `&Foo` + // in the child. We will emit two fake borrows like: + // + // ``` + // _2 = &fake shallow (*(_1.0: &Foo)); + // _3 = &fake shallow (_1.0: &Foo); + // ``` + // + // However, since this transform is responsible for replacing + // `_1.0: &Foo` with `_1.0: Foo`, that makes the second fake borrow + // obsolete, and we should replace it with a nop. + // + // As a side-note, we don't actually even care about fake borrows + // here at all since they're fully a MIR borrowck artifact, and we + // don't need to borrowck by-move MIR bodies. But it's best to preserve + // as much as we can between these two bodies :) + if let mir::StatementKind::Assign(box (_, rvalue)) = &statement.kind + && let mir::Rvalue::Ref(_, mir::BorrowKind::Fake(mir::FakeBorrowKind::Shallow), place) = + rvalue + && let mir::PlaceRef { + local: ty::CAPTURE_STRUCT_LOCAL, + projection: [mir::ProjectionElem::Field(idx, _)], + } = place.as_ref() + && let Some(&(_, _, true, _)) = self.field_remapping.get(&idx) + { + statement.kind = mir::StatementKind::Nop; + } + + self.super_statement(statement, location); + } + fn visit_local_decl(&mut self, local: mir::Local, local_decl: &mut mir::LocalDecl<'tcx>) { // Replace the type of the self arg. if local == ty::CAPTURE_STRUCT_LOCAL { local_decl.ty = self.by_move_coroutine_ty; } + self.super_local_decl(local, local_decl); } } diff --git a/compiler/rustc_mir_transform/src/cost_checker.rs b/compiler/rustc_mir_transform/src/cost_checker.rs index b23d8b9e737..00a8293966b 100644 --- a/compiler/rustc_mir_transform/src/cost_checker.rs +++ b/compiler/rustc_mir_transform/src/cost_checker.rs @@ -37,29 +37,11 @@ impl<'b, 'tcx> CostChecker<'b, 'tcx> { /// and even the full `Inline` doesn't call `visit_body`, so there's nowhere /// to put this logic in the visitor. pub(super) fn add_function_level_costs(&mut self) { - fn is_call_like(bbd: &BasicBlockData<'_>) -> bool { - use TerminatorKind::*; - match bbd.terminator().kind { - Call { .. } | TailCall { .. } | Drop { .. } | Assert { .. } | InlineAsm { .. } => { - true - } - - Goto { .. } - | SwitchInt { .. } - | UnwindResume - | UnwindTerminate(_) - | Return - | Unreachable => false, - - Yield { .. } | CoroutineDrop | FalseEdge { .. } | FalseUnwind { .. } => { - unreachable!() - } - } - } - // If the only has one Call (or similar), inlining isn't increasing the total // number of calls, so give extra encouragement to inlining that. - if self.callee_body.basic_blocks.iter().filter(|bbd| is_call_like(bbd)).count() == 1 { + if self.callee_body.basic_blocks.iter().filter(|bbd| is_call_like(bbd.terminator())).count() + == 1 + { self.bonus += CALL_PENALTY; } } @@ -193,3 +175,26 @@ impl<'tcx> Visitor<'tcx> for CostChecker<'_, 'tcx> { } } } + +/// A terminator that's more call-like (might do a bunch of work, might panic, etc) +/// than it is goto-/return-like (no side effects, etc). +/// +/// Used to treat multi-call functions (which could inline exponentially) +/// different from those that only do one or none of these "complex" things. +pub(super) fn is_call_like(terminator: &Terminator<'_>) -> bool { + use TerminatorKind::*; + match terminator.kind { + Call { .. } | TailCall { .. } | Drop { .. } | Assert { .. } | InlineAsm { .. } => true, + + Goto { .. } + | SwitchInt { .. } + | UnwindResume + | UnwindTerminate(_) + | Return + | Unreachable => false, + + Yield { .. } | CoroutineDrop | FalseEdge { .. } | FalseUnwind { .. } => { + unreachable!() + } + } +} diff --git a/compiler/rustc_mir_transform/src/gvn.rs b/compiler/rustc_mir_transform/src/gvn.rs index 981dedd5b5c..0a54c780f31 100644 --- a/compiler/rustc_mir_transform/src/gvn.rs +++ b/compiler/rustc_mir_transform/src/gvn.rs @@ -872,8 +872,14 @@ impl<'body, 'tcx> VnState<'body, 'tcx> { self.simplify_place_projection(place, location); return self.new_pointer(*place, AddressKind::Address(mutbl)); } - Rvalue::WrapUnsafeBinder(ref mut op, _) => { - return self.simplify_operand(op, location); + Rvalue::WrapUnsafeBinder(ref mut op, ty) => { + let value = self.simplify_operand(op, location)?; + Value::Cast { + kind: CastKind::Transmute, + value, + from: op.ty(self.local_decls, self.tcx), + to: ty, + } } // Operations. diff --git a/compiler/rustc_mir_transform/src/inline.rs b/compiler/rustc_mir_transform/src/inline.rs index 0183ba19475..0ab24e48d44 100644 --- a/compiler/rustc_mir_transform/src/inline.rs +++ b/compiler/rustc_mir_transform/src/inline.rs @@ -1,5 +1,6 @@ //! Inlining pass for MIR functions. +use std::assert_matches::debug_assert_matches; use std::iter; use std::ops::{Range, RangeFrom}; @@ -18,7 +19,7 @@ use rustc_session::config::{DebugInfo, OptLevel}; use rustc_span::source_map::Spanned; use tracing::{debug, instrument, trace, trace_span}; -use crate::cost_checker::CostChecker; +use crate::cost_checker::{CostChecker, is_call_like}; use crate::deref_separator::deref_finder; use crate::simplify::simplify_cfg; use crate::validate::validate_types; @@ -26,6 +27,7 @@ use crate::{check_inline, util}; pub(crate) mod cycle; +const HISTORY_DEPTH_LIMIT: usize = 20; const TOP_DOWN_DEPTH_LIMIT: usize = 5; #[derive(Clone, Debug)] @@ -117,6 +119,11 @@ trait Inliner<'tcx> { /// Should inlining happen for a given callee? fn should_inline_for_callee(&self, def_id: DefId) -> bool; + fn check_codegen_attributes_extra( + &self, + callee_attrs: &CodegenFnAttrs, + ) -> Result<(), &'static str>; + fn check_caller_mir_body(&self, body: &Body<'tcx>) -> bool; /// Returns inlining decision that is based on the examination of callee MIR body. @@ -128,10 +135,6 @@ trait Inliner<'tcx> { callee_attrs: &CodegenFnAttrs, ) -> Result<(), &'static str>; - // How many callsites in a body are we allowed to inline? We need to limit this in order - // to prevent super-linear growth in MIR size. - fn inline_limit_for_block(&self) -> Option<usize>; - /// Called when inlining succeeds. fn on_inline_success( &mut self, @@ -142,9 +145,6 @@ trait Inliner<'tcx> { /// Called when inlining failed or was not performed. fn on_inline_failure(&self, callsite: &CallSite<'tcx>, reason: &'static str); - - /// Called when the inline limit for a body is reached. - fn on_inline_limit_reached(&self) -> bool; } struct ForceInliner<'tcx> { @@ -191,6 +191,14 @@ impl<'tcx> Inliner<'tcx> for ForceInliner<'tcx> { ForceInline::should_run_pass_for_callee(self.tcx(), def_id) } + fn check_codegen_attributes_extra( + &self, + callee_attrs: &CodegenFnAttrs, + ) -> Result<(), &'static str> { + debug_assert_matches!(callee_attrs.inline, InlineAttr::Force { .. }); + Ok(()) + } + fn check_caller_mir_body(&self, _: &Body<'tcx>) -> bool { true } @@ -224,10 +232,6 @@ impl<'tcx> Inliner<'tcx> for ForceInliner<'tcx> { } } - fn inline_limit_for_block(&self) -> Option<usize> { - Some(usize::MAX) - } - fn on_inline_success( &mut self, callsite: &CallSite<'tcx>, @@ -261,10 +265,6 @@ impl<'tcx> Inliner<'tcx> for ForceInliner<'tcx> { justification: justification.map(|sym| crate::errors::ForceInlineJustification { sym }), }); } - - fn on_inline_limit_reached(&self) -> bool { - false - } } struct NormalInliner<'tcx> { @@ -278,6 +278,10 @@ struct NormalInliner<'tcx> { /// The number of `DefId`s is finite, so checking history is enough /// to ensure that we do not loop endlessly while inlining. history: Vec<DefId>, + /// How many (multi-call) callsites have we inlined for the top-level call? + /// + /// We need to limit this in order to prevent super-linear growth in MIR size. + top_down_counter: usize, /// Indicates that the caller body has been modified. changed: bool, /// Indicates that the caller is #[inline] and just calls another function, @@ -285,6 +289,12 @@ struct NormalInliner<'tcx> { caller_is_inline_forwarder: bool, } +impl<'tcx> NormalInliner<'tcx> { + fn past_depth_limit(&self) -> bool { + self.history.len() > HISTORY_DEPTH_LIMIT || self.top_down_counter > TOP_DOWN_DEPTH_LIMIT + } +} + impl<'tcx> Inliner<'tcx> for NormalInliner<'tcx> { fn new(tcx: TyCtxt<'tcx>, def_id: DefId, body: &Body<'tcx>) -> Self { let typing_env = body.typing_env(tcx); @@ -295,6 +305,7 @@ impl<'tcx> Inliner<'tcx> for NormalInliner<'tcx> { typing_env, def_id, history: Vec::new(), + top_down_counter: 0, changed: false, caller_is_inline_forwarder: matches!( codegen_fn_attrs.inline, @@ -327,6 +338,17 @@ impl<'tcx> Inliner<'tcx> for NormalInliner<'tcx> { true } + fn check_codegen_attributes_extra( + &self, + callee_attrs: &CodegenFnAttrs, + ) -> Result<(), &'static str> { + if self.past_depth_limit() && matches!(callee_attrs.inline, InlineAttr::None) { + Err("Past depth limit so not inspecting unmarked callee") + } else { + Ok(()) + } + } + fn check_caller_mir_body(&self, body: &Body<'tcx>) -> bool { // Avoid inlining into coroutines, since their `optimized_mir` is used for layout computation, // which can create a cycle, even when no attempt is made to inline the function in the other @@ -351,7 +373,11 @@ impl<'tcx> Inliner<'tcx> for NormalInliner<'tcx> { return Err("body has errors"); } - let mut threshold = if self.caller_is_inline_forwarder { + if self.past_depth_limit() && callee_body.basic_blocks.len() > 1 { + return Err("Not inlining multi-block body as we're past a depth limit"); + } + + let mut threshold = if self.caller_is_inline_forwarder || self.past_depth_limit() { tcx.sess.opts.unstable_opts.inline_mir_forwarder_threshold.unwrap_or(30) } else if tcx.cross_crate_inlinable(callsite.callee.def_id()) { tcx.sess.opts.unstable_opts.inline_mir_hint_threshold.unwrap_or(100) @@ -431,14 +457,6 @@ impl<'tcx> Inliner<'tcx> for NormalInliner<'tcx> { } } - fn inline_limit_for_block(&self) -> Option<usize> { - match self.history.len() { - 0 => Some(usize::MAX), - 1..=TOP_DOWN_DEPTH_LIMIT => Some(1), - _ => None, - } - } - fn on_inline_success( &mut self, callsite: &CallSite<'tcx>, @@ -447,13 +465,21 @@ impl<'tcx> Inliner<'tcx> for NormalInliner<'tcx> { ) { self.changed = true; + let new_calls_count = new_blocks + .clone() + .filter(|&bb| is_call_like(caller_body.basic_blocks[bb].terminator())) + .count(); + if new_calls_count > 1 { + self.top_down_counter += 1; + } + self.history.push(callsite.callee.def_id()); process_blocks(self, caller_body, new_blocks); self.history.pop(); - } - fn on_inline_limit_reached(&self) -> bool { - true + if self.history.is_empty() { + self.top_down_counter = 0; + } } fn on_inline_failure(&self, _: &CallSite<'tcx>, _: &'static str) {} @@ -482,8 +508,6 @@ fn process_blocks<'tcx, I: Inliner<'tcx>>( caller_body: &mut Body<'tcx>, blocks: Range<BasicBlock>, ) { - let Some(inline_limit) = inliner.inline_limit_for_block() else { return }; - let mut inlined_count = 0; for bb in blocks { let bb_data = &caller_body[bb]; if bb_data.is_cleanup { @@ -505,13 +529,6 @@ fn process_blocks<'tcx, I: Inliner<'tcx>>( Ok(new_blocks) => { debug!("inlined {}", callsite.callee); inliner.on_inline_success(&callsite, caller_body, new_blocks); - - inlined_count += 1; - if inlined_count == inline_limit { - if inliner.on_inline_limit_reached() { - return; - } - } } } } @@ -584,6 +601,7 @@ fn try_inlining<'tcx, I: Inliner<'tcx>>( let callee_attrs = tcx.codegen_fn_attrs(callsite.callee.def_id()); check_inline::is_inline_valid_on_fn(tcx, callsite.callee.def_id())?; check_codegen_attributes(inliner, callsite, callee_attrs)?; + inliner.check_codegen_attributes_extra(callee_attrs)?; let terminator = caller_body[callsite.block].terminator.as_ref().unwrap(); let TerminatorKind::Call { args, destination, .. } = &terminator.kind else { bug!() }; @@ -770,6 +788,8 @@ fn check_codegen_attributes<'tcx, I: Inliner<'tcx>>( return Err("has DoNotOptimize attribute"); } + inliner.check_codegen_attributes_extra(callee_attrs)?; + // Reachability pass defines which functions are eligible for inlining. Generally inlining // other functions is incorrect because they could reference symbols that aren't exported. let is_generic = callsite.callee.args.non_erasable_generics().next().is_some(); diff --git a/compiler/rustc_mir_transform/src/lint_tail_expr_drop_order.rs b/compiler/rustc_mir_transform/src/lint_tail_expr_drop_order.rs index 7d77fffa83f..29a9133abe9 100644 --- a/compiler/rustc_mir_transform/src/lint_tail_expr_drop_order.rs +++ b/compiler/rustc_mir_transform/src/lint_tail_expr_drop_order.rs @@ -2,7 +2,7 @@ use std::cell::RefCell; use std::collections::hash_map; use std::rc::Rc; -use rustc_data_structures::fx::{FxHashMap, FxHashSet}; +use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap}; use rustc_data_structures::unord::{UnordMap, UnordSet}; use rustc_errors::Subdiagnostic; use rustc_hir::CRATE_HIR_ID; @@ -25,7 +25,6 @@ use rustc_mir_dataflow::{Analysis, MaybeReachable, ResultsCursor}; use rustc_session::lint::builtin::TAIL_EXPR_DROP_ORDER; use rustc_session::lint::{self}; use rustc_span::{DUMMY_SP, Span, Symbol}; -use rustc_type_ir::data_structures::IndexMap; use tracing::debug; fn place_has_common_prefix<'tcx>(left: &Place<'tcx>, right: &Place<'tcx>) -> bool { @@ -199,7 +198,7 @@ pub(crate) fn run_lint<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId, body: &Body< // and, for each block, the vector of locations. // // We group them per-block because they tend to scheduled in the same drop ladder block. - let mut bid_per_block = IndexMap::default(); + let mut bid_per_block = FxIndexMap::default(); let mut bid_places = UnordSet::new(); let mut ty_dropped_components = UnordMap::default(); @@ -455,8 +454,8 @@ pub(crate) fn run_lint<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId, body: &Body< } /// Extract binding names if available for diagnosis -fn collect_user_names(body: &Body<'_>) -> IndexMap<Local, Symbol> { - let mut names = IndexMap::default(); +fn collect_user_names(body: &Body<'_>) -> FxIndexMap<Local, Symbol> { + let mut names = FxIndexMap::default(); for var_debug_info in &body.var_debug_info { if let mir::VarDebugInfoContents::Place(place) = &var_debug_info.value && let Some(local) = place.local_or_deref_local() @@ -470,9 +469,9 @@ fn collect_user_names(body: &Body<'_>) -> IndexMap<Local, Symbol> { /// Assign names for anonymous or temporary values for diagnosis fn assign_observables_names( locals: impl IntoIterator<Item = Local>, - user_names: &IndexMap<Local, Symbol>, -) -> IndexMap<Local, (String, bool)> { - let mut names = IndexMap::default(); + user_names: &FxIndexMap<Local, Symbol>, +) -> FxIndexMap<Local, (String, bool)> { + let mut names = FxIndexMap::default(); let mut assigned_names = FxHashSet::default(); let mut idx = 0u64; let mut fresh_name = || { diff --git a/compiler/rustc_mir_transform/src/match_branches.rs b/compiler/rustc_mir_transform/src/match_branches.rs index 9db37bf5a07..0d9d0368d37 100644 --- a/compiler/rustc_mir_transform/src/match_branches.rs +++ b/compiler/rustc_mir_transform/src/match_branches.rs @@ -5,7 +5,6 @@ use rustc_index::IndexSlice; use rustc_middle::mir::*; use rustc_middle::ty::layout::{IntegerExt, TyAndLayout}; use rustc_middle::ty::{self, ScalarInt, Ty, TyCtxt}; -use rustc_type_ir::TyKind::*; use tracing::instrument; use super::simplify::simplify_cfg; @@ -293,13 +292,13 @@ fn can_cast( ) -> bool { let from_scalar = ScalarInt::try_from_uint(src_val.into(), src_layout.size).unwrap(); let v = match src_layout.ty.kind() { - Uint(_) => from_scalar.to_uint(src_layout.size), - Int(_) => from_scalar.to_int(src_layout.size) as u128, + ty::Uint(_) => from_scalar.to_uint(src_layout.size), + ty::Int(_) => from_scalar.to_int(src_layout.size) as u128, _ => unreachable!("invalid int"), }; let size = match *cast_ty.kind() { - Int(t) => Integer::from_int_ty(&tcx, t).size(), - Uint(t) => Integer::from_uint_ty(&tcx, t).size(), + ty::Int(t) => Integer::from_int_ty(&tcx, t).size(), + ty::Uint(t) => Integer::from_uint_ty(&tcx, t).size(), _ => unreachable!("invalid int"), }; let v = size.truncate(v); diff --git a/compiler/rustc_mir_transform/src/validate.rs b/compiler/rustc_mir_transform/src/validate.rs index 4ac3a268c9c..231d7c2ef02 100644 --- a/compiler/rustc_mir_transform/src/validate.rs +++ b/compiler/rustc_mir_transform/src/validate.rs @@ -13,11 +13,10 @@ use rustc_middle::mir::visit::{NonUseContext, PlaceContext, Visitor}; use rustc_middle::mir::*; use rustc_middle::ty::adjustment::PointerCoercion; use rustc_middle::ty::{ - self, CoroutineArgsExt, InstanceKind, ScalarInt, Ty, TyCtxt, TypeVisitableExt, Variance, + self, CoroutineArgsExt, InstanceKind, ScalarInt, Ty, TyCtxt, TypeVisitableExt, Upcast, Variance, }; use rustc_middle::{bug, span_bug}; use rustc_trait_selection::traits::ObligationCtxt; -use rustc_type_ir::Upcast; use crate::util::{self, is_within_packed}; diff --git a/compiler/rustc_next_trait_solver/src/canonicalizer.rs b/compiler/rustc_next_trait_solver/src/canonicalizer.rs index 9cae7f27947..bbb4a162027 100644 --- a/compiler/rustc_next_trait_solver/src/canonicalizer.rs +++ b/compiler/rustc_next_trait_solver/src/canonicalizer.rs @@ -1,13 +1,11 @@ use std::cmp::Ordering; use rustc_type_ir::data_structures::{HashMap, ensure_sufficient_stack}; -use rustc_type_ir::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable}; use rustc_type_ir::inherent::*; use rustc_type_ir::solve::{Goal, QueryInput}; -use rustc_type_ir::visit::TypeVisitableExt; use rustc_type_ir::{ self as ty, Canonical, CanonicalTyVarKind, CanonicalVarInfo, CanonicalVarKind, InferCtxtLike, - Interner, + Interner, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt, }; use crate::delegate::SolverDelegate; diff --git a/compiler/rustc_next_trait_solver/src/coherence.rs b/compiler/rustc_next_trait_solver/src/coherence.rs index 408742747c2..53290203600 100644 --- a/compiler/rustc_next_trait_solver/src/coherence.rs +++ b/compiler/rustc_next_trait_solver/src/coherence.rs @@ -3,8 +3,9 @@ use std::ops::ControlFlow; use derive_where::derive_where; use rustc_type_ir::inherent::*; -use rustc_type_ir::visit::{TypeVisitable, TypeVisitableExt, TypeVisitor}; -use rustc_type_ir::{self as ty, InferCtxtLike, Interner}; +use rustc_type_ir::{ + self as ty, InferCtxtLike, Interner, TypeVisitable, TypeVisitableExt, TypeVisitor, +}; use tracing::instrument; /// Whether we do the orphan check relative to this crate or to some remote crate. diff --git a/compiler/rustc_next_trait_solver/src/delegate.rs b/compiler/rustc_next_trait_solver/src/delegate.rs index 850d86d91e8..259b39e2b9e 100644 --- a/compiler/rustc_next_trait_solver/src/delegate.rs +++ b/compiler/rustc_next_trait_solver/src/delegate.rs @@ -1,8 +1,7 @@ use std::ops::Deref; -use rustc_type_ir::fold::TypeFoldable; use rustc_type_ir::solve::{Certainty, Goal, NoSolution}; -use rustc_type_ir::{self as ty, InferCtxtLike, Interner}; +use rustc_type_ir::{self as ty, InferCtxtLike, Interner, TypeFoldable}; pub trait SolverDelegate: Deref<Target = Self::Infcx> + Sized { type Infcx: InferCtxtLike<Interner = Self::Interner>; diff --git a/compiler/rustc_next_trait_solver/src/resolve.rs b/compiler/rustc_next_trait_solver/src/resolve.rs index 71c87714745..992c5ddf504 100644 --- a/compiler/rustc_next_trait_solver/src/resolve.rs +++ b/compiler/rustc_next_trait_solver/src/resolve.rs @@ -1,8 +1,9 @@ use rustc_type_ir::data_structures::DelayedMap; -use rustc_type_ir::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable}; use rustc_type_ir::inherent::*; -use rustc_type_ir::visit::TypeVisitableExt; -use rustc_type_ir::{self as ty, InferCtxtLike, Interner}; +use rustc_type_ir::{ + self as ty, InferCtxtLike, Interner, TypeFoldable, TypeFolder, TypeSuperFoldable, + TypeVisitableExt, +}; use crate::delegate::SolverDelegate; diff --git a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs b/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs index bfb590e8767..384a304c4a9 100644 --- a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs @@ -3,11 +3,11 @@ pub(super) mod structural_traits; use derive_where::derive_where; -use rustc_type_ir::fold::TypeFoldable; use rustc_type_ir::inherent::*; use rustc_type_ir::lang_items::TraitSolverLangItem; -use rustc_type_ir::visit::TypeVisitableExt as _; -use rustc_type_ir::{self as ty, Interner, TypingMode, Upcast as _, elaborate}; +use rustc_type_ir::{ + self as ty, Interner, TypeFoldable, TypeVisitableExt as _, TypingMode, Upcast as _, elaborate, +}; use tracing::{debug, instrument}; use super::trait_goals::TraitGoalProvenVia; diff --git a/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs b/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs index 93804b14125..a5142de2d39 100644 --- a/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs +++ b/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs @@ -3,10 +3,12 @@ use derive_where::derive_where; use rustc_type_ir::data_structures::HashMap; -use rustc_type_ir::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable}; use rustc_type_ir::inherent::*; use rustc_type_ir::lang_items::TraitSolverLangItem; -use rustc_type_ir::{self as ty, Interner, Movability, Mutability, Upcast as _, elaborate}; +use rustc_type_ir::{ + self as ty, Interner, Movability, Mutability, TypeFoldable, TypeFolder, TypeSuperFoldable, + Upcast as _, elaborate, +}; use rustc_type_ir_macros::{TypeFoldable_Generic, TypeVisitable_Generic}; use tracing::instrument; diff --git a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/canonical.rs b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/canonical.rs index ce53a3968c7..ac6b521f665 100644 --- a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/canonical.rs +++ b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/canonical.rs @@ -12,10 +12,11 @@ use std::iter; use rustc_index::IndexVec; -use rustc_type_ir::fold::TypeFoldable; use rustc_type_ir::inherent::*; use rustc_type_ir::relate::solver_relating::RelateExt; -use rustc_type_ir::{self as ty, Canonical, CanonicalVarValues, InferCtxtLike, Interner}; +use rustc_type_ir::{ + self as ty, Canonical, CanonicalVarValues, InferCtxtLike, Interner, TypeFoldable, +}; use tracing::{debug, instrument, trace}; use crate::canonicalizer::Canonicalizer; 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 e48ee71c858..0322c9e4ab0 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 @@ -2,16 +2,18 @@ use std::ops::ControlFlow; use derive_where::derive_where; #[cfg(feature = "nightly")] -use rustc_macros::{HashStable_NoContext, TyDecodable, TyEncodable}; +use rustc_macros::{Decodable_NoContext, Encodable_NoContext, HashStable_NoContext}; use rustc_type_ir::data_structures::{HashMap, HashSet, ensure_sufficient_stack}; use rustc_type_ir::fast_reject::DeepRejectCtxt; -use rustc_type_ir::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable}; use rustc_type_ir::inherent::*; use rustc_type_ir::relate::Relate; use rustc_type_ir::relate::solver_relating::RelateExt; use rustc_type_ir::search_graph::PathKind; -use rustc_type_ir::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor}; -use rustc_type_ir::{self as ty, CanonicalVarValues, InferCtxtLike, Interner, TypingMode}; +use rustc_type_ir::{ + self as ty, CanonicalVarValues, InferCtxtLike, Interner, TypeFoldable, TypeFolder, + TypeSuperFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, + TypingMode, +}; use rustc_type_ir_macros::{Lift_Generic, TypeFoldable_Generic, TypeVisitable_Generic}; use tracing::{instrument, trace}; @@ -129,7 +131,10 @@ where #[derive_where(Clone, Debug, Default; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] -#[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Decodable_NoContext, Encodable_NoContext, HashStable_NoContext) +)] 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 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 60c20762a30..817dffa127b 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 @@ -2,9 +2,8 @@ //! behaves differently depending on the current `TypingMode`. use rustc_index::bit_set::GrowableBitSet; -use rustc_type_ir::fold::fold_regions; use rustc_type_ir::inherent::*; -use rustc_type_ir::{self as ty, Interner, TypingMode}; +use rustc_type_ir::{self as ty, Interner, TypingMode, fold_regions}; use crate::delegate::SolverDelegate; use crate::solve::{Certainty, EvalCtxt, Goal, NoSolution, QueryResult, inspect}; diff --git a/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs b/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs index 12a55664641..b72f776e5cb 100644 --- a/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs +++ b/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs @@ -5,9 +5,9 @@ use rustc_type_ir::fast_reject::DeepRejectCtxt; use rustc_type_ir::inherent::*; use rustc_type_ir::lang_items::TraitSolverLangItem; use rustc_type_ir::solve::CanonicalResponse; -use rustc_type_ir::visit::TypeVisitableExt as _; use rustc_type_ir::{ - self as ty, Interner, Movability, TraitPredicate, TypingMode, Upcast as _, elaborate, + self as ty, Interner, Movability, TraitPredicate, TypeVisitableExt as _, TypingMode, + Upcast as _, elaborate, }; use tracing::{instrument, trace}; diff --git a/compiler/rustc_parse/src/parser/attr.rs b/compiler/rustc_parse/src/parser/attr.rs index 066b570c23f..53614049f08 100644 --- a/compiler/rustc_parse/src/parser/attr.rs +++ b/compiler/rustc_parse/src/parser/attr.rs @@ -127,12 +127,29 @@ impl<'a> Parser<'a> { let lo = self.token.span; // Attributes can't have attributes of their own [Editor's note: not with that attitude] self.collect_tokens_no_attrs(|this| { + let pound_hi = this.token.span.hi(); assert!(this.eat(exp!(Pound)), "parse_attribute called in non-attribute position"); + let not_lo = this.token.span.lo(); let style = if this.eat(exp!(Bang)) { ast::AttrStyle::Inner } else { ast::AttrStyle::Outer }; - this.expect(exp!(OpenBracket))?; + let mut bracket_res = this.expect(exp!(OpenBracket)); + // If `#!` is not followed by `[` + if let Err(err) = &mut bracket_res + && style == ast::AttrStyle::Inner + && pound_hi == not_lo + { + err.note( + "the token sequence `#!` here looks like the start of \ + a shebang interpreter directive but it is not", + ); + err.help( + "if you meant this to be a shebang interpreter directive, \ + move it to the very start of the file", + ); + } + bracket_res?; let item = this.parse_attr_item(ForceCollect::No)?; this.expect(exp!(CloseBracket))?; let attr_sp = lo.to(this.prev_token.span); diff --git a/compiler/rustc_parse/src/parser/expr.rs b/compiler/rustc_parse/src/parser/expr.rs index 9b2d562a69e..0774324eae7 100644 --- a/compiler/rustc_parse/src/parser/expr.rs +++ b/compiler/rustc_parse/src/parser/expr.rs @@ -2588,7 +2588,8 @@ impl<'a> Parser<'a> { } /// Parses the condition of a `if` or `while` expression. - fn parse_expr_cond(&mut self) -> PResult<'a, P<Expr>> { + // Public because it is used in rustfmt forks such as https://github.com/tucant/rustfmt/blob/30c83df9e1db10007bdd16dafce8a86b404329b2/src/parse/macros/html.rs#L57 for custom if expressions. + pub fn parse_expr_cond(&mut self) -> PResult<'a, P<Expr>> { let attrs = self.parse_outer_attributes()?; let (mut cond, _) = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL | Restrictions::ALLOW_LET, attrs)?; diff --git a/compiler/rustc_query_impl/src/plumbing.rs b/compiler/rustc_query_impl/src/plumbing.rs index f98d6421307..fa31ef5eeb0 100644 --- a/compiler/rustc_query_impl/src/plumbing.rs +++ b/compiler/rustc_query_impl/src/plumbing.rs @@ -19,9 +19,10 @@ use rustc_middle::query::Key; use rustc_middle::query::on_disk_cache::{ AbsoluteBytePos, CacheDecoder, CacheEncoder, EncodedDepNodeIndex, }; +use rustc_middle::ty::codec::TyEncoder; use rustc_middle::ty::print::with_reduced_queries; use rustc_middle::ty::tls::{self, ImplicitCtxt}; -use rustc_middle::ty::{self, TyCtxt, TyEncoder}; +use rustc_middle::ty::{self, TyCtxt}; use rustc_query_system::dep_graph::{DepNodeParams, HasDepContext}; use rustc_query_system::ich::StableHashingContext; use rustc_query_system::query::{ diff --git a/compiler/rustc_resolve/src/build_reduced_graph.rs b/compiler/rustc_resolve/src/build_reduced_graph.rs index 42fe01b1c84..763e9207a12 100644 --- a/compiler/rustc_resolve/src/build_reduced_graph.rs +++ b/compiler/rustc_resolve/src/build_reduced_graph.rs @@ -1115,6 +1115,7 @@ impl<'a, 'ra, 'tcx> BuildReducedGraphVisitor<'a, 'ra, 'tcx> { } }); } else { + #[allow(rustc::potential_query_instability)] // FIXME for ident in single_imports.iter().cloned() { let result = self.r.maybe_resolve_ident_in_module( ModuleOrUniformRoot::Module(module), diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs index 41f4254eede..5361af98f3c 100644 --- a/compiler/rustc_resolve/src/diagnostics.rs +++ b/compiler/rustc_resolve/src/diagnostics.rs @@ -6,6 +6,7 @@ use rustc_ast::{ }; use rustc_ast_pretty::pprust; use rustc_data_structures::fx::FxHashSet; +use rustc_data_structures::unord::UnordSet; use rustc_errors::codes::*; use rustc_errors::{ Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, MultiSpan, SuggestionStyle, @@ -1467,6 +1468,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { return; } + #[allow(rustc::potential_query_instability)] // FIXME let unused_macro = self.unused_macros.iter().find_map(|(def_id, (_, unused_ident))| { if unused_ident.name == ident.name { Some((def_id, unused_ident)) } else { None } }); @@ -2863,18 +2865,11 @@ fn show_candidates( } else { // Get the unique item kinds and if there's only one, we use the right kind name // instead of the more generic "items". - let mut kinds = accessible_path_strings + let kinds = accessible_path_strings .iter() .map(|(_, descr, _, _, _)| *descr) - .collect::<FxHashSet<&str>>() - .into_iter(); - let kind = if let Some(kind) = kinds.next() - && let None = kinds.next() - { - kind - } else { - "item" - }; + .collect::<UnordSet<&str>>(); + let kind = if let Some(kind) = kinds.get_only() { kind } else { "item" }; let s = if kind.ends_with('s') { "es" } else { "s" }; ("one of these", kind, s, String::new(), "") diff --git a/compiler/rustc_resolve/src/ident.rs b/compiler/rustc_resolve/src/ident.rs index 5f0a2a597e9..27d63198836 100644 --- a/compiler/rustc_resolve/src/ident.rs +++ b/compiler/rustc_resolve/src/ident.rs @@ -946,6 +946,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { // Check if one of single imports can still define the name, // if it can then our result is not determined and can be invalidated. + #[allow(rustc::potential_query_instability)] // FIXME for single_import in &resolution.single_imports { if ignore_import == Some(*single_import) { // This branch handles a cycle in single imports. diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs index d28988cd74f..6056a69ee71 100644 --- a/compiler/rustc_resolve/src/late.rs +++ b/compiler/rustc_resolve/src/late.rs @@ -18,6 +18,7 @@ use rustc_ast::visit::{ }; use rustc_ast::*; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap}; +use rustc_data_structures::unord::{UnordMap, UnordSet}; use rustc_errors::codes::*; use rustc_errors::{ Applicability, DiagArgValue, ErrorGuaranteed, IntoDiagArg, StashKey, Suggestions, @@ -47,8 +48,6 @@ mod diagnostics; type Res = def::Res<NodeId>; -type IdentMap<T> = FxHashMap<Ident, T>; - use diagnostics::{ElisionFnParameter, LifetimeElisionCandidate, MissingLifetime}; #[derive(Copy, Clone, Debug)] @@ -273,8 +272,8 @@ impl RibKind<'_> { /// resolving, the name is looked up from inside out. #[derive(Debug)] pub(crate) struct Rib<'ra, R = Res> { - pub bindings: IdentMap<R>, - pub patterns_with_skipped_bindings: FxHashMap<DefId, Vec<(Span, Result<(), ErrorGuaranteed>)>>, + pub bindings: FxHashMap<Ident, R>, + pub patterns_with_skipped_bindings: UnordMap<DefId, Vec<(Span, Result<(), ErrorGuaranteed>)>>, pub kind: RibKind<'ra>, } @@ -1605,12 +1604,12 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> { // for better diagnostics. let mut forward_ty_ban_rib_const_param_ty = Rib { bindings: forward_ty_ban_rib.bindings.clone(), - patterns_with_skipped_bindings: FxHashMap::default(), + patterns_with_skipped_bindings: Default::default(), kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy), }; let mut forward_const_ban_rib_const_param_ty = Rib { bindings: forward_const_ban_rib.bindings.clone(), - patterns_with_skipped_bindings: FxHashMap::default(), + patterns_with_skipped_bindings: Default::default(), kind: RibKind::ForwardGenericParamBan(ForwardGenericParamBanReason::ConstParamTy), }; // We'll ban these with a `ConstParamTy` rib, so just clear these ribs for better @@ -2334,7 +2333,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> { let local_candidates = self.lifetime_elision_candidates.take(); if let Some(candidates) = local_candidates { - let distinct: FxHashSet<_> = candidates.iter().map(|(res, _)| *res).collect(); + let distinct: UnordSet<_> = candidates.iter().map(|(res, _)| *res).collect(); let lifetime_count = distinct.len(); if lifetime_count != 0 { parameter_info.push(ElisionFnParameter { @@ -2358,14 +2357,13 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> { } })); } - let mut distinct_iter = distinct.into_iter(); - if let Some(res) = distinct_iter.next() { + if !distinct.is_empty() { match elision_lifetime { // We are the first parameter to bind lifetimes. Elision::None => { - if distinct_iter.next().is_none() { + if let Some(res) = distinct.get_only() { // We have a single lifetime => success. - elision_lifetime = Elision::Param(res) + elision_lifetime = Elision::Param(*res) } else { // We have multiple lifetimes => error. elision_lifetime = Elision::Err; @@ -2890,6 +2888,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> { break; } + #[allow(rustc::potential_query_instability)] // FIXME seen_bindings .extend(parent_rib.bindings.keys().map(|ident| (*ident, ident.span))); } @@ -4004,7 +4003,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> { } } - fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut IdentMap<Res> { + fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut FxHashMap<Ident, Res> { &mut self.ribs[ns].last_mut().unwrap().bindings } @@ -5117,12 +5116,18 @@ struct ItemInfoCollector<'a, 'ra, 'tcx> { } impl ItemInfoCollector<'_, '_, '_> { - fn collect_fn_info(&mut self, sig: &FnSig, id: NodeId, attrs: &[Attribute]) { + fn collect_fn_info( + &mut self, + header: FnHeader, + decl: &FnDecl, + id: NodeId, + attrs: &[Attribute], + ) { let sig = DelegationFnSig { - header: sig.header, - param_count: sig.decl.inputs.len(), - has_self: sig.decl.has_self(), - c_variadic: sig.decl.c_variadic(), + header, + param_count: decl.inputs.len(), + has_self: decl.has_self(), + c_variadic: decl.c_variadic(), target_feature: attrs.iter().any(|attr| attr.has_name(sym::target_feature)), }; self.r.delegation_fn_sigs.insert(self.r.local_def_id(id), sig); @@ -5142,7 +5147,7 @@ impl<'ast> Visitor<'ast> for ItemInfoCollector<'_, '_, '_> { | ItemKind::Trait(box Trait { generics, .. }) | ItemKind::TraitAlias(generics, _) => { if let ItemKind::Fn(box Fn { sig, .. }) = &item.kind { - self.collect_fn_info(sig, item.id, &item.attrs); + self.collect_fn_info(sig.header, &sig.decl, item.id, &item.attrs); } let def_id = self.r.local_def_id(item.id); @@ -5154,8 +5159,17 @@ impl<'ast> Visitor<'ast> for ItemInfoCollector<'_, '_, '_> { self.r.item_generics_num_lifetimes.insert(def_id, count); } + ItemKind::ForeignMod(ForeignMod { extern_span, safety: _, abi, items }) => { + for foreign_item in items { + if let ForeignItemKind::Fn(box Fn { sig, .. }) = &foreign_item.kind { + let new_header = + FnHeader { ext: Extern::from_abi(*abi, *extern_span), ..sig.header }; + self.collect_fn_info(new_header, &sig.decl, foreign_item.id, &item.attrs); + } + } + } + ItemKind::Mod(..) - | ItemKind::ForeignMod(..) | ItemKind::Static(..) | ItemKind::Use(..) | ItemKind::ExternCrate(..) @@ -5175,7 +5189,7 @@ impl<'ast> Visitor<'ast> for ItemInfoCollector<'_, '_, '_> { fn visit_assoc_item(&mut self, item: &'ast AssocItem, ctxt: AssocCtxt) { if let AssocItemKind::Fn(box Fn { sig, .. }) = &item.kind { - self.collect_fn_info(sig, item.id, &item.attrs); + self.collect_fn_info(sig.header, &sig.decl, item.id, &item.attrs); } visit::walk_assoc_item(self, item, ctxt); } @@ -5187,6 +5201,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { let mut late_resolution_visitor = LateResolutionVisitor::new(self); late_resolution_visitor.resolve_doc_links(&krate.attrs, MaybeExported::Ok(CRATE_NODE_ID)); visit::walk_crate(&mut late_resolution_visitor, krate); + #[allow(rustc::potential_query_instability)] // FIXME for (id, span) in late_resolution_visitor.diag_metadata.unused_labels.iter() { self.lint_buffer.buffer_lint( lint::builtin::UNUSED_LABELS, diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs index 84858cfc1b1..bcfcc8000c7 100644 --- a/compiler/rustc_resolve/src/late/diagnostics.rs +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -830,6 +830,7 @@ impl<'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { if let Some(rib) = &self.last_block_rib && let RibKind::Normal = rib.kind { + #[allow(rustc::potential_query_instability)] // FIXME for (ident, &res) in &rib.bindings { if let Res::Local(_) = res && path.len() == 1 @@ -1018,6 +1019,7 @@ impl<'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { if let Some(err_code) = err.code { if err_code == E0425 { for label_rib in &self.label_ribs { + #[allow(rustc::potential_query_instability)] // FIXME for (label_ident, node_id) in &label_rib.bindings { let ident = path.last().unwrap().ident; if format!("'{ident}") == label_ident.to_string() { @@ -1177,7 +1179,10 @@ impl<'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { let [segment] = path else { return }; let None = following_seg else { return }; for rib in self.ribs[ValueNS].iter().rev() { - for (def_id, spans) in &rib.patterns_with_skipped_bindings { + let patterns_with_skipped_bindings = self.r.tcx.with_stable_hashing_context(|hcx| { + rib.patterns_with_skipped_bindings.to_sorted(&hcx, true) + }); + for (def_id, spans) in patterns_with_skipped_bindings { if let DefKind::Struct | DefKind::Variant = self.r.tcx.def_kind(*def_id) && let Some(fields) = self.r.field_idents(*def_id) { @@ -2052,7 +2057,7 @@ impl<'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { if self .r .extern_crate_map - .iter() + .items() // FIXME: This doesn't include impls like `impl Default for String`. .flat_map(|(_, crate_)| self.r.tcx.implementations_of_trait((*crate_, default_trait))) .filter_map(|(_, simplified_self_ty)| *simplified_self_ty) @@ -2261,6 +2266,7 @@ impl<'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { }; // Locals and type parameters + #[allow(rustc::potential_query_instability)] // FIXME for (ident, &res) in &rib.bindings { if filter_fn(res) && ident.span.ctxt() == rib_ctxt { names.push(TypoSuggestion::typo_from_ident(*ident, res)); @@ -2788,6 +2794,7 @@ impl<'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { let within_scope = self.is_label_valid_from_rib(rib_index); let rib = &self.label_ribs[rib_index]; + #[allow(rustc::potential_query_instability)] // FIXME let names = rib .bindings .iter() @@ -2799,6 +2806,7 @@ impl<'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { // Upon finding a similar name, get the ident that it was from - the span // contained within helps make a useful diagnostic. In addition, determine // whether this candidate is within scope. + #[allow(rustc::potential_query_instability)] // FIXME let (ident, _) = rib.bindings.iter().find(|(ident, _)| ident.name == symbol).unwrap(); (*ident, within_scope) }) diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index 495ce843fcd..447d5283e27 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -9,7 +9,6 @@ // tidy-alphabetical-start #![allow(internal_features)] #![allow(rustc::diagnostic_outside_of_impl)] -#![allow(rustc::potential_query_instability)] #![allow(rustc::untranslatable_diagnostic)] #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] #![doc(rust_logo)] @@ -47,6 +46,7 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet}; use rustc_data_structures::intern::Interned; use rustc_data_structures::steal::Steal; use rustc_data_structures::sync::FreezeReadGuard; +use rustc_data_structures::unord::UnordMap; use rustc_errors::{Applicability, Diag, ErrCode, ErrorGuaranteed}; use rustc_expand::base::{DeriveResolution, SyntaxExtension, SyntaxExtensionKind}; use rustc_feature::BUILTIN_ATTRIBUTES; @@ -1046,7 +1046,7 @@ pub struct Resolver<'ra, 'tcx> { graph_root: Module<'ra>, prelude: Option<Module<'ra>>, - extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'ra>>, + extern_prelude: FxIndexMap<Ident, ExternPreludeEntry<'ra>>, /// N.B., this is used only for better diagnostics, not name resolution itself. field_names: LocalDefIdMap<Vec<Ident>>, @@ -1079,7 +1079,7 @@ pub struct Resolver<'ra, 'tcx> { extra_lifetime_params_map: NodeMap<Vec<(Ident, NodeId, LifetimeRes)>>, /// `CrateNum` resolutions of `extern crate` items. - extern_crate_map: FxHashMap<LocalDefId, CrateNum>, + extern_crate_map: UnordMap<LocalDefId, CrateNum>, module_children: LocalDefIdMap<Vec<ModChild>>, trait_map: NodeMap<Vec<TraitCandidate>>, @@ -1102,7 +1102,7 @@ pub struct Resolver<'ra, 'tcx> { /// some AST passes can generate identifiers that only resolve to local or /// lang items. empty_module: Module<'ra>, - module_map: FxHashMap<DefId, Module<'ra>>, + module_map: FxIndexMap<DefId, Module<'ra>>, binding_parent_modules: FxHashMap<NameBinding<'ra>, Module<'ra>>, underscore_disambiguator: u32, @@ -1136,7 +1136,7 @@ pub struct Resolver<'ra, 'tcx> { macro_names: FxHashSet<Ident>, builtin_macros: FxHashMap<Symbol, BuiltinMacroState>, registered_tools: &'tcx RegisteredTools, - macro_use_prelude: FxHashMap<Symbol, NameBinding<'ra>>, + macro_use_prelude: FxIndexMap<Symbol, NameBinding<'ra>>, macro_map: FxHashMap<DefId, MacroData>, dummy_ext_bang: Arc<SyntaxExtension>, dummy_ext_derive: Arc<SyntaxExtension>, @@ -1145,7 +1145,7 @@ pub struct Resolver<'ra, 'tcx> { ast_transform_scopes: FxHashMap<LocalExpnId, Module<'ra>>, unused_macros: FxHashMap<LocalDefId, (NodeId, Ident)>, /// A map from the macro to all its potentially unused arms. - unused_macro_rules: FxIndexMap<LocalDefId, FxHashMap<usize, (Ident, Span)>>, + unused_macro_rules: FxIndexMap<LocalDefId, UnordMap<usize, (Ident, Span)>>, proc_macro_stubs: FxHashSet<LocalDefId>, /// Traces collected during macro resolution and validated when it's complete. single_segment_macro_resolutions: @@ -1259,7 +1259,7 @@ impl<'ra> ResolverArenas<'ra> { expn_id: ExpnId, span: Span, no_implicit_prelude: bool, - module_map: &mut FxHashMap<DefId, Module<'ra>>, + module_map: &mut FxIndexMap<DefId, Module<'ra>>, module_self_bindings: &mut FxHashMap<Module<'ra>, NameBinding<'ra>>, ) -> Module<'ra> { let module = Module(Interned::new_unchecked(self.modules.alloc(ModuleData::new( @@ -1404,7 +1404,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { arenas: &'ra ResolverArenas<'ra>, ) -> Resolver<'ra, 'tcx> { let root_def_id = CRATE_DEF_ID.to_def_id(); - let mut module_map = FxHashMap::default(); + let mut module_map = FxIndexMap::default(); let mut module_self_bindings = FxHashMap::default(); let graph_root = arenas.new_module( None, @@ -1421,8 +1421,8 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { ExpnId::root(), DUMMY_SP, true, - &mut FxHashMap::default(), - &mut FxHashMap::default(), + &mut Default::default(), + &mut Default::default(), ); let mut def_id_to_node_id = IndexVec::default(); @@ -1437,7 +1437,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { let mut invocation_parents = FxHashMap::default(); invocation_parents.insert(LocalExpnId::ROOT, InvocationParent::ROOT); - let mut extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'_>> = tcx + let mut extern_prelude: FxIndexMap<Ident, ExternPreludeEntry<'_>> = tcx .sess .opts .externs @@ -1536,7 +1536,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { macro_names: FxHashSet::default(), builtin_macros: Default::default(), registered_tools, - macro_use_prelude: FxHashMap::default(), + macro_use_prelude: Default::default(), macro_map: FxHashMap::default(), dummy_ext_bang: Arc::new(SyntaxExtension::dummy_bang(edition)), dummy_ext_derive: Arc::new(SyntaxExtension::dummy_derive(edition)), diff --git a/compiler/rustc_resolve/src/macros.rs b/compiler/rustc_resolve/src/macros.rs index 984dfff3ea5..7100d89ad61 100644 --- a/compiler/rustc_resolve/src/macros.rs +++ b/compiler/rustc_resolve/src/macros.rs @@ -323,6 +323,7 @@ impl<'ra, 'tcx> ResolverExpand for Resolver<'ra, 'tcx> { } fn check_unused_macros(&mut self) { + #[allow(rustc::potential_query_instability)] // FIXME for (_, &(node_id, ident)) in self.unused_macros.iter() { self.lint_buffer.buffer_lint( UNUSED_MACROS, @@ -333,10 +334,7 @@ impl<'ra, 'tcx> ResolverExpand for Resolver<'ra, 'tcx> { } for (&def_id, unused_arms) in self.unused_macro_rules.iter() { - let mut unused_arms = unused_arms.iter().collect::<Vec<_>>(); - unused_arms.sort_by_key(|&(&arm_i, _)| arm_i); - - for (&arm_i, &(ident, rule_span)) in unused_arms { + for (&arm_i, &(ident, rule_span)) in unused_arms.to_sorted_stable_ord() { if self.unused_macros.contains_key(&def_id) { // We already lint the entire macro as unused continue; diff --git a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs index b711c238d59..129a32c6edd 100644 --- a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs +++ b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs @@ -9,10 +9,9 @@ use std::iter; use rustc_hir as hir; use rustc_hir::LangItem; use rustc_middle::bug; -use rustc_middle::ty::fold::{TypeFolder, TypeSuperFoldable}; use rustc_middle::ty::{ self, ExistentialPredicateStableCmpExt as _, Instance, InstanceKind, IntTy, List, TraitRef, Ty, - TyCtxt, TypeFoldable, TypeVisitableExt, UintTy, + TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt, UintTy, }; use rustc_span::def_id::DefId; use rustc_span::sym; diff --git a/compiler/rustc_serialize/tests/opaque.rs b/compiler/rustc_serialize/tests/opaque.rs index 0543e176ae5..5aeedbdcd4e 100644 --- a/compiler/rustc_serialize/tests/opaque.rs +++ b/compiler/rustc_serialize/tests/opaque.rs @@ -3,11 +3,11 @@ use std::fmt::Debug; use std::fs; -use rustc_macros::{Decodable_Generic, Encodable_Generic}; +use rustc_macros::{Decodable_NoContext, Encodable_NoContext}; use rustc_serialize::opaque::{FileEncoder, MemDecoder}; use rustc_serialize::{Decodable, Encodable}; -#[derive(PartialEq, Clone, Debug, Encodable_Generic, Decodable_Generic)] +#[derive(PartialEq, Clone, Debug, Encodable_NoContext, Decodable_NoContext)] struct Struct { a: (), b: u8, @@ -210,7 +210,7 @@ fn test_struct() { }]); } -#[derive(PartialEq, Clone, Debug, Encodable_Generic, Decodable_Generic)] +#[derive(PartialEq, Clone, Debug, Encodable_NoContext, Decodable_NoContext)] enum Enum { Variant1, Variant2(usize, u32), @@ -259,7 +259,7 @@ fn test_tuples() { #[test] fn test_unit_like_struct() { - #[derive(Encodable_Generic, Decodable_Generic, PartialEq, Debug)] + #[derive(Encodable_NoContext, Decodable_NoContext, PartialEq, Debug)] struct UnitLikeStruct; check_round_trip(vec![UnitLikeStruct]); @@ -267,7 +267,7 @@ fn test_unit_like_struct() { #[test] fn test_box() { - #[derive(Encodable_Generic, Decodable_Generic, PartialEq, Debug)] + #[derive(Encodable_NoContext, Decodable_NoContext, PartialEq, Debug)] struct A { foo: Box<[bool]>, } @@ -280,12 +280,12 @@ fn test_box() { fn test_cell() { use std::cell::{Cell, RefCell}; - #[derive(Encodable_Generic, Decodable_Generic, PartialEq, Debug)] + #[derive(Encodable_NoContext, Decodable_NoContext, PartialEq, Debug)] struct A { baz: isize, } - #[derive(Encodable_Generic, Decodable_Generic, PartialEq, Debug)] + #[derive(Encodable_NoContext, Decodable_NoContext, PartialEq, Debug)] struct B { foo: Cell<bool>, bar: RefCell<A>, diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index dcdb7fa9c10..34755249b60 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -2709,7 +2709,12 @@ pub fn parse_crate_types_from_list(list_list: Vec<String>) -> Result<Vec<CrateTy "cdylib" => CrateType::Cdylib, "bin" => CrateType::Executable, "proc-macro" => CrateType::ProcMacro, - _ => return Err(format!("unknown crate type: `{part}`")), + _ => { + return Err(format!( + "unknown crate type: `{part}`, expected one of: \ + `lib`, `rlib`, `staticlib`, `dylib`, `cdylib`, `bin`, `proc-macro`", + )); + } }; if !crate_types.contains(&new_part) { crate_types.push(new_part) diff --git a/compiler/rustc_span/src/hygiene.rs b/compiler/rustc_span/src/hygiene.rs index 64982b858c6..62027caa353 100644 --- a/compiler/rustc_span/src/hygiene.rs +++ b/compiler/rustc_span/src/hygiene.rs @@ -982,6 +982,8 @@ pub struct ExpnData { /// Should debuginfo for the macro be collapsed to the outermost expansion site (in other /// words, was the macro definition annotated with `#[collapse_debuginfo]`)? pub(crate) collapse_debuginfo: bool, + /// When true, we do not display the note telling people to use the `-Zmacro-backtrace` flag. + pub hide_backtrace: bool, } impl !PartialEq for ExpnData {} @@ -1000,6 +1002,7 @@ impl ExpnData { allow_internal_unsafe: bool, local_inner_macros: bool, collapse_debuginfo: bool, + hide_backtrace: bool, ) -> ExpnData { ExpnData { kind, @@ -1014,6 +1017,7 @@ impl ExpnData { allow_internal_unsafe, local_inner_macros, collapse_debuginfo, + hide_backtrace, } } @@ -1038,6 +1042,7 @@ impl ExpnData { allow_internal_unsafe: false, local_inner_macros: false, collapse_debuginfo: false, + hide_backtrace: false, } } diff --git a/compiler/rustc_target/src/spec/base/fuchsia.rs b/compiler/rustc_target/src/spec/base/fuchsia.rs index 9deafcac27f..92cb0299ddb 100644 --- a/compiler/rustc_target/src/spec/base/fuchsia.rs +++ b/compiler/rustc_target/src/spec/base/fuchsia.rs @@ -7,7 +7,7 @@ pub(crate) fn opts() -> TargetOptions { // now. When using clang as the linker it will supply these options for us, // so we only list them for ld/lld. // - // https://github.com/llvm/llvm-project/blob/db9322b2066c55254e7691efeab863f43bfcc084/clang/lib/Driver/ToolChains/Fuchsia.cpp#L31 + // https://github.com/llvm/llvm-project/blob/0419db6b95e246fe9dc90b5795beb77c393eb2ce/clang/lib/Driver/ToolChains/Fuchsia.cpp#L32 let pre_link_args = TargetOptions::link_args( LinkerFlavor::Gnu(Cc::No, Lld::No), &[ @@ -18,9 +18,13 @@ pub(crate) fn opts() -> TargetOptions { "-z", "now", "-z", + "start-stop-visibility=hidden", + "-z", "rodynamic", "-z", "separate-loadable-segments", + "-z", + "rel", "--pack-dyn-relocs=relr", ], ); diff --git a/compiler/rustc_target/src/spec/targets/aarch64_unknown_fuchsia.rs b/compiler/rustc_target/src/spec/targets/aarch64_unknown_fuchsia.rs index 23ed92e62b8..8366b6d9bd8 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_unknown_fuchsia.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_unknown_fuchsia.rs @@ -1,6 +1,28 @@ -use crate::spec::{SanitizerSet, StackProbeType, Target, TargetMetadata, TargetOptions, base}; +use crate::spec::{ + Cc, LinkerFlavor, Lld, SanitizerSet, StackProbeType, Target, TargetMetadata, base, +}; pub(crate) fn target() -> Target { + let mut base = base::fuchsia::opts(); + base.cpu = "generic".into(); + base.features = "+v8a,+crc,+aes,+sha2,+neon".into(); + base.max_atomic_width = Some(128); + base.stack_probes = StackProbeType::Inline; + base.supported_sanitizers = SanitizerSet::ADDRESS + | SanitizerSet::CFI + | SanitizerSet::LEAK + | SanitizerSet::SHADOWCALLSTACK; + base.supports_xray = true; + + base.add_pre_link_args( + LinkerFlavor::Gnu(Cc::No, Lld::No), + &[ + "--execute-only", + // Enable the Cortex-A53 errata 843419 mitigation by default + "--fix-cortex-a53-843419", + ], + ); + Target { llvm_target: "aarch64-unknown-fuchsia".into(), metadata: TargetMetadata { @@ -12,14 +34,6 @@ pub(crate) fn target() -> Target { pointer_width: 64, data_layout: "e-m:e-p270:32:32-p271:32:32-p272:64:64-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128-Fn32".into(), arch: "aarch64".into(), - options: TargetOptions { - features: "+v8a".into(), - max_atomic_width: Some(128), - stack_probes: StackProbeType::Inline, - supported_sanitizers: SanitizerSet::ADDRESS - | SanitizerSet::CFI - | SanitizerSet::SHADOWCALLSTACK, - ..base::fuchsia::opts() - }, + options: base, } } diff --git a/compiler/rustc_target/src/spec/targets/riscv32_wrs_vxworks.rs b/compiler/rustc_target/src/spec/targets/riscv32_wrs_vxworks.rs index 55dc6a70627..8a4bc58e546 100644 --- a/compiler/rustc_target/src/spec/targets/riscv32_wrs_vxworks.rs +++ b/compiler/rustc_target/src/spec/targets/riscv32_wrs_vxworks.rs @@ -2,7 +2,7 @@ use crate::spec::{StackProbeType, Target, TargetMetadata, TargetOptions, base}; pub(crate) fn target() -> Target { Target { - llvm_target: "riscv32".into(), + llvm_target: "riscv32-unknown-linux-gnu".into(), metadata: TargetMetadata { description: None, tier: Some(3), diff --git a/compiler/rustc_target/src/spec/targets/riscv64_wrs_vxworks.rs b/compiler/rustc_target/src/spec/targets/riscv64_wrs_vxworks.rs index 58ded24b9c5..39aa70035e4 100644 --- a/compiler/rustc_target/src/spec/targets/riscv64_wrs_vxworks.rs +++ b/compiler/rustc_target/src/spec/targets/riscv64_wrs_vxworks.rs @@ -2,7 +2,7 @@ use crate::spec::{StackProbeType, Target, TargetMetadata, TargetOptions, base}; pub(crate) fn target() -> Target { Target { - llvm_target: "riscv64".into(), + llvm_target: "riscv64-unknown-linux-gnu".into(), metadata: TargetMetadata { description: None, tier: Some(3), diff --git a/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_fuchsia.rs b/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_fuchsia.rs index d673936f5f8..e260237ca77 100644 --- a/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_fuchsia.rs +++ b/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_fuchsia.rs @@ -1,6 +1,16 @@ -use crate::spec::{CodeModel, SanitizerSet, Target, TargetMetadata, TargetOptions, base}; +use crate::spec::{CodeModel, SanitizerSet, StackProbeType, Target, TargetMetadata, base}; pub(crate) fn target() -> Target { + let mut base = base::fuchsia::opts(); + base.code_model = Some(CodeModel::Medium); + base.cpu = "generic-rv64".into(); + base.features = "+m,+a,+f,+d,+c".into(); + base.llvm_abiname = "lp64d".into(); + base.max_atomic_width = Some(64); + base.stack_probes = StackProbeType::Inline; + base.supported_sanitizers = SanitizerSet::SHADOWCALLSTACK; + base.supports_xray = true; + Target { llvm_target: "riscv64-unknown-fuchsia".into(), metadata: TargetMetadata { @@ -12,14 +22,6 @@ pub(crate) fn target() -> Target { pointer_width: 64, data_layout: "e-m:e-p:64:64-i64:64-i128:128-n32:64-S128".into(), arch: "riscv64".into(), - options: TargetOptions { - code_model: Some(CodeModel::Medium), - cpu: "generic-rv64".into(), - features: "+m,+a,+f,+d,+c".into(), - llvm_abiname: "lp64d".into(), - max_atomic_width: Some(64), - supported_sanitizers: SanitizerSet::SHADOWCALLSTACK, - ..base::fuchsia::opts() - }, + options: base, } } diff --git a/compiler/rustc_target/src/spec/targets/x86_64_unknown_fuchsia.rs b/compiler/rustc_target/src/spec/targets/x86_64_unknown_fuchsia.rs index d41c696ac23..d7253da7e8d 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_unknown_fuchsia.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_unknown_fuchsia.rs @@ -4,7 +4,10 @@ pub(crate) fn target() -> Target { let mut base = base::fuchsia::opts(); base.cpu = "x86-64".into(); base.plt_by_default = false; - base.max_atomic_width = Some(64); + // See https://fuchsia.dev/fuchsia-src/contribute/governance/rfcs/0073_x86_64_platform_requirement, + // which corresponds to x86-64-v2. + base.features = "+cx16,+sahf,+popcnt,+sse3,+sse4.1,+sse4.2,+ssse3".into(); + base.max_atomic_width = Some(128); base.stack_probes = StackProbeType::Inline; base.supported_sanitizers = SanitizerSet::ADDRESS | SanitizerSet::CFI | SanitizerSet::LEAK; base.supports_xray = true; diff --git a/compiler/rustc_target/src/target_features.rs b/compiler/rustc_target/src/target_features.rs index 6d3b6608ea2..a32b42a6fe3 100644 --- a/compiler/rustc_target/src/target_features.rs +++ b/compiler/rustc_target/src/target_features.rs @@ -603,13 +603,18 @@ static CSKY_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ static LOONGARCH_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ // tidy-alphabetical-start ("d", Unstable(sym::loongarch_target_feature), &["f"]), + ("div32", Unstable(sym::loongarch_target_feature), &[]), ("f", Unstable(sym::loongarch_target_feature), &[]), ("frecipe", Unstable(sym::loongarch_target_feature), &[]), + ("lam-bh", Unstable(sym::loongarch_target_feature), &[]), + ("lamcas", Unstable(sym::loongarch_target_feature), &[]), ("lasx", Unstable(sym::loongarch_target_feature), &["lsx"]), ("lbt", Unstable(sym::loongarch_target_feature), &[]), + ("ld-seq-sa", Unstable(sym::loongarch_target_feature), &[]), ("lsx", Unstable(sym::loongarch_target_feature), &["d"]), ("lvz", Unstable(sym::loongarch_target_feature), &[]), ("relax", Unstable(sym::loongarch_target_feature), &[]), + ("scq", Unstable(sym::loongarch_target_feature), &[]), ("ual", Unstable(sym::loongarch_target_feature), &[]), // tidy-alphabetical-end ]; diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs index baf2489b2b8..6510dbbbe9d 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs @@ -1466,7 +1466,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } } - impl<'tcx> ty::visit::TypeVisitor<TyCtxt<'tcx>> for OpaqueTypesVisitor<'tcx> { + impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for OpaqueTypesVisitor<'tcx> { fn visit_ty(&mut self, t: Ty<'tcx>) { if let Some((kind, def_id)) = TyCategory::from_ty(self.tcx, t) { let span = self.tcx.def_span(def_id); 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 40958ec1088..0bcb5f6f3b2 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 @@ -18,7 +18,7 @@ use rustc_middle::ty::{ TypeFoldable, TypeFolder, TypeSuperFoldable, TypeckResults, }; use rustc_span::{BytePos, DUMMY_SP, FileName, Ident, Span, sym}; -use rustc_type_ir::visit::TypeVisitableExt; +use rustc_type_ir::TypeVisitableExt; use tracing::{debug, instrument, warn}; use super::nice_region_error::placeholder_error::Highlighted; diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/trait_impl_difference.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/trait_impl_difference.rs index cc2ab1c3432..74205922851 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/trait_impl_difference.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/trait_impl_difference.rs @@ -71,7 +71,7 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { } } - impl<'tcx> ty::visit::TypeVisitor<TyCtxt<'tcx>> for HighlightBuilder<'tcx> { + impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for HighlightBuilder<'tcx> { fn visit_region(&mut self, r: ty::Region<'tcx>) { if !r.has_name() && self.counter <= 3 { self.highlight.highlighting_region(r, self.counter); diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/util.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/util.rs index 245764c94ab..00f053fa599 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/util.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/util.rs @@ -3,8 +3,7 @@ use rustc_hir as hir; use rustc_hir::def_id::{DefId, LocalDefId}; -use rustc_middle::ty::fold::fold_regions; -use rustc_middle::ty::{self, Binder, Region, Ty, TyCtxt, TypeFoldable}; +use rustc_middle::ty::{self, Binder, Region, Ty, TyCtxt, TypeFoldable, fold_regions}; use rustc_span::Span; use tracing::instrument; 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 e2bdd52ba7c..07a67cde3be 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 @@ -18,12 +18,14 @@ use rustc_middle::traits::SignatureMismatchData; use rustc_middle::traits::select::OverflowError; use rustc_middle::ty::abstract_const::NotConstEvaluatable; use rustc_middle::ty::error::{ExpectedFound, TypeError}; -use rustc_middle::ty::fold::{TypeFolder, TypeSuperFoldable}; use rustc_middle::ty::print::{ PrintPolyTraitPredicateExt, PrintTraitPredicateExt as _, PrintTraitRefExt as _, with_forced_trimmed_paths, }; -use rustc_middle::ty::{self, TraitRef, Ty, TyCtxt, TypeFoldable, TypeVisitableExt, Upcast}; +use rustc_middle::ty::{ + self, TraitRef, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt, + Upcast, +}; use rustc_middle::{bug, span_bug}; use rustc_span::{BytePos, DUMMY_SP, STDLIB_STABLE_CRATES, Span, Symbol, sym}; use tracing::{debug, instrument}; diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs index 4f89f3c2b49..9383b82ff3c 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs @@ -26,7 +26,7 @@ use rustc_middle::traits::IsConstable; use rustc_middle::ty::error::TypeError; use rustc_middle::ty::print::{ PrintPolyTraitPredicateExt as _, PrintPolyTraitRefExt, PrintTraitPredicateExt as _, - with_forced_trimmed_paths, with_no_trimmed_paths, + with_forced_trimmed_paths, with_no_trimmed_paths, with_types_for_suggestion, }; use rustc_middle::ty::{ self, AdtKind, GenericArgs, InferTy, IsSuggestable, Ty, TyCtxt, TypeFoldable, TypeFolder, @@ -110,7 +110,7 @@ impl<'a, 'tcx> CoroutineData<'a, 'tcx> { fn predicate_constraint(generics: &hir::Generics<'_>, pred: ty::Predicate<'_>) -> (Span, String) { ( generics.tail_span_for_predicate_suggestion(), - format!("{} {}", generics.add_where_or_trailing_comma(), pred), + with_types_for_suggestion!(format!("{} {}", generics.add_where_or_trailing_comma(), pred)), ) } @@ -136,7 +136,8 @@ pub fn suggest_restriction<'tcx, G: EmissionGuarantee>( if hir_generics.where_clause_span.from_expansion() || hir_generics.where_clause_span.desugaring_kind().is_some() || projection.is_some_and(|projection| { - tcx.is_impl_trait_in_trait(projection.def_id) + (tcx.is_impl_trait_in_trait(projection.def_id) + && !tcx.features().return_type_notation()) || tcx.lookup_stability(projection.def_id).is_some_and(|stab| stab.is_unstable()) }) { @@ -1997,7 +1998,10 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { .iter() .enumerate() .map(|(i, ident)| { - if ident.name.is_empty() || ident.name == kw::SelfLower { + if ident.name.is_empty() + || ident.name == kw::Underscore + || ident.name == kw::SelfLower + { format!("arg{i}") } else { format!("{ident}") diff --git a/compiler/rustc_trait_selection/src/solve/delegate.rs b/compiler/rustc_trait_selection/src/solve/delegate.rs index e69bad095e3..af5a60027ba 100644 --- a/compiler/rustc_trait_selection/src/solve/delegate.rs +++ b/compiler/rustc_trait_selection/src/solve/delegate.rs @@ -8,8 +8,7 @@ use rustc_infer::infer::canonical::{ }; use rustc_infer::infer::{InferCtxt, RegionVariableOrigin, TyCtxtInferExt}; use rustc_infer::traits::solve::Goal; -use rustc_middle::ty::fold::TypeFoldable; -use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt as _}; +use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable, TypeVisitableExt as _}; use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span}; use rustc_type_ir::TypingMode; use rustc_type_ir::solve::{Certainty, NoSolution}; diff --git a/compiler/rustc_trait_selection/src/solve/inspect/analyse.rs b/compiler/rustc_trait_selection/src/solve/inspect/analyse.rs index 4b1bc316d5f..48a05ad29fb 100644 --- a/compiler/rustc_trait_selection/src/solve/inspect/analyse.rs +++ b/compiler/rustc_trait_selection/src/solve/inspect/analyse.rs @@ -15,8 +15,7 @@ use rustc_infer::infer::{DefineOpaqueTypes, InferCtxt, InferOk}; use rustc_macros::extension; use rustc_middle::traits::ObligationCause; use rustc_middle::traits::solve::{Certainty, Goal, GoalSource, NoSolution, QueryResult}; -use rustc_middle::ty::visit::{VisitorResult, try_visit}; -use rustc_middle::ty::{TyCtxt, TypeFoldable}; +use rustc_middle::ty::{TyCtxt, TypeFoldable, VisitorResult, try_visit}; use rustc_middle::{bug, ty}; use rustc_next_trait_solver::resolve::EagerResolver; use rustc_next_trait_solver::solve::inspect::{self, instantiate_canonical_state}; diff --git a/compiler/rustc_trait_selection/src/traits/coherence.rs b/compiler/rustc_trait_selection/src/traits/coherence.rs index 3b40882ef57..4c7172c3278 100644 --- a/compiler/rustc_trait_selection/src/traits/coherence.rs +++ b/compiler/rustc_trait_selection/src/traits/coherence.rs @@ -17,8 +17,9 @@ use rustc_middle::traits::query::NoSolution; use rustc_middle::traits::solve::{CandidateSource, Certainty, Goal}; use rustc_middle::traits::specialization_graph::OverlapMode; use rustc_middle::ty::fast_reject::DeepRejectCtxt; -use rustc_middle::ty::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor}; -use rustc_middle::ty::{self, Ty, TyCtxt, TypingMode}; +use rustc_middle::ty::{ + self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode, +}; pub use rustc_next_trait_solver::coherence::*; use rustc_next_trait_solver::solve::SolverDelegateEvalExt; use rustc_span::{DUMMY_SP, Span, sym}; diff --git a/compiler/rustc_trait_selection/src/traits/mod.rs b/compiler/rustc_trait_selection/src/traits/mod.rs index 105cb917571..de337710b5e 100644 --- a/compiler/rustc_trait_selection/src/traits/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/mod.rs @@ -32,11 +32,9 @@ pub use rustc_infer::traits::*; use rustc_middle::query::Providers; use rustc_middle::span_bug; use rustc_middle::ty::error::{ExpectedFound, TypeError}; -use rustc_middle::ty::fold::TypeFoldable; -use rustc_middle::ty::visit::{TypeVisitable, TypeVisitableExt}; use rustc_middle::ty::{ - self, GenericArgs, GenericArgsRef, Ty, TyCtxt, TypeFolder, TypeSuperFoldable, - TypeSuperVisitable, TypingMode, Upcast, + self, GenericArgs, GenericArgsRef, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, + TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypingMode, Upcast, }; use rustc_span::def_id::DefId; use rustc_span::{DUMMY_SP, Span}; diff --git a/compiler/rustc_trait_selection/src/traits/project.rs b/compiler/rustc_trait_selection/src/traits/project.rs index 4d9cf6620d6..be5d6286e26 100644 --- a/compiler/rustc_trait_selection/src/traits/project.rs +++ b/compiler/rustc_trait_selection/src/traits/project.rs @@ -13,9 +13,9 @@ use rustc_infer::traits::{ObligationCauseCode, PredicateObligations}; use rustc_middle::traits::select::OverflowError; use rustc_middle::traits::{BuiltinImplSource, ImplSource, ImplSourceUserDefinedData}; use rustc_middle::ty::fast_reject::DeepRejectCtxt; -use rustc_middle::ty::fold::TypeFoldable; -use rustc_middle::ty::visit::TypeVisitableExt; -use rustc_middle::ty::{self, Term, Ty, TyCtxt, TypingMode, Upcast}; +use rustc_middle::ty::{ + self, Term, Ty, TyCtxt, TypeFoldable, TypeVisitableExt, TypingMode, Upcast, +}; use rustc_middle::{bug, span_bug}; use rustc_span::sym; use rustc_type_ir::elaborate; diff --git a/compiler/rustc_trait_selection/src/traits/query/normalize.rs b/compiler/rustc_trait_selection/src/traits/query/normalize.rs index 6bf76eaee5c..165c63f3745 100644 --- a/compiler/rustc_trait_selection/src/traits/query/normalize.rs +++ b/compiler/rustc_trait_selection/src/traits/query/normalize.rs @@ -7,9 +7,10 @@ use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_infer::traits::PredicateObligations; use rustc_macros::extension; pub use rustc_middle::traits::query::NormalizationResult; -use rustc_middle::ty::fold::{FallibleTypeFolder, TypeFoldable, TypeSuperFoldable}; -use rustc_middle::ty::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitableExt}; -use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitor, TypingMode}; +use rustc_middle::ty::{ + self, FallibleTypeFolder, Ty, TyCtxt, TypeFoldable, TypeSuperFoldable, TypeSuperVisitable, + TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode, +}; use rustc_span::DUMMY_SP; use tracing::{debug, info, instrument}; diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/mod.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/mod.rs index 68feb19c55b..4bdf04311a0 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/mod.rs @@ -3,8 +3,7 @@ use std::fmt; use rustc_errors::ErrorGuaranteed; use rustc_infer::traits::PredicateObligations; use rustc_middle::traits::query::NoSolution; -use rustc_middle::ty::fold::TypeFoldable; -use rustc_middle::ty::{ParamEnvAnd, TyCtxt}; +use rustc_middle::ty::{ParamEnvAnd, TyCtxt, TypeFoldable}; use rustc_span::Span; use crate::infer::canonical::{ diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/normalize.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/normalize.rs index 2f6bbd7f4cf..f2a6ce855b4 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/normalize.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/normalize.rs @@ -3,8 +3,7 @@ use std::fmt; use rustc_middle::traits::ObligationCause; use rustc_middle::traits::query::NoSolution; pub use rustc_middle::traits::query::type_op::{DeeplyNormalize, Normalize}; -use rustc_middle::ty::fold::TypeFoldable; -use rustc_middle::ty::{self, Lift, ParamEnvAnd, Ty, TyCtxt, TypeVisitableExt}; +use rustc_middle::ty::{self, Lift, ParamEnvAnd, Ty, TyCtxt, TypeFoldable, TypeVisitableExt}; use rustc_span::Span; use crate::infer::canonical::{CanonicalQueryInput, CanonicalQueryResponse}; diff --git a/compiler/rustc_ty_utils/Cargo.toml b/compiler/rustc_ty_utils/Cargo.toml index 7e96b64408c..b14ce8a7f21 100644 --- a/compiler/rustc_ty_utils/Cargo.toml +++ b/compiler/rustc_ty_utils/Cargo.toml @@ -21,6 +21,5 @@ rustc_session = { path = "../rustc_session" } rustc_span = { path = "../rustc_span" } rustc_target = { path = "../rustc_target" } rustc_trait_selection = { path = "../rustc_trait_selection" } -rustc_type_ir = { path = "../rustc_type_ir" } tracing = "0.1" # tidy-alphabetical-end diff --git a/compiler/rustc_ty_utils/src/implied_bounds.rs b/compiler/rustc_ty_utils/src/implied_bounds.rs index aeaa83c77b5..088d5e76b86 100644 --- a/compiler/rustc_ty_utils/src/implied_bounds.rs +++ b/compiler/rustc_ty_utils/src/implied_bounds.rs @@ -6,8 +6,7 @@ use rustc_hir::def::DefKind; use rustc_hir::def_id::LocalDefId; use rustc_middle::bug; use rustc_middle::query::Providers; -use rustc_middle::ty::fold::fold_regions; -use rustc_middle::ty::{self, Ty, TyCtxt}; +use rustc_middle::ty::{self, Ty, TyCtxt, fold_regions}; use rustc_span::Span; pub(crate) fn provide(providers: &mut Providers) { diff --git a/compiler/rustc_ty_utils/src/instance.rs b/compiler/rustc_ty_utils/src/instance.rs index 90b3517eded..962e1353ebc 100644 --- a/compiler/rustc_ty_utils/src/instance.rs +++ b/compiler/rustc_ty_utils/src/instance.rs @@ -7,11 +7,10 @@ use rustc_middle::query::Providers; use rustc_middle::traits::{BuiltinImplSource, CodegenObligationError}; use rustc_middle::ty::util::AsyncDropGlueMorphology; use rustc_middle::ty::{ - self, GenericArgsRef, Instance, PseudoCanonicalInput, TyCtxt, TypeVisitableExt, + self, ClosureKind, GenericArgsRef, Instance, PseudoCanonicalInput, TyCtxt, TypeVisitableExt, }; use rustc_span::sym; use rustc_trait_selection::traits; -use rustc_type_ir::ClosureKind; use tracing::debug; use traits::translate_args; diff --git a/compiler/rustc_ty_utils/src/sig_types.rs b/compiler/rustc_ty_utils/src/sig_types.rs index d6f9277813d..5bb96f90029 100644 --- a/compiler/rustc_ty_utils/src/sig_types.rs +++ b/compiler/rustc_ty_utils/src/sig_types.rs @@ -4,10 +4,8 @@ use rustc_hir::def::DefKind; use rustc_hir::def_id::LocalDefId; use rustc_middle::span_bug; -use rustc_middle::ty::visit::{VisitorResult, try_visit}; -use rustc_middle::ty::{self, TyCtxt}; +use rustc_middle::ty::{self, TyCtxt, TypeVisitable, VisitorResult, try_visit}; use rustc_span::Span; -use rustc_type_ir::visit::TypeVisitable; use tracing::{instrument, trace}; pub trait SpannedTypeVisitor<'tcx> { diff --git a/compiler/rustc_ty_utils/src/ty.rs b/compiler/rustc_ty_utils/src/ty.rs index bb61f4bee66..9dc4f11e456 100644 --- a/compiler/rustc_ty_utils/src/ty.rs +++ b/compiler/rustc_ty_utils/src/ty.rs @@ -5,8 +5,9 @@ use rustc_hir::def::DefKind; use rustc_index::bit_set::DenseBitSet; use rustc_middle::bug; use rustc_middle::query::Providers; -use rustc_middle::ty::fold::fold_regions; -use rustc_middle::ty::{self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitor, Upcast}; +use rustc_middle::ty::{ + self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitor, Upcast, fold_regions, +}; use rustc_span::DUMMY_SP; use rustc_span::def_id::{CRATE_DEF_ID, DefId, LocalDefId}; use rustc_trait_selection::traits; @@ -14,49 +15,49 @@ use tracing::instrument; #[instrument(level = "debug", skip(tcx), ret)] fn sized_constraint_for_ty<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Option<Ty<'tcx>> { - use rustc_type_ir::TyKind::*; - match ty.kind() { // these are always sized - Bool - | Char - | Int(..) - | Uint(..) - | Float(..) - | RawPtr(..) - | Ref(..) - | FnDef(..) - | FnPtr(..) - | Array(..) - | Closure(..) - | CoroutineClosure(..) - | Coroutine(..) - | CoroutineWitness(..) - | Never - | Dynamic(_, _, ty::DynStar) => None, + ty::Bool + | ty::Char + | ty::Int(..) + | ty::Uint(..) + | ty::Float(..) + | ty::RawPtr(..) + | ty::Ref(..) + | ty::FnDef(..) + | ty::FnPtr(..) + | ty::Array(..) + | ty::Closure(..) + | ty::CoroutineClosure(..) + | ty::Coroutine(..) + | ty::CoroutineWitness(..) + | ty::Never + | ty::Dynamic(_, _, ty::DynStar) => None, // these are never sized - Str | Slice(..) | Dynamic(_, _, ty::Dyn) | Foreign(..) => Some(ty), + ty::Str | ty::Slice(..) | ty::Dynamic(_, _, ty::Dyn) | ty::Foreign(..) => Some(ty), - Pat(ty, _) => sized_constraint_for_ty(tcx, *ty), + ty::Pat(ty, _) => sized_constraint_for_ty(tcx, *ty), - Tuple(tys) => tys.last().and_then(|&ty| sized_constraint_for_ty(tcx, ty)), + ty::Tuple(tys) => tys.last().and_then(|&ty| sized_constraint_for_ty(tcx, ty)), // recursive case - Adt(adt, args) => adt.sized_constraint(tcx).and_then(|intermediate| { + ty::Adt(adt, args) => adt.sized_constraint(tcx).and_then(|intermediate| { let ty = intermediate.instantiate(tcx, args); sized_constraint_for_ty(tcx, ty) }), // these can be sized or unsized. - Param(..) | Alias(..) | Error(_) => Some(ty), + ty::Param(..) | ty::Alias(..) | ty::Error(_) => Some(ty), // We cannot instantiate the binder, so just return the *original* type back, // but only if the inner type has a sized constraint. Thus we skip the binder, // but don't actually use the result from `sized_constraint_for_ty`. - UnsafeBinder(inner_ty) => sized_constraint_for_ty(tcx, inner_ty.skip_binder()).map(|_| ty), + ty::UnsafeBinder(inner_ty) => { + sized_constraint_for_ty(tcx, inner_ty.skip_binder()).map(|_| ty) + } - Placeholder(..) | Bound(..) | Infer(..) => { + ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) => { bug!("unexpected type `{ty:?}` in sized_constraint_for_ty") } } diff --git a/compiler/rustc_type_ir/src/binder.rs b/compiler/rustc_type_ir/src/binder.rs index 0d0092ea1aa..c8b71074de7 100644 --- a/compiler/rustc_type_ir/src/binder.rs +++ b/compiler/rustc_type_ir/src/binder.rs @@ -5,7 +5,7 @@ use std::ops::{ControlFlow, Deref}; use derive_where::derive_where; #[cfg(feature = "nightly")] -use rustc_macros::{HashStable_NoContext, TyDecodable, TyEncodable}; +use rustc_macros::{Decodable_NoContext, Encodable_NoContext, HashStable_NoContext}; use tracing::instrument; use crate::data_structures::SsoHashSet; @@ -57,7 +57,7 @@ where macro_rules! impl_binder_encode_decode { ($($t:ty),+ $(,)?) => { $( - impl<I: Interner, E: crate::TyEncoder<I = I>> rustc_serialize::Encodable<E> for ty::Binder<I, $t> + impl<I: Interner, E: rustc_serialize::Encoder> rustc_serialize::Encodable<E> for ty::Binder<I, $t> where $t: rustc_serialize::Encodable<E>, I::BoundVarKinds: rustc_serialize::Encodable<E>, @@ -67,7 +67,7 @@ macro_rules! impl_binder_encode_decode { self.as_ref().skip_binder().encode(e); } } - impl<I: Interner, D: crate::TyDecoder<I = I>> rustc_serialize::Decodable<D> for ty::Binder<I, $t> + impl<I: Interner, D: rustc_serialize::Decoder> rustc_serialize::Decodable<D> for ty::Binder<I, $t> where $t: TypeVisitable<I> + rustc_serialize::Decodable<D>, I::BoundVarKinds: rustc_serialize::Decodable<D>, @@ -342,7 +342,10 @@ impl<I: Interner> TypeVisitor<I> for ValidateBoundVars<I> { #[derive_where(PartialOrd; I: Interner, T: Ord)] #[derive_where(Hash; I: Interner, T: Hash)] #[derive_where(Debug; I: Interner, T: Debug)] -#[cfg_attr(feature = "nightly", derive(TyEncodable, TyDecodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) +)] pub struct EarlyBinder<I: Interner, T> { value: T, #[derive_where(skip(Debug))] @@ -859,7 +862,7 @@ impl<'a, I: Interner> ArgFolder<'a, I> { if self.binders_passed == 0 || !val.has_escaping_bound_vars() { val } else { - ty::fold::shift_vars(self.cx, val, self.binders_passed) + ty::shift_vars(self.cx, val, self.binders_passed) } } @@ -867,7 +870,7 @@ impl<'a, I: Interner> ArgFolder<'a, I> { if self.binders_passed == 0 || !region.has_escaping_bound_vars() { region } else { - ty::fold::shift_region(self.cx, region, self.binders_passed) + ty::shift_region(self.cx, region, self.binders_passed) } } } diff --git a/compiler/rustc_type_ir/src/canonical.rs b/compiler/rustc_type_ir/src/canonical.rs index 24b2ebc1fbe..03d3194f106 100644 --- a/compiler/rustc_type_ir/src/canonical.rs +++ b/compiler/rustc_type_ir/src/canonical.rs @@ -4,7 +4,7 @@ use std::ops::Index; use derive_where::derive_where; #[cfg(feature = "nightly")] -use rustc_macros::{HashStable_NoContext, TyDecodable, TyEncodable}; +use rustc_macros::{Decodable_NoContext, Encodable_NoContext, HashStable_NoContext}; use rustc_type_ir_macros::{Lift_Generic, TypeFoldable_Generic, TypeVisitable_Generic}; use crate::inherent::*; @@ -16,7 +16,10 @@ use crate::{self as ty, Interner, TypingMode, UniverseIndex}; #[derive_where(Eq; I: Interner, V: Eq)] #[derive_where(Debug; I: Interner, V: fmt::Debug)] #[derive_where(Copy; I: Interner, V: Copy)] -#[cfg_attr(feature = "nightly", derive(TyEncodable, TyDecodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) +)] pub struct CanonicalQueryInput<I: Interner, V> { pub canonical: Canonical<I, V>, pub typing_mode: TypingMode<I>, @@ -32,7 +35,10 @@ pub struct CanonicalQueryInput<I: Interner, V> { #[derive_where(Debug; I: Interner, V: fmt::Debug)] #[derive_where(Copy; I: Interner, V: Copy)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic)] -#[cfg_attr(feature = "nightly", derive(TyEncodable, TyDecodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) +)] pub struct Canonical<I: Interner, V> { pub value: V, pub max_universe: UniverseIndex, @@ -85,7 +91,10 @@ impl<I: Interner, V: fmt::Display> fmt::Display for Canonical<I, V> { /// with fresh inference variables replacing the canonical values. #[derive_where(Clone, Copy, Hash, PartialEq, Eq, Debug; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic)] -#[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Decodable_NoContext, Encodable_NoContext, HashStable_NoContext) +)] pub struct CanonicalVarInfo<I: Interner> { pub kind: CanonicalVarKind<I>, } @@ -139,7 +148,10 @@ impl<I: Interner> CanonicalVarInfo<I> { /// that analyzes type-like values. #[derive_where(Clone, Copy, Hash, PartialEq, Eq, Debug; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic)] -#[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Decodable_NoContext, Encodable_NoContext, HashStable_NoContext) +)] pub enum CanonicalVarKind<I: Interner> { /// Some kind of type inference variable. Ty(CanonicalTyVarKind), @@ -213,7 +225,10 @@ impl<I: Interner> CanonicalVarKind<I> { /// know what set of types a given type variable can be unified with. #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic)] -#[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Decodable_NoContext, Encodable_NoContext, HashStable_NoContext) +)] pub enum CanonicalTyVarKind { /// General type variable `?T` that can be unified with arbitrary types. General(UniverseIndex), @@ -235,7 +250,10 @@ pub enum CanonicalTyVarKind { /// variables. You will need to supply it later to instantiate the /// canonicalized query response. #[derive_where(Clone, Copy, Hash, PartialEq, Eq, Debug; I: Interner)] -#[cfg_attr(feature = "nightly", derive(TyEncodable, TyDecodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) +)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] pub struct CanonicalVarValues<I: Interner> { pub var_values: I::GenericArgs, diff --git a/compiler/rustc_type_ir/src/codec.rs b/compiler/rustc_type_ir/src/codec.rs deleted file mode 100644 index f443f596373..00000000000 --- a/compiler/rustc_type_ir/src/codec.rs +++ /dev/null @@ -1,61 +0,0 @@ -use rustc_data_structures::fx::FxHashMap; -use rustc_span::{SpanDecoder, SpanEncoder}; - -use crate::{Interner, PredicateKind}; - -/// The shorthand encoding uses an enum's variant index `usize` -/// and is offset by this value so it never matches a real variant. -/// This offset is also chosen so that the first byte is never < 0x80. -pub const SHORTHAND_OFFSET: usize = 0x80; - -/// Trait for decoding to a reference. -/// -/// This is a separate trait from `Decodable` so that we can implement it for -/// upstream types, such as `FxHashSet`. -/// -/// The `TyDecodable` derive macro will use this trait for fields that are -/// references (and don't use a type alias to hide that). -/// -/// `Decodable` can still be implemented in cases where `Decodable` is required -/// by a trait bound. -pub trait RefDecodable<'tcx, D: TyDecoder> { - fn decode(d: &mut D) -> &'tcx Self; -} - -pub trait TyEncoder: SpanEncoder { - type I: Interner; - const CLEAR_CROSS_CRATE: bool; - - fn position(&self) -> usize; - - fn type_shorthands(&mut self) -> &mut FxHashMap<<Self::I as Interner>::Ty, usize>; - - fn predicate_shorthands(&mut self) -> &mut FxHashMap<PredicateKind<Self::I>, usize>; - - fn encode_alloc_id(&mut self, alloc_id: &<Self::I as Interner>::AllocId); -} - -pub trait TyDecoder: SpanDecoder { - type I: Interner; - const CLEAR_CROSS_CRATE: bool; - - fn interner(&self) -> Self::I; - - fn cached_ty_for_shorthand<F>( - &mut self, - shorthand: usize, - or_insert_with: F, - ) -> <Self::I as Interner>::Ty - where - F: FnOnce(&mut Self) -> <Self::I as Interner>::Ty; - - fn with_position<F, R>(&mut self, pos: usize, f: F) -> R - where - F: FnOnce(&mut Self) -> R; - - fn positioned_at_shorthand(&self) -> bool { - (self.peek_byte() & (SHORTHAND_OFFSET as u8)) != 0 - } - - fn decode_alloc_id(&mut self) -> <Self::I as Interner>::AllocId; -} diff --git a/compiler/rustc_type_ir/src/const_kind.rs b/compiler/rustc_type_ir/src/const_kind.rs index aafc0907ae1..70a8509b513 100644 --- a/compiler/rustc_type_ir/src/const_kind.rs +++ b/compiler/rustc_type_ir/src/const_kind.rs @@ -4,14 +4,17 @@ use derive_where::derive_where; #[cfg(feature = "nightly")] use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; #[cfg(feature = "nightly")] -use rustc_macros::{HashStable_NoContext, TyDecodable, TyEncodable}; +use rustc_macros::{Decodable_NoContext, Encodable_NoContext, HashStable_NoContext}; use rustc_type_ir_macros::{Lift_Generic, TypeFoldable_Generic, TypeVisitable_Generic}; use crate::{self as ty, DebruijnIndex, Interner}; /// Represents a constant in Rust. #[derive_where(Clone, Copy, Hash, PartialEq, Eq; I: Interner)] -#[cfg_attr(feature = "nightly", derive(TyEncodable, TyDecodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) +)] pub enum ConstKind<I: Interner> { /// A const generic parameter. Param(I::ParamConst), @@ -62,7 +65,10 @@ impl<I: Interner> fmt::Debug for ConstKind<I> { /// An unevaluated (potentially generic) constant used in the type-system. #[derive_where(Clone, Copy, Debug, Hash, PartialEq, Eq; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] -#[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Decodable_NoContext, Encodable_NoContext, HashStable_NoContext) +)] pub struct UnevaluatedConst<I: Interner> { pub def: I::DefId, pub args: I::GenericArgs, @@ -86,7 +92,7 @@ rustc_index::newtype_index! { /// An inference variable for a const, for use in const generics. #[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)] -#[cfg_attr(feature = "nightly", derive(TyEncodable, TyDecodable))] +#[cfg_attr(feature = "nightly", derive(Encodable_NoContext, Decodable_NoContext))] pub enum InferConst { /// Infer the value of the const. Var(ConstVid), diff --git a/compiler/rustc_type_ir/src/fast_reject.rs b/compiler/rustc_type_ir/src/fast_reject.rs index 9955e92b55a..11ec1f0a9fb 100644 --- a/compiler/rustc_type_ir/src/fast_reject.rs +++ b/compiler/rustc_type_ir/src/fast_reject.rs @@ -9,7 +9,7 @@ use rustc_data_structures::fingerprint::Fingerprint; #[cfg(feature = "nightly")] use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHashKey}; #[cfg(feature = "nightly")] -use rustc_macros::{HashStable_NoContext, TyDecodable, TyEncodable}; +use rustc_macros::{Decodable_NoContext, Encodable_NoContext, HashStable_NoContext}; use crate::inherent::*; use crate::visit::TypeVisitableExt as _; @@ -17,7 +17,10 @@ use crate::{self as ty, Interner}; /// See `simplify_type`. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "nightly", derive(TyEncodable, TyDecodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) +)] pub enum SimplifiedType<DefId> { Bool, Char, diff --git a/compiler/rustc_type_ir/src/generic_arg.rs b/compiler/rustc_type_ir/src/generic_arg.rs index 008268c3bff..c18cade0e39 100644 --- a/compiler/rustc_type_ir/src/generic_arg.rs +++ b/compiler/rustc_type_ir/src/generic_arg.rs @@ -1,11 +1,14 @@ use derive_where::derive_where; #[cfg(feature = "nightly")] -use rustc_macros::{HashStable_NoContext, TyDecodable, TyEncodable}; +use rustc_macros::{Decodable_NoContext, Encodable_NoContext, HashStable_NoContext}; use crate::Interner; #[derive_where(Clone, Copy, PartialEq, Eq, Debug; I: Interner)] -#[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Decodable_NoContext, Encodable_NoContext, HashStable_NoContext) +)] pub enum GenericArgKind<I: Interner> { Lifetime(I::Region), Type(I::Ty), @@ -13,7 +16,10 @@ pub enum GenericArgKind<I: Interner> { } #[derive_where(Clone, Copy, PartialEq, Eq, Debug; I: Interner)] -#[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Decodable_NoContext, Encodable_NoContext, HashStable_NoContext) +)] pub enum TermKind<I: Interner> { Ty(I::Ty), Const(I::Const), diff --git a/compiler/rustc_type_ir/src/infer_ctxt.rs b/compiler/rustc_type_ir/src/infer_ctxt.rs index d5edc9610a4..26c49510696 100644 --- a/compiler/rustc_type_ir/src/infer_ctxt.rs +++ b/compiler/rustc_type_ir/src/infer_ctxt.rs @@ -1,6 +1,6 @@ use derive_where::derive_where; #[cfg(feature = "nightly")] -use rustc_macros::{HashStable_NoContext, TyDecodable, TyEncodable}; +use rustc_macros::{Decodable_NoContext, Encodable_NoContext, HashStable_NoContext}; use rustc_type_ir_macros::{TypeFoldable_Generic, TypeVisitable_Generic}; use crate::fold::TypeFoldable; @@ -20,7 +20,10 @@ use crate::{self as ty, Interner}; /// t-types for help. #[derive_where(Clone, Copy, Hash, PartialEq, Eq, Debug; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic)] -#[cfg_attr(feature = "nightly", derive(TyEncodable, TyDecodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) +)] pub enum TypingMode<I: Interner> { /// When checking whether impls overlap, we check whether any obligations /// are guaranteed to never hold when unifying the impls. This requires us diff --git a/compiler/rustc_type_ir/src/lib.rs b/compiler/rustc_type_ir/src/lib.rs index e2dfd9173fa..62912189509 100644 --- a/compiler/rustc_type_ir/src/lib.rs +++ b/compiler/rustc_type_ir/src/lib.rs @@ -17,15 +17,10 @@ use std::hash::Hash; use rustc_macros::{Decodable, Encodable, HashStable_NoContext}; // These modules are `pub` since they are not glob-imported. -#[macro_use] -pub mod visit; -#[cfg(feature = "nightly")] -pub mod codec; pub mod data_structures; pub mod elaborate; pub mod error; pub mod fast_reject; -pub mod fold; #[cfg_attr(feature = "nightly", rustc_diagnostic_item = "type_ir_inherent")] pub mod inherent; pub mod ir_print; @@ -43,6 +38,7 @@ mod binder; mod canonical; mod const_kind; mod flags; +mod fold; mod generic_arg; mod infer_ctxt; mod interner; @@ -53,6 +49,7 @@ mod region_kind; mod ty_info; mod ty_kind; mod upcast; +mod visit; pub use AliasTyKind::*; pub use DynKind::*; @@ -62,10 +59,9 @@ pub use TyKind::*; pub use Variance::*; pub use binder::*; pub use canonical::*; -#[cfg(feature = "nightly")] -pub use codec::*; pub use const_kind::*; pub use flags::*; +pub use fold::*; pub use generic_arg::*; pub use infer_ctxt::*; pub use interner::*; @@ -77,6 +73,7 @@ pub use rustc_ast_ir::{Movability, Mutability, Pinnedness}; pub use ty_info::*; pub use ty_kind::*; pub use upcast::*; +pub use visit::*; rustc_index::newtype_index! { /// A [De Bruijn index][dbi] is a standard means of representing diff --git a/compiler/rustc_type_ir/src/opaque_ty.rs b/compiler/rustc_type_ir/src/opaque_ty.rs index 6d61a52723a..416d355fd03 100644 --- a/compiler/rustc_type_ir/src/opaque_ty.rs +++ b/compiler/rustc_type_ir/src/opaque_ty.rs @@ -1,6 +1,6 @@ use derive_where::derive_where; #[cfg(feature = "nightly")] -use rustc_macros::{HashStable_NoContext, TyDecodable, TyEncodable}; +use rustc_macros::{Decodable_NoContext, Encodable_NoContext, HashStable_NoContext}; use rustc_type_ir_macros::{TypeFoldable_Generic, TypeVisitable_Generic}; use crate::inherent::*; @@ -8,7 +8,10 @@ use crate::{self as ty, Interner}; #[derive_where(Clone, Copy, Hash, PartialEq, Eq, Debug; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic)] -#[cfg_attr(feature = "nightly", derive(TyEncodable, TyDecodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) +)] pub struct OpaqueTypeKey<I: Interner> { pub def_id: I::LocalDefId, pub args: I::GenericArgs, diff --git a/compiler/rustc_type_ir/src/predicate.rs b/compiler/rustc_type_ir/src/predicate.rs index 46385ca3a6f..22d0fa23d0c 100644 --- a/compiler/rustc_type_ir/src/predicate.rs +++ b/compiler/rustc_type_ir/src/predicate.rs @@ -3,7 +3,9 @@ use std::hash::Hash; use derive_where::derive_where; #[cfg(feature = "nightly")] -use rustc_macros::{Decodable, Encodable, HashStable_NoContext, TyDecodable, TyEncodable}; +use rustc_macros::{ + Decodable, Decodable_NoContext, Encodable, Encodable_NoContext, HashStable_NoContext, +}; use rustc_type_ir_macros::{Lift_Generic, TypeFoldable_Generic, TypeVisitable_Generic}; use crate::inherent::*; @@ -20,7 +22,10 @@ use crate::{self as ty, Interner}; #[derive_where(Eq; I: Interner, A: Eq)] #[derive_where(Debug; I: Interner, A: fmt::Debug)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic)] -#[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Decodable_NoContext, Encodable_NoContext, HashStable_NoContext) +)] pub struct OutlivesPredicate<I: Interner, A>(pub A, pub I::Region); // FIXME: We manually derive `Lift` because the `derive(Lift_Generic)` doesn't @@ -50,7 +55,10 @@ where /// that case the `Self` parameter is absent from the generic parameters. #[derive_where(Clone, Copy, Hash, PartialEq, Eq; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] -#[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Decodable_NoContext, Encodable_NoContext, HashStable_NoContext) +)] pub struct TraitRef<I: Interner> { pub def_id: I::DefId, pub args: I::GenericArgs, @@ -122,7 +130,10 @@ impl<I: Interner> ty::Binder<I, TraitRef<I>> { #[derive_where(Clone, Copy, Hash, PartialEq, Eq; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] -#[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Decodable_NoContext, Encodable_NoContext, HashStable_NoContext) +)] pub struct TraitPredicate<I: Interner> { pub trait_ref: TraitRef<I>, @@ -177,7 +188,10 @@ impl<I: Interner> fmt::Debug for TraitPredicate<I> { } #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] -#[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Decodable_NoContext, Encodable_NoContext, HashStable_NoContext) +)] pub enum ImplPolarity { /// `impl Trait for Type` Positive, @@ -215,7 +229,10 @@ impl ImplPolarity { /// Distinguished from [`ImplPolarity`] since we never compute goals with /// "reservation" level. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] -#[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Decodable_NoContext, Encodable_NoContext, HashStable_NoContext) +)] pub enum PredicatePolarity { /// `Type: Trait` Positive, @@ -244,7 +261,10 @@ impl fmt::Display for PredicatePolarity { #[derive_where(Clone, Copy, Hash, PartialEq, Eq, Debug; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] -#[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Decodable_NoContext, Encodable_NoContext, HashStable_NoContext) +)] pub enum ExistentialPredicate<I: Interner> { /// E.g., `Iterator`. Trait(ExistentialTraitRef<I>), @@ -289,7 +309,10 @@ impl<I: Interner> ty::Binder<I, ExistentialPredicate<I>> { /// type and lifetime parameters (`[X, Y]` and `['a, 'b]` above). #[derive_where(Clone, Copy, Hash, PartialEq, Eq; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] -#[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Decodable_NoContext, Encodable_NoContext, HashStable_NoContext) +)] pub struct ExistentialTraitRef<I: Interner> { pub def_id: I::DefId, pub args: I::GenericArgs, @@ -353,7 +376,10 @@ impl<I: Interner> ty::Binder<I, ExistentialTraitRef<I>> { /// A `ProjectionPredicate` for an `ExistentialTraitRef`. #[derive_where(Clone, Copy, Hash, PartialEq, Eq; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] -#[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Decodable_NoContext, Encodable_NoContext, HashStable_NoContext) +)] pub struct ExistentialProjection<I: Interner> { pub def_id: I::DefId, pub args: I::GenericArgs, @@ -485,7 +511,10 @@ impl From<ty::AliasTyKind> for AliasTermKind { /// * For an opaque type, there is no explicit syntax. #[derive_where(Clone, Copy, Hash, PartialEq, Eq, Debug; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] -#[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Decodable_NoContext, Encodable_NoContext, HashStable_NoContext) +)] pub struct AliasTerm<I: Interner> { /// The parameters of the associated or opaque item. /// @@ -656,7 +685,10 @@ impl<I: Interner> From<ty::UnevaluatedConst<I>> for AliasTerm<I> { /// instances to normalize the LHS. #[derive_where(Clone, Copy, Hash, PartialEq, Eq; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] -#[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Decodable_NoContext, Encodable_NoContext, HashStable_NoContext) +)] pub struct ProjectionPredicate<I: Interner> { pub projection_term: AliasTerm<I>, pub term: I::Term, @@ -711,7 +743,10 @@ impl<I: Interner> fmt::Debug for ProjectionPredicate<I> { /// be an unconstrained inference variable which is used as the output. #[derive_where(Clone, Copy, Hash, PartialEq, Eq; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] -#[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Decodable_NoContext, Encodable_NoContext, HashStable_NoContext) +)] pub struct NormalizesTo<I: Interner> { pub alias: AliasTerm<I>, pub term: I::Term, @@ -743,7 +778,10 @@ impl<I: Interner> fmt::Debug for NormalizesTo<I> { #[derive_where(Clone, Copy, Hash, PartialEq, Eq, Debug; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] -#[cfg_attr(feature = "nightly", derive(TyEncodable, TyDecodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) +)] pub struct HostEffectPredicate<I: Interner> { pub trait_ref: ty::TraitRef<I>, pub constness: BoundConstness, @@ -784,7 +822,10 @@ impl<I: Interner> ty::Binder<I, HostEffectPredicate<I>> { /// presenting user diagnostics. #[derive_where(Clone, Copy, Hash, PartialEq, Eq, Debug; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] -#[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Decodable_NoContext, Encodable_NoContext, HashStable_NoContext) +)] pub struct SubtypePredicate<I: Interner> { pub a_is_expected: bool, pub a: I::Ty, @@ -794,14 +835,20 @@ pub struct SubtypePredicate<I: Interner> { /// Encodes that we have to coerce *from* the `a` type to the `b` type. #[derive_where(Clone, Copy, Hash, PartialEq, Eq, Debug; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] -#[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Decodable_NoContext, Encodable_NoContext, HashStable_NoContext) +)] pub struct CoercePredicate<I: Interner> { pub a: I::Ty, pub b: I::Ty, } #[derive(Clone, Copy, Hash, PartialEq, Eq, Debug)] -#[cfg_attr(feature = "nightly", derive(TyEncodable, TyDecodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) +)] pub enum BoundConstness { /// `Type: const Trait` /// diff --git a/compiler/rustc_type_ir/src/predicate_kind.rs b/compiler/rustc_type_ir/src/predicate_kind.rs index 21f4456abd1..847dff156fe 100644 --- a/compiler/rustc_type_ir/src/predicate_kind.rs +++ b/compiler/rustc_type_ir/src/predicate_kind.rs @@ -2,7 +2,7 @@ use std::fmt; use derive_where::derive_where; #[cfg(feature = "nightly")] -use rustc_macros::{Decodable, Encodable, HashStable_NoContext, TyDecodable, TyEncodable}; +use rustc_macros::{Decodable_NoContext, Encodable_NoContext, HashStable_NoContext}; use rustc_type_ir_macros::{TypeFoldable_Generic, TypeVisitable_Generic}; use crate::{self as ty, Interner}; @@ -11,7 +11,10 @@ use crate::{self as ty, Interner}; /// by implied bounds. #[derive_where(Clone, Copy, Hash, PartialEq, Eq; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic)] -#[cfg_attr(feature = "nightly", derive(TyEncodable, TyDecodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) +)] pub enum ClauseKind<I: Interner> { /// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be /// the `Self` type of the trait reference and `A`, `B`, and `C` @@ -47,7 +50,10 @@ pub enum ClauseKind<I: Interner> { #[derive_where(Clone, Copy, Hash, PartialEq, Eq; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic)] -#[cfg_attr(feature = "nightly", derive(TyEncodable, TyDecodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) +)] pub enum PredicateKind<I: Interner> { /// Prove a clause Clause(ClauseKind<I>), @@ -97,7 +103,10 @@ pub enum PredicateKind<I: Interner> { } #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Copy)] -#[cfg_attr(feature = "nightly", derive(HashStable_NoContext, Encodable, Decodable))] +#[cfg_attr( + feature = "nightly", + derive(HashStable_NoContext, Encodable_NoContext, Decodable_NoContext) +)] pub enum AliasRelationDirection { Equate, Subtype, diff --git a/compiler/rustc_type_ir/src/region_kind.rs b/compiler/rustc_type_ir/src/region_kind.rs index e0b39737007..eae3213ead0 100644 --- a/compiler/rustc_type_ir/src/region_kind.rs +++ b/compiler/rustc_type_ir/src/region_kind.rs @@ -4,7 +4,7 @@ use derive_where::derive_where; #[cfg(feature = "nightly")] use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; #[cfg(feature = "nightly")] -use rustc_macros::{HashStable_NoContext, TyDecodable, TyEncodable}; +use rustc_macros::{Decodable_NoContext, Encodable_NoContext, HashStable_NoContext}; use self::RegionKind::*; use crate::{DebruijnIndex, Interner}; @@ -126,7 +126,7 @@ rustc_index::newtype_index! { /// [2]: https://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/ /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/hrtb.html #[derive_where(Clone, Copy, Hash, PartialEq, Eq; I: Interner)] -#[cfg_attr(feature = "nightly", derive(TyEncodable, TyDecodable))] +#[cfg_attr(feature = "nightly", derive(Encodable_NoContext, Decodable_NoContext))] pub enum RegionKind<I: Interner> { /// A region parameter; for example `'a` in `impl<'a> Trait for &'a ()`. /// diff --git a/compiler/rustc_type_ir/src/search_graph/mod.rs b/compiler/rustc_type_ir/src/search_graph/mod.rs index 9ae83928057..1acd5d5c2af 100644 --- a/compiler/rustc_type_ir/src/search_graph/mod.rs +++ b/compiler/rustc_type_ir/src/search_graph/mod.rs @@ -21,7 +21,7 @@ use std::marker::PhantomData; use derive_where::derive_where; use rustc_index::{Idx, IndexVec}; #[cfg(feature = "nightly")] -use rustc_macros::{HashStable_NoContext, TyDecodable, TyEncodable}; +use rustc_macros::{Decodable_NoContext, Encodable_NoContext, HashStable_NoContext}; use tracing::debug; use crate::data_structures::HashMap; @@ -113,7 +113,10 @@ pub trait Delegate { /// result. In the case we return an initial provisional result depending /// on the kind of cycle. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Decodable_NoContext, Encodable_NoContext, HashStable_NoContext) +)] pub enum PathKind { /// A path consisting of only inductive/unproductive steps. Their initial /// provisional result is `Err(NoSolution)`. We currently treat them as diff --git a/compiler/rustc_type_ir/src/solve/mod.rs b/compiler/rustc_type_ir/src/solve/mod.rs index de2e0f2c0ec..3aec4804b27 100644 --- a/compiler/rustc_type_ir/src/solve/mod.rs +++ b/compiler/rustc_type_ir/src/solve/mod.rs @@ -5,7 +5,7 @@ use std::hash::Hash; use derive_where::derive_where; #[cfg(feature = "nightly")] -use rustc_macros::{HashStable_NoContext, TyDecodable, TyEncodable}; +use rustc_macros::{Decodable_NoContext, Encodable_NoContext, HashStable_NoContext}; use rustc_type_ir_macros::{Lift_Generic, TypeFoldable_Generic, TypeVisitable_Generic}; use crate::search_graph::PathKind; @@ -38,7 +38,10 @@ pub struct NoSolution; #[derive_where(Eq; I: Interner, P: Eq)] #[derive_where(Debug; I: Interner, P: fmt::Debug)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] -#[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Decodable_NoContext, Encodable_NoContext, HashStable_NoContext) +)] pub struct Goal<I: Interner, P> { pub param_env: I::ParamEnv, pub predicate: P, @@ -98,7 +101,10 @@ pub enum GoalSource { #[derive_where(Eq; I: Interner, Goal<I, P>: Eq)] #[derive_where(Debug; I: Interner, Goal<I, P>: fmt::Debug)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic)] -#[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Decodable_NoContext, Encodable_NoContext, HashStable_NoContext) +)] pub struct QueryInput<I: Interner, P> { pub goal: Goal<I, P>, pub predefined_opaques_in_body: I::PredefinedOpaques, @@ -107,7 +113,10 @@ pub struct QueryInput<I: Interner, P> { /// Opaques that are defined in the inference context before a query is called. #[derive_where(Clone, Hash, PartialEq, Eq, Debug, Default; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic)] -#[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Decodable_NoContext, Encodable_NoContext, HashStable_NoContext) +)] pub struct PredefinedOpaquesData<I: Interner> { pub opaque_types: Vec<(ty::OpaqueTypeKey<I>, I::Ty)>, } @@ -178,7 +187,10 @@ pub enum CandidateSource<I: Interner> { } #[derive(Clone, Copy, Hash, PartialEq, Eq, Debug)] -#[cfg_attr(feature = "nightly", derive(HashStable_NoContext, TyEncodable, TyDecodable))] +#[cfg_attr( + feature = "nightly", + derive(HashStable_NoContext, Encodable_NoContext, Decodable_NoContext) +)] pub enum BuiltinImplSource { /// A built-in impl that is considered trivial, without any nested requirements. They /// are preferred over where-clauses, and we want to track them explicitly. diff --git a/compiler/rustc_type_ir/src/ty_kind.rs b/compiler/rustc_type_ir/src/ty_kind.rs index 83631f7fe34..9bea4482b55 100644 --- a/compiler/rustc_type_ir/src/ty_kind.rs +++ b/compiler/rustc_type_ir/src/ty_kind.rs @@ -8,7 +8,7 @@ use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; #[cfg(feature = "nightly")] use rustc_data_structures::unify::{NoError, UnifyKey, UnifyValue}; #[cfg(feature = "nightly")] -use rustc_macros::{Decodable, Encodable, HashStable_NoContext, TyDecodable, TyEncodable}; +use rustc_macros::{Decodable_NoContext, Encodable_NoContext, HashStable_NoContext}; use rustc_type_ir_macros::{Lift_Generic, TypeFoldable_Generic, TypeVisitable_Generic}; use self::TyKind::*; @@ -22,7 +22,10 @@ mod closure; /// Specifies how a trait object is represented. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] -#[cfg_attr(feature = "nightly", derive(Encodable, Decodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) +)] pub enum DynKind { /// An unsized `dyn Trait` object Dyn, @@ -36,7 +39,10 @@ pub enum DynKind { } #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] -#[cfg_attr(feature = "nightly", derive(Encodable, Decodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) +)] pub enum AliasTyKind { /// A projection `<Type as Trait>::AssocType`. /// Can get normalized away if monomorphic enough. @@ -69,7 +75,10 @@ impl AliasTyKind { /// converted to this representation using `<dyn HirTyLowerer>::lower_ty`. #[cfg_attr(feature = "nightly", rustc_diagnostic_item = "IrTyKind")] #[derive_where(Clone, Copy, Hash, PartialEq, Eq; I: Interner)] -#[cfg_attr(feature = "nightly", derive(TyEncodable, TyDecodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) +)] pub enum TyKind<I: Interner> { /// The primitive boolean type. Written as `bool`. Bool, @@ -341,7 +350,10 @@ impl<I: Interner> fmt::Debug for TyKind<I> { /// * For an opaque type, there is no explicit syntax. #[derive_where(Clone, Copy, Hash, PartialEq, Eq, Debug; I: Interner)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] -#[cfg_attr(feature = "nightly", derive(TyDecodable, TyEncodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Decodable_NoContext, Encodable_NoContext, HashStable_NoContext) +)] pub struct AliasTy<I: Interner> { /// The parameters of the associated or opaque type. /// @@ -464,7 +476,10 @@ impl<I: Interner> AliasTy<I> { } #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[cfg_attr(feature = "nightly", derive(Encodable, Decodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) +)] pub enum IntTy { Isize, I8, @@ -522,7 +537,10 @@ impl IntTy { } #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Copy)] -#[cfg_attr(feature = "nightly", derive(Encodable, Decodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) +)] pub enum UintTy { Usize, U8, @@ -580,7 +598,10 @@ impl UintTy { } #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[cfg_attr(feature = "nightly", derive(Encodable, Decodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) +)] pub enum FloatTy { F16, F32, @@ -680,7 +701,7 @@ rustc_index::newtype_index! { /// type variable for the element type since we won't know until it's /// used what the element type is supposed to be. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[cfg_attr(feature = "nightly", derive(Encodable, Decodable))] +#[cfg_attr(feature = "nightly", derive(Encodable_NoContext, Decodable_NoContext))] pub enum InferTy { /// A type variable. TyVar(TyVid), @@ -860,7 +881,10 @@ impl fmt::Debug for InferTy { } #[derive_where(Clone, Copy, PartialEq, Eq, Hash, Debug; I: Interner)] -#[cfg_attr(feature = "nightly", derive(TyEncodable, TyDecodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) +)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic)] pub struct TypeAndMut<I: Interner> { pub ty: I::Ty, @@ -868,7 +892,10 @@ pub struct TypeAndMut<I: Interner> { } #[derive_where(Clone, Copy, PartialEq, Eq, Hash; I: Interner)] -#[cfg_attr(feature = "nightly", derive(TyEncodable, TyDecodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) +)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] pub struct FnSig<I: Interner> { pub inputs_and_output: I::Tys, @@ -1010,7 +1037,8 @@ impl<I: Interner> Deref for UnsafeBinderInner<I> { } #[cfg(feature = "nightly")] -impl<I: Interner, E: crate::TyEncoder<I = I>> rustc_serialize::Encodable<E> for UnsafeBinderInner<I> +impl<I: Interner, E: rustc_serialize::Encoder> rustc_serialize::Encodable<E> + for UnsafeBinderInner<I> where I::Ty: rustc_serialize::Encodable<E>, I::BoundVarKinds: rustc_serialize::Encodable<E>, @@ -1022,7 +1050,8 @@ where } #[cfg(feature = "nightly")] -impl<I: Interner, D: crate::TyDecoder<I = I>> rustc_serialize::Decodable<D> for UnsafeBinderInner<I> +impl<I: Interner, D: rustc_serialize::Decoder> rustc_serialize::Decodable<D> + for UnsafeBinderInner<I> where I::Ty: TypeVisitable<I> + rustc_serialize::Decodable<D>, I::BoundVarKinds: rustc_serialize::Decodable<D>, @@ -1038,7 +1067,10 @@ where // This is just a `FnSig` without the `FnHeader` fields. #[derive_where(Clone, Copy, Debug, PartialEq, Eq, Hash; I: Interner)] -#[cfg_attr(feature = "nightly", derive(TyEncodable, TyDecodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) +)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] pub struct FnSigTys<I: Interner> { pub inputs_and_output: I::Tys, @@ -1087,7 +1119,10 @@ impl<I: Interner> ty::Binder<I, FnSigTys<I>> { } #[derive_where(Clone, Copy, Debug, PartialEq, Eq, Hash; I: Interner)] -#[cfg_attr(feature = "nightly", derive(TyEncodable, TyDecodable, HashStable_NoContext))] +#[cfg_attr( + feature = "nightly", + derive(Encodable_NoContext, Decodable_NoContext, HashStable_NoContext) +)] #[derive(TypeVisitable_Generic, TypeFoldable_Generic, Lift_Generic)] pub struct FnHeader<I: Interner> { pub c_variadic: bool, diff --git a/compiler/rustc_type_ir_macros/src/lib.rs b/compiler/rustc_type_ir_macros/src/lib.rs index 640299c2167..8eefecdc980 100644 --- a/compiler/rustc_type_ir_macros/src/lib.rs +++ b/compiler/rustc_type_ir_macros/src/lib.rs @@ -45,12 +45,12 @@ fn type_visitable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::Tok s.add_bounds(synstructure::AddBounds::Fields); let body_visit = s.each(|bind| { quote! { - match ::rustc_type_ir::visit::VisitorResult::branch( - ::rustc_type_ir::visit::TypeVisitable::visit_with(#bind, __visitor) + match ::rustc_type_ir::VisitorResult::branch( + ::rustc_type_ir::TypeVisitable::visit_with(#bind, __visitor) ) { ::core::ops::ControlFlow::Continue(()) => {}, ::core::ops::ControlFlow::Break(r) => { - return ::rustc_type_ir::visit::VisitorResult::from_residual(r); + return ::rustc_type_ir::VisitorResult::from_residual(r); }, } } @@ -58,14 +58,14 @@ fn type_visitable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::Tok s.bind_with(|_| synstructure::BindStyle::Move); s.bound_impl( - quote!(::rustc_type_ir::visit::TypeVisitable<I>), + quote!(::rustc_type_ir::TypeVisitable<I>), quote! { - fn visit_with<__V: ::rustc_type_ir::visit::TypeVisitor<I>>( + fn visit_with<__V: ::rustc_type_ir::TypeVisitor<I>>( &self, __visitor: &mut __V ) -> __V::Result { match *self { #body_visit } - <__V::Result as ::rustc_type_ir::visit::VisitorResult>::output() + <__V::Result as ::rustc_type_ir::VisitorResult>::output() } }, ) @@ -93,7 +93,7 @@ fn type_foldable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::Toke bind.to_token_stream() } else { quote! { - ::rustc_type_ir::fold::TypeFoldable::try_fold_with(#bind, __folder)? + ::rustc_type_ir::TypeFoldable::try_fold_with(#bind, __folder)? } } }) @@ -105,9 +105,9 @@ fn type_foldable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::Toke s.filter(|bi| !has_ignore_attr(&bi.ast().attrs, "type_foldable", "identity")); s.add_bounds(synstructure::AddBounds::Fields); s.bound_impl( - quote!(::rustc_type_ir::fold::TypeFoldable<I>), + quote!(::rustc_type_ir::TypeFoldable<I>), quote! { - fn try_fold_with<__F: ::rustc_type_ir::fold::FallibleTypeFolder<I>>( + fn try_fold_with<__F: ::rustc_type_ir::FallibleTypeFolder<I>>( self, __folder: &mut __F ) -> Result<Self, __F::Error> { diff --git a/config.example.toml b/config.example.toml index c3d2ad094ce..0700a317109 100644 --- a/config.example.toml +++ b/config.example.toml @@ -446,6 +446,10 @@ # a specific version. #ccache = false +# List of paths to exclude from the build and test processes. +# For example, exclude = ["tests/ui", "src/tools/tidy"]. +#exclude = [] + # ============================================================================= # General install configuration options # ============================================================================= diff --git a/library/alloc/src/rc.rs b/library/alloc/src/rc.rs index fc1cee28d03..619d9f258e3 100644 --- a/library/alloc/src/rc.rs +++ b/library/alloc/src/rc.rs @@ -1327,11 +1327,14 @@ impl<T: ?Sized> Rc<T> { /// /// # Safety /// - /// The pointer must have been obtained through `Rc::into_raw`, the - /// associated `Rc` instance must be valid (i.e. the strong count must be at + /// The pointer must have been obtained through `Rc::into_raw` and must satisfy the + /// same layout requirements specified in [`Rc::from_raw_in`][from_raw_in]. + /// The associated `Rc` instance must be valid (i.e. the strong count must be at /// least 1) for the duration of this method, and `ptr` must point to a block of memory /// allocated by the global allocator. /// + /// [from_raw_in]: Rc::from_raw_in + /// /// # Examples /// /// ``` @@ -1360,12 +1363,15 @@ impl<T: ?Sized> Rc<T> { /// /// # Safety /// - /// The pointer must have been obtained through `Rc::into_raw`, the - /// associated `Rc` instance must be valid (i.e. the strong count must be at + /// The pointer must have been obtained through `Rc::into_raw`and must satisfy the + /// same layout requirements specified in [`Rc::from_raw_in`][from_raw_in]. + /// The associated `Rc` instance must be valid (i.e. the strong count must be at /// least 1) when invoking this method, and `ptr` must point to a block of memory /// allocated by the global allocator. This method can be used to release the final `Rc` and /// backing storage, but **should not** be called after the final `Rc` has been released. /// + /// [from_raw_in]: Rc::from_raw_in + /// /// # Examples /// /// ``` @@ -1623,10 +1629,13 @@ impl<T: ?Sized, A: Allocator> Rc<T, A> { /// /// # Safety /// - /// The pointer must have been obtained through `Rc::into_raw`, the - /// associated `Rc` instance must be valid (i.e. the strong count must be at + /// The pointer must have been obtained through `Rc::into_raw` and must satisfy the + /// same layout requirements specified in [`Rc::from_raw_in`][from_raw_in]. + /// The associated `Rc` instance must be valid (i.e. the strong count must be at /// least 1) for the duration of this method, and `ptr` must point to a block of memory - /// allocated by `alloc` + /// allocated by `alloc`. + /// + /// [from_raw_in]: Rc::from_raw_in /// /// # Examples /// @@ -1665,11 +1674,14 @@ impl<T: ?Sized, A: Allocator> Rc<T, A> { /// /// # Safety /// - /// The pointer must have been obtained through `Rc::into_raw`, the - /// associated `Rc` instance must be valid (i.e. the strong count must be at + /// The pointer must have been obtained through `Rc::into_raw`and must satisfy the + /// same layout requirements specified in [`Rc::from_raw_in`][from_raw_in]. + /// The associated `Rc` instance must be valid (i.e. the strong count must be at /// least 1) when invoking this method, and `ptr` must point to a block of memory - /// allocated by `alloc`. This method can be used to release the final `Rc` and backing storage, - /// but **should not** be called after the final `Rc` has been released. + /// allocated by `alloc`. This method can be used to release the final `Rc` and + /// backing storage, but **should not** be called after the final `Rc` has been released. + /// + /// [from_raw_in]: Rc::from_raw_in /// /// # Examples /// diff --git a/library/alloc/src/sync.rs b/library/alloc/src/sync.rs index 4999319f618..104cb35c23b 100644 --- a/library/alloc/src/sync.rs +++ b/library/alloc/src/sync.rs @@ -1453,11 +1453,14 @@ impl<T: ?Sized> Arc<T> { /// /// # Safety /// - /// The pointer must have been obtained through `Arc::into_raw`, and the - /// associated `Arc` instance must be valid (i.e. the strong count must be at + /// The pointer must have been obtained through `Arc::into_raw` and must satisfy the + /// same layout requirements specified in [`Arc::from_raw_in`][from_raw_in]. + /// The associated `Arc` instance must be valid (i.e. the strong count must be at /// least 1) for the duration of this method, and `ptr` must point to a block of memory /// allocated by the global allocator. /// + /// [from_raw_in]: Arc::from_raw_in + /// /// # Examples /// /// ``` @@ -1488,13 +1491,16 @@ impl<T: ?Sized> Arc<T> { /// /// # Safety /// - /// The pointer must have been obtained through `Arc::into_raw`, and the - /// associated `Arc` instance must be valid (i.e. the strong count must be at + /// The pointer must have been obtained through `Arc::into_raw` and must satisfy the + /// same layout requirements specified in [`Arc::from_raw_in`][from_raw_in]. + /// The associated `Arc` instance must be valid (i.e. the strong count must be at /// least 1) when invoking this method, and `ptr` must point to a block of memory /// allocated by the global allocator. This method can be used to release the final /// `Arc` and backing storage, but **should not** be called after the final `Arc` has been /// released. /// + /// [from_raw_in]: Arc::from_raw_in + /// /// # Examples /// /// ``` @@ -1806,11 +1812,14 @@ impl<T: ?Sized, A: Allocator> Arc<T, A> { /// /// # Safety /// - /// The pointer must have been obtained through `Arc::into_raw`, and the - /// associated `Arc` instance must be valid (i.e. the strong count must be at - /// least 1) for the duration of this method,, and `ptr` must point to a block of memory + /// The pointer must have been obtained through `Arc::into_raw` and must satisfy the + /// same layout requirements specified in [`Arc::from_raw_in`][from_raw_in]. + /// The associated `Arc` instance must be valid (i.e. the strong count must be at + /// least 1) for the duration of this method, and `ptr` must point to a block of memory /// allocated by `alloc`. /// + /// [from_raw_in]: Arc::from_raw_in + /// /// # Examples /// /// ``` @@ -1850,13 +1859,16 @@ impl<T: ?Sized, A: Allocator> Arc<T, A> { /// /// # Safety /// - /// The pointer must have been obtained through `Arc::into_raw`, the - /// associated `Arc` instance must be valid (i.e. the strong count must be at + /// The pointer must have been obtained through `Arc::into_raw` and must satisfy the + /// same layout requirements specified in [`Arc::from_raw_in`][from_raw_in]. + /// The associated `Arc` instance must be valid (i.e. the strong count must be at /// least 1) when invoking this method, and `ptr` must point to a block of memory /// allocated by `alloc`. This method can be used to release the final /// `Arc` and backing storage, but **should not** be called after the final `Arc` has been /// released. /// + /// [from_raw_in]: Arc::from_raw_in + /// /// # Examples /// /// ``` diff --git a/library/core/src/any.rs b/library/core/src/any.rs index 9ed2c8e9f3a..10f2a11d558 100644 --- a/library/core/src/any.rs +++ b/library/core/src/any.rs @@ -109,7 +109,7 @@ use crate::{fmt, hash, intrinsics}; // unsafe traits and unsafe methods (i.e., `type_id` would still be safe to call, // but we would likely want to indicate as such in documentation). #[stable(feature = "rust1", since = "1.0.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "Any")] +#[rustc_diagnostic_item = "Any"] pub trait Any: 'static { /// Gets the `TypeId` of `self`. /// diff --git a/library/core/src/array/ascii.rs b/library/core/src/array/ascii.rs index e2faef855bc..792a57e3fa2 100644 --- a/library/core/src/array/ascii.rs +++ b/library/core/src/array/ascii.rs @@ -1,6 +1,5 @@ use crate::ascii; -#[cfg(not(test))] impl<const N: usize> [u8; N] { /// Converts this array of bytes into an array of ASCII characters, /// or returns `None` if any of the characters is non-ASCII. diff --git a/library/core/src/bool.rs b/library/core/src/bool.rs index 3c589ca5dfa..d525ab425e6 100644 --- a/library/core/src/bool.rs +++ b/library/core/src/bool.rs @@ -56,7 +56,7 @@ impl bool { /// ``` #[doc(alias = "then_with")] #[stable(feature = "lazy_bool_to_option", since = "1.50.0")] - #[cfg_attr(not(test), rustc_diagnostic_item = "bool_then")] + #[rustc_diagnostic_item = "bool_then"] #[inline] pub fn then<T, F: FnOnce() -> T>(self, f: F) -> Option<T> { if self { Some(f()) } else { None } diff --git a/library/core/src/cell.rs b/library/core/src/cell.rs index cbf00106c51..1a320b316a4 100644 --- a/library/core/src/cell.rs +++ b/library/core/src/cell.rs @@ -304,7 +304,7 @@ pub use once::OnceCell; /// ``` /// /// See the [module-level documentation](self) for more. -#[cfg_attr(not(test), rustc_diagnostic_item = "Cell")] +#[rustc_diagnostic_item = "Cell"] #[stable(feature = "rust1", since = "1.0.0")] #[repr(transparent)] #[rustc_pub_transparent] @@ -725,7 +725,7 @@ impl<T, const N: usize> Cell<[T; N]> { /// A mutable memory location with dynamically checked borrow rules /// /// See the [module-level documentation](self) for more. -#[cfg_attr(not(test), rustc_diagnostic_item = "RefCell")] +#[rustc_diagnostic_item = "RefCell"] #[stable(feature = "rust1", since = "1.0.0")] pub struct RefCell<T: ?Sized> { borrow: Cell<BorrowFlag>, diff --git a/library/core/src/char/methods.rs b/library/core/src/char/methods.rs index bb71af339b8..fa584953bed 100644 --- a/library/core/src/char/methods.rs +++ b/library/core/src/char/methods.rs @@ -1178,7 +1178,7 @@ impl char { #[must_use] #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")] #[rustc_const_stable(feature = "const_char_is_ascii", since = "1.32.0")] - #[cfg_attr(not(test), rustc_diagnostic_item = "char_is_ascii")] + #[rustc_diagnostic_item = "char_is_ascii"] #[inline] pub const fn is_ascii(&self) -> bool { *self as u32 <= 0x7F diff --git a/library/core/src/clone.rs b/library/core/src/clone.rs index c777dd995a6..e0ac0bfc528 100644 --- a/library/core/src/clone.rs +++ b/library/core/src/clone.rs @@ -262,34 +262,150 @@ pub struct AssertParamIsCopy<T: Copy + ?Sized> { _field: crate::marker::PhantomData<T>, } -/// A generalization of [`Clone`] to dynamically-sized types stored in arbitrary containers. +/// A generalization of [`Clone`] to [dynamically-sized types][DST] stored in arbitrary containers. /// -/// This trait is implemented for all types implementing [`Clone`], and also [slices](slice) of all -/// such types. You may also implement this trait to enable cloning trait objects and custom DSTs -/// (structures containing dynamically-sized fields). +/// This trait is implemented for all types implementing [`Clone`], [slices](slice) of all +/// such types, and other dynamically-sized types in the standard library. +/// You may also implement this trait to enable cloning custom DSTs +/// (structures containing dynamically-sized fields), or use it as a supertrait to enable +/// cloning a [trait object]. +/// +/// This trait is normally used via operations on container types which support DSTs, +/// so you should not typically need to call `.clone_to_uninit()` explicitly except when +/// implementing such a container or otherwise performing explicit management of an allocation, +/// or when implementing `CloneToUninit` itself. /// /// # Safety /// -/// Implementations must ensure that when `.clone_to_uninit(dst)` returns normally rather than -/// panicking, it always leaves `*dst` initialized as a valid value of type `Self`. +/// Implementations must ensure that when `.clone_to_uninit(dest)` returns normally rather than +/// panicking, it always leaves `*dest` initialized as a valid value of type `Self`. +/// +/// # Examples +/// +// FIXME(#126799): when `Box::clone` allows use of `CloneToUninit`, rewrite these examples with it +// since `Rc` is a distraction. +/// +/// If you are defining a trait, you can add `CloneToUninit` as a supertrait to enable cloning of +/// `dyn` values of your trait: +/// +/// ``` +/// #![feature(clone_to_uninit)] +/// use std::rc::Rc; +/// +/// trait Foo: std::fmt::Debug + std::clone::CloneToUninit { +/// fn modify(&mut self); +/// fn value(&self) -> i32; +/// } +/// +/// impl Foo for i32 { +/// fn modify(&mut self) { +/// *self *= 10; +/// } +/// fn value(&self) -> i32 { +/// *self +/// } +/// } +/// +/// let first: Rc<dyn Foo> = Rc::new(1234); +/// +/// let mut second = first.clone(); +/// Rc::make_mut(&mut second).modify(); // make_mut() will call clone_to_uninit() +/// +/// assert_eq!(first.value(), 1234); +/// assert_eq!(second.value(), 12340); +/// ``` +/// +/// The following is an example of implementing `CloneToUninit` for a custom DST. +/// (It is essentially a limited form of what `derive(CloneToUninit)` would do, +/// if such a derive macro existed.) /// -/// # See also +/// ``` +/// #![feature(clone_to_uninit)] +/// use std::clone::CloneToUninit; +/// use std::mem::offset_of; +/// use std::rc::Rc; +/// +/// #[derive(PartialEq)] +/// struct MyDst<T: ?Sized> { +/// label: String, +/// contents: T, +/// } /// -/// * [`Clone::clone_from`] is a safe function which may be used instead when `Self` is a [`Sized`] +/// unsafe impl<T: ?Sized + CloneToUninit> CloneToUninit for MyDst<T> { +/// unsafe fn clone_to_uninit(&self, dest: *mut u8) { +/// // The offset of `self.contents` is dynamic because it depends on the alignment of T +/// // which can be dynamic (if `T = dyn SomeTrait`). Therefore, we have to obtain it +/// // dynamically by examining `self`, rather than using `offset_of!`. +/// // +/// // SAFETY: `self` by definition points somewhere before `&self.contents` in the same +/// // allocation. +/// let offset_of_contents = unsafe { +/// (&raw const self.contents).byte_offset_from_unsigned(self) +/// }; +/// +/// // Clone the *sized* fields of `self` (just one, in this example). +/// // (By cloning this first and storing it temporarily in a local variable, we avoid +/// // leaking it in case of any panic, using the ordinary automatic cleanup of local +/// // variables. Such a leak would be sound, but undesirable.) +/// let label = self.label.clone(); +/// +/// // SAFETY: The caller must provide a `dest` such that these field offsets are valid +/// // to write to. +/// unsafe { +/// // Clone the unsized field directly from `self` to `dest`. +/// self.contents.clone_to_uninit(dest.add(offset_of_contents)); +/// +/// // Now write all the sized fields. +/// // +/// // Note that we only do this once all of the clone() and clone_to_uninit() calls +/// // have completed, and therefore we know that there are no more possible panics; +/// // this ensures no memory leaks in case of panic. +/// dest.add(offset_of!(Self, label)).cast::<String>().write(label); +/// } +/// // All fields of the struct have been initialized; therefore, the struct is initialized, +/// // and we have satisfied our `unsafe impl CloneToUninit` obligations. +/// } +/// } +/// +/// fn main() { +/// // Construct MyDst<[u8; 4]>, then coerce to MyDst<[u8]>. +/// let first: Rc<MyDst<[u8]>> = Rc::new(MyDst { +/// label: String::from("hello"), +/// contents: [1, 2, 3, 4], +/// }); +/// +/// let mut second = first.clone(); +/// // make_mut() will call clone_to_uninit(). +/// for elem in Rc::make_mut(&mut second).contents.iter_mut() { +/// *elem *= 10; +/// } +/// +/// assert_eq!(first.contents, [1, 2, 3, 4]); +/// assert_eq!(second.contents, [10, 20, 30, 40]); +/// assert_eq!(second.label, "hello"); +/// } +/// ``` +/// +/// # See Also +/// +/// * [`Clone::clone_from`] is a safe function which may be used instead when [`Self: Sized`](Sized) /// and the destination is already initialized; it may be able to reuse allocations owned by -/// the destination. +/// the destination, whereas `clone_to_uninit` cannot, since its destination is assumed to be +/// uninitialized. /// * [`ToOwned`], which allocates a new destination container. /// /// [`ToOwned`]: ../../std/borrow/trait.ToOwned.html +/// [DST]: https://doc.rust-lang.org/reference/dynamically-sized-types.html +/// [trait object]: https://doc.rust-lang.org/reference/types/trait-object.html #[unstable(feature = "clone_to_uninit", issue = "126799")] pub unsafe trait CloneToUninit { - /// Performs copy-assignment from `self` to `dst`. + /// Performs copy-assignment from `self` to `dest`. /// - /// This is analogous to `std::ptr::write(dst.cast(), self.clone())`, - /// except that `self` may be a dynamically-sized type ([`!Sized`](Sized)). + /// This is analogous to `std::ptr::write(dest.cast(), self.clone())`, + /// except that `Self` may be a dynamically-sized type ([`!Sized`](Sized)). /// - /// Before this function is called, `dst` may point to uninitialized memory. - /// After this function is called, `dst` will point to initialized memory; it will be + /// Before this function is called, `dest` may point to uninitialized memory. + /// After this function is called, `dest` will point to initialized memory; it will be /// sound to create a `&Self` reference from the pointer with the [pointer metadata] /// from `self`. /// @@ -297,8 +413,8 @@ pub unsafe trait CloneToUninit { /// /// Behavior is undefined if any of the following conditions are violated: /// - /// * `dst` must be [valid] for writes for `size_of_val(self)` bytes. - /// * `dst` must be properly aligned to `align_of_val(self)`. + /// * `dest` must be [valid] for writes for `size_of_val(self)` bytes. + /// * `dest` must be properly aligned to `align_of_val(self)`. /// /// [valid]: crate::ptr#safety /// [pointer metadata]: crate::ptr::metadata() @@ -307,27 +423,26 @@ pub unsafe trait CloneToUninit { /// /// This function may panic. (For example, it might panic if memory allocation for a clone /// of a value owned by `self` fails.) - /// If the call panics, then `*dst` should be treated as uninitialized memory; it must not be + /// If the call panics, then `*dest` should be treated as uninitialized memory; it must not be /// read or dropped, because even if it was previously valid, it may have been partially /// overwritten. /// - /// The caller may also need to take care to deallocate the allocation pointed to by `dst`, - /// if applicable, to avoid a memory leak, and may need to take other precautions to ensure - /// soundness in the presence of unwinding. + /// The caller may wish to to take care to deallocate the allocation pointed to by `dest`, + /// if applicable, to avoid a memory leak (but this is not a requirement). /// /// Implementors should avoid leaking values by, upon unwinding, dropping all component values /// that might have already been created. (For example, if a `[Foo]` of length 3 is being /// cloned, and the second of the three calls to `Foo::clone()` unwinds, then the first `Foo` /// cloned should be dropped.) - unsafe fn clone_to_uninit(&self, dst: *mut u8); + unsafe fn clone_to_uninit(&self, dest: *mut u8); } #[unstable(feature = "clone_to_uninit", issue = "126799")] unsafe impl<T: Clone> CloneToUninit for T { #[inline] - unsafe fn clone_to_uninit(&self, dst: *mut u8) { + unsafe fn clone_to_uninit(&self, dest: *mut u8) { // SAFETY: we're calling a specialization with the same contract - unsafe { <T as self::uninit::CopySpec>::clone_one(self, dst.cast::<T>()) } + unsafe { <T as self::uninit::CopySpec>::clone_one(self, dest.cast::<T>()) } } } @@ -335,10 +450,10 @@ unsafe impl<T: Clone> CloneToUninit for T { unsafe impl<T: Clone> CloneToUninit for [T] { #[inline] #[cfg_attr(debug_assertions, track_caller)] - unsafe fn clone_to_uninit(&self, dst: *mut u8) { - let dst: *mut [T] = dst.with_metadata_of(self); + unsafe fn clone_to_uninit(&self, dest: *mut u8) { + let dest: *mut [T] = dest.with_metadata_of(self); // SAFETY: we're calling a specialization with the same contract - unsafe { <T as self::uninit::CopySpec>::clone_slice(self, dst) } + unsafe { <T as self::uninit::CopySpec>::clone_slice(self, dest) } } } @@ -346,21 +461,21 @@ unsafe impl<T: Clone> CloneToUninit for [T] { unsafe impl CloneToUninit for str { #[inline] #[cfg_attr(debug_assertions, track_caller)] - unsafe fn clone_to_uninit(&self, dst: *mut u8) { + unsafe fn clone_to_uninit(&self, dest: *mut u8) { // SAFETY: str is just a [u8] with UTF-8 invariant - unsafe { self.as_bytes().clone_to_uninit(dst) } + unsafe { self.as_bytes().clone_to_uninit(dest) } } } #[unstable(feature = "clone_to_uninit", issue = "126799")] unsafe impl CloneToUninit for crate::ffi::CStr { #[cfg_attr(debug_assertions, track_caller)] - unsafe fn clone_to_uninit(&self, dst: *mut u8) { + unsafe fn clone_to_uninit(&self, dest: *mut u8) { // SAFETY: For now, CStr is just a #[repr(trasnsparent)] [c_char] with some invariants. // And we can cast [c_char] to [u8] on all supported platforms (see: to_bytes_with_nul). // The pointer metadata properly preserves the length (so NUL is also copied). // See: `cstr_metadata_is_length_with_nul` in tests. - unsafe { self.to_bytes_with_nul().clone_to_uninit(dst) } + unsafe { self.to_bytes_with_nul().clone_to_uninit(dest) } } } diff --git a/library/core/src/cmp.rs b/library/core/src/cmp.rs index b29251b4b43..25bd17d5802 100644 --- a/library/core/src/cmp.rs +++ b/library/core/src/cmp.rs @@ -1481,7 +1481,7 @@ pub macro PartialOrd($item:item) { #[inline] #[must_use] #[stable(feature = "rust1", since = "1.0.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "cmp_min")] +#[rustc_diagnostic_item = "cmp_min"] pub fn min<T: Ord>(v1: T, v2: T) -> T { v1.min(v2) } @@ -1573,7 +1573,7 @@ pub fn min_by_key<T, F: FnMut(&T) -> K, K: Ord>(v1: T, v2: T, mut f: F) -> T { #[inline] #[must_use] #[stable(feature = "rust1", since = "1.0.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "cmp_max")] +#[rustc_diagnostic_item = "cmp_max"] pub fn max<T: Ord>(v1: T, v2: T) -> T { v1.max(v2) } diff --git a/library/core/src/convert/mod.rs b/library/core/src/convert/mod.rs index 43fd54f881d..e1b10e1074d 100644 --- a/library/core/src/convert/mod.rs +++ b/library/core/src/convert/mod.rs @@ -214,7 +214,7 @@ pub const fn identity<T>(x: T) -> T { /// is_hello(s); /// ``` #[stable(feature = "rust1", since = "1.0.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "AsRef")] +#[rustc_diagnostic_item = "AsRef"] pub trait AsRef<T: ?Sized> { /// Converts this type into a shared reference of the (usually inferred) input type. #[stable(feature = "rust1", since = "1.0.0")] @@ -365,7 +365,7 @@ pub trait AsRef<T: ?Sized> { /// Note, however, that APIs don't need to be generic. In many cases taking a `&mut [u8]` or /// `&mut Vec<u8>`, for example, is the better choice (callers need to pass the correct type then). #[stable(feature = "rust1", since = "1.0.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "AsMut")] +#[rustc_diagnostic_item = "AsMut"] pub trait AsMut<T: ?Sized> { /// Converts this type into a mutable reference of the (usually inferred) input type. #[stable(feature = "rust1", since = "1.0.0")] diff --git a/library/core/src/default.rs b/library/core/src/default.rs index 4c30290ff26..044997a81a9 100644 --- a/library/core/src/default.rs +++ b/library/core/src/default.rs @@ -101,7 +101,7 @@ use crate::ascii::Char as AsciiChar; /// bar: f32, /// } /// ``` -#[cfg_attr(not(test), rustc_diagnostic_item = "Default")] +#[rustc_diagnostic_item = "Default"] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_trivial_field_reads] pub trait Default: Sized { diff --git a/library/core/src/error.rs b/library/core/src/error.rs index 94847685ec9..bfa392003b9 100644 --- a/library/core/src/error.rs +++ b/library/core/src/error.rs @@ -47,7 +47,7 @@ use crate::fmt::{self, Debug, Display, Formatter}; /// impl Error for ReadConfigError {} /// ``` #[stable(feature = "rust1", since = "1.0.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "Error")] +#[rustc_diagnostic_item = "Error"] #[rustc_has_incoherent_inherent_impls] #[allow(multiple_supertrait_upcastable)] pub trait Error: Debug + Display { diff --git a/library/core/src/fmt/mod.rs b/library/core/src/fmt/mod.rs index e0dc632df70..a0f5b00cd2d 100644 --- a/library/core/src/fmt/mod.rs +++ b/library/core/src/fmt/mod.rs @@ -18,7 +18,7 @@ mod num; mod rt; #[stable(feature = "fmt_flags_align", since = "1.28.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "Alignment")] +#[rustc_diagnostic_item = "Alignment"] /// Possible alignments returned by `Formatter::align` #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum Alignment { diff --git a/library/core/src/intrinsics/mod.rs b/library/core/src/intrinsics/mod.rs index ead7b2d2965..078f7552c87 100644 --- a/library/core/src/intrinsics/mod.rs +++ b/library/core/src/intrinsics/mod.rs @@ -90,6 +90,7 @@ pub unsafe fn drop_in_place<T: ?Sized>(to_drop: *mut T) { // memory, which is not valid for either `&` or `&mut`. /// Stores a value if the current value is the same as the `old` value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `compare_exchange` method by passing @@ -99,6 +100,7 @@ pub unsafe fn drop_in_place<T: ?Sized>(to_drop: *mut T) { #[rustc_nounwind] pub unsafe fn atomic_cxchg_relaxed_relaxed<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool); /// Stores a value if the current value is the same as the `old` value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `compare_exchange` method by passing @@ -108,6 +110,7 @@ pub unsafe fn atomic_cxchg_relaxed_relaxed<T: Copy>(dst: *mut T, old: T, src: T) #[rustc_nounwind] pub unsafe fn atomic_cxchg_relaxed_acquire<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool); /// Stores a value if the current value is the same as the `old` value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `compare_exchange` method by passing @@ -117,6 +120,7 @@ pub unsafe fn atomic_cxchg_relaxed_acquire<T: Copy>(dst: *mut T, old: T, src: T) #[rustc_nounwind] pub unsafe fn atomic_cxchg_relaxed_seqcst<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool); /// Stores a value if the current value is the same as the `old` value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `compare_exchange` method by passing @@ -126,6 +130,7 @@ pub unsafe fn atomic_cxchg_relaxed_seqcst<T: Copy>(dst: *mut T, old: T, src: T) #[rustc_nounwind] pub unsafe fn atomic_cxchg_acquire_relaxed<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool); /// Stores a value if the current value is the same as the `old` value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `compare_exchange` method by passing @@ -135,6 +140,7 @@ pub unsafe fn atomic_cxchg_acquire_relaxed<T: Copy>(dst: *mut T, old: T, src: T) #[rustc_nounwind] pub unsafe fn atomic_cxchg_acquire_acquire<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool); /// Stores a value if the current value is the same as the `old` value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `compare_exchange` method by passing @@ -144,6 +150,7 @@ pub unsafe fn atomic_cxchg_acquire_acquire<T: Copy>(dst: *mut T, old: T, src: T) #[rustc_nounwind] pub unsafe fn atomic_cxchg_acquire_seqcst<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool); /// Stores a value if the current value is the same as the `old` value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `compare_exchange` method by passing @@ -153,6 +160,7 @@ pub unsafe fn atomic_cxchg_acquire_seqcst<T: Copy>(dst: *mut T, old: T, src: T) #[rustc_nounwind] pub unsafe fn atomic_cxchg_release_relaxed<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool); /// Stores a value if the current value is the same as the `old` value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `compare_exchange` method by passing @@ -162,6 +170,7 @@ pub unsafe fn atomic_cxchg_release_relaxed<T: Copy>(dst: *mut T, old: T, src: T) #[rustc_nounwind] pub unsafe fn atomic_cxchg_release_acquire<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool); /// Stores a value if the current value is the same as the `old` value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `compare_exchange` method by passing @@ -171,6 +180,7 @@ pub unsafe fn atomic_cxchg_release_acquire<T: Copy>(dst: *mut T, old: T, src: T) #[rustc_nounwind] pub unsafe fn atomic_cxchg_release_seqcst<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool); /// Stores a value if the current value is the same as the `old` value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `compare_exchange` method by passing @@ -180,6 +190,7 @@ pub unsafe fn atomic_cxchg_release_seqcst<T: Copy>(dst: *mut T, old: T, src: T) #[rustc_nounwind] pub unsafe fn atomic_cxchg_acqrel_relaxed<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool); /// Stores a value if the current value is the same as the `old` value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `compare_exchange` method by passing @@ -189,6 +200,7 @@ pub unsafe fn atomic_cxchg_acqrel_relaxed<T: Copy>(dst: *mut T, old: T, src: T) #[rustc_nounwind] pub unsafe fn atomic_cxchg_acqrel_acquire<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool); /// Stores a value if the current value is the same as the `old` value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `compare_exchange` method by passing @@ -198,6 +210,7 @@ pub unsafe fn atomic_cxchg_acqrel_acquire<T: Copy>(dst: *mut T, old: T, src: T) #[rustc_nounwind] pub unsafe fn atomic_cxchg_acqrel_seqcst<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool); /// Stores a value if the current value is the same as the `old` value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `compare_exchange` method by passing @@ -207,6 +220,7 @@ pub unsafe fn atomic_cxchg_acqrel_seqcst<T: Copy>(dst: *mut T, old: T, src: T) - #[rustc_nounwind] pub unsafe fn atomic_cxchg_seqcst_relaxed<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool); /// Stores a value if the current value is the same as the `old` value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `compare_exchange` method by passing @@ -216,6 +230,7 @@ pub unsafe fn atomic_cxchg_seqcst_relaxed<T: Copy>(dst: *mut T, old: T, src: T) #[rustc_nounwind] pub unsafe fn atomic_cxchg_seqcst_acquire<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool); /// Stores a value if the current value is the same as the `old` value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `compare_exchange` method by passing @@ -226,6 +241,7 @@ pub unsafe fn atomic_cxchg_seqcst_acquire<T: Copy>(dst: *mut T, old: T, src: T) pub unsafe fn atomic_cxchg_seqcst_seqcst<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool); /// Stores a value if the current value is the same as the `old` value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `compare_exchange_weak` method by passing @@ -239,6 +255,7 @@ pub unsafe fn atomic_cxchgweak_relaxed_relaxed<T: Copy>( _src: T, ) -> (T, bool); /// Stores a value if the current value is the same as the `old` value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `compare_exchange_weak` method by passing @@ -252,6 +269,7 @@ pub unsafe fn atomic_cxchgweak_relaxed_acquire<T: Copy>( _src: T, ) -> (T, bool); /// Stores a value if the current value is the same as the `old` value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `compare_exchange_weak` method by passing @@ -261,6 +279,7 @@ pub unsafe fn atomic_cxchgweak_relaxed_acquire<T: Copy>( #[rustc_nounwind] pub unsafe fn atomic_cxchgweak_relaxed_seqcst<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool); /// Stores a value if the current value is the same as the `old` value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `compare_exchange_weak` method by passing @@ -274,6 +293,7 @@ pub unsafe fn atomic_cxchgweak_acquire_relaxed<T: Copy>( _src: T, ) -> (T, bool); /// Stores a value if the current value is the same as the `old` value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `compare_exchange_weak` method by passing @@ -287,6 +307,7 @@ pub unsafe fn atomic_cxchgweak_acquire_acquire<T: Copy>( _src: T, ) -> (T, bool); /// Stores a value if the current value is the same as the `old` value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `compare_exchange_weak` method by passing @@ -296,6 +317,7 @@ pub unsafe fn atomic_cxchgweak_acquire_acquire<T: Copy>( #[rustc_nounwind] pub unsafe fn atomic_cxchgweak_acquire_seqcst<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool); /// Stores a value if the current value is the same as the `old` value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `compare_exchange_weak` method by passing @@ -309,6 +331,7 @@ pub unsafe fn atomic_cxchgweak_release_relaxed<T: Copy>( _src: T, ) -> (T, bool); /// Stores a value if the current value is the same as the `old` value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `compare_exchange_weak` method by passing @@ -322,6 +345,7 @@ pub unsafe fn atomic_cxchgweak_release_acquire<T: Copy>( _src: T, ) -> (T, bool); /// Stores a value if the current value is the same as the `old` value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `compare_exchange_weak` method by passing @@ -331,6 +355,7 @@ pub unsafe fn atomic_cxchgweak_release_acquire<T: Copy>( #[rustc_nounwind] pub unsafe fn atomic_cxchgweak_release_seqcst<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool); /// Stores a value if the current value is the same as the `old` value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `compare_exchange_weak` method by passing @@ -340,6 +365,7 @@ pub unsafe fn atomic_cxchgweak_release_seqcst<T: Copy>(dst: *mut T, old: T, src: #[rustc_nounwind] pub unsafe fn atomic_cxchgweak_acqrel_relaxed<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool); /// Stores a value if the current value is the same as the `old` value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `compare_exchange_weak` method by passing @@ -349,6 +375,7 @@ pub unsafe fn atomic_cxchgweak_acqrel_relaxed<T: Copy>(dst: *mut T, old: T, src: #[rustc_nounwind] pub unsafe fn atomic_cxchgweak_acqrel_acquire<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool); /// Stores a value if the current value is the same as the `old` value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `compare_exchange_weak` method by passing @@ -358,6 +385,7 @@ pub unsafe fn atomic_cxchgweak_acqrel_acquire<T: Copy>(dst: *mut T, old: T, src: #[rustc_nounwind] pub unsafe fn atomic_cxchgweak_acqrel_seqcst<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool); /// Stores a value if the current value is the same as the `old` value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `compare_exchange_weak` method by passing @@ -367,6 +395,7 @@ pub unsafe fn atomic_cxchgweak_acqrel_seqcst<T: Copy>(dst: *mut T, old: T, src: #[rustc_nounwind] pub unsafe fn atomic_cxchgweak_seqcst_relaxed<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool); /// Stores a value if the current value is the same as the `old` value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `compare_exchange_weak` method by passing @@ -376,6 +405,7 @@ pub unsafe fn atomic_cxchgweak_seqcst_relaxed<T: Copy>(dst: *mut T, old: T, src: #[rustc_nounwind] pub unsafe fn atomic_cxchgweak_seqcst_acquire<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool); /// Stores a value if the current value is the same as the `old` value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `compare_exchange_weak` method by passing @@ -386,6 +416,7 @@ pub unsafe fn atomic_cxchgweak_seqcst_acquire<T: Copy>(dst: *mut T, old: T, src: pub unsafe fn atomic_cxchgweak_seqcst_seqcst<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool); /// Loads the current value of the pointer. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `load` method by passing @@ -394,6 +425,7 @@ pub unsafe fn atomic_cxchgweak_seqcst_seqcst<T: Copy>(dst: *mut T, old: T, src: #[rustc_nounwind] pub unsafe fn atomic_load_seqcst<T: Copy>(src: *const T) -> T; /// Loads the current value of the pointer. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `load` method by passing @@ -402,6 +434,7 @@ pub unsafe fn atomic_load_seqcst<T: Copy>(src: *const T) -> T; #[rustc_nounwind] pub unsafe fn atomic_load_acquire<T: Copy>(src: *const T) -> T; /// Loads the current value of the pointer. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `load` method by passing @@ -417,6 +450,7 @@ pub unsafe fn atomic_load_relaxed<T: Copy>(src: *const T) -> T; pub unsafe fn atomic_load_unordered<T: Copy>(src: *const T) -> T; /// Stores the value at the specified memory location. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `store` method by passing @@ -425,6 +459,7 @@ pub unsafe fn atomic_load_unordered<T: Copy>(src: *const T) -> T; #[rustc_nounwind] pub unsafe fn atomic_store_seqcst<T: Copy>(dst: *mut T, val: T); /// Stores the value at the specified memory location. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `store` method by passing @@ -433,6 +468,7 @@ pub unsafe fn atomic_store_seqcst<T: Copy>(dst: *mut T, val: T); #[rustc_nounwind] pub unsafe fn atomic_store_release<T: Copy>(dst: *mut T, val: T); /// Stores the value at the specified memory location. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `store` method by passing @@ -448,6 +484,7 @@ pub unsafe fn atomic_store_relaxed<T: Copy>(dst: *mut T, val: T); pub unsafe fn atomic_store_unordered<T: Copy>(dst: *mut T, val: T); /// Stores the value at the specified memory location, returning the old value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `swap` method by passing @@ -456,6 +493,7 @@ pub unsafe fn atomic_store_unordered<T: Copy>(dst: *mut T, val: T); #[rustc_nounwind] pub unsafe fn atomic_xchg_seqcst<T: Copy>(dst: *mut T, src: T) -> T; /// Stores the value at the specified memory location, returning the old value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `swap` method by passing @@ -464,6 +502,7 @@ pub unsafe fn atomic_xchg_seqcst<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_xchg_acquire<T: Copy>(dst: *mut T, src: T) -> T; /// Stores the value at the specified memory location, returning the old value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `swap` method by passing @@ -472,6 +511,7 @@ pub unsafe fn atomic_xchg_acquire<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_xchg_release<T: Copy>(dst: *mut T, src: T) -> T; /// Stores the value at the specified memory location, returning the old value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `swap` method by passing @@ -480,6 +520,7 @@ pub unsafe fn atomic_xchg_release<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_xchg_acqrel<T: Copy>(dst: *mut T, src: T) -> T; /// Stores the value at the specified memory location, returning the old value. +/// `T` must be an integer or pointer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `swap` method by passing @@ -489,6 +530,9 @@ pub unsafe fn atomic_xchg_acqrel<T: Copy>(dst: *mut T, src: T) -> T; pub unsafe fn atomic_xchg_relaxed<T: Copy>(dst: *mut T, src: T) -> T; /// Adds to the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new +/// value stored at `*dst` will have the provenance of the old value stored there. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `fetch_add` method by passing @@ -497,6 +541,9 @@ pub unsafe fn atomic_xchg_relaxed<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_xadd_seqcst<T: Copy>(dst: *mut T, src: T) -> T; /// Adds to the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new +/// value stored at `*dst` will have the provenance of the old value stored there. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `fetch_add` method by passing @@ -505,6 +552,9 @@ pub unsafe fn atomic_xadd_seqcst<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_xadd_acquire<T: Copy>(dst: *mut T, src: T) -> T; /// Adds to the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new +/// value stored at `*dst` will have the provenance of the old value stored there. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `fetch_add` method by passing @@ -513,6 +563,9 @@ pub unsafe fn atomic_xadd_acquire<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_xadd_release<T: Copy>(dst: *mut T, src: T) -> T; /// Adds to the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new +/// value stored at `*dst` will have the provenance of the old value stored there. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `fetch_add` method by passing @@ -521,6 +574,9 @@ pub unsafe fn atomic_xadd_release<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_xadd_acqrel<T: Copy>(dst: *mut T, src: T) -> T; /// Adds to the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new +/// value stored at `*dst` will have the provenance of the old value stored there. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `fetch_add` method by passing @@ -530,6 +586,9 @@ pub unsafe fn atomic_xadd_acqrel<T: Copy>(dst: *mut T, src: T) -> T; pub unsafe fn atomic_xadd_relaxed<T: Copy>(dst: *mut T, src: T) -> T; /// Subtract from the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new +/// value stored at `*dst` will have the provenance of the old value stored there. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `fetch_sub` method by passing @@ -538,6 +597,9 @@ pub unsafe fn atomic_xadd_relaxed<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_xsub_seqcst<T: Copy>(dst: *mut T, src: T) -> T; /// Subtract from the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new +/// value stored at `*dst` will have the provenance of the old value stored there. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `fetch_sub` method by passing @@ -546,6 +608,9 @@ pub unsafe fn atomic_xsub_seqcst<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_xsub_acquire<T: Copy>(dst: *mut T, src: T) -> T; /// Subtract from the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new +/// value stored at `*dst` will have the provenance of the old value stored there. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `fetch_sub` method by passing @@ -554,6 +619,9 @@ pub unsafe fn atomic_xsub_acquire<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_xsub_release<T: Copy>(dst: *mut T, src: T) -> T; /// Subtract from the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new +/// value stored at `*dst` will have the provenance of the old value stored there. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `fetch_sub` method by passing @@ -562,6 +630,9 @@ pub unsafe fn atomic_xsub_release<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_xsub_acqrel<T: Copy>(dst: *mut T, src: T) -> T; /// Subtract from the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new +/// value stored at `*dst` will have the provenance of the old value stored there. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `fetch_sub` method by passing @@ -571,6 +642,9 @@ pub unsafe fn atomic_xsub_acqrel<T: Copy>(dst: *mut T, src: T) -> T; pub unsafe fn atomic_xsub_relaxed<T: Copy>(dst: *mut T, src: T) -> T; /// Bitwise and with the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new +/// value stored at `*dst` will have the provenance of the old value stored there. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `fetch_and` method by passing @@ -579,6 +653,9 @@ pub unsafe fn atomic_xsub_relaxed<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_and_seqcst<T: Copy>(dst: *mut T, src: T) -> T; /// Bitwise and with the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new +/// value stored at `*dst` will have the provenance of the old value stored there. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `fetch_and` method by passing @@ -587,6 +664,9 @@ pub unsafe fn atomic_and_seqcst<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_and_acquire<T: Copy>(dst: *mut T, src: T) -> T; /// Bitwise and with the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new +/// value stored at `*dst` will have the provenance of the old value stored there. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `fetch_and` method by passing @@ -595,6 +675,9 @@ pub unsafe fn atomic_and_acquire<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_and_release<T: Copy>(dst: *mut T, src: T) -> T; /// Bitwise and with the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new +/// value stored at `*dst` will have the provenance of the old value stored there. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `fetch_and` method by passing @@ -603,6 +686,9 @@ pub unsafe fn atomic_and_release<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_and_acqrel<T: Copy>(dst: *mut T, src: T) -> T; /// Bitwise and with the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new +/// value stored at `*dst` will have the provenance of the old value stored there. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `fetch_and` method by passing @@ -612,6 +698,9 @@ pub unsafe fn atomic_and_acqrel<T: Copy>(dst: *mut T, src: T) -> T; pub unsafe fn atomic_and_relaxed<T: Copy>(dst: *mut T, src: T) -> T; /// Bitwise nand with the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new +/// value stored at `*dst` will have the provenance of the old value stored there. /// /// The stabilized version of this intrinsic is available on the /// [`AtomicBool`] type via the `fetch_nand` method by passing @@ -620,6 +709,9 @@ pub unsafe fn atomic_and_relaxed<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_nand_seqcst<T: Copy>(dst: *mut T, src: T) -> T; /// Bitwise nand with the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new +/// value stored at `*dst` will have the provenance of the old value stored there. /// /// The stabilized version of this intrinsic is available on the /// [`AtomicBool`] type via the `fetch_nand` method by passing @@ -628,6 +720,9 @@ pub unsafe fn atomic_nand_seqcst<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_nand_acquire<T: Copy>(dst: *mut T, src: T) -> T; /// Bitwise nand with the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new +/// value stored at `*dst` will have the provenance of the old value stored there. /// /// The stabilized version of this intrinsic is available on the /// [`AtomicBool`] type via the `fetch_nand` method by passing @@ -636,6 +731,9 @@ pub unsafe fn atomic_nand_acquire<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_nand_release<T: Copy>(dst: *mut T, src: T) -> T; /// Bitwise nand with the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new +/// value stored at `*dst` will have the provenance of the old value stored there. /// /// The stabilized version of this intrinsic is available on the /// [`AtomicBool`] type via the `fetch_nand` method by passing @@ -644,6 +742,9 @@ pub unsafe fn atomic_nand_release<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_nand_acqrel<T: Copy>(dst: *mut T, src: T) -> T; /// Bitwise nand with the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new +/// value stored at `*dst` will have the provenance of the old value stored there. /// /// The stabilized version of this intrinsic is available on the /// [`AtomicBool`] type via the `fetch_nand` method by passing @@ -653,6 +754,9 @@ pub unsafe fn atomic_nand_acqrel<T: Copy>(dst: *mut T, src: T) -> T; pub unsafe fn atomic_nand_relaxed<T: Copy>(dst: *mut T, src: T) -> T; /// Bitwise or with the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new +/// value stored at `*dst` will have the provenance of the old value stored there. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `fetch_or` method by passing @@ -661,6 +765,9 @@ pub unsafe fn atomic_nand_relaxed<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_or_seqcst<T: Copy>(dst: *mut T, src: T) -> T; /// Bitwise or with the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new +/// value stored at `*dst` will have the provenance of the old value stored there. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `fetch_or` method by passing @@ -669,6 +776,9 @@ pub unsafe fn atomic_or_seqcst<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_or_acquire<T: Copy>(dst: *mut T, src: T) -> T; /// Bitwise or with the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new +/// value stored at `*dst` will have the provenance of the old value stored there. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `fetch_or` method by passing @@ -677,6 +787,9 @@ pub unsafe fn atomic_or_acquire<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_or_release<T: Copy>(dst: *mut T, src: T) -> T; /// Bitwise or with the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new +/// value stored at `*dst` will have the provenance of the old value stored there. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `fetch_or` method by passing @@ -685,6 +798,9 @@ pub unsafe fn atomic_or_release<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_or_acqrel<T: Copy>(dst: *mut T, src: T) -> T; /// Bitwise or with the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new +/// value stored at `*dst` will have the provenance of the old value stored there. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `fetch_or` method by passing @@ -694,6 +810,9 @@ pub unsafe fn atomic_or_acqrel<T: Copy>(dst: *mut T, src: T) -> T; pub unsafe fn atomic_or_relaxed<T: Copy>(dst: *mut T, src: T) -> T; /// Bitwise xor with the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new +/// value stored at `*dst` will have the provenance of the old value stored there. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `fetch_xor` method by passing @@ -702,6 +821,9 @@ pub unsafe fn atomic_or_relaxed<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_xor_seqcst<T: Copy>(dst: *mut T, src: T) -> T; /// Bitwise xor with the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new +/// value stored at `*dst` will have the provenance of the old value stored there. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `fetch_xor` method by passing @@ -710,6 +832,9 @@ pub unsafe fn atomic_xor_seqcst<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_xor_acquire<T: Copy>(dst: *mut T, src: T) -> T; /// Bitwise xor with the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new +/// value stored at `*dst` will have the provenance of the old value stored there. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `fetch_xor` method by passing @@ -718,6 +843,9 @@ pub unsafe fn atomic_xor_acquire<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_xor_release<T: Copy>(dst: *mut T, src: T) -> T; /// Bitwise xor with the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new +/// value stored at `*dst` will have the provenance of the old value stored there. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `fetch_xor` method by passing @@ -726,6 +854,9 @@ pub unsafe fn atomic_xor_release<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_xor_acqrel<T: Copy>(dst: *mut T, src: T) -> T; /// Bitwise xor with the current value, returning the previous value. +/// `T` must be an integer or pointer type. +/// If `T` is a pointer type, the provenance of `src` is ignored: both the return value and the new +/// value stored at `*dst` will have the provenance of the old value stored there. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] types via the `fetch_xor` method by passing @@ -735,6 +866,7 @@ pub unsafe fn atomic_xor_acqrel<T: Copy>(dst: *mut T, src: T) -> T; pub unsafe fn atomic_xor_relaxed<T: Copy>(dst: *mut T, src: T) -> T; /// Maximum with the current value using a signed comparison. +/// `T` must be a signed integer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] signed integer types via the `fetch_max` method by passing @@ -743,6 +875,7 @@ pub unsafe fn atomic_xor_relaxed<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_max_seqcst<T: Copy>(dst: *mut T, src: T) -> T; /// Maximum with the current value using a signed comparison. +/// `T` must be a signed integer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] signed integer types via the `fetch_max` method by passing @@ -751,6 +884,7 @@ pub unsafe fn atomic_max_seqcst<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_max_acquire<T: Copy>(dst: *mut T, src: T) -> T; /// Maximum with the current value using a signed comparison. +/// `T` must be a signed integer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] signed integer types via the `fetch_max` method by passing @@ -759,6 +893,7 @@ pub unsafe fn atomic_max_acquire<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_max_release<T: Copy>(dst: *mut T, src: T) -> T; /// Maximum with the current value using a signed comparison. +/// `T` must be a signed integer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] signed integer types via the `fetch_max` method by passing @@ -766,7 +901,8 @@ pub unsafe fn atomic_max_release<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_intrinsic] #[rustc_nounwind] pub unsafe fn atomic_max_acqrel<T: Copy>(dst: *mut T, src: T) -> T; -/// Maximum with the current value. +/// Maximum with the current value using a signed comparison. +/// `T` must be a signed integer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] signed integer types via the `fetch_max` method by passing @@ -776,6 +912,7 @@ pub unsafe fn atomic_max_acqrel<T: Copy>(dst: *mut T, src: T) -> T; pub unsafe fn atomic_max_relaxed<T: Copy>(dst: *mut T, src: T) -> T; /// Minimum with the current value using a signed comparison. +/// `T` must be a signed integer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] signed integer types via the `fetch_min` method by passing @@ -784,6 +921,7 @@ pub unsafe fn atomic_max_relaxed<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_min_seqcst<T: Copy>(dst: *mut T, src: T) -> T; /// Minimum with the current value using a signed comparison. +/// `T` must be a signed integer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] signed integer types via the `fetch_min` method by passing @@ -792,6 +930,7 @@ pub unsafe fn atomic_min_seqcst<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_min_acquire<T: Copy>(dst: *mut T, src: T) -> T; /// Minimum with the current value using a signed comparison. +/// `T` must be a signed integer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] signed integer types via the `fetch_min` method by passing @@ -800,6 +939,7 @@ pub unsafe fn atomic_min_acquire<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_min_release<T: Copy>(dst: *mut T, src: T) -> T; /// Minimum with the current value using a signed comparison. +/// `T` must be a signed integer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] signed integer types via the `fetch_min` method by passing @@ -808,6 +948,7 @@ pub unsafe fn atomic_min_release<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_min_acqrel<T: Copy>(dst: *mut T, src: T) -> T; /// Minimum with the current value using a signed comparison. +/// `T` must be a signed integer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] signed integer types via the `fetch_min` method by passing @@ -817,6 +958,7 @@ pub unsafe fn atomic_min_acqrel<T: Copy>(dst: *mut T, src: T) -> T; pub unsafe fn atomic_min_relaxed<T: Copy>(dst: *mut T, src: T) -> T; /// Minimum with the current value using an unsigned comparison. +/// `T` must be an unsigned integer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] unsigned integer types via the `fetch_min` method by passing @@ -825,6 +967,7 @@ pub unsafe fn atomic_min_relaxed<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_umin_seqcst<T: Copy>(dst: *mut T, src: T) -> T; /// Minimum with the current value using an unsigned comparison. +/// `T` must be an unsigned integer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] unsigned integer types via the `fetch_min` method by passing @@ -833,6 +976,7 @@ pub unsafe fn atomic_umin_seqcst<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_umin_acquire<T: Copy>(dst: *mut T, src: T) -> T; /// Minimum with the current value using an unsigned comparison. +/// `T` must be an unsigned integer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] unsigned integer types via the `fetch_min` method by passing @@ -841,6 +985,7 @@ pub unsafe fn atomic_umin_acquire<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_umin_release<T: Copy>(dst: *mut T, src: T) -> T; /// Minimum with the current value using an unsigned comparison. +/// `T` must be an unsigned integer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] unsigned integer types via the `fetch_min` method by passing @@ -849,6 +994,7 @@ pub unsafe fn atomic_umin_release<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_umin_acqrel<T: Copy>(dst: *mut T, src: T) -> T; /// Minimum with the current value using an unsigned comparison. +/// `T` must be an unsigned integer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] unsigned integer types via the `fetch_min` method by passing @@ -858,6 +1004,7 @@ pub unsafe fn atomic_umin_acqrel<T: Copy>(dst: *mut T, src: T) -> T; pub unsafe fn atomic_umin_relaxed<T: Copy>(dst: *mut T, src: T) -> T; /// Maximum with the current value using an unsigned comparison. +/// `T` must be an unsigned integer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] unsigned integer types via the `fetch_max` method by passing @@ -866,6 +1013,7 @@ pub unsafe fn atomic_umin_relaxed<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_umax_seqcst<T: Copy>(dst: *mut T, src: T) -> T; /// Maximum with the current value using an unsigned comparison. +/// `T` must be an unsigned integer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] unsigned integer types via the `fetch_max` method by passing @@ -874,6 +1022,7 @@ pub unsafe fn atomic_umax_seqcst<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_umax_acquire<T: Copy>(dst: *mut T, src: T) -> T; /// Maximum with the current value using an unsigned comparison. +/// `T` must be an unsigned integer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] unsigned integer types via the `fetch_max` method by passing @@ -882,6 +1031,7 @@ pub unsafe fn atomic_umax_acquire<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_umax_release<T: Copy>(dst: *mut T, src: T) -> T; /// Maximum with the current value using an unsigned comparison. +/// `T` must be an unsigned integer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] unsigned integer types via the `fetch_max` method by passing @@ -890,6 +1040,7 @@ pub unsafe fn atomic_umax_release<T: Copy>(dst: *mut T, src: T) -> T; #[rustc_nounwind] pub unsafe fn atomic_umax_acqrel<T: Copy>(dst: *mut T, src: T) -> T; /// Maximum with the current value using an unsigned comparison. +/// `T` must be an unsigned integer type. /// /// The stabilized version of this intrinsic is available on the /// [`atomic`] unsigned integer types via the `fetch_max` method by passing @@ -1623,10 +1774,14 @@ pub fn ptr_mask<T>(ptr: *const T, mask: usize) -> *const T; /// a size of `count` * `size_of::<T>()` and an alignment of /// `min_align_of::<T>()` /// -/// The volatile parameter is set to `true`, so it will not be optimized out -/// unless size is equal to zero. -/// /// This intrinsic does not have a stable counterpart. +/// # Safety +/// +/// The safety requirements are consistent with [`copy_nonoverlapping`] +/// while the read and write behaviors are volatile, +/// which means it will not be optimized out unless `_count` or `size_of::<T>()` is equal to zero. +/// +/// [`copy_nonoverlapping`]: ptr::copy_nonoverlapping #[rustc_intrinsic] #[rustc_nounwind] pub unsafe fn volatile_copy_nonoverlapping_memory<T>(dst: *mut T, src: *const T, count: usize); @@ -1645,10 +1800,13 @@ pub unsafe fn volatile_copy_memory<T>(dst: *mut T, src: *const T, count: usize); /// size of `count * size_of::<T>()` and an alignment of /// `min_align_of::<T>()`. /// -/// The volatile parameter is set to `true`, so it will not be optimized out -/// unless size is equal to zero. -/// /// This intrinsic does not have a stable counterpart. +/// # Safety +/// +/// The safety requirements are consistent with [`write_bytes`] while the write behavior is volatile, +/// which means it will not be optimized out unless `_count` or `size_of::<T>()` is equal to zero. +/// +/// [`write_bytes`]: ptr::write_bytes #[rustc_intrinsic] #[rustc_nounwind] pub unsafe fn volatile_set_memory<T>(dst: *mut T, val: u8, count: usize); @@ -3190,8 +3348,18 @@ pub const fn is_val_statically_known<T: Copy>(_arg: T) -> bool { /// The stabilized form of this intrinsic is [`crate::mem::swap`]. /// /// # Safety +/// Behavior is undefined if any of the following conditions are violated: +/// +/// * Both `x` and `y` must be [valid] for both reads and writes. /// -/// `x` and `y` are readable and writable as `T`, and non-overlapping. +/// * Both `x` and `y` must be properly aligned. +/// +/// * The region of memory beginning at `x` must *not* overlap with the region of memory +/// beginning at `y`. +/// +/// * The memory pointed by `x` and `y` must both contain values of type `T`. +/// +/// [valid]: crate::ptr#safety #[rustc_nounwind] #[inline] #[rustc_intrinsic] diff --git a/library/core/src/iter/adapters/enumerate.rs b/library/core/src/iter/adapters/enumerate.rs index ac15e3767fc..f9c388e8564 100644 --- a/library/core/src/iter/adapters/enumerate.rs +++ b/library/core/src/iter/adapters/enumerate.rs @@ -14,7 +14,7 @@ use crate::ops::Try; #[derive(Clone, Debug)] #[must_use = "iterators are lazy and do nothing unless consumed"] #[stable(feature = "rust1", since = "1.0.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "Enumerate")] +#[rustc_diagnostic_item = "Enumerate"] pub struct Enumerate<I> { iter: I, count: usize, diff --git a/library/core/src/iter/sources/repeat.rs b/library/core/src/iter/sources/repeat.rs index 243f938bce2..c4f5a483e5c 100644 --- a/library/core/src/iter/sources/repeat.rs +++ b/library/core/src/iter/sources/repeat.rs @@ -56,7 +56,7 @@ use crate::num::NonZero; /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "iter_repeat")] +#[rustc_diagnostic_item = "iter_repeat"] pub fn repeat<T: Clone>(elt: T) -> Repeat<T> { Repeat { element: elt } } diff --git a/library/core/src/iter/traits/double_ended.rs b/library/core/src/iter/traits/double_ended.rs index 3b126785728..7dabaece955 100644 --- a/library/core/src/iter/traits/double_ended.rs +++ b/library/core/src/iter/traits/double_ended.rs @@ -37,7 +37,7 @@ use crate::ops::{ControlFlow, Try}; /// assert_eq!(None, iter.next_back()); /// ``` #[stable(feature = "rust1", since = "1.0.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "DoubleEndedIterator")] +#[rustc_diagnostic_item = "DoubleEndedIterator"] pub trait DoubleEndedIterator: Iterator { /// Removes and returns an element from the end of the iterator. /// diff --git a/library/core/src/iter/traits/iterator.rs b/library/core/src/iter/traits/iterator.rs index 10ae43ac3fc..075da022854 100644 --- a/library/core/src/iter/traits/iterator.rs +++ b/library/core/src/iter/traits/iterator.rs @@ -862,7 +862,7 @@ pub trait Iterator { /// Note that `iter.filter(f).next()` is equivalent to `iter.find(f)`. #[inline] #[stable(feature = "rust1", since = "1.0.0")] - #[cfg_attr(not(test), rustc_diagnostic_item = "iter_filter")] + #[rustc_diagnostic_item = "iter_filter"] fn filter<P>(self, predicate: P) -> Filter<Self, P> where Self: Sized, @@ -954,7 +954,7 @@ pub trait Iterator { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - #[cfg_attr(not(test), rustc_diagnostic_item = "enumerate_method")] + #[rustc_diagnostic_item = "enumerate_method"] fn enumerate(self) -> Enumerate<Self> where Self: Sized, @@ -1972,11 +1972,20 @@ pub trait Iterator { #[inline] #[stable(feature = "rust1", since = "1.0.0")] #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"] - #[cfg_attr(not(test), rustc_diagnostic_item = "iterator_collect_fn")] + #[rustc_diagnostic_item = "iterator_collect_fn"] fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized, { + // This is too aggressive to turn on for everything all the time, but PR#137908 + // accidentally noticed that some rustc iterators had malformed `size_hint`s, + // so this will help catch such things in debug-assertions-std runners, + // even if users won't actually ever see it. + if cfg!(debug_assertions) { + let hint = self.size_hint(); + assert!(hint.1.is_none_or(|high| high >= hint.0), "Malformed size_hint {hint:?}"); + } + FromIterator::from_iter(self) } @@ -3367,7 +3376,7 @@ pub trait Iterator { /// assert_eq!(v_map, vec![1, 2, 3]); /// ``` #[stable(feature = "iter_copied", since = "1.36.0")] - #[cfg_attr(not(test), rustc_diagnostic_item = "iter_copied")] + #[rustc_diagnostic_item = "iter_copied"] fn copied<'a, T: 'a>(self) -> Copied<Self> where Self: Sized + Iterator<Item = &'a T>, @@ -3415,7 +3424,7 @@ pub trait Iterator { /// assert_eq!(&[vec![23]], &faster[..]); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - #[cfg_attr(not(test), rustc_diagnostic_item = "iter_cloned")] + #[rustc_diagnostic_item = "iter_cloned"] fn cloned<'a, T: 'a>(self) -> Cloned<Self> where Self: Sized + Iterator<Item = &'a T>, diff --git a/library/core/src/lib.rs b/library/core/src/lib.rs index 6e058069756..e1ca69edcbb 100644 --- a/library/core/src/lib.rs +++ b/library/core/src/lib.rs @@ -43,18 +43,6 @@ //! which do not trigger a panic can be assured that this function is never //! called. The `lang` attribute is called `eh_personality`. -// Since core defines many fundamental lang items, all tests live in a -// separate crate, coretests (library/coretests), to avoid bizarre issues. -// -// Here we explicitly #[cfg]-out this whole crate when testing. If we don't do -// this, both the generated test artifact and the linked libtest (which -// transitively includes core) will both define the same set of lang items, -// and this will cause the E0152 "found duplicate lang item" error. See -// discussion in #50466 for details. -// -// This cfg won't affect doc tests. -#![cfg(not(test))] -// #![stable(feature = "core", since = "1.6.0")] #![doc( html_playground_url = "https://play.rust-lang.org/", @@ -64,7 +52,6 @@ )] #![doc(rust_logo)] #![doc(cfg_hide( - not(test), no_fp_fmt_parse, target_pointer_width = "16", target_pointer_width = "32", @@ -228,13 +215,9 @@ extern crate self as core; #[allow(unused)] use prelude::rust_2024::*; -#[cfg(not(test))] // See #65860 #[macro_use] mod macros; -// We don't export this through #[macro_export] for now, to avoid breakage. -// See https://github.com/rust-lang/rust/issues/82913 -#[cfg(not(test))] #[unstable(feature = "assert_matches", issue = "82775")] /// Unstable module containing the unstable `assert_matches` macro. pub mod assert_matches { diff --git a/library/core/src/macros/mod.rs b/library/core/src/macros/mod.rs index a527a2ea5aa..fa0d882181a 100644 --- a/library/core/src/macros/mod.rs +++ b/library/core/src/macros/mod.rs @@ -37,7 +37,7 @@ macro_rules! panic { /// ``` #[macro_export] #[stable(feature = "rust1", since = "1.0.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "assert_eq_macro")] +#[rustc_diagnostic_item = "assert_eq_macro"] #[allow_internal_unstable(panic_internals)] macro_rules! assert_eq { ($left:expr, $right:expr $(,)?) => { @@ -93,7 +93,7 @@ macro_rules! assert_eq { /// ``` #[macro_export] #[stable(feature = "assert_ne", since = "1.13.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "assert_ne_macro")] +#[rustc_diagnostic_item = "assert_ne_macro"] #[allow_internal_unstable(panic_internals)] macro_rules! assert_ne { ($left:expr, $right:expr $(,)?) => { @@ -331,7 +331,7 @@ macro_rules! debug_assert { /// ``` #[macro_export] #[stable(feature = "rust1", since = "1.0.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "debug_assert_eq_macro")] +#[rustc_diagnostic_item = "debug_assert_eq_macro"] macro_rules! debug_assert_eq { ($($arg:tt)*) => { if $crate::cfg!(debug_assertions) { @@ -361,7 +361,7 @@ macro_rules! debug_assert_eq { /// ``` #[macro_export] #[stable(feature = "assert_ne", since = "1.13.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "debug_assert_ne_macro")] +#[rustc_diagnostic_item = "debug_assert_ne_macro"] macro_rules! debug_assert_ne { ($($arg:tt)*) => { if $crate::cfg!(debug_assertions) { @@ -442,7 +442,7 @@ pub macro debug_assert_matches($($arg:tt)*) { /// ``` #[macro_export] #[stable(feature = "matches_macro", since = "1.42.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "matches_macro")] +#[rustc_diagnostic_item = "matches_macro"] macro_rules! matches { ($expression:expr, $pattern:pat $(if $guard:expr)? $(,)?) => { match $expression { @@ -617,7 +617,7 @@ macro_rules! r#try { /// ``` #[macro_export] #[stable(feature = "rust1", since = "1.0.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "write_macro")] +#[rustc_diagnostic_item = "write_macro"] macro_rules! write { ($dst:expr, $($arg:tt)*) => { $dst.write_fmt($crate::format_args!($($arg)*)) @@ -651,7 +651,7 @@ macro_rules! write { /// ``` #[macro_export] #[stable(feature = "rust1", since = "1.0.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "writeln_macro")] +#[rustc_diagnostic_item = "writeln_macro"] #[allow_internal_unstable(format_args_nl)] macro_rules! writeln { ($dst:expr $(,)?) => { @@ -718,7 +718,7 @@ macro_rules! writeln { #[rustc_builtin_macro(unreachable)] #[allow_internal_unstable(edition_panic)] #[stable(feature = "rust1", since = "1.0.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "unreachable_macro")] +#[rustc_diagnostic_item = "unreachable_macro"] macro_rules! unreachable { // Expands to either `$crate::panic::unreachable_2015` or `$crate::panic::unreachable_2021` // depending on the edition of the caller. @@ -803,7 +803,7 @@ macro_rules! unreachable { /// ``` #[macro_export] #[stable(feature = "rust1", since = "1.0.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "unimplemented_macro")] +#[rustc_diagnostic_item = "unimplemented_macro"] #[allow_internal_unstable(panic_internals)] macro_rules! unimplemented { () => { @@ -883,7 +883,7 @@ macro_rules! unimplemented { /// ``` #[macro_export] #[stable(feature = "todo_macro", since = "1.40.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "todo_macro")] +#[rustc_diagnostic_item = "todo_macro"] #[allow_internal_unstable(panic_internals)] macro_rules! todo { () => { @@ -995,7 +995,7 @@ pub(crate) mod builtin { /// and cannot be stored for later use. /// This is a known limitation, see [#92698](https://github.com/rust-lang/rust/issues/92698). #[stable(feature = "rust1", since = "1.0.0")] - #[cfg_attr(not(test), rustc_diagnostic_item = "format_args_macro")] + #[rustc_diagnostic_item = "format_args_macro"] #[allow_internal_unsafe] #[allow_internal_unstable(fmt_internals)] #[rustc_builtin_macro] @@ -1342,7 +1342,7 @@ pub(crate) mod builtin { #[stable(feature = "rust1", since = "1.0.0")] #[rustc_builtin_macro] #[macro_export] - #[cfg_attr(not(test), rustc_diagnostic_item = "include_str_macro")] + #[rustc_diagnostic_item = "include_str_macro"] macro_rules! include_str { ($file:expr $(,)?) => {{ /* compiler built-in */ }}; } @@ -1382,7 +1382,7 @@ pub(crate) mod builtin { #[stable(feature = "rust1", since = "1.0.0")] #[rustc_builtin_macro] #[macro_export] - #[cfg_attr(not(test), rustc_diagnostic_item = "include_bytes_macro")] + #[rustc_diagnostic_item = "include_bytes_macro"] macro_rules! include_bytes { ($file:expr $(,)?) => {{ /* compiler built-in */ }}; } diff --git a/library/core/src/marker.rs b/library/core/src/marker.rs index e234f105b0b..68011310d2c 100644 --- a/library/core/src/marker.rs +++ b/library/core/src/marker.rs @@ -82,7 +82,7 @@ macro marker_impls { /// [arc]: ../../std/sync/struct.Arc.html /// [ub]: ../../reference/behavior-considered-undefined.html #[stable(feature = "rust1", since = "1.0.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "Send")] +#[rustc_diagnostic_item = "Send"] #[diagnostic::on_unimplemented( message = "`{Self}` cannot be sent between threads safely", label = "`{Self}` cannot be sent between threads safely" @@ -465,9 +465,13 @@ impl<T: ?Sized> Copy for &T {} /// Notably, this doesn't include all trivially-destructible types for semver /// reasons. /// -/// Bikeshed name for now. +/// Bikeshed name for now. This trait does not do anything other than reflect the +/// set of types that are allowed within unions for field validity. #[unstable(feature = "bikeshed_guaranteed_no_drop", issue = "none")] #[lang = "bikeshed_guaranteed_no_drop"] +#[rustc_deny_explicit_impl] +#[rustc_do_not_implement_via_object] +#[doc(hidden)] pub trait BikeshedGuaranteedNoDrop {} /// Types for which it is safe to share references between threads. @@ -541,7 +545,7 @@ pub trait BikeshedGuaranteedNoDrop {} /// [transmute]: crate::mem::transmute /// [nomicon-send-and-sync]: ../../nomicon/send-and-sync.html #[stable(feature = "rust1", since = "1.0.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "Sync")] +#[rustc_diagnostic_item = "Sync"] #[lang = "sync"] #[rustc_on_unimplemented( on( @@ -1301,7 +1305,7 @@ pub trait FnPtr: Copy + Clone { /// ``` #[rustc_builtin_macro(CoercePointee, attributes(pointee))] #[allow_internal_unstable(dispatch_from_dyn, coerce_unsized, unsize, coerce_pointee_validated)] -#[cfg_attr(not(test), rustc_diagnostic_item = "CoercePointee")] +#[rustc_diagnostic_item = "CoercePointee"] #[unstable(feature = "derive_coerce_pointee", issue = "123430")] pub macro CoercePointee($item:item) { /* compiler built-in */ diff --git a/library/core/src/mem/mod.rs b/library/core/src/mem/mod.rs index caab7a6ddb5..27387754633 100644 --- a/library/core/src/mem/mod.rs +++ b/library/core/src/mem/mod.rs @@ -140,7 +140,7 @@ pub use crate::intrinsics::transmute; #[inline] #[rustc_const_stable(feature = "const_forget", since = "1.46.0")] #[stable(feature = "rust1", since = "1.0.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "mem_forget")] +#[rustc_diagnostic_item = "mem_forget"] pub const fn forget<T>(t: T) { let _ = ManuallyDrop::new(t); } @@ -300,7 +300,7 @@ pub fn forget_unsized<T: ?Sized>(t: T) { #[stable(feature = "rust1", since = "1.0.0")] #[rustc_promotable] #[rustc_const_stable(feature = "const_mem_size_of", since = "1.24.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "mem_size_of")] +#[rustc_diagnostic_item = "mem_size_of"] pub const fn size_of<T>() -> usize { intrinsics::size_of::<T>() } @@ -328,7 +328,7 @@ pub const fn size_of<T>() -> usize { #[must_use] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_stable(feature = "const_size_of_val", since = "1.85.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "mem_size_of_val")] +#[rustc_diagnostic_item = "mem_size_of_val"] pub const fn size_of_val<T: ?Sized>(val: &T) -> usize { // SAFETY: `val` is a reference, so it's a valid raw pointer unsafe { intrinsics::size_of_val(val) } @@ -846,7 +846,7 @@ pub fn take<T: Default>(dest: &mut T) -> T { #[stable(feature = "rust1", since = "1.0.0")] #[must_use = "if you don't need the old value, you can just assign the new value directly"] #[rustc_const_stable(feature = "const_replace", since = "1.83.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "mem_replace")] +#[rustc_diagnostic_item = "mem_replace"] pub const fn replace<T>(dest: &mut T, src: T) -> T { // It may be tempting to use `swap` to avoid `unsafe` here. Don't! // The compiler optimizes the implementation below to two `memcpy`s @@ -856,8 +856,13 @@ pub const fn replace<T>(dest: &mut T, src: T) -> T { // such that the old value is not duplicated. Nothing is dropped and // nothing here can panic. unsafe { - let result = ptr::read(dest); - ptr::write(dest, src); + // Ideally we wouldn't use the intrinsics here, but going through the + // `ptr` methods introduces two unnecessary UbChecks, so until we can + // remove those for pointers that come from references, this uses the + // intrinsics instead so this stays very cheap in MIR (and debug). + + let result = crate::intrinsics::read_via_copy(dest); + crate::intrinsics::write_via_move(dest, src); result } } @@ -926,7 +931,7 @@ pub const fn replace<T>(dest: &mut T, src: T) -> T { /// [`RefCell`]: crate::cell::RefCell #[inline] #[stable(feature = "rust1", since = "1.0.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "mem_drop")] +#[rustc_diagnostic_item = "mem_drop"] pub fn drop<T>(_x: T) {} /// Bitwise-copies a value. @@ -1149,7 +1154,7 @@ impl<T> fmt::Debug for Discriminant<T> { /// ``` #[stable(feature = "discriminant_value", since = "1.21.0")] #[rustc_const_stable(feature = "const_discriminant", since = "1.75.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "mem_discriminant")] +#[rustc_diagnostic_item = "mem_discriminant"] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces pub const fn discriminant<T>(v: &T) -> Discriminant<T> { Discriminant(intrinsics::discriminant_value(v)) @@ -1249,42 +1254,56 @@ impl<T> SizedTypeProperties for T {} /// Expands to the offset in bytes of a field from the beginning of the given type. /// -/// Structs, enums, unions and tuples are supported. -/// -/// Nested field accesses may be used, but not array indexes. +/// The type may be a `struct`, `enum`, `union`, or tuple. /// -/// If the nightly-only feature `offset_of_enum` is enabled, -/// variants may be traversed as if they were fields. -/// Variants themselves do not have an offset. +/// The field may be a nested field (`field1.field2`), but not an array index. +/// The field must be visible to the call site. /// -/// Visibility is respected - all types and fields must be visible to the call site: +/// The offset is returned as a [`usize`]. /// -/// ``` -/// mod nested { -/// #[repr(C)] -/// pub struct Struct { -/// private: u8, -/// } -/// } +/// # Offsets of, and in, dynamically sized types /// -/// // assert_eq!(mem::offset_of!(nested::Struct, private), 0); -/// // ^^^ error[E0616]: field `private` of struct `Struct` is private -/// ``` +/// The field’s type must be [`Sized`], but it may be located in a [dynamically sized] container. +/// If the field type is dynamically sized, then you cannot use `offset_of!` (since the field's +/// alignment, and therefore its offset, may also be dynamic) and must take the offset from an +/// actual pointer to the container instead. /// -/// Only [`Sized`] fields are supported, but the container may be unsized: /// ``` /// # use core::mem; +/// # use core::fmt::Debug; /// #[repr(C)] -/// pub struct Struct { +/// pub struct Struct<T: ?Sized> { /// a: u8, -/// b: [u8], +/// b: T, /// } /// -/// assert_eq!(mem::offset_of!(Struct, a), 0); // OK -/// // assert_eq!(mem::offset_of!(Struct, b), 1); -/// // ^^^ error[E0277]: doesn't have a size known at compile-time +/// #[derive(Debug)] +/// #[repr(C, align(4))] +/// struct Align4(u32); +/// +/// assert_eq!(mem::offset_of!(Struct<dyn Debug>, a), 0); // OK — Sized field +/// assert_eq!(mem::offset_of!(Struct<Align4>, b), 4); // OK — not DST +/// +/// // assert_eq!(mem::offset_of!(Struct<dyn Debug>, b), 1); +/// // ^^^ error[E0277]: ... cannot be known at compilation time +/// +/// // To obtain the offset of a !Sized field, examine a concrete value +/// // instead of using offset_of!. +/// let value: Struct<Align4> = Struct { a: 1, b: Align4(2) }; +/// let ref_unsized: &Struct<dyn Debug> = &value; +/// let offset_of_b = unsafe { +/// (&raw const ref_unsized.b).byte_offset_from_unsigned(ref_unsized) +/// }; +/// assert_eq!(offset_of_b, 4); /// ``` /// +/// If you need to obtain the offset of a field of a `!Sized` type, then, since the offset may +/// depend on the particular value being stored (in particular, `dyn Trait` values have a +/// dynamically-determined alignment), you must retrieve the offset from a specific reference +/// or pointer, and so you cannot use `offset_of!` to work without one. +/// +/// # Layout is subject to change +/// /// Note that type layout is, in general, [subject to change and /// platform-specific](https://doc.rust-lang.org/reference/type-layout.html). If /// layout stability is required, consider using an [explicit `repr` attribute]. @@ -1320,11 +1339,16 @@ impl<T> SizedTypeProperties for T {} /// /// [explicit `repr` attribute]: https://doc.rust-lang.org/reference/type-layout.html#representations /// +/// # Unstable features +/// +/// The following unstable features expand the functionality of `offset_of!`: +/// +/// * [`offset_of_enum`] — allows `enum` variants to be traversed as if they were fields. +/// * [`offset_of_slice`] — allows getting the offset of a field of type `[T]`. +/// /// # Examples /// /// ``` -/// #![feature(offset_of_enum)] -/// /// use std::mem; /// #[repr(C)] /// struct FieldStruct { @@ -1346,18 +1370,11 @@ impl<T> SizedTypeProperties for T {} /// struct NestedB(u8); /// /// assert_eq!(mem::offset_of!(NestedA, b.0), 0); -/// -/// #[repr(u8)] -/// enum Enum { -/// A(u8, u16), -/// B { one: u8, two: u16 }, -/// } -/// -/// assert_eq!(mem::offset_of!(Enum, A.0), 1); -/// assert_eq!(mem::offset_of!(Enum, B.two), 2); -/// -/// assert_eq!(mem::offset_of!(Option<&u8>, Some.0), 0); /// ``` +/// +/// [dynamically sized]: https://doc.rust-lang.org/reference/dynamically-sized-types.html +/// [`offset_of_enum`]: https://doc.rust-lang.org/nightly/unstable-book/language-features/offset-of-enum.html +/// [`offset_of_slice`]: https://doc.rust-lang.org/nightly/unstable-book/language-features/offset-of-slice.html #[stable(feature = "offset_of", since = "1.77.0")] #[allow_internal_unstable(builtin_syntax)] pub macro offset_of($Container:ty, $($fields:expr)+ $(,)?) { diff --git a/library/core/src/net/ip_addr.rs b/library/core/src/net/ip_addr.rs index 8e4417ec461..7aa5ed60d04 100644 --- a/library/core/src/net/ip_addr.rs +++ b/library/core/src/net/ip_addr.rs @@ -25,7 +25,7 @@ use crate::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, Not}; /// assert_eq!(localhost_v4.is_ipv6(), false); /// assert_eq!(localhost_v4.is_ipv4(), true); /// ``` -#[cfg_attr(not(test), rustc_diagnostic_item = "IpAddr")] +#[rustc_diagnostic_item = "IpAddr"] #[stable(feature = "ip_addr", since = "1.7.0")] #[derive(Copy, Clone, Eq, PartialEq, Hash, PartialOrd, Ord)] pub enum IpAddr { diff --git a/library/core/src/net/socket_addr.rs b/library/core/src/net/socket_addr.rs index 57f47e66e81..21753d00924 100644 --- a/library/core/src/net/socket_addr.rs +++ b/library/core/src/net/socket_addr.rs @@ -8,11 +8,15 @@ use crate::net::{IpAddr, Ipv4Addr, Ipv6Addr}; /// as possibly some version-dependent additional information. See [`SocketAddrV4`]'s and /// [`SocketAddrV6`]'s respective documentation for more details. /// -/// The size of a `SocketAddr` instance may vary depending on the target operating -/// system. -/// /// [IP address]: IpAddr /// +/// # Portability +/// +/// `SocketAddr` is intended to be a portable representation of socket addresses and is likely not +/// the same as the internal socket address type used by the target operating system's API. Like all +/// `repr(Rust)` structs, however, its exact layout remains undefined and should not be relied upon +/// between builds. +/// /// # Examples /// /// ``` @@ -42,13 +46,16 @@ pub enum SocketAddr { /// /// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses. /// -/// The size of a `SocketAddrV4` struct may vary depending on the target operating -/// system. Do not assume that this type has the same memory layout as the underlying -/// system representation. -/// /// [IETF RFC 793]: https://tools.ietf.org/html/rfc793 /// [`IPv4` address]: Ipv4Addr /// +/// # Portability +/// +/// `SocketAddrV4` is intended to be a portable representation of socket addresses and is likely not +/// the same as the internal socket address type used by the target operating system's API. Like all +/// `repr(Rust)` structs, however, its exact layout remains undefined and should not be relied upon +/// between builds. +/// /// # Textual representation /// /// `SocketAddrV4` provides a [`FromStr`](crate::str::FromStr) implementation. @@ -84,13 +91,16 @@ pub struct SocketAddrV4 { /// /// See [`SocketAddr`] for a type encompassing both IPv4 and IPv6 socket addresses. /// -/// The size of a `SocketAddrV6` struct may vary depending on the target operating -/// system. Do not assume that this type has the same memory layout as the underlying -/// system representation. -/// /// [IETF RFC 2553, Section 3.3]: https://tools.ietf.org/html/rfc2553#section-3.3 /// [`IPv6` address]: Ipv6Addr /// +/// # Portability +/// +/// `SocketAddrV6` is intended to be a portable representation of socket addresses and is likely not +/// the same as the internal socket address type used by the target operating system's API. Like all +/// `repr(Rust)` structs, however, its exact layout remains undefined and should not be relied upon +/// between builds. +/// /// # Textual representation /// /// `SocketAddrV6` provides a [`FromStr`](crate::str::FromStr) implementation, diff --git a/library/core/src/num/f128.rs b/library/core/src/num/f128.rs index 5e45974b3d4..b17190971c3 100644 --- a/library/core/src/num/f128.rs +++ b/library/core/src/num/f128.rs @@ -12,11 +12,9 @@ #![unstable(feature = "f128", issue = "116909")] use crate::convert::FloatToInt; -#[cfg(not(test))] -use crate::intrinsics; -use crate::mem; use crate::num::FpCategory; use crate::panic::const_assert; +use crate::{intrinsics, mem}; /// Basic mathematical constants. #[unstable(feature = "f128", issue = "116909")] @@ -138,7 +136,6 @@ pub mod consts { pub const LN_10: f128 = 2.30258509299404568401799145468436420760110148862877297603333_f128; } -#[cfg(not(test))] impl f128 { // FIXME(f16_f128): almost all methods in this `impl` are missing examples and a const // implementation. Add these once we can run code on all platforms and have f16/f128 in CTFE. diff --git a/library/core/src/num/f16.rs b/library/core/src/num/f16.rs index e3176cd1688..d20677f43b4 100644 --- a/library/core/src/num/f16.rs +++ b/library/core/src/num/f16.rs @@ -12,11 +12,9 @@ #![unstable(feature = "f16", issue = "116909")] use crate::convert::FloatToInt; -#[cfg(not(test))] -use crate::intrinsics; -use crate::mem; use crate::num::FpCategory; use crate::panic::const_assert; +use crate::{intrinsics, mem}; /// Basic mathematical constants. #[unstable(feature = "f16", issue = "116909")] @@ -133,7 +131,6 @@ pub mod consts { pub const LN_10: f16 = 2.30258509299404568401799145468436421_f16; } -#[cfg(not(test))] impl f16 { // FIXME(f16_f128): almost all methods in this `impl` are missing examples and a const // implementation. Add these once we can run code on all platforms and have f16/f128 in CTFE. diff --git a/library/core/src/num/f32.rs b/library/core/src/num/f32.rs index de1557ccc90..79d864e1b19 100644 --- a/library/core/src/num/f32.rs +++ b/library/core/src/num/f32.rs @@ -12,11 +12,9 @@ #![stable(feature = "rust1", since = "1.0.0")] use crate::convert::FloatToInt; -#[cfg(not(test))] -use crate::intrinsics; -use crate::mem; use crate::num::FpCategory; use crate::panic::const_assert; +use crate::{intrinsics, mem}; /// The radix or base of the internal representation of `f32`. /// Use [`f32::RADIX`] instead. @@ -386,7 +384,6 @@ pub mod consts { pub const LN_10: f32 = 2.30258509299404568401799145468436421_f32; } -#[cfg(not(test))] impl f32 { /// The radix or base of the internal representation of `f32`. #[stable(feature = "assoc_int_consts", since = "1.43.0")] @@ -416,7 +413,7 @@ impl f32 { /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon /// [`MANTISSA_DIGITS`]: f32::MANTISSA_DIGITS #[stable(feature = "assoc_int_consts", since = "1.43.0")] - #[cfg_attr(not(test), rustc_diagnostic_item = "f32_epsilon")] + #[rustc_diagnostic_item = "f32_epsilon"] pub const EPSILON: f32 = 1.19209290e-07_f32; /// Smallest finite `f32` value. diff --git a/library/core/src/num/f64.rs b/library/core/src/num/f64.rs index 65b5f3b9af0..ca28b40bb3a 100644 --- a/library/core/src/num/f64.rs +++ b/library/core/src/num/f64.rs @@ -12,11 +12,9 @@ #![stable(feature = "rust1", since = "1.0.0")] use crate::convert::FloatToInt; -#[cfg(not(test))] -use crate::intrinsics; -use crate::mem; use crate::num::FpCategory; use crate::panic::const_assert; +use crate::{intrinsics, mem}; /// The radix or base of the internal representation of `f64`. /// Use [`f64::RADIX`] instead. @@ -386,7 +384,6 @@ pub mod consts { pub const LN_10: f64 = 2.30258509299404568401799145468436421_f64; } -#[cfg(not(test))] impl f64 { /// The radix or base of the internal representation of `f64`. #[stable(feature = "assoc_int_consts", since = "1.43.0")] @@ -415,7 +412,7 @@ impl f64 { /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon /// [`MANTISSA_DIGITS`]: f64::MANTISSA_DIGITS #[stable(feature = "assoc_int_consts", since = "1.43.0")] - #[cfg_attr(not(test), rustc_diagnostic_item = "f64_epsilon")] + #[rustc_diagnostic_item = "f64_epsilon"] pub const EPSILON: f64 = 2.2204460492503131e-16_f64; /// Smallest finite `f64` value. diff --git a/library/core/src/ops/control_flow.rs b/library/core/src/ops/control_flow.rs index 8993e14fcd3..0d910685927 100644 --- a/library/core/src/ops/control_flow.rs +++ b/library/core/src/ops/control_flow.rs @@ -79,7 +79,7 @@ use crate::{convert, ops}; /// [`Break`]: ControlFlow::Break /// [`Continue`]: ControlFlow::Continue #[stable(feature = "control_flow_enum_type", since = "1.55.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "ControlFlow")] +#[rustc_diagnostic_item = "ControlFlow"] // ControlFlow should not implement PartialOrd or Ord, per RFC 3058: // https://rust-lang.github.io/rfcs/3058-try-trait-v2.html#traits-for-controlflow #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] diff --git a/library/core/src/option.rs b/library/core/src/option.rs index f668c6f0672..7ec0ac71271 100644 --- a/library/core/src/option.rs +++ b/library/core/src/option.rs @@ -924,7 +924,7 @@ impl<T> Option<T> { #[inline] #[track_caller] #[stable(feature = "rust1", since = "1.0.0")] - #[cfg_attr(not(test), rustc_diagnostic_item = "option_expect")] + #[rustc_diagnostic_item = "option_expect"] #[rustc_allow_const_fn_unstable(const_precise_live_drops)] #[rustc_const_stable(feature = "const_option", since = "1.83.0")] pub const fn expect(self, msg: &str) -> T { @@ -969,7 +969,7 @@ impl<T> Option<T> { #[inline(always)] #[track_caller] #[stable(feature = "rust1", since = "1.0.0")] - #[cfg_attr(not(test), rustc_diagnostic_item = "option_unwrap")] + #[rustc_diagnostic_item = "option_unwrap"] #[rustc_allow_const_fn_unstable(const_precise_live_drops)] #[rustc_const_stable(feature = "const_option", since = "1.83.0")] pub const fn unwrap(self) -> T { diff --git a/library/core/src/panic/unwind_safe.rs b/library/core/src/panic/unwind_safe.rs index 37859212c0e..a60f0799c0e 100644 --- a/library/core/src/panic/unwind_safe.rs +++ b/library/core/src/panic/unwind_safe.rs @@ -82,7 +82,7 @@ use crate::task::{Context, Poll}; /// [`AssertUnwindSafe`] wrapper struct can be used to force this trait to be /// implemented for any closed over variables passed to `catch_unwind`. #[stable(feature = "catch_unwind", since = "1.9.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "unwind_safe_trait")] +#[rustc_diagnostic_item = "unwind_safe_trait"] #[diagnostic::on_unimplemented( message = "the type `{Self}` may not be safely transferred across an unwind boundary", label = "`{Self}` may not be safely transferred across an unwind boundary" @@ -98,7 +98,7 @@ pub auto trait UnwindSafe {} /// This is a "helper marker trait" used to provide impl blocks for the /// [`UnwindSafe`] trait, for more information see that documentation. #[stable(feature = "catch_unwind", since = "1.9.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "ref_unwind_safe_trait")] +#[rustc_diagnostic_item = "ref_unwind_safe_trait"] #[diagnostic::on_unimplemented( message = "the type `{Self}` may contain interior mutability and a reference may not be safely \ transferrable across a catch_unwind boundary", diff --git a/library/core/src/ptr/const_ptr.rs b/library/core/src/ptr/const_ptr.rs index 9a4f916803e..7d0839aff3f 100644 --- a/library/core/src/ptr/const_ptr.rs +++ b/library/core/src/ptr/const_ptr.rs @@ -193,7 +193,6 @@ impl<T: ?Sized> *const T { /// This is an [Exposed Provenance][crate::ptr#exposed-provenance] API. /// /// [`with_exposed_provenance`]: with_exposed_provenance - #[must_use] #[inline(always)] #[stable(feature = "exposed_provenance", since = "1.84.0")] pub fn expose_provenance(self) -> usize { diff --git a/library/core/src/result.rs b/library/core/src/result.rs index ee98a47523f..48ab9267f21 100644 --- a/library/core/src/result.rs +++ b/library/core/src/result.rs @@ -654,7 +654,7 @@ impl<T, E> Result<T, E> { /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] - #[cfg_attr(not(test), rustc_diagnostic_item = "result_ok_method")] + #[rustc_diagnostic_item = "result_ok_method"] pub fn ok(self) -> Option<T> { match self { Ok(x) => Some(x), diff --git a/library/core/src/slice/ascii.rs b/library/core/src/slice/ascii.rs index 51b25fa40e3..91befdb8c78 100644 --- a/library/core/src/slice/ascii.rs +++ b/library/core/src/slice/ascii.rs @@ -7,7 +7,6 @@ use crate::fmt::{self, Write}; use crate::intrinsics::const_eval_select; use crate::{ascii, iter, ops}; -#[cfg(not(test))] impl [u8] { /// Checks if all bytes in this slice are within the ASCII range. #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")] diff --git a/library/core/src/slice/mod.rs b/library/core/src/slice/mod.rs index 3570d8d0876..2c699ee9fdd 100644 --- a/library/core/src/slice/mod.rs +++ b/library/core/src/slice/mod.rs @@ -97,7 +97,6 @@ enum Direction { Back, } -#[cfg(not(test))] impl<T> [T] { /// Returns the number of elements in the slice. /// @@ -1045,7 +1044,7 @@ impl<T> [T] { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] - #[cfg_attr(not(test), rustc_diagnostic_item = "slice_iter")] + #[rustc_diagnostic_item = "slice_iter"] pub fn iter(&self) -> Iter<'_, T> { Iter::new(self) } @@ -4844,7 +4843,6 @@ impl<T, const N: usize> [[T; N]] { } } -#[cfg(not(test))] impl [f32] { /// Sorts the slice of floats. /// @@ -4873,7 +4871,6 @@ impl [f32] { } } -#[cfg(not(test))] impl [f64] { /// Sorts the slice of floats. /// diff --git a/library/core/src/str/mod.rs b/library/core/src/str/mod.rs index 83ad10db2da..5cc08f8a71a 100644 --- a/library/core/src/str/mod.rs +++ b/library/core/src/str/mod.rs @@ -114,7 +114,6 @@ fn slice_error_fail_rt(s: &str, begin: usize, end: usize) -> ! { ); } -#[cfg(not(test))] impl str { /// Returns the length of `self`. /// @@ -134,7 +133,7 @@ impl str { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_stable(feature = "const_str_len", since = "1.39.0")] - #[cfg_attr(not(test), rustc_diagnostic_item = "str_len")] + #[rustc_diagnostic_item = "str_len"] #[must_use] #[inline] pub const fn len(&self) -> usize { @@ -1029,7 +1028,7 @@ impl str { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] - #[cfg_attr(not(test), rustc_diagnostic_item = "str_chars")] + #[rustc_diagnostic_item = "str_chars"] pub fn chars(&self) -> Chars<'_> { Chars { iter: self.as_bytes().iter() } } @@ -1160,7 +1159,7 @@ impl str { #[must_use = "this returns the split string as an iterator, \ without modifying the original"] #[stable(feature = "split_whitespace", since = "1.1.0")] - #[cfg_attr(not(test), rustc_diagnostic_item = "str_split_whitespace")] + #[rustc_diagnostic_item = "str_split_whitespace"] #[inline] pub fn split_whitespace(&self) -> SplitWhitespace<'_> { SplitWhitespace { inner: self.split(IsWhitespace).filter(IsNotEmpty) } @@ -1355,7 +1354,7 @@ impl str { /// assert!(bananas.starts_with(&['a', 'b', 'c', 'd'])); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - #[cfg_attr(not(test), rustc_diagnostic_item = "str_starts_with")] + #[rustc_diagnostic_item = "str_starts_with"] pub fn starts_with<P: Pattern>(&self, pat: P) -> bool { pat.is_prefix_of(self) } @@ -1380,7 +1379,7 @@ impl str { /// assert!(!bananas.ends_with("nana")); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - #[cfg_attr(not(test), rustc_diagnostic_item = "str_ends_with")] + #[rustc_diagnostic_item = "str_ends_with"] pub fn ends_with<P: Pattern>(&self, pat: P) -> bool where for<'a> P::Searcher<'a>: ReverseSearcher<'a>, @@ -2114,7 +2113,7 @@ impl str { #[must_use = "this returns the trimmed string as a slice, \ without modifying the original"] #[stable(feature = "rust1", since = "1.0.0")] - #[cfg_attr(not(test), rustc_diagnostic_item = "str_trim")] + #[rustc_diagnostic_item = "str_trim"] pub fn trim(&self) -> &str { self.trim_matches(|c: char| c.is_whitespace()) } @@ -2153,7 +2152,7 @@ impl str { #[must_use = "this returns the trimmed string as a new slice, \ without modifying the original"] #[stable(feature = "trim_direction", since = "1.30.0")] - #[cfg_attr(not(test), rustc_diagnostic_item = "str_trim_start")] + #[rustc_diagnostic_item = "str_trim_start"] pub fn trim_start(&self) -> &str { self.trim_start_matches(|c: char| c.is_whitespace()) } @@ -2192,7 +2191,7 @@ impl str { #[must_use = "this returns the trimmed string as a new slice, \ without modifying the original"] #[stable(feature = "trim_direction", since = "1.30.0")] - #[cfg_attr(not(test), rustc_diagnostic_item = "str_trim_end")] + #[rustc_diagnostic_item = "str_trim_end"] pub fn trim_end(&self) -> &str { self.trim_end_matches(|c: char| c.is_whitespace()) } diff --git a/library/core/src/sync/atomic.rs b/library/core/src/sync/atomic.rs index 54a65c8459e..88bee622031 100644 --- a/library/core/src/sync/atomic.rs +++ b/library/core/src/sync/atomic.rs @@ -295,7 +295,7 @@ unsafe impl Sync for AtomicBool {} /// loads and stores of pointers. Its size depends on the target pointer's size. #[cfg(target_has_atomic_load_store = "ptr")] #[stable(feature = "rust1", since = "1.0.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "AtomicPtr")] +#[rustc_diagnostic_item = "AtomicPtr"] #[cfg_attr(target_pointer_width = "16", repr(C, align(2)))] #[cfg_attr(target_pointer_width = "32", repr(C, align(4)))] #[cfg_attr(target_pointer_width = "64", repr(C, align(8)))] @@ -3446,7 +3446,7 @@ atomic_int! { stable(feature = "integer_atomics_stable", since = "1.34.0"), rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"), rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"), - cfg_attr(not(test), rustc_diagnostic_item = "AtomicI8"), + rustc_diagnostic_item = "AtomicI8", "i8", "", atomic_min, atomic_max, @@ -3465,7 +3465,7 @@ atomic_int! { stable(feature = "integer_atomics_stable", since = "1.34.0"), rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"), rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"), - cfg_attr(not(test), rustc_diagnostic_item = "AtomicU8"), + rustc_diagnostic_item = "AtomicU8", "u8", "", atomic_umin, atomic_umax, @@ -3484,7 +3484,7 @@ atomic_int! { stable(feature = "integer_atomics_stable", since = "1.34.0"), rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"), rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"), - cfg_attr(not(test), rustc_diagnostic_item = "AtomicI16"), + rustc_diagnostic_item = "AtomicI16", "i16", "", atomic_min, atomic_max, @@ -3503,7 +3503,7 @@ atomic_int! { stable(feature = "integer_atomics_stable", since = "1.34.0"), rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"), rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"), - cfg_attr(not(test), rustc_diagnostic_item = "AtomicU16"), + rustc_diagnostic_item = "AtomicU16", "u16", "", atomic_umin, atomic_umax, @@ -3522,7 +3522,7 @@ atomic_int! { stable(feature = "integer_atomics_stable", since = "1.34.0"), rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"), rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"), - cfg_attr(not(test), rustc_diagnostic_item = "AtomicI32"), + rustc_diagnostic_item = "AtomicI32", "i32", "", atomic_min, atomic_max, @@ -3541,7 +3541,7 @@ atomic_int! { stable(feature = "integer_atomics_stable", since = "1.34.0"), rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"), rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"), - cfg_attr(not(test), rustc_diagnostic_item = "AtomicU32"), + rustc_diagnostic_item = "AtomicU32", "u32", "", atomic_umin, atomic_umax, @@ -3560,7 +3560,7 @@ atomic_int! { stable(feature = "integer_atomics_stable", since = "1.34.0"), rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"), rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"), - cfg_attr(not(test), rustc_diagnostic_item = "AtomicI64"), + rustc_diagnostic_item = "AtomicI64", "i64", "", atomic_min, atomic_max, @@ -3579,7 +3579,7 @@ atomic_int! { stable(feature = "integer_atomics_stable", since = "1.34.0"), rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"), rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"), - cfg_attr(not(test), rustc_diagnostic_item = "AtomicU64"), + rustc_diagnostic_item = "AtomicU64", "u64", "", atomic_umin, atomic_umax, @@ -3598,7 +3598,7 @@ atomic_int! { unstable(feature = "integer_atomics", issue = "99069"), rustc_const_unstable(feature = "integer_atomics", issue = "99069"), rustc_const_unstable(feature = "integer_atomics", issue = "99069"), - cfg_attr(not(test), rustc_diagnostic_item = "AtomicI128"), + rustc_diagnostic_item = "AtomicI128", "i128", "#![feature(integer_atomics)]\n\n", atomic_min, atomic_max, @@ -3617,7 +3617,7 @@ atomic_int! { unstable(feature = "integer_atomics", issue = "99069"), rustc_const_unstable(feature = "integer_atomics", issue = "99069"), rustc_const_unstable(feature = "integer_atomics", issue = "99069"), - cfg_attr(not(test), rustc_diagnostic_item = "AtomicU128"), + rustc_diagnostic_item = "AtomicU128", "u128", "#![feature(integer_atomics)]\n\n", atomic_umin, atomic_umax, @@ -3640,7 +3640,7 @@ macro_rules! atomic_int_ptr_sized { stable(feature = "atomic_nand", since = "1.27.0"), rustc_const_stable(feature = "const_ptr_sized_atomics", since = "1.24.0"), rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"), - cfg_attr(not(test), rustc_diagnostic_item = "AtomicIsize"), + rustc_diagnostic_item = "AtomicIsize", "isize", "", atomic_min, atomic_max, @@ -3659,7 +3659,7 @@ macro_rules! atomic_int_ptr_sized { stable(feature = "atomic_nand", since = "1.27.0"), rustc_const_stable(feature = "const_ptr_sized_atomics", since = "1.24.0"), rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"), - cfg_attr(not(test), rustc_diagnostic_item = "AtomicUsize"), + rustc_diagnostic_item = "AtomicUsize", "usize", "", atomic_umin, atomic_umax, diff --git a/library/core/src/task/wake.rs b/library/core/src/task/wake.rs index 3f57b04753a..9b8fefe42af 100644 --- a/library/core/src/task/wake.rs +++ b/library/core/src/task/wake.rs @@ -402,7 +402,7 @@ impl<'a> ContextBuilder<'a> { /// [`Wake`]: ../../alloc/task/trait.Wake.html #[repr(transparent)] #[stable(feature = "futures_api", since = "1.36.0")] -#[cfg_attr(not(test), rustc_diagnostic_item = "Waker")] +#[rustc_diagnostic_item = "Waker"] pub struct Waker { waker: RawWaker, } diff --git a/library/core/src/time.rs b/library/core/src/time.rs index 37b5c1076fa..18c03b4a6f8 100644 --- a/library/core/src/time.rs +++ b/library/core/src/time.rs @@ -77,7 +77,7 @@ const DAYS_PER_WEEK: u64 = 7; /// crate to do so. #[stable(feature = "duration", since = "1.3.0")] #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] -#[cfg_attr(not(test), rustc_diagnostic_item = "Duration")] +#[rustc_diagnostic_item = "Duration"] pub struct Duration { secs: u64, nanos: Nanoseconds, // Always 0 <= nanos < NANOS_PER_SEC diff --git a/library/std/src/collections/hash/map.rs b/library/std/src/collections/hash/map.rs index ff4a4b35ce4..2487f5a2a50 100644 --- a/library/std/src/collections/hash/map.rs +++ b/library/std/src/collections/hash/map.rs @@ -208,20 +208,32 @@ use crate::ops::Index; /// # Usage in `const` and `static` /// /// As explained above, `HashMap` is randomly seeded: each `HashMap` instance uses a different seed, -/// which means that `HashMap::new` cannot be used in const context. To construct a `HashMap` in the -/// initializer of a `const` or `static` item, you will have to use a different hasher that does not -/// involve a random seed, as demonstrated in the following example. **A `HashMap` constructed this -/// way is not resistant against HashDoS!** +/// which means that `HashMap::new` normally cannot be used in a `const` or `static` initializer. /// +/// However, if you need to use a `HashMap` in a `const` or `static` initializer while retaining +/// random seed generation, you can wrap the `HashMap` in [`LazyLock`]. +/// +/// Alternatively, you can construct a `HashMap` in a `const` or `static` initializer using a different +/// hasher that does not rely on a random seed. **Be aware that a `HashMap` created this way is not +/// resistant to HashDoS attacks!** +/// +/// [`LazyLock`]: crate::sync::LazyLock /// ```rust /// use std::collections::HashMap; /// use std::hash::{BuildHasherDefault, DefaultHasher}; -/// use std::sync::Mutex; +/// use std::sync::{LazyLock, Mutex}; /// -/// const EMPTY_MAP: HashMap<String, Vec<i32>, BuildHasherDefault<DefaultHasher>> = +/// // HashMaps with a fixed, non-random hasher +/// const NONRANDOM_EMPTY_MAP: HashMap<String, Vec<i32>, BuildHasherDefault<DefaultHasher>> = /// HashMap::with_hasher(BuildHasherDefault::new()); -/// static MAP: Mutex<HashMap<String, Vec<i32>, BuildHasherDefault<DefaultHasher>>> = +/// static NONRANDOM_MAP: Mutex<HashMap<String, Vec<i32>, BuildHasherDefault<DefaultHasher>>> = /// Mutex::new(HashMap::with_hasher(BuildHasherDefault::new())); +/// +/// // HashMaps using LazyLock to retain random seeding +/// const RANDOM_EMPTY_MAP: LazyLock<HashMap<String, Vec<i32>>> = +/// LazyLock::new(HashMap::new); +/// static RANDOM_MAP: LazyLock<Mutex<HashMap<String, Vec<i32>>>> = +/// LazyLock::new(|| Mutex::new(HashMap::new())); /// ``` #[cfg_attr(not(test), rustc_diagnostic_item = "HashMap")] @@ -1278,69 +1290,6 @@ where } } -impl<K, V, S> HashMap<K, V, S> -where - S: BuildHasher, -{ - /// Creates a raw entry builder for the `HashMap`. - /// - /// Raw entries provide the lowest level of control for searching and - /// manipulating a map. They must be manually initialized with a hash and - /// then manually searched. After this, insertions into a vacant entry - /// still require an owned key to be provided. - /// - /// Raw entries are useful for such exotic situations as: - /// - /// * Hash memoization - /// * Deferring the creation of an owned key until it is known to be required - /// * Using a search key that doesn't work with the Borrow trait - /// * Using custom comparison logic without newtype wrappers - /// - /// Because raw entries provide much more low-level control, it's much easier - /// to put the `HashMap` into an inconsistent state which, while memory-safe, - /// will cause the map to produce seemingly random results. Higher-level and - /// more foolproof APIs like `entry` should be preferred when possible. - /// - /// In particular, the hash used to initialize the raw entry must still be - /// consistent with the hash of the key that is ultimately stored in the entry. - /// This is because implementations of `HashMap` may need to recompute hashes - /// when resizing, at which point only the keys are available. - /// - /// Raw entries give mutable access to the keys. This must not be used - /// to modify how the key would compare or hash, as the map will not re-evaluate - /// where the key should go, meaning the keys may become "lost" if their - /// location does not reflect their state. For instance, if you change a key - /// so that the map now contains keys which compare equal, search may start - /// acting erratically, with two keys randomly masking each other. Implementations - /// are free to assume this doesn't happen (within the limits of memory-safety). - #[inline] - #[unstable(feature = "hash_raw_entry", issue = "56167")] - pub fn raw_entry_mut(&mut self) -> RawEntryBuilderMut<'_, K, V, S> { - RawEntryBuilderMut { map: self } - } - - /// Creates a raw immutable entry builder for the `HashMap`. - /// - /// Raw entries provide the lowest level of control for searching and - /// manipulating a map. They must be manually initialized with a hash and - /// then manually searched. - /// - /// This is useful for - /// * Hash memoization - /// * Using a search key that doesn't work with the Borrow trait - /// * Using custom comparison logic without newtype wrappers - /// - /// Unless you are in such a situation, higher-level and more foolproof APIs like - /// `get` should be preferred. - /// - /// Immutable raw entries have very limited use; you might instead want `raw_entry_mut`. - #[inline] - #[unstable(feature = "hash_raw_entry", issue = "56167")] - pub fn raw_entry(&self) -> RawEntryBuilder<'_, K, V, S> { - RawEntryBuilder { map: self } - } -} - #[stable(feature = "rust1", since = "1.0.0")] impl<K, V, S> Clone for HashMap<K, V, S> where @@ -1828,404 +1777,6 @@ impl<K, V> Default for IntoValues<K, V> { } } -/// A builder for computing where in a HashMap a key-value pair would be stored. -/// -/// See the [`HashMap::raw_entry_mut`] docs for usage examples. -#[unstable(feature = "hash_raw_entry", issue = "56167")] -pub struct RawEntryBuilderMut<'a, K: 'a, V: 'a, S: 'a> { - map: &'a mut HashMap<K, V, S>, -} - -/// A view into a single entry in a map, which may either be vacant or occupied. -/// -/// This is a lower-level version of [`Entry`]. -/// -/// This `enum` is constructed through the [`raw_entry_mut`] method on [`HashMap`], -/// then calling one of the methods of that [`RawEntryBuilderMut`]. -/// -/// [`raw_entry_mut`]: HashMap::raw_entry_mut -#[unstable(feature = "hash_raw_entry", issue = "56167")] -pub enum RawEntryMut<'a, K: 'a, V: 'a, S: 'a> { - /// An occupied entry. - Occupied(RawOccupiedEntryMut<'a, K, V, S>), - /// A vacant entry. - Vacant(RawVacantEntryMut<'a, K, V, S>), -} - -/// A view into an occupied entry in a `HashMap`. -/// It is part of the [`RawEntryMut`] enum. -#[unstable(feature = "hash_raw_entry", issue = "56167")] -pub struct RawOccupiedEntryMut<'a, K: 'a, V: 'a, S: 'a> { - base: base::RawOccupiedEntryMut<'a, K, V, S>, -} - -/// A view into a vacant entry in a `HashMap`. -/// It is part of the [`RawEntryMut`] enum. -#[unstable(feature = "hash_raw_entry", issue = "56167")] -pub struct RawVacantEntryMut<'a, K: 'a, V: 'a, S: 'a> { - base: base::RawVacantEntryMut<'a, K, V, S>, -} - -/// A builder for computing where in a HashMap a key-value pair would be stored. -/// -/// See the [`HashMap::raw_entry`] docs for usage examples. -#[unstable(feature = "hash_raw_entry", issue = "56167")] -pub struct RawEntryBuilder<'a, K: 'a, V: 'a, S: 'a> { - map: &'a HashMap<K, V, S>, -} - -impl<'a, K, V, S> RawEntryBuilderMut<'a, K, V, S> -where - S: BuildHasher, -{ - /// Creates a `RawEntryMut` from the given key. - #[inline] - #[unstable(feature = "hash_raw_entry", issue = "56167")] - pub fn from_key<Q: ?Sized>(self, k: &Q) -> RawEntryMut<'a, K, V, S> - where - K: Borrow<Q>, - Q: Hash + Eq, - { - map_raw_entry(self.map.base.raw_entry_mut().from_key(k)) - } - - /// Creates a `RawEntryMut` from the given key and its hash. - #[inline] - #[unstable(feature = "hash_raw_entry", issue = "56167")] - pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S> - where - K: Borrow<Q>, - Q: Eq, - { - map_raw_entry(self.map.base.raw_entry_mut().from_key_hashed_nocheck(hash, k)) - } - - /// Creates a `RawEntryMut` from the given hash. - #[inline] - #[unstable(feature = "hash_raw_entry", issue = "56167")] - pub fn from_hash<F>(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S> - where - for<'b> F: FnMut(&'b K) -> bool, - { - map_raw_entry(self.map.base.raw_entry_mut().from_hash(hash, is_match)) - } -} - -impl<'a, K, V, S> RawEntryBuilder<'a, K, V, S> -where - S: BuildHasher, -{ - /// Access an entry by key. - #[inline] - #[unstable(feature = "hash_raw_entry", issue = "56167")] - pub fn from_key<Q: ?Sized>(self, k: &Q) -> Option<(&'a K, &'a V)> - where - K: Borrow<Q>, - Q: Hash + Eq, - { - self.map.base.raw_entry().from_key(k) - } - - /// Access an entry by a key and its hash. - #[inline] - #[unstable(feature = "hash_raw_entry", issue = "56167")] - pub fn from_key_hashed_nocheck<Q: ?Sized>(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)> - where - K: Borrow<Q>, - Q: Hash + Eq, - { - self.map.base.raw_entry().from_key_hashed_nocheck(hash, k) - } - - /// Access an entry by hash. - #[inline] - #[unstable(feature = "hash_raw_entry", issue = "56167")] - pub fn from_hash<F>(self, hash: u64, is_match: F) -> Option<(&'a K, &'a V)> - where - F: FnMut(&K) -> bool, - { - self.map.base.raw_entry().from_hash(hash, is_match) - } -} - -impl<'a, K, V, S> RawEntryMut<'a, K, V, S> { - /// Ensures a value is in the entry by inserting the default if empty, and returns - /// mutable references to the key and value in the entry. - /// - /// # Examples - /// - /// ``` - /// #![feature(hash_raw_entry)] - /// use std::collections::HashMap; - /// - /// let mut map: HashMap<&str, u32> = HashMap::new(); - /// - /// map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 3); - /// assert_eq!(map["poneyland"], 3); - /// - /// *map.raw_entry_mut().from_key("poneyland").or_insert("poneyland", 10).1 *= 2; - /// assert_eq!(map["poneyland"], 6); - /// ``` - #[inline] - #[unstable(feature = "hash_raw_entry", issue = "56167")] - pub fn or_insert(self, default_key: K, default_val: V) -> (&'a mut K, &'a mut V) - where - K: Hash, - S: BuildHasher, - { - match self { - RawEntryMut::Occupied(entry) => entry.into_key_value(), - RawEntryMut::Vacant(entry) => entry.insert(default_key, default_val), - } - } - - /// Ensures a value is in the entry by inserting the result of the default function if empty, - /// and returns mutable references to the key and value in the entry. - /// - /// # Examples - /// - /// ``` - /// #![feature(hash_raw_entry)] - /// use std::collections::HashMap; - /// - /// let mut map: HashMap<&str, String> = HashMap::new(); - /// - /// map.raw_entry_mut().from_key("poneyland").or_insert_with(|| { - /// ("poneyland", "hoho".to_string()) - /// }); - /// - /// assert_eq!(map["poneyland"], "hoho".to_string()); - /// ``` - #[inline] - #[unstable(feature = "hash_raw_entry", issue = "56167")] - pub fn or_insert_with<F>(self, default: F) -> (&'a mut K, &'a mut V) - where - F: FnOnce() -> (K, V), - K: Hash, - S: BuildHasher, - { - match self { - RawEntryMut::Occupied(entry) => entry.into_key_value(), - RawEntryMut::Vacant(entry) => { - let (k, v) = default(); - entry.insert(k, v) - } - } - } - - /// Provides in-place mutable access to an occupied entry before any - /// potential inserts into the map. - /// - /// # Examples - /// - /// ``` - /// #![feature(hash_raw_entry)] - /// use std::collections::HashMap; - /// - /// let mut map: HashMap<&str, u32> = HashMap::new(); - /// - /// map.raw_entry_mut() - /// .from_key("poneyland") - /// .and_modify(|_k, v| { *v += 1 }) - /// .or_insert("poneyland", 42); - /// assert_eq!(map["poneyland"], 42); - /// - /// map.raw_entry_mut() - /// .from_key("poneyland") - /// .and_modify(|_k, v| { *v += 1 }) - /// .or_insert("poneyland", 0); - /// assert_eq!(map["poneyland"], 43); - /// ``` - #[inline] - #[unstable(feature = "hash_raw_entry", issue = "56167")] - pub fn and_modify<F>(self, f: F) -> Self - where - F: FnOnce(&mut K, &mut V), - { - match self { - RawEntryMut::Occupied(mut entry) => { - { - let (k, v) = entry.get_key_value_mut(); - f(k, v); - } - RawEntryMut::Occupied(entry) - } - RawEntryMut::Vacant(entry) => RawEntryMut::Vacant(entry), - } - } -} - -impl<'a, K, V, S> RawOccupiedEntryMut<'a, K, V, S> { - /// Gets a reference to the key in the entry. - #[inline] - #[must_use] - #[unstable(feature = "hash_raw_entry", issue = "56167")] - pub fn key(&self) -> &K { - self.base.key() - } - - /// Gets a mutable reference to the key in the entry. - #[inline] - #[must_use] - #[unstable(feature = "hash_raw_entry", issue = "56167")] - pub fn key_mut(&mut self) -> &mut K { - self.base.key_mut() - } - - /// Converts the entry into a mutable reference to the key in the entry - /// with a lifetime bound to the map itself. - #[inline] - #[must_use = "`self` will be dropped if the result is not used"] - #[unstable(feature = "hash_raw_entry", issue = "56167")] - pub fn into_key(self) -> &'a mut K { - self.base.into_key() - } - - /// Gets a reference to the value in the entry. - #[inline] - #[must_use] - #[unstable(feature = "hash_raw_entry", issue = "56167")] - pub fn get(&self) -> &V { - self.base.get() - } - - /// Converts the `OccupiedEntry` into a mutable reference to the value in the entry - /// with a lifetime bound to the map itself. - #[inline] - #[must_use = "`self` will be dropped if the result is not used"] - #[unstable(feature = "hash_raw_entry", issue = "56167")] - pub fn into_mut(self) -> &'a mut V { - self.base.into_mut() - } - - /// Gets a mutable reference to the value in the entry. - #[inline] - #[must_use] - #[unstable(feature = "hash_raw_entry", issue = "56167")] - pub fn get_mut(&mut self) -> &mut V { - self.base.get_mut() - } - - /// Gets a reference to the key and value in the entry. - #[inline] - #[must_use] - #[unstable(feature = "hash_raw_entry", issue = "56167")] - pub fn get_key_value(&mut self) -> (&K, &V) { - self.base.get_key_value() - } - - /// Gets a mutable reference to the key and value in the entry. - #[inline] - #[unstable(feature = "hash_raw_entry", issue = "56167")] - pub fn get_key_value_mut(&mut self) -> (&mut K, &mut V) { - self.base.get_key_value_mut() - } - - /// Converts the `OccupiedEntry` into a mutable reference to the key and value in the entry - /// with a lifetime bound to the map itself. - #[inline] - #[must_use = "`self` will be dropped if the result is not used"] - #[unstable(feature = "hash_raw_entry", issue = "56167")] - pub fn into_key_value(self) -> (&'a mut K, &'a mut V) { - self.base.into_key_value() - } - - /// Sets the value of the entry, and returns the entry's old value. - #[inline] - #[unstable(feature = "hash_raw_entry", issue = "56167")] - pub fn insert(&mut self, value: V) -> V { - self.base.insert(value) - } - - /// Sets the value of the entry, and returns the entry's old value. - #[inline] - #[unstable(feature = "hash_raw_entry", issue = "56167")] - pub fn insert_key(&mut self, key: K) -> K { - self.base.insert_key(key) - } - - /// Takes the value out of the entry, and returns it. - #[inline] - #[unstable(feature = "hash_raw_entry", issue = "56167")] - pub fn remove(self) -> V { - self.base.remove() - } - - /// Take the ownership of the key and value from the map. - #[inline] - #[unstable(feature = "hash_raw_entry", issue = "56167")] - pub fn remove_entry(self) -> (K, V) { - self.base.remove_entry() - } -} - -impl<'a, K, V, S> RawVacantEntryMut<'a, K, V, S> { - /// Sets the value of the entry with the `VacantEntry`'s key, - /// and returns a mutable reference to it. - #[inline] - #[unstable(feature = "hash_raw_entry", issue = "56167")] - pub fn insert(self, key: K, value: V) -> (&'a mut K, &'a mut V) - where - K: Hash, - S: BuildHasher, - { - self.base.insert(key, value) - } - - /// Sets the value of the entry with the VacantEntry's key, - /// and returns a mutable reference to it. - #[inline] - #[unstable(feature = "hash_raw_entry", issue = "56167")] - pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V) - where - K: Hash, - S: BuildHasher, - { - self.base.insert_hashed_nocheck(hash, key, value) - } -} - -#[unstable(feature = "hash_raw_entry", issue = "56167")] -impl<K, V, S> Debug for RawEntryBuilderMut<'_, K, V, S> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("RawEntryBuilder").finish_non_exhaustive() - } -} - -#[unstable(feature = "hash_raw_entry", issue = "56167")] -impl<K: Debug, V: Debug, S> Debug for RawEntryMut<'_, K, V, S> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match *self { - RawEntryMut::Vacant(ref v) => f.debug_tuple("RawEntry").field(v).finish(), - RawEntryMut::Occupied(ref o) => f.debug_tuple("RawEntry").field(o).finish(), - } - } -} - -#[unstable(feature = "hash_raw_entry", issue = "56167")] -impl<K: Debug, V: Debug, S> Debug for RawOccupiedEntryMut<'_, K, V, S> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("RawOccupiedEntryMut") - .field("key", self.key()) - .field("value", self.get()) - .finish_non_exhaustive() - } -} - -#[unstable(feature = "hash_raw_entry", issue = "56167")] -impl<K, V, S> Debug for RawVacantEntryMut<'_, K, V, S> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("RawVacantEntryMut").finish_non_exhaustive() - } -} - -#[unstable(feature = "hash_raw_entry", issue = "56167")] -impl<K, V, S> Debug for RawEntryBuilder<'_, K, V, S> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("RawEntryBuilder").finish_non_exhaustive() - } -} - /// A view into a single entry in a map, which may either be vacant or occupied. /// /// This `enum` is constructed from the [`entry`] method on [`HashMap`]. @@ -3298,16 +2849,6 @@ pub(super) fn map_try_reserve_error(err: hashbrown::TryReserveError) -> TryReser } } -#[inline] -fn map_raw_entry<'a, K: 'a, V: 'a, S: 'a>( - raw: base::RawEntryMut<'a, K, V, S>, -) -> RawEntryMut<'a, K, V, S> { - match raw { - base::RawEntryMut::Occupied(base) => RawEntryMut::Occupied(RawOccupiedEntryMut { base }), - base::RawEntryMut::Vacant(base) => RawEntryMut::Vacant(RawVacantEntryMut { base }), - } -} - #[allow(dead_code)] fn assert_covariance() { fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> { diff --git a/library/std/src/collections/hash/map/tests.rs b/library/std/src/collections/hash/map/tests.rs index a275488a556..9f7df20a1d7 100644 --- a/library/std/src/collections/hash/map/tests.rs +++ b/library/std/src/collections/hash/map/tests.rs @@ -852,99 +852,6 @@ fn test_try_reserve() { } } -#[test] -fn test_raw_entry() { - use super::RawEntryMut::{Occupied, Vacant}; - - let xs = [(1i32, 10i32), (2, 20), (3, 30), (4, 40), (5, 50), (6, 60)]; - - let mut map: HashMap<_, _> = xs.iter().cloned().collect(); - - let compute_hash = |map: &HashMap<i32, i32>, k: i32| -> u64 { - use core::hash::{BuildHasher, Hash, Hasher}; - - let mut hasher = map.hasher().build_hasher(); - k.hash(&mut hasher); - hasher.finish() - }; - - // Existing key (insert) - match map.raw_entry_mut().from_key(&1) { - Vacant(_) => unreachable!(), - Occupied(mut view) => { - assert_eq!(view.get(), &10); - assert_eq!(view.insert(100), 10); - } - } - let hash1 = compute_hash(&map, 1); - assert_eq!(map.raw_entry().from_key(&1).unwrap(), (&1, &100)); - assert_eq!(map.raw_entry().from_hash(hash1, |k| *k == 1).unwrap(), (&1, &100)); - assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash1, &1).unwrap(), (&1, &100)); - assert_eq!(map.len(), 6); - - // Existing key (update) - match map.raw_entry_mut().from_key(&2) { - Vacant(_) => unreachable!(), - Occupied(mut view) => { - let v = view.get_mut(); - let new_v = (*v) * 10; - *v = new_v; - } - } - let hash2 = compute_hash(&map, 2); - assert_eq!(map.raw_entry().from_key(&2).unwrap(), (&2, &200)); - assert_eq!(map.raw_entry().from_hash(hash2, |k| *k == 2).unwrap(), (&2, &200)); - assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash2, &2).unwrap(), (&2, &200)); - assert_eq!(map.len(), 6); - - // Existing key (take) - let hash3 = compute_hash(&map, 3); - match map.raw_entry_mut().from_key_hashed_nocheck(hash3, &3) { - Vacant(_) => unreachable!(), - Occupied(view) => { - assert_eq!(view.remove_entry(), (3, 30)); - } - } - assert_eq!(map.raw_entry().from_key(&3), None); - assert_eq!(map.raw_entry().from_hash(hash3, |k| *k == 3), None); - assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash3, &3), None); - assert_eq!(map.len(), 5); - - // Nonexistent key (insert) - match map.raw_entry_mut().from_key(&10) { - Occupied(_) => unreachable!(), - Vacant(view) => { - assert_eq!(view.insert(10, 1000), (&mut 10, &mut 1000)); - } - } - assert_eq!(map.raw_entry().from_key(&10).unwrap(), (&10, &1000)); - assert_eq!(map.len(), 6); - - // Ensure all lookup methods produce equivalent results. - for k in 0..12 { - let hash = compute_hash(&map, k); - let v = map.get(&k).cloned(); - let kv = v.as_ref().map(|v| (&k, v)); - - assert_eq!(map.raw_entry().from_key(&k), kv); - assert_eq!(map.raw_entry().from_hash(hash, |q| *q == k), kv); - assert_eq!(map.raw_entry().from_key_hashed_nocheck(hash, &k), kv); - - match map.raw_entry_mut().from_key(&k) { - Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv), - Vacant(_) => assert_eq!(v, None), - } - match map.raw_entry_mut().from_key_hashed_nocheck(hash, &k) { - Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv), - Vacant(_) => assert_eq!(v, None), - } - match map.raw_entry_mut().from_hash(hash, |q| *q == k) { - Occupied(mut o) => assert_eq!(Some(o.get_key_value()), kv), - Vacant(_) => assert_eq!(v, None), - } - } -} - mod test_extract_if { use super::*; use crate::panic::{AssertUnwindSafe, catch_unwind}; diff --git a/library/std/src/io/buffered/bufreader.rs b/library/std/src/io/buffered/bufreader.rs index 697fb5974a3..40441dc057d 100644 --- a/library/std/src/io/buffered/bufreader.rs +++ b/library/std/src/io/buffered/bufreader.rs @@ -109,9 +109,13 @@ impl<R: Read + ?Sized> BufReader<R> { /// /// `n` must be less than or equal to `capacity`. /// - /// the returned slice may be less than `n` bytes long if + /// The returned slice may be less than `n` bytes long if /// end of file is reached. /// + /// After calling this method, you may call [`consume`](BufRead::consume) + /// with a value less than or equal to `n` to advance over some or all of + /// the returned bytes. + /// /// ## Examples /// /// ```rust diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index 938b8c6e4f4..35ada678740 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -666,6 +666,8 @@ pub mod arch { pub use std_detect::is_loongarch_feature_detected; #[unstable(feature = "is_riscv_feature_detected", issue = "111192")] pub use std_detect::is_riscv_feature_detected; + #[unstable(feature = "stdarch_s390x_feature_detection", issue = "135413")] + pub use std_detect::is_s390x_feature_detected; #[stable(feature = "simd_x86", since = "1.27.0")] pub use std_detect::is_x86_feature_detected; #[unstable(feature = "stdarch_mips_feature_detection", issue = "111188")] diff --git a/library/std/src/os/unix/fs.rs b/library/std/src/os/unix/fs.rs index 04a45fd035a..0427feb2955 100644 --- a/library/std/src/os/unix/fs.rs +++ b/library/std/src/os/unix/fs.rs @@ -276,63 +276,89 @@ impl FileExt for fs::File { } /// Unix-specific extensions to [`fs::Permissions`]. +/// +/// # Examples +/// +/// ```no_run +/// use std::fs::{File, Permissions}; +/// use std::io::{ErrorKind, Result as IoResult}; +/// use std::os::unix::fs::PermissionsExt; +/// +/// fn main() -> IoResult<()> { +/// let name = "test_file_for_permissions"; +/// +/// // make sure file does not exist +/// let _ = std::fs::remove_file(name); +/// assert_eq!( +/// File::open(name).unwrap_err().kind(), +/// ErrorKind::NotFound, +/// "file already exists" +/// ); +/// +/// // full read/write/execute mode bits for owner of file +/// // that we want to add to existing mode bits +/// let my_mode = 0o700; +/// +/// // create new file with specified permissions +/// { +/// let file = File::create(name)?; +/// let mut permissions = file.metadata()?.permissions(); +/// eprintln!("Current permissions: {:o}", permissions.mode()); +/// +/// // make sure new permissions are not already set +/// assert!( +/// permissions.mode() & my_mode != my_mode, +/// "permissions already set" +/// ); +/// +/// // either use `set_mode` to change an existing Permissions struct +/// permissions.set_mode(permissions.mode() | my_mode); +/// +/// // or use `from_mode` to construct a new Permissions struct +/// permissions = Permissions::from_mode(permissions.mode() | my_mode); +/// +/// // write new permissions to file +/// file.set_permissions(permissions)?; +/// } +/// +/// let permissions = File::open(name)?.metadata()?.permissions(); +/// eprintln!("New permissions: {:o}", permissions.mode()); +/// +/// // assert new permissions were set +/// assert_eq!( +/// permissions.mode() & my_mode, +/// my_mode, +/// "new permissions not set" +/// ); +/// Ok(()) +/// } +/// ``` +/// +/// ```no_run +/// use std::fs::Permissions; +/// use std::os::unix::fs::PermissionsExt; +/// +/// // read/write for owner and read for others +/// let my_mode = 0o644; +/// let mut permissions = Permissions::from_mode(my_mode); +/// assert_eq!(permissions.mode(), my_mode); +/// +/// // read/write/execute for owner +/// let other_mode = 0o700; +/// permissions.set_mode(other_mode); +/// assert_eq!(permissions.mode(), other_mode); +/// ``` #[stable(feature = "fs_ext", since = "1.1.0")] pub trait PermissionsExt { - /// Returns the underlying raw `st_mode` bits that contain the standard - /// Unix permissions for this file. - /// - /// # Examples - /// - /// ```no_run - /// use std::fs::File; - /// use std::os::unix::fs::PermissionsExt; - /// - /// fn main() -> std::io::Result<()> { - /// let f = File::create("foo.txt")?; - /// let metadata = f.metadata()?; - /// let permissions = metadata.permissions(); - /// - /// println!("permissions: {:o}", permissions.mode()); - /// Ok(()) - /// } - /// ``` + /// Returns the mode permission bits #[stable(feature = "fs_ext", since = "1.1.0")] fn mode(&self) -> u32; - /// Sets the underlying raw bits for this set of permissions. - /// - /// # Examples - /// - /// ```no_run - /// use std::fs::File; - /// use std::os::unix::fs::PermissionsExt; - /// - /// fn main() -> std::io::Result<()> { - /// let f = File::create("foo.txt")?; - /// let metadata = f.metadata()?; - /// let mut permissions = metadata.permissions(); - /// - /// permissions.set_mode(0o644); // Read/write for owner and read for others. - /// assert_eq!(permissions.mode(), 0o644); - /// Ok(()) - /// } - /// ``` + /// Sets the mode permission bits. #[stable(feature = "fs_ext", since = "1.1.0")] fn set_mode(&mut self, mode: u32); - /// Creates a new instance of `Permissions` from the given set of Unix - /// permission bits. - /// - /// # Examples - /// - /// ``` - /// use std::fs::Permissions; - /// use std::os::unix::fs::PermissionsExt; - /// - /// // Read/write for owner and read for others. - /// let permissions = Permissions::from_mode(0o644); - /// assert_eq!(permissions.mode(), 0o644); - /// ``` + /// Creates a new instance from the given mode permission bits. #[stable(feature = "fs_ext", since = "1.1.0")] #[cfg_attr(not(test), rustc_diagnostic_item = "permissions_from_mode")] fn from_mode(mode: u32) -> Self; diff --git a/library/std/src/path.rs b/library/std/src/path.rs index f9f3b488f0d..980213be7ea 100644 --- a/library/std/src/path.rs +++ b/library/std/src/path.rs @@ -294,11 +294,6 @@ where } } -// Detect scheme on Redox -pub(crate) fn has_redox_scheme(s: &[u8]) -> bool { - cfg!(target_os = "redox") && s.contains(&b':') -} - //////////////////////////////////////////////////////////////////////////////// // Cross-platform, iterator-independent parsing //////////////////////////////////////////////////////////////////////////////// @@ -2834,8 +2829,7 @@ impl Path { Components { path: self.as_u8_slice(), prefix, - has_physical_root: has_physical_root(self.as_u8_slice(), prefix) - || has_redox_scheme(self.as_u8_slice()), + has_physical_root: has_physical_root(self.as_u8_slice(), prefix), front: State::Prefix, back: State::Body, } diff --git a/library/std/src/sys/pal/uefi/helpers.rs b/library/std/src/sys/pal/uefi/helpers.rs index 0a2a8f5ef67..60c33c637d7 100644 --- a/library/std/src/sys/pal/uefi/helpers.rs +++ b/library/std/src/sys/pal/uefi/helpers.rs @@ -216,6 +216,60 @@ pub(crate) fn device_path_to_text(path: NonNull<device_path::Protocol>) -> io::R Err(io::const_error!(io::ErrorKind::NotFound, "no device path to text protocol found")) } +fn device_node_to_text(path: NonNull<device_path::Protocol>) -> io::Result<OsString> { + fn node_to_text( + protocol: NonNull<device_path_to_text::Protocol>, + path: NonNull<device_path::Protocol>, + ) -> io::Result<OsString> { + let path_ptr: *mut r_efi::efi::Char16 = unsafe { + ((*protocol.as_ptr()).convert_device_node_to_text)( + path.as_ptr(), + // DisplayOnly + r_efi::efi::Boolean::FALSE, + // AllowShortcuts + r_efi::efi::Boolean::FALSE, + ) + }; + + let path = os_string_from_raw(path_ptr) + .ok_or(io::const_error!(io::ErrorKind::InvalidData, "Invalid path"))?; + + if let Some(boot_services) = crate::os::uefi::env::boot_services() { + let boot_services: NonNull<r_efi::efi::BootServices> = boot_services.cast(); + unsafe { + ((*boot_services.as_ptr()).free_pool)(path_ptr.cast()); + } + } + + Ok(path) + } + + static LAST_VALID_HANDLE: AtomicPtr<crate::ffi::c_void> = + AtomicPtr::new(crate::ptr::null_mut()); + + if let Some(handle) = NonNull::new(LAST_VALID_HANDLE.load(Ordering::Acquire)) { + if let Ok(protocol) = open_protocol::<device_path_to_text::Protocol>( + handle, + device_path_to_text::PROTOCOL_GUID, + ) { + return node_to_text(protocol, path); + } + } + + let device_path_to_text_handles = locate_handles(device_path_to_text::PROTOCOL_GUID)?; + for handle in device_path_to_text_handles { + if let Ok(protocol) = open_protocol::<device_path_to_text::Protocol>( + handle, + device_path_to_text::PROTOCOL_GUID, + ) { + LAST_VALID_HANDLE.store(handle.as_ptr(), Ordering::Release); + return node_to_text(protocol, path); + } + } + + Err(io::const_error!(io::ErrorKind::NotFound, "No device path to text protocol found")) +} + /// Gets RuntimeServices. pub(crate) fn runtime_services() -> Option<NonNull<r_efi::efi::RuntimeServices>> { let system_table: NonNull<r_efi::efi::SystemTable> = @@ -319,6 +373,11 @@ impl<'a> BorrowedDevicePath<'a> { pub(crate) fn to_text(&self) -> io::Result<OsString> { device_path_to_text(self.protocol) } + + #[expect(dead_code)] + pub(crate) const fn iter(&'a self) -> DevicePathIterator<'a> { + DevicePathIterator::new(DevicePathNode::new(self.protocol)) + } } impl<'a> crate::fmt::Debug for BorrowedDevicePath<'a> { @@ -330,6 +389,126 @@ impl<'a> crate::fmt::Debug for BorrowedDevicePath<'a> { } } +pub(crate) struct DevicePathIterator<'a>(Option<DevicePathNode<'a>>); + +impl<'a> DevicePathIterator<'a> { + const fn new(node: DevicePathNode<'a>) -> Self { + if node.is_end() { Self(None) } else { Self(Some(node)) } + } +} + +impl<'a> Iterator for DevicePathIterator<'a> { + type Item = DevicePathNode<'a>; + + fn next(&mut self) -> Option<Self::Item> { + let cur_node = self.0?; + + let next_node = unsafe { cur_node.next_node() }; + self.0 = if next_node.is_end() { None } else { Some(next_node) }; + + Some(cur_node) + } +} + +#[derive(Copy, Clone)] +pub(crate) struct DevicePathNode<'a> { + protocol: NonNull<r_efi::protocols::device_path::Protocol>, + phantom: PhantomData<&'a r_efi::protocols::device_path::Protocol>, +} + +impl<'a> DevicePathNode<'a> { + pub(crate) const fn new(protocol: NonNull<r_efi::protocols::device_path::Protocol>) -> Self { + Self { protocol, phantom: PhantomData } + } + + pub(crate) const fn length(&self) -> u16 { + let len = unsafe { (*self.protocol.as_ptr()).length }; + u16::from_le_bytes(len) + } + + pub(crate) const fn node_type(&self) -> u8 { + unsafe { (*self.protocol.as_ptr()).r#type } + } + + pub(crate) const fn sub_type(&self) -> u8 { + unsafe { (*self.protocol.as_ptr()).sub_type } + } + + pub(crate) fn data(&self) -> &[u8] { + let length: usize = self.length().into(); + + // Some nodes do not have any special data + if length > 4 { + let raw_ptr: *const u8 = self.protocol.as_ptr().cast(); + let data = unsafe { raw_ptr.add(4) }; + unsafe { crate::slice::from_raw_parts(data, length - 4) } + } else { + &[] + } + } + + pub(crate) const fn is_end(&self) -> bool { + self.node_type() == r_efi::protocols::device_path::TYPE_END + && self.sub_type() == r_efi::protocols::device_path::End::SUBTYPE_ENTIRE + } + + #[expect(dead_code)] + pub(crate) const fn is_end_instance(&self) -> bool { + self.node_type() == r_efi::protocols::device_path::TYPE_END + && self.sub_type() == r_efi::protocols::device_path::End::SUBTYPE_INSTANCE + } + + pub(crate) unsafe fn next_node(&self) -> Self { + let node = unsafe { + self.protocol + .cast::<u8>() + .add(self.length().into()) + .cast::<r_efi::protocols::device_path::Protocol>() + }; + Self::new(node) + } + + #[expect(dead_code)] + pub(crate) fn to_path(&'a self) -> BorrowedDevicePath<'a> { + BorrowedDevicePath::new(self.protocol) + } + + pub(crate) fn to_text(&self) -> io::Result<OsString> { + device_node_to_text(self.protocol) + } +} + +impl<'a> PartialEq for DevicePathNode<'a> { + fn eq(&self, other: &Self) -> bool { + let self_len = self.length(); + let other_len = other.length(); + + self_len == other_len + && unsafe { + compiler_builtins::mem::memcmp( + self.protocol.as_ptr().cast(), + other.protocol.as_ptr().cast(), + usize::from(self_len), + ) == 0 + } + } +} + +impl<'a> crate::fmt::Debug for DevicePathNode<'a> { + fn fmt(&self, f: &mut crate::fmt::Formatter<'_>) -> crate::fmt::Result { + match self.to_text() { + Ok(p) => p.fmt(f), + Err(_) => f + .debug_struct("DevicePathNode") + .field("type", &self.node_type()) + .field("sub_type", &self.sub_type()) + .field("length", &self.length()) + .field("specific_device_path_data", &self.data()) + .finish(), + } + } +} + pub(crate) struct OwnedProtocol<T> { guid: r_efi::efi::Guid, handle: NonNull<crate::ffi::c_void>, diff --git a/library/std/src/sys/pal/unix/os.rs b/library/std/src/sys/pal/unix/os.rs index 3a238d160cb..91f55fcd32b 100644 --- a/library/std/src/sys/pal/unix/os.rs +++ b/library/std/src/sys/pal/unix/os.rs @@ -484,7 +484,12 @@ pub fn current_exe() -> io::Result<PathBuf> { } } -#[cfg(any(target_os = "redox", target_os = "rtems"))] +#[cfg(target_os = "redox")] +pub fn current_exe() -> io::Result<PathBuf> { + crate::fs::read_to_string("/scheme/sys/exe").map(PathBuf::from) +} + +#[cfg(target_os = "rtems")] pub fn current_exe() -> io::Result<PathBuf> { crate::fs::read_to_string("sys:exe").map(PathBuf::from) } diff --git a/library/std/src/sys/pal/unix/process/process_common.rs b/library/std/src/sys/pal/unix/process/process_common.rs index 0ea9db211b3..dd41921f263 100644 --- a/library/std/src/sys/pal/unix/process/process_common.rs +++ b/library/std/src/sys/pal/unix/process/process_common.rs @@ -19,8 +19,6 @@ use crate::{fmt, io, ptr}; cfg_if::cfg_if! { if #[cfg(target_os = "fuchsia")] { // fuchsia doesn't have /dev/null - } else if #[cfg(target_os = "redox")] { - const DEV_NULL: &CStr = c"null:"; } else if #[cfg(target_os = "vxworks")] { const DEV_NULL: &CStr = c"/null"; } else { diff --git a/library/std/src/sys/path/unix.rs b/library/std/src/sys/path/unix.rs index 361e99964f1..faa2616a632 100644 --- a/library/std/src/sys/path/unix.rs +++ b/library/std/src/sys/path/unix.rs @@ -62,10 +62,7 @@ pub(crate) fn absolute(path: &Path) -> io::Result<PathBuf> { } pub(crate) fn is_absolute(path: &Path) -> bool { - if cfg!(target_os = "redox") { - // FIXME: Allow Redox prefixes - path.has_root() || crate::path::has_redox_scheme(path.as_u8_slice()) - } else if cfg!(any(unix, target_os = "hermit", target_os = "wasi")) { + if cfg!(any(unix, target_os = "hermit", target_os = "wasi")) { path.has_root() } else { path.has_root() && path.prefix().is_some() diff --git a/library/std/tests/run-time-detect.rs b/library/std/tests/run-time-detect.rs index dd14c0266aa..e59ae2f3d7f 100644 --- a/library/std/tests/run-time-detect.rs +++ b/library/std/tests/run-time-detect.rs @@ -9,6 +9,10 @@ feature(stdarch_aarch64_feature_detection) )] #![cfg_attr( + all(target_arch = "s390x", target_os = "linux"), + feature(stdarch_s390x_feature_detection) +)] +#![cfg_attr( all(target_arch = "powerpc", target_os = "linux"), feature(stdarch_powerpc_feature_detection) )] @@ -133,6 +137,32 @@ fn powerpc64_linux() { } #[test] +#[cfg(all(target_arch = "s390x", target_os = "linux"))] +fn s390x_linux() { + use std::arch::is_s390x_feature_detected; + // tidy-alphabetical-start + println!("deflate-conversion: {}", is_s390x_feature_detected!("deflate-conversion")); + println!("enhanced-sort: {}", is_s390x_feature_detected!("enhanced-sort")); + println!("guarded-storage: {}", is_s390x_feature_detected!("guarded-storage")); + println!("high-word: {}", is_s390x_feature_detected!("high-word")); + println!("nnp-assist: {}", is_s390x_feature_detected!("nnp-assist")); + println!("transactional-execution: {}", is_s390x_feature_detected!("transactional-execution")); + println!("vector-enhancements-1: {}", is_s390x_feature_detected!("vector-enhancements-1")); + println!("vector-enhancements-2: {}", is_s390x_feature_detected!("vector-enhancements-2")); + println!( + "vector-packed-decimal-enhancement-2: {}", + is_s390x_feature_detected!("vector-packed-decimal-enhancement-2") + ); + println!( + "vector-packed-decimal-enhancement: {}", + is_s390x_feature_detected!("vector-packed-decimal-enhancement") + ); + println!("vector-packed-decimal: {}", is_s390x_feature_detected!("vector-packed-decimal")); + println!("vector: {}", is_s390x_feature_detected!("vector")); + // tidy-alphabetical-end +} + +#[test] #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] fn x86_all() { use std::arch::is_x86_feature_detected; diff --git a/src/bootstrap/Cargo.toml b/src/bootstrap/Cargo.toml index 2ea2596088f..d3e2b9e05e9 100644 --- a/src/bootstrap/Cargo.toml +++ b/src/bootstrap/Cargo.toml @@ -28,11 +28,6 @@ name = "rustdoc" path = "src/bin/rustdoc.rs" test = false -[[bin]] -name = "sccache-plus-cl" -path = "src/bin/sccache-plus-cl.rs" -test = false - [dependencies] # Most of the time updating these dependencies requires modifications to the # bootstrap codebase(e.g., https://github.com/rust-lang/rust/issues/124565); diff --git a/src/bootstrap/src/bin/sccache-plus-cl.rs b/src/bootstrap/src/bin/sccache-plus-cl.rs deleted file mode 100644 index c161d69d5f7..00000000000 --- a/src/bootstrap/src/bin/sccache-plus-cl.rs +++ /dev/null @@ -1,43 +0,0 @@ -use std::env; -use std::process::{self, Command}; - -fn main() { - let target = env::var("SCCACHE_TARGET").unwrap(); - // Locate the actual compiler that we're invoking - - // SAFETY: we're in main, there are no other threads - unsafe { - env::set_var("CC", env::var_os("SCCACHE_CC").unwrap()); - env::set_var("CXX", env::var_os("SCCACHE_CXX").unwrap()); - } - - let mut cfg = cc::Build::new(); - cfg.cargo_metadata(false) - .out_dir("/") - .target(&target) - .host(&target) - .opt_level(0) - .warnings(false) - .debug(false); - let compiler = cfg.get_compiler(); - - // Invoke sccache with said compiler - let sccache_path = env::var_os("SCCACHE_PATH").unwrap(); - let mut cmd = Command::new(sccache_path); - cmd.arg(compiler.path()); - for (k, v) in compiler.env() { - cmd.env(k, v); - } - for arg in env::args().skip(1) { - cmd.arg(arg); - } - - if let Ok(s) = env::var("SCCACHE_EXTRA_ARGS") { - for s in s.split_whitespace() { - cmd.arg(s); - } - } - - let status = cmd.status().expect("failed to spawn"); - process::exit(status.code().unwrap_or(2)) -} diff --git a/src/bootstrap/src/core/build_steps/compile.rs b/src/bootstrap/src/core/build_steps/compile.rs index 20084a65b8a..7c83c53d2c2 100644 --- a/src/bootstrap/src/core/build_steps/compile.rs +++ b/src/bootstrap/src/core/build_steps/compile.rs @@ -67,7 +67,7 @@ impl Std { self } - #[allow(clippy::wrong_self_convention)] + #[expect(clippy::wrong_self_convention)] pub fn is_for_mir_opt_tests(mut self, is_for_mir_opt_tests: bool) -> Self { self.is_for_mir_opt_tests = is_for_mir_opt_tests; self diff --git a/src/bootstrap/src/core/build_steps/dist.rs b/src/bootstrap/src/core/build_steps/dist.rs index c393eb55c62..ffb60bd5634 100644 --- a/src/bootstrap/src/core/build_steps/dist.rs +++ b/src/bootstrap/src/core/build_steps/dist.rs @@ -2378,7 +2378,7 @@ impl Step for Bootstrap { let tarball = Tarball::new(builder, "bootstrap", &target.triple); let bootstrap_outdir = &builder.bootstrap_out; - for file in &["bootstrap", "rustc", "rustdoc", "sccache-plus-cl"] { + for file in &["bootstrap", "rustc", "rustdoc"] { tarball.add_file(bootstrap_outdir.join(exe(file, target)), "bootstrap/bin", 0o755); } @@ -2481,7 +2481,7 @@ impl Step for Gcc { fn run(self, builder: &Builder<'_>) -> Self::Output { let tarball = Tarball::new(builder, "gcc", &self.target.triple); let output = builder.ensure(super::gcc::Gcc { target: self.target }); - tarball.add_file(output.libgccjit, ".", 0o644); + tarball.add_file(output.libgccjit, "lib", 0o644); tarball.generate() } } diff --git a/src/bootstrap/src/core/build_steps/gcc.rs b/src/bootstrap/src/core/build_steps/gcc.rs index 5a4bc9bdbcb..0aa2a332531 100644 --- a/src/bootstrap/src/core/build_steps/gcc.rs +++ b/src/bootstrap/src/core/build_steps/gcc.rs @@ -63,11 +63,7 @@ impl Step for Gcc { } build_gcc(&metadata, builder, target); - - let lib_alias = metadata.install_dir.join("lib/libgccjit.so.0"); - if !lib_alias.exists() { - t!(builder.symlink_file(&libgccjit_path, lib_alias)); - } + create_lib_alias(builder, &libgccjit_path); t!(metadata.stamp.write()); @@ -75,6 +71,15 @@ impl Step for Gcc { } } +/// Creates a libgccjit.so.0 alias next to libgccjit.so if it does not +/// already exist +fn create_lib_alias(builder: &Builder<'_>, libgccjit: &PathBuf) { + let lib_alias = libgccjit.parent().unwrap().join("libgccjit.so.0"); + if !lib_alias.exists() { + t!(builder.symlink_file(libgccjit, lib_alias)); + } +} + pub struct Meta { stamp: BuildStamp, out_dir: PathBuf, @@ -109,8 +114,10 @@ fn try_download_gcc(builder: &Builder<'_>, target: TargetSelection) -> Option<Pa builder.config.download_ci_gcc(&sha, &root); t!(gcc_stamp.write()); } - // FIXME: put libgccjit.so into a lib directory in dist::Gcc - Some(root.join("libgccjit.so")) + + let libgccjit = root.join("lib").join("libgccjit.so"); + create_lib_alias(builder, &libgccjit); + Some(libgccjit) } #[cfg(test)] @@ -177,6 +184,14 @@ fn libgccjit_built_path(install_dir: &Path) -> PathBuf { } fn build_gcc(metadata: &Meta, builder: &Builder<'_>, target: TargetSelection) { + if builder.build.cc_tool(target).is_like_clang() + || builder.build.cxx_tool(target).is_like_clang() + { + panic!( + "Attempting to build GCC using Clang, which is known to misbehave. Please use GCC as the host C/C++ compiler. " + ); + } + let Meta { stamp: _, out_dir, install_dir, root } = metadata; t!(fs::create_dir_all(out_dir)); @@ -203,18 +218,13 @@ fn build_gcc(metadata: &Meta, builder: &Builder<'_>, target: TargetSelection) { let mut configure_cmd = command(src_dir.join("configure")); configure_cmd .current_dir(out_dir) - // On CI, we compile GCC with Clang. - // The -Wno-everything flag is needed to make GCC compile with Clang 19. - // `-g -O2` are the default flags that are otherwise used by Make. - // FIXME(kobzol): change the flags once we have [gcc] configuration in config.toml. - .env("CXXFLAGS", "-Wno-everything -g -O2") - .env("CFLAGS", "-Wno-everything -g -O2") .arg("--enable-host-shared") - .arg("--enable-languages=jit") + .arg("--enable-languages=c,jit,lto") .arg("--enable-checking=release") .arg("--disable-bootstrap") .arg("--disable-multilib") .arg(format!("--prefix={}", install_dir.display())); + let cc = builder.build.cc(target).display().to_string(); let cc = builder .build diff --git a/src/bootstrap/src/core/build_steps/llvm.rs b/src/bootstrap/src/core/build_steps/llvm.rs index 40d701f22c1..e324cf745ff 100644 --- a/src/bootstrap/src/core/build_steps/llvm.rs +++ b/src/bootstrap/src/core/build_steps/llvm.rs @@ -735,57 +735,17 @@ fn configure_cmake( None => (builder.cc(target), builder.cxx(target).unwrap()), }; - // Handle msvc + ninja + ccache specially (this is what the bots use) - if target.is_msvc() && builder.ninja() && builder.config.ccache.is_some() { - let mut wrap_cc = env::current_exe().expect("failed to get cwd"); - wrap_cc.set_file_name("sccache-plus-cl.exe"); - - cfg.define("CMAKE_C_COMPILER", sanitize_cc(&wrap_cc)) - .define("CMAKE_CXX_COMPILER", sanitize_cc(&wrap_cc)); - cfg.env("SCCACHE_PATH", builder.config.ccache.as_ref().unwrap()) - .env("SCCACHE_TARGET", target.triple) - .env("SCCACHE_CC", &cc) - .env("SCCACHE_CXX", &cxx); - - // Building LLVM on MSVC can be a little ludicrous at times. We're so far - // off the beaten path here that I'm not really sure this is even half - // supported any more. Here we're trying to: - // - // * Build LLVM on MSVC - // * Build LLVM with `clang-cl` instead of `cl.exe` - // * Build a project with `sccache` - // * Build for 32-bit as well - // * Build with Ninja - // - // For `cl.exe` there are different binaries to compile 32/64 bit which - // we use but for `clang-cl` there's only one which internally - // multiplexes via flags. As a result it appears that CMake's detection - // of a compiler's architecture and such on MSVC **doesn't** pass any - // custom flags we pass in CMAKE_CXX_FLAGS below. This means that if we - // use `clang-cl.exe` it's always diagnosed as a 64-bit compiler which - // definitely causes problems since all the env vars are pointing to - // 32-bit libraries. - // - // To hack around this... again... we pass an argument that's - // unconditionally passed in the sccache shim. This'll get CMake to - // correctly diagnose it's doing a 32-bit compilation and LLVM will - // internally configure itself appropriately. - if builder.config.llvm_clang_cl.is_some() && target.contains("i686") { - cfg.env("SCCACHE_EXTRA_ARGS", "-m32"); - } - } else { - // If ccache is configured we inform the build a little differently how - // to invoke ccache while also invoking our compilers. - if use_compiler_launcher { - if let Some(ref ccache) = builder.config.ccache { - cfg.define("CMAKE_C_COMPILER_LAUNCHER", ccache) - .define("CMAKE_CXX_COMPILER_LAUNCHER", ccache); - } + // If ccache is configured we inform the build a little differently how + // to invoke ccache while also invoking our compilers. + if use_compiler_launcher { + if let Some(ref ccache) = builder.config.ccache { + cfg.define("CMAKE_C_COMPILER_LAUNCHER", ccache) + .define("CMAKE_CXX_COMPILER_LAUNCHER", ccache); } - cfg.define("CMAKE_C_COMPILER", sanitize_cc(&cc)) - .define("CMAKE_CXX_COMPILER", sanitize_cc(&cxx)) - .define("CMAKE_ASM_COMPILER", sanitize_cc(&cc)); } + cfg.define("CMAKE_C_COMPILER", sanitize_cc(&cc)) + .define("CMAKE_CXX_COMPILER", sanitize_cc(&cxx)) + .define("CMAKE_ASM_COMPILER", sanitize_cc(&cc)); cfg.build_arg("-j").build_arg(builder.jobs().to_string()); // FIXME(madsmtm): Allow `cmake-rs` to select flags by itself by passing diff --git a/src/bootstrap/src/core/build_steps/setup.rs b/src/bootstrap/src/core/build_steps/setup.rs index e198a8dd6a5..45f9f52cb82 100644 --- a/src/bootstrap/src/core/build_steps/setup.rs +++ b/src/bootstrap/src/core/build_steps/setup.rs @@ -582,10 +582,12 @@ Select which editor you would like to set up [default: None]: "; EditorKind::Emacs => &[ "51068d4747a13732440d1a8b8f432603badb1864fa431d83d0fd4f8fa57039e0", "d29af4d949bbe2371eac928a3c31cf9496b1701aa1c45f11cd6c759865ad5c45", + "b5dd299b93dca3ceeb9b335f929293cb3d4bf4977866fbe7ceeac2a8a9f99088", ], EditorKind::Helix => &[ "2d3069b8cf1b977e5d4023965eb6199597755e6c96c185ed5f2854f98b83d233", "6736d61409fbebba0933afd2e4c44ff2f97c1cb36cf0299a7f4a7819b8775040", + "f252dcc30ca85a193a699581e5e929d5bd6c19d40d7a7ade5e257a9517a124a5", ], EditorKind::Vim | EditorKind::VsCode => &[ "ea67e259dedf60d4429b6c349a564ffcd1563cf41c920a856d1f5b16b4701ac8", @@ -598,10 +600,12 @@ Select which editor you would like to set up [default: None]: "; "811fb3b063c739d261fd8590dd30242e117908f5a095d594fa04585daa18ec4d", "4eecb58a2168b252077369da446c30ed0e658301efe69691979d1ef0443928f4", "c394386e6133bbf29ffd32c8af0bb3d4aac354cba9ee051f29612aa9350f8f8d", + "e53e9129ca5ee5dcbd6ec8b68c2d87376474eb154992deba3c6d9ab1703e0717", + ], + EditorKind::Zed => &[ + "bbce727c269d1bd0c98afef4d612eb4ce27aea3c3a8968c5f10b31affbc40b6c", + "a5380cf5dd9328731aecc5dfb240d16dac46ed272126b9728006151ef42f5909", ], - EditorKind::Zed => { - &["bbce727c269d1bd0c98afef4d612eb4ce27aea3c3a8968c5f10b31affbc40b6c"] - } } } diff --git a/src/bootstrap/src/core/build_steps/suggest.rs b/src/bootstrap/src/core/build_steps/suggest.rs index ba9b1b2fc33..6a6731cafc5 100644 --- a/src/bootstrap/src/core/build_steps/suggest.rs +++ b/src/bootstrap/src/core/build_steps/suggest.rs @@ -1,7 +1,5 @@ //! Attempt to magically identify good tests to run -#![cfg_attr(feature = "build-metrics", allow(unused))] - use std::path::PathBuf; use std::str::FromStr; diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs index e80f8f9a4b7..cff286e99fa 100644 --- a/src/bootstrap/src/core/build_steps/test.rs +++ b/src/bootstrap/src/core/build_steps/test.rs @@ -1908,8 +1908,6 @@ NOTE: if you're sure you want to do this, please open an issue as to why. In the llvm_components_passed = true; } if !builder.is_rust_llvm(target) { - // FIXME: missing Rust patches is not the same as being system llvm; we should rename the flag at some point. - // Inspecting the tests with `// no-system-llvm` in src/test *looks* like this is doing the right thing, though. cmd.arg("--system-llvm"); } @@ -3377,7 +3375,7 @@ impl Step for CodegenCranelift { /* let mut prepare_cargo = build_cargo(); prepare_cargo.arg("--").arg("prepare").arg("--download-dir").arg(&download_dir); - #[allow(deprecated)] + #[expect(deprecated)] builder.config.try_run(&mut prepare_cargo.into()).unwrap(); */ @@ -3508,7 +3506,7 @@ impl Step for CodegenGCC { /* let mut prepare_cargo = build_cargo(); prepare_cargo.arg("--").arg("prepare"); - #[allow(deprecated)] + #[expect(deprecated)] builder.config.try_run(&mut prepare_cargo.into()).unwrap(); */ diff --git a/src/bootstrap/src/core/build_steps/tool.rs b/src/bootstrap/src/core/build_steps/tool.rs index 016f09cb2a8..aaf6712102c 100644 --- a/src/bootstrap/src/core/build_steps/tool.rs +++ b/src/bootstrap/src/core/build_steps/tool.rs @@ -209,7 +209,7 @@ impl Step for ToolBuild { } } -#[allow(clippy::too_many_arguments)] // FIXME: reduce the number of args and remove this. +#[expect(clippy::too_many_arguments)] // FIXME: reduce the number of args and remove this. pub fn prepare_tool_cargo( builder: &Builder<'_>, compiler: Compiler, @@ -1024,7 +1024,7 @@ pub struct LibcxxVersionTool { pub target: TargetSelection, } -#[allow(dead_code)] +#[expect(dead_code)] #[derive(Debug, Clone)] pub enum LibcxxVersion { Gnu(usize), diff --git a/src/bootstrap/src/core/builder/mod.rs b/src/bootstrap/src/core/builder/mod.rs index 0b49751f73c..0b6b8513cc3 100644 --- a/src/bootstrap/src/core/builder/mod.rs +++ b/src/bootstrap/src/core/builder/mod.rs @@ -1285,7 +1285,6 @@ impl<'a> Builder<'a> { host: TargetSelection, target: TargetSelection, ) -> Compiler { - #![allow(clippy::let_and_return)] let mut resolved_compiler = if self.build.force_use_stage2(stage) { trace!(target: "COMPILER_FOR", ?stage, "force_use_stage2"); self.compiler(2, self.config.build) diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index a07c40bdc83..18624a7c78f 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -959,6 +959,7 @@ define_config! { jobs: Option<u32> = "jobs", compiletest_diff_tool: Option<String> = "compiletest-diff-tool", ccache: Option<StringOrBool> = "ccache", + exclude: Option<Vec<PathBuf>> = "exclude", } } @@ -1397,22 +1398,6 @@ impl Config { "flags.exclude" = ?flags.exclude ); - config.skip = flags - .skip - .into_iter() - .chain(flags.exclude) - .map(|p| { - // Never return top-level path here as it would break `--skip` - // logic on rustc's internal test framework which is utilized - // by compiletest. - if cfg!(windows) { - PathBuf::from(p.to_str().unwrap().replace('/', "\\")) - } else { - p - } - }) - .collect(); - #[cfg(feature = "tracing")] span!( target: "CONFIG_HANDLING", @@ -1658,8 +1643,29 @@ impl Config { jobs, compiletest_diff_tool, mut ccache, + exclude, } = toml.build.unwrap_or_default(); + let mut paths: Vec<PathBuf> = flags.skip.into_iter().chain(flags.exclude).collect(); + + if let Some(exclude) = exclude { + paths.extend(exclude); + } + + config.skip = paths + .into_iter() + .map(|p| { + // Never return top-level path here as it would break `--skip` + // logic on rustc's internal test framework which is utilized + // by compiletest. + if cfg!(windows) { + PathBuf::from(p.to_str().unwrap().replace('/', "\\")) + } else { + p + } + }) + .collect(); + config.jobs = Some(threads_from_config(flags.jobs.unwrap_or(jobs.unwrap_or(0)))); if let Some(file_build) = build { diff --git a/src/bootstrap/src/core/config/mod.rs b/src/bootstrap/src/core/config/mod.rs index 9f09dd13f29..179e15e778b 100644 --- a/src/bootstrap/src/core/config/mod.rs +++ b/src/bootstrap/src/core/config/mod.rs @@ -1,4 +1,4 @@ -#[allow(clippy::module_inception)] +#[expect(clippy::module_inception)] mod config; pub mod flags; #[cfg(test)] diff --git a/src/bootstrap/src/core/config/tests.rs b/src/bootstrap/src/core/config/tests.rs index eff5e033742..c7b6f3681b8 100644 --- a/src/bootstrap/src/core/config/tests.rs +++ b/src/bootstrap/src/core/config/tests.rs @@ -515,3 +515,18 @@ fn test_explicit_stage() { assert!(!config.explicit_stage_from_config); assert!(!config.is_explicit_stage()); } + +#[test] +fn test_exclude() { + let exclude_path = "compiler"; + let config = parse(&format!("build.exclude=[\"{}\"]", exclude_path)); + + let first_excluded = config + .skip + .first() + .expect("Expected at least one excluded path") + .to_str() + .expect("Failed to convert excluded path to string"); + + assert_eq!(first_excluded, exclude_path); +} diff --git a/src/bootstrap/src/core/download.rs b/src/bootstrap/src/core/download.rs index 95feb41ffd0..98eff664a5b 100644 --- a/src/bootstrap/src/core/download.rs +++ b/src/bootstrap/src/core/download.rs @@ -19,7 +19,7 @@ static SHOULD_FIX_BINS_AND_DYLIBS: OnceLock<bool> = OnceLock::new(); /// `Config::try_run` wrapper for this module to avoid warnings on `try_run`, since we don't have access to a `builder` yet. fn try_run(config: &Config, cmd: &mut Command) -> Result<(), ()> { - #[allow(deprecated)] + #[expect(deprecated)] config.try_run(cmd) } diff --git a/src/bootstrap/src/lib.rs b/src/bootstrap/src/lib.rs index fc408437838..91574f8bf5d 100644 --- a/src/bootstrap/src/lib.rs +++ b/src/bootstrap/src/lib.rs @@ -27,6 +27,7 @@ use std::{env, fs, io, str}; use build_helper::ci::gha; use build_helper::exit; +use cc::Tool; use termcolor::{ColorChoice, StandardStream, WriteColor}; use utils::build_stamp::BuildStamp; use utils::channel::GitInfo; @@ -74,7 +75,7 @@ const LLD_FILE_NAMES: &[&str] = &["ld.lld", "ld64.lld", "lld-link", "wasm-ld"]; /// Extra `--check-cfg` to add when building the compiler or tools /// (Mode restriction, config name, config values (if any)) -#[allow(clippy::type_complexity)] // It's fine for hard-coded list and type is explained above. +#[expect(clippy::type_complexity)] // It's fine for hard-coded list and type is explained above. const EXTRA_CHECK_CFGS: &[(Option<Mode>, &str, Option<&[&'static str]>)] = &[ (None, "bootstrap", None), (Some(Mode::Rustc), "llvm_enzyme", None), @@ -1218,6 +1219,16 @@ Executed at: {executed_at}"#, self.cc.borrow()[&target].path().into() } + /// Returns the internal `cc::Tool` for the C compiler. + fn cc_tool(&self, target: TargetSelection) -> Tool { + self.cc.borrow()[&target].clone() + } + + /// Returns the internal `cc::Tool` for the C++ compiler. + fn cxx_tool(&self, target: TargetSelection) -> Tool { + self.cxx.borrow()[&target].clone() + } + /// Returns C flags that `cc-rs` thinks should be enabled for the /// specified target by default. fn cc_handled_clags(&self, target: TargetSelection, c: CLang) -> Vec<String> { diff --git a/src/bootstrap/src/utils/change_tracker.rs b/src/bootstrap/src/utils/change_tracker.rs index 8036c592108..f8478725c4c 100644 --- a/src/bootstrap/src/utils/change_tracker.rs +++ b/src/bootstrap/src/utils/change_tracker.rs @@ -380,4 +380,9 @@ pub const CONFIG_CHANGE_HISTORY: &[ChangeInfo] = &[ severity: ChangeSeverity::Warning, summary: "Removed `src/tools/rls` tool as it was deprecated long time ago.", }, + ChangeInfo { + change_id: 137147, + severity: ChangeSeverity::Info, + summary: "New option `build.exclude` that adds support for excluding test.", + }, ]; diff --git a/src/bootstrap/src/utils/exec.rs b/src/bootstrap/src/utils/exec.rs index 7eb9ab96c8a..d07300e21d0 100644 --- a/src/bootstrap/src/utils/exec.rs +++ b/src/bootstrap/src/utils/exec.rs @@ -125,7 +125,7 @@ impl BootstrapCommand { Self { failure_behavior: BehaviorOnFailure::DelayFail, ..self } } - #[allow(dead_code)] + #[expect(dead_code)] pub fn fail_fast(self) -> Self { Self { failure_behavior: BehaviorOnFailure::Exit, ..self } } @@ -280,7 +280,7 @@ impl CommandOutput { !self.is_success() } - #[allow(dead_code)] + #[expect(dead_code)] pub fn status(&self) -> Option<ExitStatus> { match self.status { CommandStatus::Finished(status) => Some(status), @@ -332,7 +332,6 @@ impl Default for CommandOutput { /// Helper trait to format both Command and BootstrapCommand as a short execution line, /// without all the other details (e.g. environment variables). -#[allow(unused)] pub trait FormatShortCmd { fn format_short_cmd(&self) -> String; } diff --git a/src/bootstrap/src/utils/metrics.rs b/src/bootstrap/src/utils/metrics.rs index 57766fd63fb..885fff9c32c 100644 --- a/src/bootstrap/src/utils/metrics.rs +++ b/src/bootstrap/src/utils/metrics.rs @@ -76,7 +76,7 @@ impl BuildMetrics { // Consider all the stats gathered so far as the parent's. if !state.running_steps.is_empty() { - self.collect_stats(&mut *state); + self.collect_stats(&mut state); } state.system_info.refresh_cpu_usage(); @@ -102,7 +102,7 @@ impl BuildMetrics { let mut state = self.state.borrow_mut(); - self.collect_stats(&mut *state); + self.collect_stats(&mut state); let step = state.running_steps.pop().unwrap(); if state.running_steps.is_empty() { @@ -224,6 +224,7 @@ impl BuildMetrics { t!(serde_json::to_writer(&mut file, &json)); } + #[expect(clippy::only_used_in_recursion)] fn prepare_json_step(&self, step: StepMetrics) -> JsonNode { let mut children = Vec::new(); children.extend(step.children.into_iter().map(|child| self.prepare_json_step(child))); diff --git a/src/ci/citool/src/jobs.rs b/src/ci/citool/src/jobs.rs index 45a188fb234..0de8b740227 100644 --- a/src/ci/citool/src/jobs.rs +++ b/src/ci/citool/src/jobs.rs @@ -24,6 +24,8 @@ pub struct Job { /// Free additional disk space in the job, by removing unused packages. #[serde(default)] pub free_disk: Option<bool>, + /// Documentation link to a resource that could help people debug this CI job. + pub doc_url: Option<String>, } impl Job { @@ -103,6 +105,8 @@ struct GithubActionsJob { continue_on_error: Option<bool>, #[serde(skip_serializing_if = "Option::is_none")] free_disk: Option<bool>, + #[serde(skip_serializing_if = "Option::is_none")] + doc_url: Option<String>, } /// Skip CI jobs that are not supposed to be executed on the given `channel`. @@ -188,6 +192,7 @@ fn calculate_jobs( env, continue_on_error: job.continue_on_error, free_disk: job.free_disk, + doc_url: job.doc_url, } }) .collect(); diff --git a/src/ci/citool/src/merge_report.rs b/src/ci/citool/src/merge_report.rs index 17e42d49286..62daa2e6853 100644 --- a/src/ci/citool/src/merge_report.rs +++ b/src/ci/citool/src/merge_report.rs @@ -1,8 +1,8 @@ -use std::cmp::Reverse; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; +use std::path::PathBuf; use anyhow::Context; -use build_helper::metrics::{JsonRoot, TestOutcome}; +use build_helper::metrics::{JsonRoot, TestOutcome, TestSuiteMetadata}; use crate::jobs::JobDatabase; use crate::metrics::get_test_suites; @@ -13,8 +13,10 @@ type JobName = String; /// Computes a post merge CI analysis report between the `parent` and `current` commits. pub fn post_merge_report(job_db: JobDatabase, parent: Sha, current: Sha) -> anyhow::Result<()> { let jobs = download_all_metrics(&job_db, &parent, ¤t)?; - let diffs = aggregate_test_diffs(&jobs)?; - report_test_changes(diffs); + let aggregated_test_diffs = aggregate_test_diffs(&jobs)?; + + println!("Comparing {parent} (base) -> {current} (this PR)\n"); + report_test_diffs(aggregated_test_diffs); Ok(()) } @@ -54,7 +56,16 @@ Maybe it was newly added?"#, Ok(jobs) } +/// Downloads job metrics of the given job for the given commit. +/// Caches the result on the local disk. fn download_job_metrics(job_name: &str, sha: &str) -> anyhow::Result<JsonRoot> { + let cache_path = PathBuf::from(".citool-cache").join(sha).join(job_name).join("metrics.json"); + if let Some(cache_entry) = + std::fs::read_to_string(&cache_path).ok().and_then(|data| serde_json::from_str(&data).ok()) + { + return Ok(cache_entry); + } + let url = get_metrics_url(job_name, sha); let mut response = ureq::get(&url).call()?; if !response.status().is_success() { @@ -68,6 +79,13 @@ fn download_job_metrics(job_name: &str, sha: &str) -> anyhow::Result<JsonRoot> { .body_mut() .read_json() .with_context(|| anyhow::anyhow!("cannot deserialize metrics from {url}"))?; + + // Ignore errors if cache cannot be created + if std::fs::create_dir_all(cache_path.parent().unwrap()).is_ok() { + if let Ok(serialized) = serde_json::to_string(&data) { + let _ = std::fs::write(&cache_path, &serialized); + } + } Ok(data) } @@ -76,81 +94,80 @@ fn get_metrics_url(job_name: &str, sha: &str) -> String { format!("https://ci-artifacts.rust-lang.org/rustc-builds{suffix}/{sha}/metrics-{job_name}.json") } +/// Represents a difference in the outcome of tests between a base and a current commit. +/// Maps test diffs to jobs that contained them. +#[derive(Debug)] +struct AggregatedTestDiffs { + diffs: HashMap<TestDiff, Vec<JobName>>, +} + fn aggregate_test_diffs( jobs: &HashMap<JobName, JobMetrics>, -) -> anyhow::Result<Vec<AggregatedTestDiffs>> { - let mut job_diffs = vec![]; +) -> anyhow::Result<AggregatedTestDiffs> { + let mut diffs: HashMap<TestDiff, Vec<JobName>> = HashMap::new(); // Aggregate test suites for (name, metrics) in jobs { if let Some(parent) = &metrics.parent { let tests_parent = aggregate_tests(parent); let tests_current = aggregate_tests(&metrics.current); - let test_diffs = calculate_test_diffs(tests_parent, tests_current); - if !test_diffs.is_empty() { - job_diffs.push((name.clone(), test_diffs)); + for diff in calculate_test_diffs(tests_parent, tests_current) { + diffs.entry(diff).or_default().push(name.to_string()); } } } - // Aggregate jobs with the same diff, as often the same diff will appear in many jobs - let job_diffs: HashMap<Vec<(Test, TestOutcomeDiff)>, Vec<String>> = - job_diffs.into_iter().fold(HashMap::new(), |mut acc, (job, diffs)| { - acc.entry(diffs).or_default().push(job); - acc - }); + Ok(AggregatedTestDiffs { diffs }) +} - Ok(job_diffs - .into_iter() - .map(|(test_diffs, jobs)| AggregatedTestDiffs { jobs, test_diffs }) - .collect()) +#[derive(Eq, PartialEq, Hash, Debug)] +enum TestOutcomeDiff { + ChangeOutcome { before: TestOutcome, after: TestOutcome }, + Missing { before: TestOutcome }, + Added(TestOutcome), } -fn calculate_test_diffs( - reference: TestSuiteData, - current: TestSuiteData, -) -> Vec<(Test, TestOutcomeDiff)> { - let mut diffs = vec![]; +#[derive(Eq, PartialEq, Hash, Debug)] +struct TestDiff { + test: Test, + diff: TestOutcomeDiff, +} + +fn calculate_test_diffs(parent: TestSuiteData, current: TestSuiteData) -> HashSet<TestDiff> { + let mut diffs = HashSet::new(); for (test, outcome) in ¤t.tests { - match reference.tests.get(test) { + match parent.tests.get(test) { Some(before) => { if before != outcome { - diffs.push(( - test.clone(), - TestOutcomeDiff::ChangeOutcome { + diffs.insert(TestDiff { + test: test.clone(), + diff: TestOutcomeDiff::ChangeOutcome { before: before.clone(), after: outcome.clone(), }, - )); + }); } } - None => diffs.push((test.clone(), TestOutcomeDiff::Added(outcome.clone()))), + None => { + diffs.insert(TestDiff { + test: test.clone(), + diff: TestOutcomeDiff::Added(outcome.clone()), + }); + } } } - for (test, outcome) in &reference.tests { + for (test, outcome) in &parent.tests { if !current.tests.contains_key(test) { - diffs.push((test.clone(), TestOutcomeDiff::Missing { before: outcome.clone() })); + diffs.insert(TestDiff { + test: test.clone(), + diff: TestOutcomeDiff::Missing { before: outcome.clone() }, + }); } } diffs } -/// Represents a difference in the outcome of tests between a base and a current commit. -#[derive(Debug)] -struct AggregatedTestDiffs { - /// All jobs that had the exact same test diffs. - jobs: Vec<String>, - test_diffs: Vec<(Test, TestOutcomeDiff)>, -} - -#[derive(Eq, PartialEq, Hash, Debug)] -enum TestOutcomeDiff { - ChangeOutcome { before: TestOutcome, after: TestOutcome }, - Missing { before: TestOutcome }, - Added(TestOutcome), -} - /// Aggregates test suite executions from all bootstrap invocations in a given CI job. #[derive(Default)] struct TestSuiteData { @@ -160,6 +177,7 @@ struct TestSuiteData { #[derive(Hash, PartialEq, Eq, Debug, Clone)] struct Test { name: String, + is_doctest: bool, } /// Extracts all tests from the passed metrics and map them to their outcomes. @@ -168,7 +186,10 @@ fn aggregate_tests(metrics: &JsonRoot) -> TestSuiteData { let test_suites = get_test_suites(&metrics); for suite in test_suites { for test in &suite.tests { - let test_entry = Test { name: normalize_test_name(&test.name) }; + // Poor man's detection of doctests based on the "(line XYZ)" suffix + let is_doctest = matches!(suite.metadata, TestSuiteMetadata::CargoPackage { .. }) + && test.name.contains("(line"); + let test_entry = Test { name: normalize_test_name(&test.name), is_doctest }; tests.insert(test_entry, test.outcome.clone()); } } @@ -181,16 +202,13 @@ fn normalize_test_name(name: &str) -> String { } /// Prints test changes in Markdown format to stdout. -fn report_test_changes(mut diffs: Vec<AggregatedTestDiffs>) { +fn report_test_diffs(diff: AggregatedTestDiffs) { println!("## Test differences"); - if diffs.is_empty() { + if diff.diffs.is_empty() { println!("No test diffs found"); return; } - // Sort diffs in decreasing order by diff count - diffs.sort_by_key(|entry| Reverse(entry.test_diffs.len())); - fn format_outcome(outcome: &TestOutcome) -> String { match outcome { TestOutcome::Passed => "pass".to_string(), @@ -219,36 +237,79 @@ fn report_test_changes(mut diffs: Vec<AggregatedTestDiffs>) { } } - let max_diff_count = 10; - let max_job_count = 5; - let max_test_count = 10; - - for diff in diffs.iter().take(max_diff_count) { - let mut jobs = diff.jobs.clone(); - jobs.sort(); - - let jobs = jobs.iter().take(max_job_count).map(|j| format!("`{j}`")).collect::<Vec<_>>(); + fn format_job_group(group: u64) -> String { + format!("**J{group}**") + } - let extra_jobs = diff.jobs.len().saturating_sub(max_job_count); - let suffix = if extra_jobs > 0 { - format!(" (and {extra_jobs} {})", pluralize("other", extra_jobs)) - } else { - String::new() + // It would be quite noisy to repeat the jobs that contained the test changes after/next to + // every test diff. At the same time, grouping the test diffs by + // [unique set of jobs that contained them] also doesn't work well, because the test diffs + // would have to be duplicated several times. + // Instead, we create a set of unique job groups, and then print a job group after each test. + // We then print the job groups at the end, as a sort of index. + let mut grouped_diffs: Vec<(&TestDiff, u64)> = vec![]; + let mut job_list_to_group: HashMap<&[JobName], u64> = HashMap::new(); + let mut job_index: Vec<&[JobName]> = vec![]; + + let original_diff_count = diff.diffs.len(); + let diffs = diff + .diffs + .into_iter() + .filter(|(diff, _)| !diff.test.is_doctest) + .map(|(diff, mut jobs)| { + jobs.sort(); + (diff, jobs) + }) + .collect::<Vec<_>>(); + let doctest_count = original_diff_count.saturating_sub(diffs.len()); + + let max_diff_count = 100; + for (diff, jobs) in diffs.iter().take(max_diff_count) { + let jobs = &*jobs; + let job_group = match job_list_to_group.get(jobs.as_slice()) { + Some(id) => *id, + None => { + let id = job_index.len() as u64; + job_index.push(jobs); + job_list_to_group.insert(jobs, id); + id + } }; - println!("- {}{suffix}", jobs.join(",")); + grouped_diffs.push((diff, job_group)); + } - let extra_tests = diff.test_diffs.len().saturating_sub(max_test_count); - for (test, outcome_diff) in diff.test_diffs.iter().take(max_test_count) { - println!(" - {}: {}", test.name, format_diff(&outcome_diff)); - } - if extra_tests > 0 { - println!(" - (and {extra_tests} additional {})", pluralize("tests", extra_tests)); - } + // Sort diffs by job group and test name + grouped_diffs.sort_by(|(d1, g1), (d2, g2)| g1.cmp(&g2).then(d1.test.name.cmp(&d2.test.name))); + + for (diff, job_group) in grouped_diffs { + println!( + "- `{}`: {} ({})", + diff.test.name, + format_diff(&diff.diff), + format_job_group(job_group) + ); } let extra_diffs = diffs.len().saturating_sub(max_diff_count); if extra_diffs > 0 { - println!("\n(and {extra_diffs} additional {})", pluralize("diff", extra_diffs)); + println!("\n(and {extra_diffs} additional {})", pluralize("test diff", extra_diffs)); + } + + if doctest_count > 0 { + println!( + "\nAdditionally, {doctest_count} doctest {} were found. These are ignored, as they are noisy.", + pluralize("diff", doctest_count) + ); + } + + // Now print the job group index + println!("\n**Job group index**\n"); + for (group, jobs) in job_index.into_iter().enumerate() { + println!( + "- {}: {}", + format_job_group(group as u64), + jobs.iter().map(|j| format!("`{j}`")).collect::<Vec<_>>().join(", ") + ); } } diff --git a/src/ci/citool/tests/jobs.rs b/src/ci/citool/tests/jobs.rs index 1d81d58f893..788f5e7e4f6 100644 --- a/src/ci/citool/tests/jobs.rs +++ b/src/ci/citool/tests/jobs.rs @@ -40,7 +40,7 @@ try-job: dist-i686-msvc"#, fn pr_jobs() { let stdout = get_matrix("pull_request", "commit", "refs/heads/pr/1234"); insta::assert_snapshot!(stdout, @r#" - jobs=[{"name":"mingw-check","full_name":"PR - mingw-check","os":"ubuntu-24.04","env":{"PR_CI_JOB":1},"free_disk":true},{"name":"mingw-check-tidy","full_name":"PR - mingw-check-tidy","os":"ubuntu-24.04","env":{"PR_CI_JOB":1},"continue_on_error":true,"free_disk":true}] + jobs=[{"name":"mingw-check","full_name":"PR - mingw-check","os":"ubuntu-24.04","env":{"PR_CI_JOB":1},"free_disk":true},{"name":"mingw-check-tidy","full_name":"PR - mingw-check-tidy","os":"ubuntu-24.04","env":{"PR_CI_JOB":1},"continue_on_error":true,"free_disk":true,"doc_url":"https://foo.bar"}] run_type=pr "#); } diff --git a/src/ci/citool/tests/test-jobs.yml b/src/ci/citool/tests/test-jobs.yml index 56b9ced2071..ff4d1772f59 100644 --- a/src/ci/citool/tests/test-jobs.yml +++ b/src/ci/citool/tests/test-jobs.yml @@ -75,6 +75,7 @@ pr: <<: *job-linux-4c - name: mingw-check-tidy continue_on_error: true + doc_url: https://foo.bar <<: *job-linux-4c # Jobs that run when you perform a try build (@bors try) diff --git a/src/ci/docker/host-aarch64/aarch64-gnu-debug/Dockerfile b/src/ci/docker/host-aarch64/aarch64-gnu-debug/Dockerfile index eb39861d8c7..cf030f6830e 100644 --- a/src/ci/docker/host-aarch64/aarch64-gnu-debug/Dockerfile +++ b/src/ci/docker/host-aarch64/aarch64-gnu-debug/Dockerfile @@ -30,7 +30,6 @@ COPY scripts/sccache.sh /scripts/ RUN sh /scripts/sccache.sh ENV RUSTBUILD_FORCE_CLANG_BASED_TESTS 1 -ENV RUN_CHECK_WITH_PARALLEL_QUERIES 1 # llvm.use-linker conflicts with downloading CI LLVM ENV NO_DOWNLOAD_CI_LLVM 1 diff --git a/src/ci/docker/host-x86_64/dist-x86_64-linux/Dockerfile b/src/ci/docker/host-x86_64/dist-x86_64-linux/Dockerfile index f54ecef1e30..ae5bf8946dd 100644 --- a/src/ci/docker/host-x86_64/dist-x86_64-linux/Dockerfile +++ b/src/ci/docker/host-x86_64/dist-x86_64-linux/Dockerfile @@ -101,7 +101,9 @@ ENV SCRIPT python3 ../x.py build --set rust.debug=true opt-dist && \ ./build/$HOSTS/stage0-tools-bin/opt-dist linux-ci -- python3 ../x.py dist \ --host $HOSTS --target $HOSTS \ --include-default-paths \ - build-manifest bootstrap gcc + build-manifest bootstrap && \ + # Use GCC for building GCC, as it seems to behave badly when built with Clang + CC=/rustroot/bin/cc CXX=/rustroot/bin/c++ python3 ../x.py dist gcc ENV CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_LINKER=clang # This is the only builder which will create source tarballs diff --git a/src/ci/docker/host-x86_64/dist-x86_64-netbsd/build-netbsd-toolchain.sh b/src/ci/docker/host-x86_64/dist-x86_64-netbsd/build-netbsd-toolchain.sh index 4a42f5da29f..ad21836253b 100755 --- a/src/ci/docker/host-x86_64/dist-x86_64-netbsd/build-netbsd-toolchain.sh +++ b/src/ci/docker/host-x86_64/dist-x86_64-netbsd/build-netbsd-toolchain.sh @@ -41,8 +41,6 @@ cd netbsd mkdir -p /x-tools/x86_64-unknown-netbsd/sysroot -# URL=https://ci-mirrors.rust-lang.org/rustc - # Hashes come from https://cdn.netbsd.org/pub/NetBSD/security/hashes/NetBSD-9.0_hashes.asc SRC_SHA=2c791ae009a6929c6fc893ec5df7e62910ee8207e0b2159d6937309c03efe175b6ae1e445829a13d041b6851334ad35c521f2fa03c97675d4a05f1fafe58ede0 GNUSRC_SHA=3710085a73feecf6a843415271ec794c90146b03f6bbd30f07c9e0c79febf8995d557e40194f1e05db655e4f5ef2fae97563f8456fceaae65d4ea98857a83b1c @@ -51,22 +49,16 @@ SYSSRC_SHA=60b9ddf4cc6402256473e2e1eefeabd9001aa4e205208715ecc6d6fc3f5b400e46994 BASE_SHA=b5926b107cebf40c3c19b4f6cd039b610987dd7f819e7cdde3bd1e5230a856906e7930b15ab242d52ced9f0bda01d574be59488b8dbb95fa5df2987d0a70995f COMP_SHA=38ea54f30d5fc2afea87e5096f06873e00182789e8ad9cec0cb3e9f7c538c1aa4779e63fd401a36ba02676158e83fa5c95e8e87898db59c1914fb206aecd82d2 -# FIXME: the archive URL is being used temporarily while the CDN is down. -# We should serve this from our own CDN -# SOURCE_URL=https://cdn.netbsd.org/pub/NetBSD/NetBSD-9.0/source/sets -SOURCE_URL=http://archive.netbsd.org/pub/NetBSD-archive/NetBSD-9.0/source/sets -download src.tgz "$SOURCE_URL/src.tgz" "$SRC_SHA" tar xzf src.tgz -download gnusrc.tgz "$SOURCE_URL/gnusrc.tgz" "$GNUSRC_SHA" tar xzf gnusrc.tgz -download sharesrc.tgz "$SOURCE_URL/sharesrc.tgz" "$SHARESRC_SHA" tar xzf sharesrc.tgz -download syssrc.tgz "$SOURCE_URL/syssrc.tgz" "$SYSSRC_SHA" tar xzf syssrc.tgz - -# FIXME: the archive URL is being used temporarily while the CDN is down. -# We should serve this from our own CDN -# BINARY_URL=https://cdn.netbsd.org/pub/NetBSD/NetBSD-9.0/amd64/binary/sets -BINARY_URL=http://archive.netbsd.org/pub/NetBSD-archive/NetBSD-9.0/amd64/binary/sets -download base.tar.xz "$BINARY_URL/base.tar.xz" "$BASE_SHA" \ +SOURCE_URL=https://ci-mirrors.rust-lang.org/rustc/2025-03-14-netbsd-9.0-src +download src.tgz "$SOURCE_URL-src.tgz" "$SRC_SHA" tar xzf src.tgz +download gnusrc.tgz "$SOURCE_URL-gnusrc.tgz" "$GNUSRC_SHA" tar xzf gnusrc.tgz +download sharesrc.tgz "$SOURCE_URL-sharesrc.tgz" "$SHARESRC_SHA" tar xzf sharesrc.tgz +download syssrc.tgz "$SOURCE_URL-syssrc.tgz" "$SYSSRC_SHA" tar xzf syssrc.tgz + +BINARY_URL=https://ci-mirrors.rust-lang.org/rustc/2025-03-14-netbsd-9.0-amd64-binary +download base.tar.xz "$BINARY_URL-base.tar.xz" "$BASE_SHA" \ tar xJf base.tar.xz -C /x-tools/x86_64-unknown-netbsd/sysroot ./usr/include ./usr/lib ./lib -download comp.tar.xz "$BINARY_URL/comp.tar.xz" "$COMP_SHA" \ +download comp.tar.xz "$BINARY_URL-comp.tar.xz" "$COMP_SHA" \ tar xJf comp.tar.xz -C /x-tools/x86_64-unknown-netbsd/sysroot ./usr/include ./usr/lib cd usr/src diff --git a/src/ci/docker/host-x86_64/mingw-check/Dockerfile b/src/ci/docker/host-x86_64/mingw-check/Dockerfile index 9234c6dc921..b32fa6c8e4e 100644 --- a/src/ci/docker/host-x86_64/mingw-check/Dockerfile +++ b/src/ci/docker/host-x86_64/mingw-check/Dockerfile @@ -41,8 +41,6 @@ COPY host-x86_64/mingw-check/check-default-config-profiles.sh /scripts/ COPY host-x86_64/mingw-check/validate-toolstate.sh /scripts/ COPY host-x86_64/mingw-check/validate-error-codes.sh /scripts/ -ENV RUN_CHECK_WITH_PARALLEL_QUERIES 1 - # Check library crates on all tier 1 targets. # We disable optimized compiler built-ins because that requires a C toolchain for the target. # We also skip the x86_64-unknown-linux-gnu target as it is well-tested by other jobs. diff --git a/src/ci/docker/host-x86_64/x86_64-gnu-debug/Dockerfile b/src/ci/docker/host-x86_64/x86_64-gnu-debug/Dockerfile index 292dbfd20a5..b97568b0819 100644 --- a/src/ci/docker/host-x86_64/x86_64-gnu-debug/Dockerfile +++ b/src/ci/docker/host-x86_64/x86_64-gnu-debug/Dockerfile @@ -30,7 +30,6 @@ COPY scripts/sccache.sh /scripts/ RUN sh /scripts/sccache.sh ENV RUSTBUILD_FORCE_CLANG_BASED_TESTS 1 -ENV RUN_CHECK_WITH_PARALLEL_QUERIES 1 # llvm.use-linker conflicts with downloading CI LLVM ENV NO_DOWNLOAD_CI_LLVM 1 diff --git a/src/ci/docker/run.sh b/src/ci/docker/run.sh index 6658b83efc8..2805bb1118d 100755 --- a/src/ci/docker/run.sh +++ b/src/ci/docker/run.sh @@ -361,6 +361,7 @@ docker \ --env TOOLSTATE_PUBLISH \ --env RUST_CI_OVERRIDE_RELEASE_CHANNEL \ --env CI_JOB_NAME="${CI_JOB_NAME-$IMAGE}" \ + --env CI_JOB_DOC_URL="${CI_JOB_DOC_URL}" \ --env BASE_COMMIT="$BASE_COMMIT" \ --env DIST_TRY_BUILD \ --env PR_CI_JOB \ diff --git a/src/ci/docker/scripts/sccache.sh b/src/ci/docker/scripts/sccache.sh index f66671c64d2..dba617d8bc8 100644 --- a/src/ci/docker/scripts/sccache.sh +++ b/src/ci/docker/scripts/sccache.sh @@ -6,10 +6,10 @@ set -ex case "$(uname -m)" in x86_64) - url="https://ci-mirrors.rust-lang.org/rustc/2025-01-07-sccache-v0.9.1-x86_64-unknown-linux-musl" + url="https://ci-mirrors.rust-lang.org/rustc/2025-02-24-sccache-v0.10.0-x86_64-unknown-linux-musl" ;; aarch64) - url="https://ci-mirrors.rust-lang.org/rustc/2025-01-07-sccache-v0.9.1-aarch64-unknown-linux-musl" + url="https://ci-mirrors.rust-lang.org/rustc/2025-02-24-sccache-v0.10.0-aarch64-unknown-linux-musl" ;; *) echo "unsupported architecture: $(uname -m)" diff --git a/src/ci/github-actions/jobs.yml b/src/ci/github-actions/jobs.yml index eba55338ff8..d8c3625af28 100644 --- a/src/ci/github-actions/jobs.yml +++ b/src/ci/github-actions/jobs.yml @@ -267,11 +267,13 @@ auto: # nightly features to compile, and this job would fail if # executed on beta and stable. only_on_channel: nightly + doc_url: https://rustc-dev-guide.rust-lang.org/tests/fuchsia.html <<: *job-linux-8c # Tests integration with Rust for Linux. # Builds stage 1 compiler and tries to compile a few RfL examples with it. - name: x86_64-rust-for-linux + doc_url: https://rustc-dev-guide.rust-lang.org/tests/rust-for-linux.html <<: *job-linux-4c - name: x86_64-gnu diff --git a/src/ci/run.sh b/src/ci/run.sh index b874f71832d..63e79c737d6 100755 --- a/src/ci/run.sh +++ b/src/ci/run.sh @@ -6,6 +6,10 @@ if [ -n "$CI_JOB_NAME" ]; then echo "[CI_JOB_NAME=$CI_JOB_NAME]" fi +if [ -n "$CI_JOB_DOC_URL" ]; then + echo "[CI_JOB_DOC_URL=$CI_JOB_DOC_URL]" +fi + if [ "$NO_CHANGE_USER" = "" ]; then if [ "$LOCAL_USER_ID" != "" ]; then id -u user &>/dev/null || useradd --shell /bin/bash -u $LOCAL_USER_ID -o -c "" -m user @@ -54,13 +58,8 @@ if [ "$FORCE_CI_RUSTC" == "" ]; then DISABLE_CI_RUSTC_IF_INCOMPATIBLE=1 fi -if ! isCI || isCiBranch auto || isCiBranch beta || isCiBranch try || isCiBranch try-perf || \ - isCiBranch automation/bors/try; then - RUST_CONFIGURE_ARGS="$RUST_CONFIGURE_ARGS --set build.print-step-timings --enable-verbose-tests" - RUST_CONFIGURE_ARGS="$RUST_CONFIGURE_ARGS --set build.metrics" - HAS_METRICS=1 -fi - +RUST_CONFIGURE_ARGS="$RUST_CONFIGURE_ARGS --set build.print-step-timings --enable-verbose-tests" +RUST_CONFIGURE_ARGS="$RUST_CONFIGURE_ARGS --set build.metrics" RUST_CONFIGURE_ARGS="$RUST_CONFIGURE_ARGS --enable-verbose-configure" RUST_CONFIGURE_ARGS="$RUST_CONFIGURE_ARGS --enable-sccache" RUST_CONFIGURE_ARGS="$RUST_CONFIGURE_ARGS --disable-manage-submodules" @@ -261,23 +260,6 @@ else do_make "$RUST_CHECK_TARGET" fi -if [ "$RUN_CHECK_WITH_PARALLEL_QUERIES" != "" ]; then - rm -f config.toml - $SRC/configure --set change-id=99999999 - - # Save the build metrics before we wipe the directory - if [ "$HAS_METRICS" = 1 ]; then - mv build/metrics.json . - fi - rm -rf build - if [ "$HAS_METRICS" = 1 ]; then - mkdir build - mv metrics.json build - fi - - CARGO_INCREMENTAL=0 ../x check -fi - echo "::group::sccache stats" -sccache --show-stats || true +sccache --show-adv-stats || true echo "::endgroup::" diff --git a/src/ci/scripts/install-sccache.sh b/src/ci/scripts/install-sccache.sh index e143152f330..b055e76a805 100755 --- a/src/ci/scripts/install-sccache.sh +++ b/src/ci/scripts/install-sccache.sh @@ -8,11 +8,13 @@ IFS=$'\n\t' source "$(cd "$(dirname "$0")" && pwd)/../shared.sh" if isMacOS; then - curl -fo /usr/local/bin/sccache "${MIRRORS_BASE}/2021-08-25-sccache-v0.2.15-x86_64-apple-darwin" + curl -fo /usr/local/bin/sccache \ + "${MIRRORS_BASE}/2025-02-24-sccache-v0.10.0-x86_64-apple-darwin" chmod +x /usr/local/bin/sccache elif isWindows; then mkdir -p sccache - curl -fo sccache/sccache.exe "${MIRRORS_BASE}/2018-04-26-sccache-x86_64-pc-windows-msvc" + curl -fo sccache/sccache.exe \ + "${MIRRORS_BASE}/2025-02-24-sccache-v0.10.0-x86_64-pc-windows-msvc.exe" ciCommandAddPath "$(pwd)/sccache" fi diff --git a/src/doc/rustc-dev-guide/README.md b/src/doc/rustc-dev-guide/README.md index 2464ffbbc50..6a25a91f56a 100644 --- a/src/doc/rustc-dev-guide/README.md +++ b/src/doc/rustc-dev-guide/README.md @@ -82,6 +82,7 @@ cargo +stable install josh-proxy --git https://github.com/josh-project/josh --ta Older versions of `josh-proxy` may not round trip commits losslessly so it is important to install this exact version. ### Pull changes from `rust-lang/rust` into this repository + 1) Checkout a new branch that will be used to create a PR into `rust-lang/rustc-dev-guide` 2) Run the pull command ``` @@ -95,3 +96,15 @@ Older versions of `josh-proxy` may not round trip commits losslessly so it is im $ cargo run --manifest-path josh-sync/Cargo.toml rustc-push <branch-name> <gh-username> ``` 2) Create a PR from `<branch-name>` into `rust-lang/rust` + +#### Minimal git config + +For simplicity (ease of implementation purposes), the josh-sync script simply calls out to system git. This means that the git invocation may be influenced by global (or local) git configuration. + +You may observe "Nothing to pull" even if you *know* rustc-pull has something to pull if your global git config sets `fetch.prunetags = true` (and possibly other configurations may cause unexpected outcomes). + +To minimize the likelihood of this happening, you may wish to keep a separate *minimal* git config that *only* has `[user]` entries from global git config, then repoint system git to use the minimal git config instead. E.g. + +``` +$ GIT_CONFIG_GLOBAL=/path/to/minimal/gitconfig GIT_CONFIG_SYSTEM='' cargo +stable run --manifest-path josh-sync/Cargo.toml -- rustc-pull +``` diff --git a/src/doc/rustc-dev-guide/rust-version b/src/doc/rustc-dev-guide/rust-version index ce21bb8ef39..eb779d9ab05 100644 --- a/src/doc/rustc-dev-guide/rust-version +++ b/src/doc/rustc-dev-guide/rust-version @@ -1 +1 @@ -4ecd70ddd1039a3954056c1071e40278048476fa +8536f201ffdb2c24925d7f9e87996d7dca93428b diff --git a/src/doc/rustc-dev-guide/src/SUMMARY.md b/src/doc/rustc-dev-guide/src/SUMMARY.md index 106db508ebb..ce74c741b39 100644 --- a/src/doc/rustc-dev-guide/src/SUMMARY.md +++ b/src/doc/rustc-dev-guide/src/SUMMARY.md @@ -178,7 +178,7 @@ - [Inference details](./opaque-types-impl-trait-inference.md) - [Return Position Impl Trait In Trait](./return-position-impl-trait-in-trait.md) - [Region inference restrictions][opaque-infer] -- [Effect checking](./effects.md) +- [Const condition checking](./effects.md) - [Pattern and Exhaustiveness Checking](./pat-exhaustive-checking.md) - [Unsafety Checking](./unsafety-checking.md) - [MIR dataflow](./mir/dataflow.md) diff --git a/src/doc/rustc-dev-guide/src/backend/updating-llvm.md b/src/doc/rustc-dev-guide/src/backend/updating-llvm.md index 92d4ce32f92..0b45956b160 100644 --- a/src/doc/rustc-dev-guide/src/backend/updating-llvm.md +++ b/src/doc/rustc-dev-guide/src/backend/updating-llvm.md @@ -116,14 +116,14 @@ so let's go through each in detail. at the time of the branch, and the remaining part is the current date. -2. Apply Rust-specific patches to the llvm-project repository. +1. Apply Rust-specific patches to the llvm-project repository. All features and bugfixes are upstream, but there's often some weird build-related patches that don't make sense to upstream. These patches are typically the latest patches in the rust-lang/llvm-project branch that rustc is currently using. -3. Build the new LLVM in the `rust` repository. +1. Build the new LLVM in the `rust` repository. To do this, you'll want to update the `src/llvm-project` repository to your branch, and the revision you've created. @@ -151,7 +151,7 @@ so let's go through each in detail. download-ci-llvm = false ``` -4. Test for regressions across other platforms. LLVM often has at least one bug +1. Test for regressions across other platforms. LLVM often has at least one bug for non-tier-1 architectures, so it's good to do some more testing before sending this to bors! If you're low on resources you can send the PR as-is now to bors, though, and it'll get tested anyway. @@ -170,22 +170,17 @@ so let's go through each in detail. * `./src/ci/docker/run.sh dist-various-2` * `./src/ci/docker/run.sh armhf-gnu` -5. Prepare a PR to `rust-lang/rust`. Work with maintainers of +1. Prepare a PR to `rust-lang/rust`. Work with maintainers of `rust-lang/llvm-project` to get your commit in a branch of that repository, and then you can send a PR to `rust-lang/rust`. You'll change at least `src/llvm-project` and will likely also change [`llvm-wrapper`] as well. - <!-- date-check: Sep 2024 --> + <!-- date-check: mar 2025 --> > For prior art, here are some previous LLVM updates: - > - [LLVM 11](https://github.com/rust-lang/rust/pull/73526) - > - [LLVM 12](https://github.com/rust-lang/rust/pull/81451) - > - [LLVM 13](https://github.com/rust-lang/rust/pull/87570) - > - [LLVM 14](https://github.com/rust-lang/rust/pull/93577) - > - [LLVM 15](https://github.com/rust-lang/rust/pull/99464) - > - [LLVM 16](https://github.com/rust-lang/rust/pull/109474) > - [LLVM 17](https://github.com/rust-lang/rust/pull/115959) > - [LLVM 18](https://github.com/rust-lang/rust/pull/120055) > - [LLVM 19](https://github.com/rust-lang/rust/pull/127513) + > - [LLVM 20](https://github.com/rust-lang/rust/pull/135763) Note that sometimes it's easiest to land [`llvm-wrapper`] compatibility as a PR before actually updating `src/llvm-project`. @@ -194,7 +189,7 @@ so let's go through each in detail. others interested in trying out the new LLVM can benefit from work you've done to update the C++ bindings. -3. Over the next few months, +1. Over the next few months, LLVM will continually push commits to its `release/a.b` branch. We will often want to have those bug fixes as well. The merge process for that is to use `git merge` itself to merge LLVM's @@ -202,9 +197,9 @@ so let's go through each in detail. This is typically done multiple times when necessary while LLVM's release branch is baking. -4. LLVM then announces the release of version `a.b`. +1. LLVM then announces the release of version `a.b`. -5. After LLVM's official release, +1. After LLVM's official release, we follow the process of creating a new branch on the rust-lang/llvm-project repository again, this time with a new date. diff --git a/src/doc/rustc-dev-guide/src/building/bootstrapping/debugging-bootstrap.md b/src/doc/rustc-dev-guide/src/building/bootstrapping/debugging-bootstrap.md index 24b9783ddf0..35d33ebdb0e 100644 --- a/src/doc/rustc-dev-guide/src/building/bootstrapping/debugging-bootstrap.md +++ b/src/doc/rustc-dev-guide/src/building/bootstrapping/debugging-bootstrap.md @@ -129,7 +129,7 @@ Both `tracing::*` macros and the `tracing::instrument` proc-macro attribute need ```rs #[cfg(feature = "tracing")] -use tracing::{instrument, trace}; +use tracing::instrument; struct Foo; @@ -138,7 +138,6 @@ impl Step for Foo { #[cfg_attr(feature = "tracing", instrument(level = "trace", name = "Foo::should_run", skip_all))] fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { - #[cfg(feature = "tracing")] trace!(?run, "entered Foo::should_run"); todo!() @@ -154,7 +153,6 @@ impl Step for Foo { ), )] fn run(self, builder: &Builder<'_>) -> Self::Output { - #[cfg(feature = "tracing")] trace!(?run, "entered Foo::run"); todo!() diff --git a/src/doc/rustc-dev-guide/src/building/new-target.md b/src/doc/rustc-dev-guide/src/building/new-target.md index cd215277e69..14d10d4a59d 100644 --- a/src/doc/rustc-dev-guide/src/building/new-target.md +++ b/src/doc/rustc-dev-guide/src/building/new-target.md @@ -4,12 +4,11 @@ These are a set of steps to add support for a new target. There are numerous end states and paths to get there, so not all sections may be relevant to your desired goal. -See also the associated documentation in the -[target tier policy][target_tier_policy_add]. +See also the associated documentation in the [target tier policy]. <!-- toc --> -[target_tier_policy_add]: https://doc.rust-lang.org/rustc/target-tier-policy.html#adding-a-new-target +[target tier policy]: https://doc.rust-lang.org/rustc/target-tier-policy.html#adding-a-new-target ## Specifying a new LLVM diff --git a/src/doc/rustc-dev-guide/src/effects.md b/src/doc/rustc-dev-guide/src/effects.md index 1fda7bcbb13..c7aa2714668 100644 --- a/src/doc/rustc-dev-guide/src/effects.md +++ b/src/doc/rustc-dev-guide/src/effects.md @@ -1,66 +1,159 @@ -# Effects and effect checking - -Note: all of this describes the implementation of the unstable `effects` and -`const_trait_impl` features. None of this implementation is usable or visible from -stable Rust. - -The implementation of const traits and `~const` bounds is a limited effect system. -It is used to allow trait bounds on `const fn` to be used within the `const fn` for -method calls. Within the function, in order to know whether a method on a trait -bound is `const`, we need to know whether there is a `~const` bound for the trait. -In order to know whether we can instantiate a `~const` bound on a `const fn`, we -need to know whether there is a `const_trait` impl for the type and trait being -used (or whether the `const fn` is used at runtime, then any type implementing the -trait is ok, just like with other bounds). - -We perform these checks via a const generic boolean that gets attached to all -`const fn` and `const trait`. The following sections will explain the desugarings -and the way we perform the checks at call sites. - -The const generic boolean is inverted to the meaning of `const`. In the compiler -it is called `host`, because it enables "host APIs" like `static` items, network -access, disk access, random numbers and everything else that isn't available in -`const` contexts. So `false` means "const", `true` means "not const" and if it's -a generic parameter, it means "maybe const" (meaning we're in a const fn or const -trait). - -## `const fn` - -All `const fn` have a `#[rustc_host] const host: bool` generic parameter that is -hidden from users. Any `~const Trait` bounds in the generics list or `where` bounds -of a `const fn` get converted to `Trait<host> + Trait<true>` bounds. The `Trait<true>` -exists so that associated types of the generic param can be used from projections -like `<T as Trait>::Assoc`, because there are no `<T as ~const Trait>` projections for now. - -## `#[const_trait] trait`s - -The `#[const_trait]` attribute gives the marked trait a `#[rustc_host] const host: bool` -generic parameter. All functions of the trait "inherit" this generic parameter, just like -they have all the regular generic parameters of the trait. Any `~const Trait` super-trait -bounds get desugared to `Trait<host> + Trait<true>` in order to allow using associated -types and consts of the super traits in the trait declaration. This is necessary, because -`<Self as SuperTrait>::Assoc` is always `<Self as SuperTrait<true>>::Assoc` as there is -no `<Self as ~const SuperTrait>` syntax. - -## `typeck` performing method and function call checks. - -When generic parameters are instantiated for any items, the `host` generic parameter -is always instantiated as an inference variable. This is a special kind of inference var -that is not part of the type or const inference variables, similar to how we have -special inference variables for type variables that we know to be an integer, but not -yet which one. These separate inference variables fall back to `true` at -the end of typeck (in `fallback_effects`) to ensure that `let _ = some_fn_item_name;` -will keep compiling. - -All actually used (in function calls, casts, or anywhere else) function items, will -have the `enforce_context_effects` method invoked. -It trivially returns if the function being called has no `host` generic parameter. - -In order to error if a non-const function is called in a const context, we have not -yet disabled the const-check logic that happens on MIR, because -`enforce_context_effects` does not yet perform this check. - -The function call's `host` parameter is then equated to the context's `host` value, -which almost always trivially succeeds, as it was an inference var. If the inference -var has already been bound (since the function item is invoked twice), the second -invocation checks it against the first. +# Effects and const condition checking + +## The `HostEffect` predicate + +[`HostEffectPredicate`]s are a kind of predicate from `~const Tr` or `const Tr` +bounds. It has a trait reference, and a `constness` which could be `Maybe` or +`Const` depending on the bound. Because `~const Tr`, or rather `Maybe` bounds +apply differently based on whichever contexts they are in, they have different +behavior than normal bounds. Where normal trait bounds on a function such as +`T: Tr` are collected within the [`predicates_of`] query to be proven when a +function is called and to be assumed within the function, bounds such as +`T: ~const Tr` will behave as a normal trait bound and add `T: Tr` to the result +from `predicates_of`, but also adds a `HostEffectPredicate` to the +[`const_conditions`] query. + +On the other hand, `T: const Tr` bounds do not change meaning across contexts, +therefore they will result in `HostEffect(T: Tr, const)` being added to +`predicates_of`, and not `const_conditions`. + +[`HostEffectPredicate`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_type_ir/predicate/struct.HostEffectPredicate.html +[`predicates_of`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/struct.TyCtxt.html#method.predicates_of +[`const_conditions`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/struct.TyCtxt.html#method.const_conditions + +## The `const_conditions` query + +`predicates_of` represents a set of predicates that need to be proven to use an +item. For example, to use `foo` in the example below: + +```rust +fn foo<T>() where T: Default {} +``` + +We must be able to prove that `T` implements `Default`. In a similar vein, +`const_conditions` represents a set of predicates that need to be proven to use +an item *in const contexts*. If we adjust the example above to use `const` trait +bounds: + +```rust +const fn foo<T>() where T: ~const Default {} +``` + +Then `foo` would get a `HostEffect(T: Default, maybe)` in the `const_conditions` +query, suggesting that in order to call `foo` from const contexts, one must +prove that `T` has a const implementation of `Default`. + +## Enforcement of `const_conditions` + +`const_conditions` are currently checked in various places. + +Every call in HIR from a const context (which includes `const fn` and `const` +items) will check that `const_conditions` of the function we are calling hold. +This is done in [`FnCtxt::enforce_context_effects`]. Note that we don't check +if the function is only referred to but not called, as the following code needs +to compile: + +```rust +const fn hi<T: ~const Default>() -> T { + T::default() +} +const X: fn() -> u32 = hi::<u32>; +``` + +For a trait `impl` to be well-formed, we must be able to prove the +`const_conditions` of the trait from the `impl`'s environment. This is checked +in [`wfcheck::check_impl`]. + +Here's an example: + +```rust +#[const_trait] +trait Bar {} +#[const_trait] +trait Foo: ~const Bar {} +// `const_conditions` contains `HostEffect(Self: Bar, maybe)` + +impl const Bar for () {} +impl const Foo for () {} +// ^ here we check `const_conditions` for the impl to be well-formed +``` + +Methods of trait impls must not have stricter bounds than the method of the +trait that they are implementing. To check that the methods are compatible, a +hybrid environment is constructed with the predicates of the `impl` plus the +predicates of the trait method, and we attempt to prove the predicates of the +impl method. We do the same for `const_conditions`: + +```rust +#[const_trait] +trait Foo { + fn hi<T: ~const Default>(); +} + +impl<T: ~const Clone> Foo for Vec<T> { + fn hi<T: ~const PartialEq>(); + // ^ we can't prove `T: ~const PartialEq` given `T: ~const Clone` and + // `T: ~const Default`, therefore we know that the method on the impl + // is stricter than the method on the trait. +} +``` + +These checks are done in [`compare_method_predicate_entailment`]. A similar +function that does the same check for associated types is called +[`compare_type_predicate_entailment`]. Both of these need to consider +`const_conditions` when in const contexts. + +In MIR, as part of const checking, `const_conditions` of items that are called +are revalidated again in [`Checker::revalidate_conditional_constness`]. + +[`compare_method_predicate_entailment`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir_analysis/check/compare_impl_item/fn.compare_method_predicate_entailment.html +[`compare_type_predicate_entailment`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir_analysis/check/compare_impl_item/fn.compare_type_predicate_entailment.html +[`FnCtxt::enforce_context_effects`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir_typeck/fn_ctxt/struct.FnCtxt.html#method.enforce_context_effects +[`wfcheck::check_impl`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir_analysis/check/wfcheck/fn.check_impl.html +[`Checker::revalidate_conditional_constness`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_const_eval/check_consts/check/struct.Checker.html#method.revalidate_conditional_constness + +## `explicit_implied_const_bounds` on associated types and traits + +Bounds on associated types, opaque types, and supertraits such as +```rust +trait Foo: ~const PartialEq { + type X: ~const PartialEq; +} + +fn foo() -> impl ~const PartialEq { + // ^ unimplemented syntax +} +``` + +Have their bounds represented differently. Unlike `const_conditions` which need +to be proved for callers, and can be assumed inside the definition (e.g. trait +bounds on functions), these bounds need to be proved at definition (at the impl, +or when returning the opaque) but can be assumed for callers. The non-const +equivalent of these bounds are called [`explicit_item_bounds`]. + +These bounds are checked in [`compare_impl_item::check_type_bounds`] for HIR +typeck, [`evaluate_host_effect_from_item_bounds`] in the old solver and +[`consider_additional_alias_assumptions`] in the new solver. + +[`explicit_item_bounds`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/struct.TyCtxt.html#method.explicit_item_bounds +[`compare_impl_item::check_type_bounds`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir_analysis/check/compare_impl_item/fn.check_type_bounds.html +[`evaluate_host_effect_from_item_bounds`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_trait_selection/traits/effects/fn.evaluate_host_effect_from_item_bounds.html +[`consider_additional_alias_assumptions`]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_next_trait_solver/solve/assembly/trait.GoalKind.html#tymethod.consider_additional_alias_assumptions + +## Proving `HostEffectPredicate`s + +`HostEffectPredicate`s are implemented both in the [old solver] and the [new +trait solver]. In general, we can prove a `HostEffect` predicate when either of +these conditions are met: + +* The predicate can be assumed from caller bounds; +* The type has a `const` `impl` for the trait, *and* that const conditions on +the impl holds, *and* that the `explicit_implied_const_bounds` on the trait +holds; or +* The type has a built-in implementation for the trait in const contexts. For +example, `Fn` may be implemented by function items if their const conditions +are satisfied, or `Destruct` is implemented in const contexts if the type can +be dropped at compile time. + +[old solver]: https://doc.rust-lang.org/nightly/nightly-rustc/src/rustc_trait_selection/traits/effects.rs.html +[new trait solver]: https://doc.rust-lang.org/nightly/nightly-rustc/src/rustc_next_trait_solver/solve/effect_goals.rs.html diff --git a/src/doc/rustc-dev-guide/src/solve/trait-solving.md b/src/doc/rustc-dev-guide/src/solve/trait-solving.md index 345ee0b094e..c1eb1a94b96 100644 --- a/src/doc/rustc-dev-guide/src/solve/trait-solving.md +++ b/src/doc/rustc-dev-guide/src/solve/trait-solving.md @@ -2,8 +2,7 @@ This chapter describes how trait solving works with the new WIP solver located in [`rustc_trait_selection/solve`][solve]. Feel free to also look at the docs for -[the current solver](../traits/resolution.md) and [the chalk solver](../traits/chalk.md) -can be found separately. +[the current solver](../traits/resolution.md) and [the chalk solver](../traits/chalk.md). ## Core concepts diff --git a/src/doc/rustc-dev-guide/src/tests/directives.md b/src/doc/rustc-dev-guide/src/tests/directives.md index 14f18a7ecf7..d5b896a8eee 100644 --- a/src/doc/rustc-dev-guide/src/tests/directives.md +++ b/src/doc/rustc-dev-guide/src/tests/directives.md @@ -119,8 +119,7 @@ for more details. These directives are used to ignore the test in some situations, which means the test won't be compiled or run. -* `ignore-X` where `X` is a target detail or stage will ignore the test - accordingly (see below) +* `ignore-X` where `X` is a target detail or other criteria on which to ignore the test (see below) * `only-X` is like `ignore-X`, but will *only* run the test on that target or stage * `ignore-test` always ignores the test. This can be used to temporarily disable @@ -139,8 +138,8 @@ Some examples of `X` in `ignore-X` or `only-X`: matches that target as well as the emscripten targets. - Pointer width: `32bit`, `64bit` - Endianness: `endian-big` +- Stage: `stage1`, `stage2` - Binary format: `elf` -- Stage: `stage0`, `stage1`, `stage2` - Channel: `stable`, `beta` - When cross compiling: `cross-compile` - When [remote testing] is used: `remote` @@ -196,7 +195,6 @@ settings: The following directives will check LLVM support: -- `no-system-llvm` — ignores if the system llvm is used - `exact-llvm-major-version: 19` — ignores if the llvm major version does not match the specified llvm major version. - `min-llvm-version: 13.0` — ignored if the LLVM version is less than the given diff --git a/src/doc/rustc-dev-guide/src/tests/running.md b/src/doc/rustc-dev-guide/src/tests/running.md index 9ddf0afee0c..03d4123cb02 100644 --- a/src/doc/rustc-dev-guide/src/tests/running.md +++ b/src/doc/rustc-dev-guide/src/tests/running.md @@ -24,8 +24,8 @@ collection. The test results are cached and previously successful tests are `ignored` during testing. The stdout/stderr contents as well as a timestamp file for every test -can be found under `build/<target-triple>/test/` for the given -`<target-triple>`. To force-rerun a test (e.g. in case the test runner fails to +can be found under `build/<target-tuple>/test/` for the given +`<target-tuple>`. To force-rerun a test (e.g. in case the test runner fails to notice a change) you can use the `--force-rerun` CLI option. > **Note on requirements of external dependencies** @@ -49,7 +49,7 @@ test suite ([`tests/ui`]): ./x test tests/ui ``` -This will run the `ui` test suite. Of course, the choice of test suites is +Of course, the choice of test suites is somewhat arbitrary, and may not suit the task you are doing. For example, if you are hacking on debuginfo, you may be better off with the debuginfo test suite: @@ -112,8 +112,8 @@ crates, you have to specify those explicitly. ./x test --stage 1 library/std ``` -By listing which test suites you want to run you avoid having to run tests for -components you did not change at all. +By listing which test suites you want to run, +you avoid having to run tests for components you did not change at all. <div class="warning"> Note that bors only runs the tests with the full stage 2 build; therefore, while @@ -172,16 +172,18 @@ additional arguments to the compiler when building the tests. ## Editing and updating the reference files If you have changed the compiler's output intentionally, or you are making a new -test, you can pass `--bless` to the test subcommand. E.g. if some tests in -`tests/ui` are failing, you can run +test, you can pass `--bless` to the test subcommand. + +As an example, +if some tests in `tests/ui` are failing, you can run this command: ```text ./x test tests/ui --bless ``` -to automatically adjust the `.stderr`, `.stdout` or `.fixed` files of -all tests. Of course you can also target just specific tests with the -`--test-args your_test_name` flag, just like when running the tests. +It automatically adjusts the `.stderr`, `.stdout`, or `.fixed` files of all `test/ui` tests. +Of course you can also target just specific tests with the `--test-args your_test_name` flag, +just like when running the tests without the `--bless` flag. ## Configuring test running @@ -190,7 +192,7 @@ There are a few options for running tests: * `config.toml` has the `rust.verbose-tests` option. If `false`, each test will print a single dot (the default). If `true`, the name of every test will be printed. This is equivalent to the `--quiet` option in the [Rust test - harness](https://doc.rust-lang.org/rustc/tests/) + harness](https://doc.rust-lang.org/rustc/tests/). * The environment variable `RUST_TEST_THREADS` can be set to the number of concurrent threads to use for testing. diff --git a/src/doc/unstable-book/src/language-features/offset-of-enum.md b/src/doc/unstable-book/src/language-features/offset-of-enum.md new file mode 100644 index 00000000000..1960d6299eb --- /dev/null +++ b/src/doc/unstable-book/src/language-features/offset-of-enum.md @@ -0,0 +1,29 @@ +# `offset_of_slice` + +The tracking issue for this feature is: [#120141] + +[#120141]: https://github.com/rust-lang/rust/issues/120141 + +------------------------ + +When the `offset_of_enum` feature is enabled, the [`offset_of!`] macro may be used to obtain the +offsets of fields of `enum`s; to express this, `enum` variants may be traversed as if they were +fields. Variants themselves do not have an offset, so they cannot appear as the last path component. + +```rust +#![feature(offset_of_enum)] +use std::mem; + +#[repr(u8)] +enum Enum { + A(u8, u16), + B { one: u8, two: u16 }, +} + +assert_eq!(mem::offset_of!(Enum, A.0), 1); +assert_eq!(mem::offset_of!(Enum, B.two), 2); + +assert_eq!(mem::offset_of!(Option<&u8>, Some.0), 0); +``` + +[`offset_of!`]: ../../std/mem/macro.offset_of.html diff --git a/src/doc/unstable-book/src/language-features/offset-of-slice.md b/src/doc/unstable-book/src/language-features/offset-of-slice.md new file mode 100644 index 00000000000..c887fa07f67 --- /dev/null +++ b/src/doc/unstable-book/src/language-features/offset-of-slice.md @@ -0,0 +1,30 @@ +# `offset_of_slice` + +The tracking issue for this feature is: [#126151] + +[#126151]: https://github.com/rust-lang/rust/issues/126151 + +------------------------ + +When the `offset_of_slice` feature is enabled, the [`offset_of!`] macro may be used to determine +the offset of fields whose type is `[T]`, that is, a slice of dynamic size. + +In general, fields whose type is dynamically sized do not have statically known offsets because +they do not have statically known alignments. However, `[T]` has the same alignment as `T`, so +it specifically may be allowed. + +```rust +#![feature(offset_of_slice)] + +#[repr(C)] +pub struct Struct { + head: u32, + tail: [u8], +} + +fn main() { + assert_eq!(std::mem::offset_of!(Struct, tail), 4); +} +``` + +[`offset_of!`]: ../../std/mem/macro.offset_of.html diff --git a/src/etc/lldb_batchmode.py b/src/etc/lldb_batchmode.py index cf88c53e085..5cc9bb23628 100644 --- a/src/etc/lldb_batchmode.py +++ b/src/etc/lldb_batchmode.py @@ -40,7 +40,7 @@ def print_debug(s): def normalize_whitespace(s): """Replace newlines, tabs, multiple spaces, etc with exactly one space""" - return re.sub("\s+", " ", s) + return re.sub(r"\s+", " ", s) def breakpoint_callback(frame, bp_loc, dict): @@ -234,7 +234,7 @@ try: if ( command == "run" or command == "r" - or re.match("^process\s+launch.*", command) + or re.match(r"^process\s+launch.*", command) ): # Before starting to run the program, let the thread sleep a bit, so all # breakpoint added events can be processed diff --git a/src/etc/rust_analyzer_eglot.el b/src/etc/rust_analyzer_eglot.el index 7b4309f8e18..6b40371d9af 100644 --- a/src/etc/rust_analyzer_eglot.el +++ b/src/etc/rust_analyzer_eglot.el @@ -8,7 +8,6 @@ "check" "--json-output"]) :linkedProjects ["Cargo.toml" - "src/tools/x/Cargo.toml" "src/bootstrap/Cargo.toml" "src/tools/rust-analyzer/Cargo.toml" "compiler/rustc_codegen_cranelift/Cargo.toml" diff --git a/src/etc/rust_analyzer_helix.toml b/src/etc/rust_analyzer_helix.toml index afddd089eb1..05fc7716a72 100644 --- a/src/etc/rust_analyzer_helix.toml +++ b/src/etc/rust_analyzer_helix.toml @@ -15,7 +15,6 @@ linkedProjects = [ "library/Cargo.toml", "src/bootstrap/Cargo.toml", "src/tools/rust-analyzer/Cargo.toml", - "src/tools/x/Cargo.toml", ] [language-server.rust-analyzer.config.check] diff --git a/src/etc/rust_analyzer_settings.json b/src/etc/rust_analyzer_settings.json index b104356d44c..da7d326a512 100644 --- a/src/etc/rust_analyzer_settings.json +++ b/src/etc/rust_analyzer_settings.json @@ -10,7 +10,6 @@ "rust-analyzer.linkedProjects": [ "Cargo.toml", "library/Cargo.toml", - "src/tools/x/Cargo.toml", "src/bootstrap/Cargo.toml", "src/tools/rust-analyzer/Cargo.toml", "compiler/rustc_codegen_cranelift/Cargo.toml", diff --git a/src/etc/rust_analyzer_zed.json b/src/etc/rust_analyzer_zed.json index 469ea050621..abc6ddbc213 100644 --- a/src/etc/rust_analyzer_zed.json +++ b/src/etc/rust_analyzer_zed.json @@ -22,7 +22,6 @@ "linkedProjects": [ "Cargo.toml", "library/Cargo.toml", - "src/tools/x/Cargo.toml", "src/bootstrap/Cargo.toml", "src/tools/rust-analyzer/Cargo.toml", "compiler/rustc_codegen_cranelift/Cargo.toml", diff --git a/src/librustdoc/clean/auto_trait.rs b/src/librustdoc/clean/auto_trait.rs index 185898c31b7..6ace626fdcd 100644 --- a/src/librustdoc/clean/auto_trait.rs +++ b/src/librustdoc/clean/auto_trait.rs @@ -2,8 +2,7 @@ use rustc_data_structures::fx::{FxIndexMap, FxIndexSet, IndexEntry}; use rustc_hir as hir; use rustc_infer::infer::region_constraints::{Constraint, RegionConstraintData}; use rustc_middle::bug; -use rustc_middle::ty::fold::fold_regions; -use rustc_middle::ty::{self, Region, Ty}; +use rustc_middle::ty::{self, Region, Ty, fold_regions}; use rustc_span::def_id::DefId; use rustc_span::symbol::{Symbol, kw}; use rustc_trait_selection::traits::auto_trait::{self, RegionTarget}; diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 0f476c8c9ff..929402d4170 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1488,6 +1488,9 @@ pub(crate) fn clean_middle_assoc_item(assoc_item: &ty::AssocItem, cx: &mut DocCo // The only time this happens is if we're inside the rustdoc for Fn(), // which only has one associated type, which is not a GAT, so whatever. } + GenericArgs::ReturnTypeNotation => { + // Never move these. + } } bounds.extend(mem::take(pred_bounds)); false @@ -2553,36 +2556,42 @@ fn clean_generic_args<'tcx>( generic_args: &hir::GenericArgs<'tcx>, cx: &mut DocContext<'tcx>, ) -> GenericArgs { - // FIXME(return_type_notation): Fix RTN parens rendering - if let Some((inputs, output)) = generic_args.paren_sugar_inputs_output() { - let inputs = inputs.iter().map(|x| clean_ty(x, cx)).collect(); - let output = match output.kind { - hir::TyKind::Tup(&[]) => None, - _ => Some(Box::new(clean_ty(output, cx))), - }; - GenericArgs::Parenthesized { inputs, output } - } else { - let args = generic_args - .args - .iter() - .map(|arg| match arg { - hir::GenericArg::Lifetime(lt) if !lt.is_anonymous() => { - GenericArg::Lifetime(clean_lifetime(lt, cx)) - } - hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()), - hir::GenericArg::Type(ty) => GenericArg::Type(clean_ty(ty.as_unambig_ty(), cx)), - hir::GenericArg::Const(ct) => { - GenericArg::Const(Box::new(clean_const(ct.as_unambig_ct(), cx))) - } - hir::GenericArg::Infer(_inf) => GenericArg::Infer, - }) - .collect(); - let constraints = generic_args - .constraints - .iter() - .map(|c| clean_assoc_item_constraint(c, cx)) - .collect::<ThinVec<_>>(); - GenericArgs::AngleBracketed { args, constraints } + match generic_args.parenthesized { + hir::GenericArgsParentheses::No => { + let args = generic_args + .args + .iter() + .map(|arg| match arg { + hir::GenericArg::Lifetime(lt) if !lt.is_anonymous() => { + GenericArg::Lifetime(clean_lifetime(lt, cx)) + } + hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()), + hir::GenericArg::Type(ty) => GenericArg::Type(clean_ty(ty.as_unambig_ty(), cx)), + hir::GenericArg::Const(ct) => { + GenericArg::Const(Box::new(clean_const(ct.as_unambig_ct(), cx))) + } + hir::GenericArg::Infer(_inf) => GenericArg::Infer, + }) + .collect(); + let constraints = generic_args + .constraints + .iter() + .map(|c| clean_assoc_item_constraint(c, cx)) + .collect::<ThinVec<_>>(); + GenericArgs::AngleBracketed { args, constraints } + } + hir::GenericArgsParentheses::ParenSugar => { + let Some((inputs, output)) = generic_args.paren_sugar_inputs_output() else { + bug!(); + }; + let inputs = inputs.iter().map(|x| clean_ty(x, cx)).collect(); + let output = match output.kind { + hir::TyKind::Tup(&[]) => None, + _ => Some(Box::new(clean_ty(output, cx))), + }; + GenericArgs::Parenthesized { inputs, output } + } + hir::GenericArgsParentheses::ReturnTypeNotation => GenericArgs::ReturnTypeNotation, } } diff --git a/src/librustdoc/clean/simplify.rs b/src/librustdoc/clean/simplify.rs index b8db82e540c..41943b94d1e 100644 --- a/src/librustdoc/clean/simplify.rs +++ b/src/librustdoc/clean/simplify.rs @@ -102,6 +102,10 @@ pub(crate) fn merge_bounds( } } }, + PP::ReturnTypeNotation => { + // Cannot merge bounds with RTN. + return false; + } }; true }) diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index 228d9108e4e..3f9023659db 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -2259,8 +2259,12 @@ impl GenericArg { #[derive(Clone, PartialEq, Eq, Debug, Hash)] pub(crate) enum GenericArgs { + /// `<args, constraints = ..>` AngleBracketed { args: ThinVec<GenericArg>, constraints: ThinVec<AssocItemConstraint> }, + /// `(inputs) -> output` Parenthesized { inputs: ThinVec<Type>, output: Option<Box<Type>> }, + /// `(..)` + ReturnTypeNotation, } impl GenericArgs { @@ -2270,6 +2274,7 @@ impl GenericArgs { args.is_empty() && constraints.is_empty() } GenericArgs::Parenthesized { inputs, output } => inputs.is_empty() && output.is_none(), + GenericArgs::ReturnTypeNotation => false, } } pub(crate) fn constraints(&self) -> Box<dyn Iterator<Item = AssocItemConstraint> + '_> { @@ -2294,6 +2299,7 @@ impl GenericArgs { }) .into_iter(), ), + GenericArgs::ReturnTypeNotation => Box::new([].into_iter()), } } } @@ -2305,8 +2311,10 @@ impl<'a> IntoIterator for &'a GenericArgs { match self { GenericArgs::AngleBracketed { args, .. } => Box::new(args.iter().cloned()), GenericArgs::Parenthesized { inputs, .. } => { + // FIXME: This isn't really right, since `Fn(A, B)` is `Fn<(A, B)>` Box::new(inputs.iter().cloned().map(GenericArg::Type)) } + GenericArgs::ReturnTypeNotation => Box::new([].into_iter()), } } } diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index e93b9eb272a..41e9a5a6651 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -332,6 +332,9 @@ impl clean::GenericArgs { } } } + clean::GenericArgs::ReturnTypeNotation => { + f.write_str("(..)")?; + } } Ok(()) }) diff --git a/src/librustdoc/json/conversions.rs b/src/librustdoc/json/conversions.rs index 6369433a4b5..a5351b350dd 100644 --- a/src/librustdoc/json/conversions.rs +++ b/src/librustdoc/json/conversions.rs @@ -176,6 +176,7 @@ impl FromClean<clean::GenericArgs> for GenericArgs { inputs: inputs.into_json(renderer), output: output.map(|a| (*a).into_json(renderer)), }, + ReturnTypeNotation => GenericArgs::ReturnTypeNotation, } } } diff --git a/src/rustdoc-json-types/lib.rs b/src/rustdoc-json-types/lib.rs index 8ec7cffe066..44e82c7d8b1 100644 --- a/src/rustdoc-json-types/lib.rs +++ b/src/rustdoc-json-types/lib.rs @@ -30,7 +30,7 @@ pub type FxHashMap<K, V> = HashMap<K, V>; // re-export for use in src/librustdoc /// This integer is incremented with every breaking change to the API, /// and is returned along with the JSON blob as [`Crate::format_version`]. /// Consuming code should assert that this value matches the format version(s) that it supports. -pub const FORMAT_VERSION: u32 = 41; +pub const FORMAT_VERSION: u32 = 42; /// The root of the emitted JSON blob. /// @@ -229,6 +229,8 @@ pub enum GenericArgs { /// The output type provided after the `->`, if present. output: Option<Type>, }, + /// `T::method(..)` + ReturnTypeNotation, } /// One argument in a list of generic arguments to a path segment. diff --git a/src/tools/cargo b/src/tools/cargo -Subproject ab1463d632528e39daf35f263e10c14cbe590ce +Subproject 6cf8267012570f63d6b86e85a2ae5627de52df9 diff --git a/src/tools/clippy/clippy_utils/src/mir/possible_borrower.rs b/src/tools/clippy/clippy_utils/src/mir/possible_borrower.rs index 605764cef89..db07b640416 100644 --- a/src/tools/clippy/clippy_utils/src/mir/possible_borrower.rs +++ b/src/tools/clippy/clippy_utils/src/mir/possible_borrower.rs @@ -6,7 +6,7 @@ use rustc_index::bit_set::DenseBitSet; use rustc_lint::LateContext; use rustc_middle::mir::visit::Visitor as _; use rustc_middle::mir::{self, Mutability}; -use rustc_middle::ty::visit::TypeVisitor; +use rustc_middle::ty::TypeVisitor; use rustc_middle::ty::{self, TyCtxt}; use rustc_mir_dataflow::impls::MaybeStorageLive; use rustc_mir_dataflow::{Analysis, ResultsCursor}; diff --git a/src/tools/clippy/tests/ui/derive_ord_xor_partial_ord.stderr b/src/tools/clippy/tests/ui/derive_ord_xor_partial_ord.stderr index 6bbe54eeaa6..76dca3c7947 100644 --- a/src/tools/clippy/tests/ui/derive_ord_xor_partial_ord.stderr +++ b/src/tools/clippy/tests/ui/derive_ord_xor_partial_ord.stderr @@ -11,7 +11,6 @@ LL | impl PartialOrd for DeriveOrd { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = note: `-D clippy::derive-ord-xor-partial-ord` implied by `-D warnings` = help: to override `-D warnings` add `#[allow(clippy::derive_ord_xor_partial_ord)]` - = note: this error originates in the derive macro `Ord` (in Nightly builds, run with -Z macro-backtrace for more info) error: you are deriving `Ord` but have implemented `PartialOrd` explicitly --> tests/ui/derive_ord_xor_partial_ord.rs:33:10 @@ -24,7 +23,6 @@ note: `PartialOrd` implemented here | LL | impl PartialOrd<DeriveOrdWithExplicitTypeVariable> for DeriveOrdWithExplicitTypeVariable { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - = note: this error originates in the derive macro `Ord` (in Nightly builds, run with -Z macro-backtrace for more info) error: you are implementing `Ord` explicitly but have derived `PartialOrd` --> tests/ui/derive_ord_xor_partial_ord.rs:47:1 @@ -42,7 +40,6 @@ note: `PartialOrd` implemented here | LL | #[derive(PartialOrd, PartialEq, Eq)] | ^^^^^^^^^^ - = note: this error originates in the derive macro `PartialOrd` (in Nightly builds, run with -Z macro-backtrace for more info) error: you are implementing `Ord` explicitly but have derived `PartialOrd` --> tests/ui/derive_ord_xor_partial_ord.rs:69:5 @@ -60,7 +57,6 @@ note: `PartialOrd` implemented here | LL | #[derive(PartialOrd, PartialEq, Eq)] | ^^^^^^^^^^ - = note: this error originates in the derive macro `PartialOrd` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 4 previous errors diff --git a/src/tools/clippy/tests/ui/derived_hash_with_manual_eq.stderr b/src/tools/clippy/tests/ui/derived_hash_with_manual_eq.stderr index 19a24e75281..55740780c8a 100644 --- a/src/tools/clippy/tests/ui/derived_hash_with_manual_eq.stderr +++ b/src/tools/clippy/tests/ui/derived_hash_with_manual_eq.stderr @@ -10,7 +10,6 @@ note: `PartialEq` implemented here LL | impl PartialEq for Bar { | ^^^^^^^^^^^^^^^^^^^^^^ = note: `#[deny(clippy::derived_hash_with_manual_eq)]` on by default - = note: this error originates in the derive macro `Hash` (in Nightly builds, run with -Z macro-backtrace for more info) error: you are deriving `Hash` but have implemented `PartialEq` explicitly --> tests/ui/derived_hash_with_manual_eq.rs:23:10 @@ -23,7 +22,6 @@ note: `PartialEq` implemented here | LL | impl PartialEq<Baz> for Baz { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ - = note: this error originates in the derive macro `Hash` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 2 previous errors diff --git a/src/tools/clippy/tests/ui/diverging_sub_expression.stderr b/src/tools/clippy/tests/ui/diverging_sub_expression.stderr index 3e417aa39cd..ba08eb4e5f4 100644 --- a/src/tools/clippy/tests/ui/diverging_sub_expression.stderr +++ b/src/tools/clippy/tests/ui/diverging_sub_expression.stderr @@ -36,8 +36,6 @@ error: sub-expression diverges | LL | _ => true || panic!("boo"), | ^^^^^^^^^^^^^ - | - = note: this error originates in the macro `$crate::panic::panic_2021` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) error: sub-expression diverges --> tests/ui/diverging_sub_expression.rs:52:29 diff --git a/src/tools/clippy/tests/ui/fallible_impl_from.stderr b/src/tools/clippy/tests/ui/fallible_impl_from.stderr index d773fc3a6d7..402494b39f3 100644 --- a/src/tools/clippy/tests/ui/fallible_impl_from.stderr +++ b/src/tools/clippy/tests/ui/fallible_impl_from.stderr @@ -38,7 +38,6 @@ note: potential failure(s) | LL | panic!(); | ^^^^^^^^ - = note: this error originates in the macro `$crate::panic::panic_2021` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) error: consider implementing `TryFrom` instead --> tests/ui/fallible_impl_from.rs:40:1 @@ -64,7 +63,6 @@ LL | } else if s.parse::<u32>().unwrap() != 42 { | ^^^^^^^^^^^^^^^^^^^^^^^^^ LL | panic!("{:?}", s); | ^^^^^^^^^^^^^^^^^ - = note: this error originates in the macro `$crate::panic::panic_2021` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) error: consider implementing `TryFrom` instead --> tests/ui/fallible_impl_from.rs:60:1 @@ -85,7 +83,6 @@ LL | if s.parse::<u32>().ok().unwrap() != 42 { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ LL | panic!("{:?}", s); | ^^^^^^^^^^^^^^^^^ - = note: this error originates in the macro `$crate::panic::panic_2021` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 4 previous errors diff --git a/src/tools/clippy/tests/ui/impl_hash_with_borrow_str_and_bytes.stderr b/src/tools/clippy/tests/ui/impl_hash_with_borrow_str_and_bytes.stderr index 7328f563ce1..c327ce3f7ca 100644 --- a/src/tools/clippy/tests/ui/impl_hash_with_borrow_str_and_bytes.stderr +++ b/src/tools/clippy/tests/ui/impl_hash_with_borrow_str_and_bytes.stderr @@ -23,7 +23,6 @@ LL | #[derive(Hash)] = note: ... as (`hash("abc") != hash("abc".as_bytes())` = help: consider either removing one of the `Borrow` implementations (`Borrow<str>` or `Borrow<[u8]>`) ... = help: ... or not implementing `Hash` for this type - = note: this error originates in the derive macro `Hash` (in Nightly builds, run with -Z macro-backtrace for more info) error: the semantics of `Borrow<T>` around `Hash` can't be satisfied when both `Borrow<str>` and `Borrow<[u8]>` are implemented --> tests/ui/impl_hash_with_borrow_str_and_bytes.rs:117:6 diff --git a/src/tools/clippy/tests/ui/issue-7447.stderr b/src/tools/clippy/tests/ui/issue-7447.stderr index 5e28c142384..09a75c6b8d2 100644 --- a/src/tools/clippy/tests/ui/issue-7447.stderr +++ b/src/tools/clippy/tests/ui/issue-7447.stderr @@ -6,15 +6,12 @@ LL | byte_view(panic!()); | = note: `-D clippy::diverging-sub-expression` implied by `-D warnings` = help: to override `-D warnings` add `#[allow(clippy::diverging_sub_expression)]` - = note: this error originates in the macro `$crate::panic::panic_2021` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) error: sub-expression diverges --> tests/ui/issue-7447.rs:29:19 | LL | group_entries(panic!()); | ^^^^^^^^ - | - = note: this error originates in the macro `$crate::panic::panic_2021` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 2 previous errors diff --git a/src/tools/clippy/tests/ui/same_name_method.stderr b/src/tools/clippy/tests/ui/same_name_method.stderr index fefdb5c9c23..b2624ac4d26 100644 --- a/src/tools/clippy/tests/ui/same_name_method.stderr +++ b/src/tools/clippy/tests/ui/same_name_method.stderr @@ -23,7 +23,6 @@ note: existing `clone` defined here | LL | #[derive(Clone)] | ^^^^^ - = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) error: method's name is the same as an existing method in a trait --> tests/ui/same_name_method.rs:46:13 diff --git a/src/tools/compiletest/src/runtest/incremental.rs b/src/tools/compiletest/src/runtest/incremental.rs index 591aff0defe..ea985866a05 100644 --- a/src/tools/compiletest/src/runtest/incremental.rs +++ b/src/tools/compiletest/src/runtest/incremental.rs @@ -65,7 +65,7 @@ impl TestCx<'_> { // FIXME(#41968): Move this check to tidy? if !errors::load_errors(&self.testpaths.file, self.revision).is_empty() { - self.fatal("compile-pass tests with expected warnings should be moved to ui/"); + self.fatal("build-pass tests with expected warnings should be moved to ui/"); } } diff --git a/src/tools/jsondoclint/src/validator.rs b/src/tools/jsondoclint/src/validator.rs index 791b231c27a..8c9e4c8bb3a 100644 --- a/src/tools/jsondoclint/src/validator.rs +++ b/src/tools/jsondoclint/src/validator.rs @@ -326,6 +326,7 @@ impl<'a> Validator<'a> { self.check_type(o); } } + GenericArgs::ReturnTypeNotation => {} } } diff --git a/src/tools/linkchecker/Cargo.toml b/src/tools/linkchecker/Cargo.toml index f1be6e9e749..7123d43eb56 100644 --- a/src/tools/linkchecker/Cargo.toml +++ b/src/tools/linkchecker/Cargo.toml @@ -9,4 +9,4 @@ path = "main.rs" [dependencies] regex = "1" -html5ever = "0.27.0" +html5ever = "0.29.0" diff --git a/src/tools/linkchecker/main.rs b/src/tools/linkchecker/main.rs index 19340b5d07a..84cba3f8c44 100644 --- a/src/tools/linkchecker/main.rs +++ b/src/tools/linkchecker/main.rs @@ -16,7 +16,7 @@ //! A few exceptions are allowed as there's known bugs in rustdoc, but this //! should catch the majority of "broken link" cases. -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::collections::{HashMap, HashSet}; use std::io::ErrorKind; use std::path::{Component, Path, PathBuf}; @@ -544,7 +544,7 @@ fn parse_html<Sink: TokenSink>(source: &str, sink: Sink) -> Sink { let mut input = BufferQueue::default(); input.push_back(tendril.try_reinterpret().unwrap()); - let mut tok = Tokenizer::new(sink, TokenizerOpts::default()); + let tok = Tokenizer::new(sink, TokenizerOpts::default()); let _ = tok.feed(&mut input); assert!(input.is_empty()); tok.end(); @@ -554,8 +554,8 @@ fn parse_html<Sink: TokenSink>(source: &str, sink: Sink) -> Sink { #[derive(Default)] struct AttrCollector { attr_name: &'static [u8], - base: Option<String>, - found_attrs: Vec<(u64, String)>, + base: Cell<Option<String>>, + found_attrs: RefCell<Vec<(u64, String)>>, /// Tracks whether or not it is inside a <script> tag. /// /// A lot of our sources have JSON script tags which have HTML embedded @@ -564,13 +564,13 @@ struct AttrCollector { /// `TokenSinkResult::Script(…)` (and then maybe switch parser?), but I /// don't fully understand the best way to use that, and this seems good /// enough for now. - in_script: bool, + in_script: Cell<bool>, } impl TokenSink for AttrCollector { type Handle = (); - fn process_token(&mut self, token: Token, line_number: u64) -> TokenSinkResult<()> { + fn process_token(&self, token: Token, line_number: u64) -> TokenSinkResult<()> { match token { TagToken(tag) => { let tag_name = tag.name.as_bytes(); @@ -578,20 +578,20 @@ impl TokenSink for AttrCollector { if let Some(href) = tag.attrs.iter().find(|attr| attr.name.local.as_bytes() == b"href") { - self.base = Some(href.value.to_string()); + self.base.set(Some(href.value.to_string())); } return TokenSinkResult::Continue; } else if tag_name == b"script" { - self.in_script = !self.in_script; + self.in_script.set(!self.in_script.get()); } - if self.in_script { + if self.in_script.get() { return TokenSinkResult::Continue; } for attr in tag.attrs.iter() { let name = attr.name.local.as_bytes(); if name == self.attr_name { let url = attr.value.to_string(); - self.found_attrs.push((line_number, url)); + self.found_attrs.borrow_mut().push((line_number, url)); } } } @@ -607,7 +607,7 @@ impl TokenSink for AttrCollector { fn get_urls(source: &str) -> (Option<String>, Vec<(u64, String)>) { let collector = AttrCollector { attr_name: b"href", ..AttrCollector::default() }; let sink = parse_html(source, collector); - (sink.base, sink.found_attrs) + (sink.base.into_inner(), sink.found_attrs.into_inner()) } /// Retrieves id="..." attributes from HTML elements. @@ -619,7 +619,7 @@ fn parse_ids(ids: &mut HashSet<String>, file: &str, source: &str, report: &mut R let collector = AttrCollector { attr_name: b"id", ..AttrCollector::default() }; let sink = parse_html(source, collector); - for (line_number, id) in sink.found_attrs { + for (line_number, id) in sink.found_attrs.into_inner() { let encoded = small_url_encode(&id); if let Some(id) = ids.replace(id) { report.errors += 1; diff --git a/src/tools/miri/src/alloc_addresses/mod.rs b/src/tools/miri/src/alloc_addresses/mod.rs index 5d257029a46..0a2d3ac63a7 100644 --- a/src/tools/miri/src/alloc_addresses/mod.rs +++ b/src/tools/miri/src/alloc_addresses/mod.rs @@ -377,7 +377,6 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { fn get_global_alloc_bytes( &self, id: AllocId, - kind: MemoryKind, bytes: &[u8], align: Align, ) -> InterpResult<'tcx, MiriAllocBytes> { @@ -386,7 +385,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { // In native lib mode, MiriAllocBytes for global allocations are handled via `prepared_alloc_bytes`. // This additional call ensures that some `MiriAllocBytes` are always prepared, just in case // this function gets called before the first time `addr_from_alloc_id` gets called. - this.addr_from_alloc_id(id, kind)?; + this.addr_from_alloc_id(id, MiriMemoryKind::Global.into())?; // The memory we need here will have already been allocated during an earlier call to // `addr_from_alloc_id` for this allocation. So don't create a new `MiriAllocBytes` here, instead // fetch the previously prepared bytes from `prepared_alloc_bytes`. diff --git a/src/tools/miri/src/machine.rs b/src/tools/miri/src/machine.rs index dbb092f6728..90beffbf830 100644 --- a/src/tools/miri/src/machine.rs +++ b/src/tools/miri/src/machine.rs @@ -814,6 +814,59 @@ impl<'tcx> MiriMachine<'tcx> { .and_then(|(_allocated, deallocated)| *deallocated) .map(Span::data) } + + fn init_allocation( + ecx: &MiriInterpCx<'tcx>, + id: AllocId, + kind: MemoryKind, + size: Size, + align: Align, + ) -> InterpResult<'tcx, AllocExtra<'tcx>> { + if ecx.machine.tracked_alloc_ids.contains(&id) { + ecx.emit_diagnostic(NonHaltingDiagnostic::CreatedAlloc(id, size, align, kind)); + } + + let borrow_tracker = ecx + .machine + .borrow_tracker + .as_ref() + .map(|bt| bt.borrow_mut().new_allocation(id, size, kind, &ecx.machine)); + + let data_race = ecx.machine.data_race.as_ref().map(|data_race| { + data_race::AllocState::new_allocation( + data_race, + &ecx.machine.threads, + size, + kind, + ecx.machine.current_span(), + ) + }); + let weak_memory = ecx.machine.weak_memory.then(weak_memory::AllocState::new_allocation); + + // If an allocation is leaked, we want to report a backtrace to indicate where it was + // allocated. We don't need to record a backtrace for allocations which are allowed to + // leak. + let backtrace = if kind.may_leak() || !ecx.machine.collect_leak_backtraces { + None + } else { + Some(ecx.generate_stacktrace()) + }; + + if matches!(kind, MemoryKind::Machine(kind) if kind.should_save_allocation_span()) { + ecx.machine + .allocation_spans + .borrow_mut() + .insert(id, (ecx.machine.current_span(), None)); + } + + interp_ok(AllocExtra { + borrow_tracker, + data_race, + weak_memory, + backtrace, + sync: FxHashMap::default(), + }) + } } impl VisitProvenance for MiriMachine<'_> { @@ -1200,57 +1253,15 @@ impl<'tcx> Machine<'tcx> for MiriMachine<'tcx> { } } - fn init_alloc_extra( + fn init_local_allocation( ecx: &MiriInterpCx<'tcx>, id: AllocId, kind: MemoryKind, size: Size, align: Align, ) -> InterpResult<'tcx, Self::AllocExtra> { - if ecx.machine.tracked_alloc_ids.contains(&id) { - ecx.emit_diagnostic(NonHaltingDiagnostic::CreatedAlloc(id, size, align, kind)); - } - - let borrow_tracker = ecx - .machine - .borrow_tracker - .as_ref() - .map(|bt| bt.borrow_mut().new_allocation(id, size, kind, &ecx.machine)); - - let data_race = ecx.machine.data_race.as_ref().map(|data_race| { - data_race::AllocState::new_allocation( - data_race, - &ecx.machine.threads, - size, - kind, - ecx.machine.current_span(), - ) - }); - let weak_memory = ecx.machine.weak_memory.then(weak_memory::AllocState::new_allocation); - - // If an allocation is leaked, we want to report a backtrace to indicate where it was - // allocated. We don't need to record a backtrace for allocations which are allowed to - // leak. - let backtrace = if kind.may_leak() || !ecx.machine.collect_leak_backtraces { - None - } else { - Some(ecx.generate_stacktrace()) - }; - - if matches!(kind, MemoryKind::Machine(kind) if kind.should_save_allocation_span()) { - ecx.machine - .allocation_spans - .borrow_mut() - .insert(id, (ecx.machine.current_span(), None)); - } - - interp_ok(AllocExtra { - borrow_tracker, - data_race, - weak_memory, - backtrace, - sync: FxHashMap::default(), - }) + assert!(kind != MiriMemoryKind::Global.into()); + MiriMachine::init_allocation(ecx, id, kind, size, align) } fn adjust_alloc_root_pointer( @@ -1340,13 +1351,13 @@ impl<'tcx> Machine<'tcx> for MiriMachine<'tcx> { alloc: &'b Allocation, ) -> InterpResult<'tcx, Cow<'b, Allocation<Self::Provenance, Self::AllocExtra, Self::Bytes>>> { - let kind = Self::GLOBAL_KIND.unwrap().into(); let alloc = alloc.adjust_from_tcx( &ecx.tcx, - |bytes, align| ecx.get_global_alloc_bytes(id, kind, bytes, align), + |bytes, align| ecx.get_global_alloc_bytes(id, bytes, align), |ptr| ecx.global_root_pointer(ptr), )?; - let extra = Self::init_alloc_extra(ecx, id, kind, alloc.size(), alloc.align)?; + let kind = MiriMemoryKind::Global.into(); + let extra = MiriMachine::init_allocation(ecx, id, kind, alloc.size(), alloc.align)?; interp_ok(Cow::Owned(alloc.with_extra(extra))) } diff --git a/src/tools/miri/tests/fail/alloc/alloc_error_handler_custom.stderr b/src/tools/miri/tests/fail/alloc/alloc_error_handler_custom.stderr index 1a9e7574339..7e8c198b6a3 100644 --- a/src/tools/miri/tests/fail/alloc/alloc_error_handler_custom.stderr +++ b/src/tools/miri/tests/fail/alloc/alloc_error_handler_custom.stderr @@ -21,7 +21,6 @@ note: inside `miri_start` | LL | handle_alloc_error(Layout::for_value(&0)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - = note: this error originates in the attribute macro `alloc_error_handler` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/src/tools/miri/tests/fail/both_borrows/aliasing_mut4.tree.stderr b/src/tools/miri/tests/fail/both_borrows/aliasing_mut4.tree.stderr index 5162368b51f..e8babf02163 100644 --- a/src/tools/miri/tests/fail/both_borrows/aliasing_mut4.tree.stderr +++ b/src/tools/miri/tests/fail/both_borrows/aliasing_mut4.tree.stderr @@ -1,8 +1,8 @@ error: Undefined Behavior: write access through <TAG> at ALLOC[0x0] is forbidden --> RUSTLIB/core/src/mem/mod.rs:LL:CC | -LL | ptr::write(dest, src); - | ^^^^^^^^^^^^^^^^^^^^^ write access through <TAG> at ALLOC[0x0] is forbidden +LL | crate::intrinsics::write_via_move(dest, src); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ write access through <TAG> at ALLOC[0x0] is forbidden | = help: this indicates a potential bug in the program: it performed an invalid operation, but the Tree Borrows rules it violated are still experimental = help: the accessed tag <TAG> is foreign to the protected tag <TAG> (i.e., it is not a child) diff --git a/src/tools/miri/tests/fail/erroneous_const.stderr b/src/tools/miri/tests/fail/erroneous_const.stderr index 2906ac6b20a..6f1e3529ccc 100644 --- a/src/tools/miri/tests/fail/erroneous_const.stderr +++ b/src/tools/miri/tests/fail/erroneous_const.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of `PrintName::<i32>::VOID` failed | LL | const VOID: ! = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2021` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> tests/fail/erroneous_const.rs:LL:CC diff --git a/src/tools/miri/tests/fail/panic/no_std.stderr b/src/tools/miri/tests/fail/panic/no_std.stderr index d54f2a58776..b1d98ffc7a9 100644 --- a/src/tools/miri/tests/fail/panic/no_std.stderr +++ b/src/tools/miri/tests/fail/panic/no_std.stderr @@ -13,7 +13,6 @@ note: inside `miri_start` | LL | panic!("blarg I am dead") | ^^^^^^^^^^^^^^^^^^^^^^^^^ - = note: this error originates in the macro `$crate::panic::panic_2021` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace diff --git a/src/tools/miri/tests/fail/panic/panic_abort1.stderr b/src/tools/miri/tests/fail/panic/panic_abort1.stderr index ca32722942f..c950b2b4ea6 100644 --- a/src/tools/miri/tests/fail/panic/panic_abort1.stderr +++ b/src/tools/miri/tests/fail/panic/panic_abort1.stderr @@ -22,7 +22,6 @@ note: inside `main` | LL | std::panic!("panicking from libstd"); | ^ - = note: this error originates in the macro `$crate::panic::panic_2021` which comes from the expansion of the macro `std::panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace diff --git a/src/tools/miri/tests/fail/panic/panic_abort2.stderr b/src/tools/miri/tests/fail/panic/panic_abort2.stderr index 8d113d80588..9a9266ec493 100644 --- a/src/tools/miri/tests/fail/panic/panic_abort2.stderr +++ b/src/tools/miri/tests/fail/panic/panic_abort2.stderr @@ -22,7 +22,6 @@ note: inside `main` | LL | std::panic!("{}-panicking from libstd", 42); | ^ - = note: this error originates in the macro `$crate::panic::panic_2021` which comes from the expansion of the macro `std::panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace diff --git a/src/tools/miri/tests/fail/panic/panic_abort3.stderr b/src/tools/miri/tests/fail/panic/panic_abort3.stderr index 2ce753ba689..f04a2b0f3f1 100644 --- a/src/tools/miri/tests/fail/panic/panic_abort3.stderr +++ b/src/tools/miri/tests/fail/panic/panic_abort3.stderr @@ -22,7 +22,6 @@ note: inside `main` | LL | core::panic!("panicking from libcore"); | ^ - = note: this error originates in the macro `$crate::panic::panic_2021` which comes from the expansion of the macro `core::panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace diff --git a/src/tools/miri/tests/fail/panic/panic_abort4.stderr b/src/tools/miri/tests/fail/panic/panic_abort4.stderr index c9c5ae107b7..e71c4879ea3 100644 --- a/src/tools/miri/tests/fail/panic/panic_abort4.stderr +++ b/src/tools/miri/tests/fail/panic/panic_abort4.stderr @@ -22,7 +22,6 @@ note: inside `main` | LL | core::panic!("{}-panicking from libcore", 42); | ^ - = note: this error originates in the macro `$crate::panic::panic_2021` which comes from the expansion of the macro `core::panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace diff --git a/src/tools/opt-dist/src/tests.rs b/src/tools/opt-dist/src/tests.rs index 8b3bd77141b..c8759bb6ff6 100644 --- a/src/tools/opt-dist/src/tests.rs +++ b/src/tools/opt-dist/src/tests.rs @@ -1,3 +1,5 @@ +use std::path::Path; + use anyhow::Context; use camino::{Utf8Path, Utf8PathBuf}; @@ -86,36 +88,57 @@ llvm-config = "{llvm_config}" log::info!("Using following `config.toml` for running tests:\n{config_content}"); // Simulate a stage 0 compiler with the extracted optimized dist artifacts. - std::fs::write("config.toml", config_content)?; - - let x_py = env.checkout_path().join("x.py"); - let mut args = vec![ - env.python_binary(), - x_py.as_str(), - "test", - "--build", - env.host_tuple(), - "--stage", - "0", - "tests/assembly", - "tests/codegen", - "tests/codegen-units", - "tests/incremental", - "tests/mir-opt", - "tests/pretty", - "tests/run-make/glibc-symbols-x86_64-unknown-linux-gnu", - "tests/ui", - "tests/crashes", - ]; - for test_path in env.skipped_tests() { - args.extend(["--skip", test_path]); + with_backed_up_file(Path::new("config.toml"), &config_content, || { + let x_py = env.checkout_path().join("x.py"); + let mut args = vec![ + env.python_binary(), + x_py.as_str(), + "test", + "--build", + env.host_tuple(), + "--stage", + "0", + "tests/assembly", + "tests/codegen", + "tests/codegen-units", + "tests/incremental", + "tests/mir-opt", + "tests/pretty", + "tests/run-make/glibc-symbols-x86_64-unknown-linux-gnu", + "tests/ui", + "tests/crashes", + ]; + for test_path in env.skipped_tests() { + args.extend(["--skip", test_path]); + } + cmd(&args) + .env("COMPILETEST_FORCE_STAGE0", "1") + // Also run dist-only tests + .env("COMPILETEST_ENABLE_DIST_TESTS", "1") + .run() + .context("Cannot execute tests") + }) +} + +/// Backup `path` (if it exists), then write `contents` into it, and then restore the original +/// contents of the file. +fn with_backed_up_file<F>(path: &Path, contents: &str, func: F) -> anyhow::Result<()> +where + F: FnOnce() -> anyhow::Result<()>, +{ + let original_contents = + if path.is_file() { Some(std::fs::read_to_string(path)?) } else { None }; + + // Overwrite it with new contents + std::fs::write(path, contents)?; + + let ret = func(); + + if let Some(original_contents) = original_contents { + std::fs::write(path, original_contents)?; } - cmd(&args) - .env("COMPILETEST_FORCE_STAGE0", "1") - // Also run dist-only tests - .env("COMPILETEST_ENABLE_DIST_TESTS", "1") - .run() - .context("Cannot execute tests") + + ret } /// Tries to find the version of the dist artifacts (either nightly, beta, or 1.XY.Z). diff --git a/src/tools/rustbook/Cargo.lock b/src/tools/rustbook/Cargo.lock index ddcf315a267..e54747c129a 100644 --- a/src/tools/rustbook/Cargo.lock +++ b/src/tools/rustbook/Cargo.lock @@ -553,6 +553,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" [[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] name = "html5ever" version = "0.27.0" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -874,9 +880,9 @@ dependencies = [ [[package]] name = "mdbook" -version = "0.4.45" +version = "0.4.47" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b07d36d96ffe1b5b16ddf2bc80b3b26bb7a498b2a6591061250bf0af8e8095ad" +checksum = "7e1a8fe3a4a01f28dab245c474cb7b95ccb4d3d2f17a5419a3d949f474c45e84" dependencies = [ "ammonia", "anyhow", @@ -886,6 +892,7 @@ dependencies = [ "elasticlunr-rs", "env_logger", "handlebars", + "hex", "log", "memchr", "once_cell", @@ -894,6 +901,7 @@ dependencies = [ "regex", "serde", "serde_json", + "sha2", "shlex", "tempfile", "toml 0.5.11", diff --git a/src/tools/rustbook/Cargo.toml b/src/tools/rustbook/Cargo.toml index 6aec0bec0fa..831233e3065 100644 --- a/src/tools/rustbook/Cargo.toml +++ b/src/tools/rustbook/Cargo.toml @@ -15,6 +15,6 @@ mdbook-i18n-helpers = "0.3.3" mdbook-spec = { path = "../../doc/reference/mdbook-spec" } [dependencies.mdbook] -version = "0.4.45" +version = "0.4.47" default-features = false features = ["search"] diff --git a/src/tools/rustbook/src/main.rs b/src/tools/rustbook/src/main.rs index 33f2a51215d..4b510e308c9 100644 --- a/src/tools/rustbook/src/main.rs +++ b/src/tools/rustbook/src/main.rs @@ -151,6 +151,7 @@ fn get_book_dir(args: &ArgMatches) -> PathBuf { fn load_book(book_dir: &Path) -> Result3<MDBook> { let mut book = MDBook::load(book_dir)?; book.config.set("output.html.input-404", "").unwrap(); + book.config.set("output.html.hash-files", true).unwrap(); Ok(book) } diff --git a/src/tools/tidy/src/deps.rs b/src/tools/tidy/src/deps.rs index 569d3c67b04..81c55ecaa7a 100644 --- a/src/tools/tidy/src/deps.rs +++ b/src/tools/tidy/src/deps.rs @@ -81,7 +81,6 @@ pub(crate) const WORKSPACES: &[(&str, ExceptionList, Option<(&[&str], &[&str])>, ("src/tools/rust-analyzer", EXCEPTIONS_RUST_ANALYZER, None, &[]), ("src/tools/rustbook", EXCEPTIONS_RUSTBOOK, None, &["src/doc/book", "src/doc/reference"]), ("src/tools/rustc-perf", EXCEPTIONS_RUSTC_PERF, None, &["src/tools/rustc-perf"]), - ("src/tools/x", &[], None, &[]), // tidy-alphabetical-end ]; diff --git a/src/tools/tidy/src/main.rs b/src/tools/tidy/src/main.rs index bc3519142dd..4078d462f55 100644 --- a/src/tools/tidy/src/main.rs +++ b/src/tools/tidy/src/main.rs @@ -29,6 +29,7 @@ fn main() { FromStr::from_str(&env::args().nth(4).expect("need concurrency")) .expect("concurrency must be a number"); + let root_manifest = root_path.join("Cargo.toml"); let src_path = root_path.join("src"); let tests_path = root_path.join("tests"); let library_path = root_path.join("library"); @@ -137,6 +138,7 @@ fn main() { check!(edition, &compiler_path); check!(edition, &library_path); + check!(alphabetical, &root_manifest); check!(alphabetical, &src_path); check!(alphabetical, &tests_path); check!(alphabetical, &compiler_path); diff --git a/src/tools/x/Cargo.lock b/src/tools/x/Cargo.lock deleted file mode 100644 index 09e5c750749..00000000000 --- a/src/tools/x/Cargo.lock +++ /dev/null @@ -1,7 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 3 - -[[package]] -name = "x" -version = "0.1.1" diff --git a/tests/codegen/enum/enum-two-variants-match.rs b/tests/codegen/enum/enum-two-variants-match.rs index e5978bfc761..c1f208d7909 100644 --- a/tests/codegen/enum/enum-two-variants-match.rs +++ b/tests/codegen/enum/enum-two-variants-match.rs @@ -7,19 +7,22 @@ // CHECK-LABEL: @option_match #[no_mangle] pub fn option_match(x: Option<i32>) -> u16 { - // CHECK: %x = alloca [8 x i8] - // CHECK: store i32 %0, ptr %x - // CHECK: %[[TAG:.+]] = load i32, ptr %x - // CHECK-SAME: !range ![[ZERO_ONE_32:[0-9]+]] - // CHECK: %[[DISCR:.+]] = zext i32 %[[TAG]] to i64 + // CHECK-NOT: %x = alloca + // CHECK: %[[OUT:.+]] = alloca [2 x i8] + // CHECK-NOT: %x = alloca + + // CHECK: %[[DISCR:.+]] = zext i32 %x.0 to i64 // CHECK: %[[COND:.+]] = trunc nuw i64 %[[DISCR]] to i1 // CHECK: br i1 %[[COND]], label %[[TRUE:[a-z0-9]+]], label %[[FALSE:[a-z0-9]+]] // CHECK: [[TRUE]]: - // CHECK: store i16 13 + // CHECK: store i16 13, ptr %[[OUT]] // CHECK: [[FALSE]]: - // CHECK: store i16 42 + // CHECK: store i16 42, ptr %[[OUT]] + + // CHECK: %[[RET:.+]] = load i16, ptr %[[OUT]] + // CHECK: ret i16 %[[RET]] match x { Some(_) => 13, None => 42, @@ -29,23 +32,23 @@ pub fn option_match(x: Option<i32>) -> u16 { // CHECK-LABEL: @result_match #[no_mangle] pub fn result_match(x: Result<u64, i64>) -> u16 { - // CHECK: %x = alloca [16 x i8] - // CHECK: store i64 %0, ptr %x - // CHECK: %[[DISCR:.+]] = load i64, ptr %x - // CHECK-SAME: !range ![[ZERO_ONE_64:[0-9]+]] - // CHECK: %[[COND:.+]] = trunc nuw i64 %[[DISCR]] to i1 + // CHECK-NOT: %x = alloca + // CHECK: %[[OUT:.+]] = alloca [2 x i8] + // CHECK-NOT: %x = alloca + + // CHECK: %[[COND:.+]] = trunc nuw i64 %x.0 to i1 // CHECK: br i1 %[[COND]], label %[[TRUE:[a-z0-9]+]], label %[[FALSE:[a-z0-9]+]] // CHECK: [[TRUE]]: - // CHECK: store i16 13 + // CHECK: store i16 13, ptr %[[OUT]] // CHECK: [[FALSE]]: - // CHECK: store i16 42 + // CHECK: store i16 42, ptr %[[OUT]] + + // CHECK: %[[RET:.+]] = load i16, ptr %[[OUT]] + // CHECK: ret i16 %[[RET]] match x { Err(_) => 13, Ok(_) => 42, } } - -// CHECK: ![[ZERO_ONE_32]] = !{i32 0, i32 2} -// CHECK: ![[ZERO_ONE_64]] = !{i64 0, i64 2} diff --git a/tests/codegen/intrinsics/cold_path2.rs b/tests/codegen/intrinsics/cold_path2.rs index 54ee473e620..0891c878fd9 100644 --- a/tests/codegen/intrinsics/cold_path2.rs +++ b/tests/codegen/intrinsics/cold_path2.rs @@ -25,8 +25,8 @@ pub fn test(x: Option<bool>) { path_b(); } - // CHECK-LABEL: @test( - // CHECK: %[[IS_NONE:.+]] = icmp eq i8 %0, 2 + // CHECK-LABEL: void @test(i8{{.+}}%x) + // CHECK: %[[IS_NONE:.+]] = icmp eq i8 %x, 2 // CHECK: br i1 %[[IS_NONE]], label %bb2, label %bb1, !prof ![[NUM:[0-9]+]] // CHECK: bb1: // CHECK: path_a diff --git a/tests/codegen/match-optimizes-away.rs b/tests/codegen/match-optimizes-away.rs index 8a70d993423..5e9be72a09f 100644 --- a/tests/codegen/match-optimizes-away.rs +++ b/tests/codegen/match-optimizes-away.rs @@ -1,5 +1,4 @@ -// -//@ compile-flags: -Copt-level=3 +//@ compile-flags: -Copt-level=3 -Zmerge-functions=disabled #![crate_type = "lib"] pub enum Three { @@ -18,9 +17,9 @@ pub enum Four { #[no_mangle] pub fn three_valued(x: Three) -> Three { - // CHECK-LABEL: @three_valued + // CHECK-LABEL: i8 @three_valued(i8{{.+}}%x) // CHECK-NEXT: {{^.*:$}} - // CHECK-NEXT: ret i8 %0 + // CHECK-NEXT: ret i8 %x match x { Three::A => Three::A, Three::B => Three::B, @@ -30,9 +29,9 @@ pub fn three_valued(x: Three) -> Three { #[no_mangle] pub fn four_valued(x: Four) -> Four { - // CHECK-LABEL: @four_valued + // CHECK-LABEL: i16 @four_valued(i16{{.+}}%x) // CHECK-NEXT: {{^.*:$}} - // CHECK-NEXT: ret i16 %0 + // CHECK-NEXT: ret i16 %x match x { Four::A => Four::A, Four::B => Four::B, diff --git a/tests/codegen/range-loop.rs b/tests/codegen/range-loop.rs new file mode 100644 index 00000000000..b131beb40dd --- /dev/null +++ b/tests/codegen/range-loop.rs @@ -0,0 +1,44 @@ +//@ ignore-std-debug-assertions +//@ compile-flags: -Copt-level=3 -C no-prepopulate-passes + +#![crate_type = "lib"] + +// Ensure that MIR optimizations have cleaned things up enough that the IR we +// emit is good even without running the LLVM optimizations. + +// CHECK-NOT: define + +// CHECK-LABEL: define{{.+}}void @call_for_zero_to_n +#[no_mangle] +pub fn call_for_zero_to_n(n: u32, f: fn(u32)) { + // CHECK: start: + // CHECK-NOT: alloca + // CHECK: %[[IND:.+]] = alloca [4 x i8] + // CHECK-NEXT: %[[ALWAYS_SOME_OPTION:.+]] = alloca + // CHECK-NOT: alloca + // CHECK: store i32 0, ptr %[[IND]], + // CHECK: br label %[[HEAD:.+]] + + // CHECK: [[HEAD]]: + // CHECK: %[[T1:.+]] = load i32, ptr %[[IND]], + // CHECK: %[[NOT_DONE:.+]] = icmp ult i32 %[[T1]], %n + // CHECK: br i1 %[[NOT_DONE]], label %[[BODY:.+]], label %[[BREAK:.+]] + + // CHECK: [[BREAK]]: + // CHECK: ret void + + // CHECK: [[BODY]]: + // CHECK: %[[T2:.+]] = load i32, ptr %[[IND]], + // CHECK: %[[T3:.+]] = add nuw i32 %[[T2]], 1 + // CHECK: store i32 %[[T3]], ptr %[[IND]], + + // CHECK: store i32 %[[T2]] + // CHECK: %[[T4:.+]] = load i32 + // CHECK: call void %f(i32{{.+}}%[[T4]]) + + for i in 0..n { + f(i); + } +} + +// CHECK-NOT: define diff --git a/tests/codegen/try_question_mark_nop.rs b/tests/codegen/try_question_mark_nop.rs index ca15e510173..23a084c51f4 100644 --- a/tests/codegen/try_question_mark_nop.rs +++ b/tests/codegen/try_question_mark_nop.rs @@ -17,10 +17,10 @@ use std::ptr::NonNull; pub fn option_nop_match_32(x: Option<u32>) -> Option<u32> { // CHECK: start: // TWENTY-NEXT: %[[IS_SOME:.+]] = trunc nuw i32 %0 to i1 - // TWENTY-NEXT: %.2 = select i1 %[[IS_SOME]], i32 %1, i32 undef + // TWENTY-NEXT: %[[PAYLOAD:.+]] = select i1 %[[IS_SOME]], i32 %1, i32 undef // CHECK-NEXT: [[REG1:%.*]] = insertvalue { i32, i32 } poison, i32 %0, 0 // NINETEEN-NEXT: [[REG2:%.*]] = insertvalue { i32, i32 } [[REG1]], i32 %1, 1 - // TWENTY-NEXT: [[REG2:%.*]] = insertvalue { i32, i32 } [[REG1]], i32 %.2, 1 + // TWENTY-NEXT: [[REG2:%.*]] = insertvalue { i32, i32 } [[REG1]], i32 %[[PAYLOAD]], 1 // CHECK-NEXT: ret { i32, i32 } [[REG2]] match x { Some(x) => Some(x), @@ -33,7 +33,7 @@ pub fn option_nop_match_32(x: Option<u32>) -> Option<u32> { pub fn option_nop_traits_32(x: Option<u32>) -> Option<u32> { // CHECK: start: // TWENTY-NEXT: %[[IS_SOME:.+]] = trunc nuw i32 %0 to i1 - // TWENTY-NEXT: %.1 = select i1 %[[IS_SOME]], i32 %1, i32 undef + // TWENTY-NEXT: select i1 %[[IS_SOME]], i32 %1, i32 undef // CHECK-NEXT: insertvalue { i32, i32 } // CHECK-NEXT: insertvalue { i32, i32 } // CHECK-NEXT: ret { i32, i32 } diff --git a/tests/crashes/125059.rs b/tests/crashes/125059.rs deleted file mode 100644 index 7e9f7414816..00000000000 --- a/tests/crashes/125059.rs +++ /dev/null @@ -1,12 +0,0 @@ -//@ known-bug: rust-lang/rust#125059 -#![feature(deref_patterns)] -#![allow(incomplete_features)] - -fn simple_vec(vec: Vec<u32>) -> u32 { - (|| match Vec::<u32>::new() { - deref!([]) => 100, - _ => 2000, - })() -} - -fn main() {} diff --git a/tests/mir-opt/async_closure_fake_read_for_by_move.foo-{closure#0}-{closure#0}.built.after.mir b/tests/mir-opt/async_closure_fake_read_for_by_move.foo-{closure#0}-{closure#0}.built.after.mir new file mode 100644 index 00000000000..0c8a17ff70b --- /dev/null +++ b/tests/mir-opt/async_closure_fake_read_for_by_move.foo-{closure#0}-{closure#0}.built.after.mir @@ -0,0 +1,81 @@ +// MIR for `foo::{closure#0}::{closure#0}` after built + +fn foo::{closure#0}::{closure#0}(_1: {async closure body@$DIR/async_closure_fake_read_for_by_move.rs:12:27: 15:6}, _2: ResumeTy) -> () +yields () + { + debug _task_context => _2; + debug f => (*(_1.0: &&Foo)); + let mut _0: (); + let mut _3: &Foo; + let mut _4: &&Foo; + let mut _5: &&&Foo; + let mut _6: isize; + let mut _7: bool; + + bb0: { + PlaceMention((*(_1.0: &&Foo))); + _6 = discriminant((*(*(_1.0: &&Foo)))); + switchInt(move _6) -> [0: bb2, otherwise: bb1]; + } + + bb1: { + _0 = const (); + goto -> bb10; + } + + bb2: { + falseEdge -> [real: bb5, imaginary: bb1]; + } + + bb3: { + goto -> bb1; + } + + bb4: { + FakeRead(ForMatchedPlace(None), (*(_1.0: &&Foo))); + unreachable; + } + + bb5: { + _3 = &fake shallow (*(*(_1.0: &&Foo))); + _4 = &fake shallow (*(_1.0: &&Foo)); + _5 = &fake shallow (_1.0: &&Foo); + StorageLive(_7); + _7 = const true; + switchInt(move _7) -> [0: bb8, otherwise: bb7]; + } + + bb6: { + falseEdge -> [real: bb3, imaginary: bb1]; + } + + bb7: { + StorageDead(_7); + FakeRead(ForMatchGuard, _3); + FakeRead(ForMatchGuard, _4); + FakeRead(ForMatchGuard, _5); + _0 = const (); + goto -> bb10; + } + + bb8: { + goto -> bb9; + } + + bb9: { + StorageDead(_7); + goto -> bb6; + } + + bb10: { + drop(_1) -> [return: bb11, unwind: bb12]; + } + + bb11: { + return; + } + + bb12 (cleanup): { + resume; + } +} diff --git a/tests/mir-opt/async_closure_fake_read_for_by_move.foo-{closure#0}-{closure#1}.built.after.mir b/tests/mir-opt/async_closure_fake_read_for_by_move.foo-{closure#0}-{closure#1}.built.after.mir new file mode 100644 index 00000000000..bd0baddb1f8 --- /dev/null +++ b/tests/mir-opt/async_closure_fake_read_for_by_move.foo-{closure#0}-{closure#1}.built.after.mir @@ -0,0 +1,64 @@ +// MIR for `foo::{closure#0}::{closure#1}` after built + +fn foo::{closure#0}::{closure#1}(_1: {async closure body@$DIR/async_closure_fake_read_for_by_move.rs:12:27: 15:6}, _2: ResumeTy) -> () +yields () + { + debug _task_context => _2; + debug f => (_1.0: &Foo); + let mut _0: (); + let mut _3: &Foo; + let mut _4: &&Foo; + let mut _5: &&&Foo; + let mut _6: isize; + let mut _7: bool; + + bb0: { + PlaceMention((_1.0: &Foo)); + _6 = discriminant((*(_1.0: &Foo))); + switchInt(move _6) -> [0: bb2, otherwise: bb1]; + } + + bb1: { + _0 = const (); + goto -> bb6; + } + + bb2: { + falseEdge -> [real: bb3, imaginary: bb1]; + } + + bb3: { + _3 = &fake shallow (*(_1.0: &Foo)); + _4 = &fake shallow (_1.0: &Foo); + nop; + StorageLive(_7); + _7 = const true; + switchInt(move _7) -> [0: bb5, otherwise: bb4]; + } + + bb4: { + StorageDead(_7); + FakeRead(ForMatchGuard, _3); + FakeRead(ForMatchGuard, _4); + FakeRead(ForMatchGuard, _5); + _0 = const (); + goto -> bb6; + } + + bb5: { + StorageDead(_7); + falseEdge -> [real: bb1, imaginary: bb1]; + } + + bb6: { + drop(_1) -> [return: bb7, unwind: bb8]; + } + + bb7: { + return; + } + + bb8 (cleanup): { + resume; + } +} diff --git a/tests/mir-opt/async_closure_fake_read_for_by_move.rs b/tests/mir-opt/async_closure_fake_read_for_by_move.rs new file mode 100644 index 00000000000..3c5aec94bbf --- /dev/null +++ b/tests/mir-opt/async_closure_fake_read_for_by_move.rs @@ -0,0 +1,18 @@ +//@ edition:2021 +// skip-filecheck + +enum Foo { + Bar, + Baz, +} + +// EMIT_MIR async_closure_fake_read_for_by_move.foo-{closure#0}-{closure#0}.built.after.mir +// EMIT_MIR async_closure_fake_read_for_by_move.foo-{closure#0}-{closure#1}.built.after.mir +fn foo(f: &Foo) { + let x = async move || match f { + Foo::Bar if true => {} + _ => {} + }; +} + +fn main() {} diff --git a/tests/mir-opt/gvn_on_unsafe_binder.propagate.GVN.diff b/tests/mir-opt/gvn_on_unsafe_binder.propagate.GVN.diff new file mode 100644 index 00000000000..e28d04f1d58 --- /dev/null +++ b/tests/mir-opt/gvn_on_unsafe_binder.propagate.GVN.diff @@ -0,0 +1,35 @@ +- // MIR for `propagate` before GVN ++ // MIR for `propagate` after GVN + + fn propagate() -> unsafe<> i32 { + let mut _0: unsafe<> i32; + let _1: i32; + let mut _3: i32; + scope 1 { + debug x => _1; + let _2: unsafe<> i32; + scope 2 { + debug binder => _2; + } + } + + bb0: { +- StorageLive(_1); ++ nop; + _1 = const 1_i32; + StorageLive(_2); + StorageLive(_3); +- _3 = copy _1; +- _2 = wrap_binder!(move _3; unsafe<> i32); ++ _3 = const 1_i32; ++ _2 = const {transmute(0x00000001): unsafe<> i32}; + StorageDead(_3); +- _0 = move _2; ++ _0 = const {transmute(0x00000001): unsafe<> i32}; + StorageDead(_2); +- StorageDead(_1); ++ nop; + return; + } + } + diff --git a/tests/mir-opt/gvn_on_unsafe_binder.rs b/tests/mir-opt/gvn_on_unsafe_binder.rs new file mode 100644 index 00000000000..b3c0576f990 --- /dev/null +++ b/tests/mir-opt/gvn_on_unsafe_binder.rs @@ -0,0 +1,29 @@ +// skip-filecheck +//@ test-mir-pass: GVN + +// EMIT_MIR gvn_on_unsafe_binder.test.GVN.diff +// EMIT_MIR gvn_on_unsafe_binder.propagate.GVN.diff + +#![feature(unsafe_binders)] + +use std::unsafe_binder::wrap_binder; + +// Test for ICE <https://github.com/rust-lang/rust/issues/137846>. +fn test() { + unsafe { + let x = 1; + let binder: unsafe<'a> &'a i32 = wrap_binder!(&x); + } +} + +// Test that GVN propagates const values through unsafe binders. +// +// The lifetime `'a` is redundant (and doesn't print when we print out the type). +// However, we need it so that rustfmt doesn't rip out the `unsafe<>` part for now. +fn propagate() -> unsafe<'a> i32 { + unsafe { + let x = 1; + let binder: unsafe<'a> i32 = wrap_binder!(x); + binder + } +} diff --git a/tests/mir-opt/gvn_on_unsafe_binder.test.GVN.diff b/tests/mir-opt/gvn_on_unsafe_binder.test.GVN.diff new file mode 100644 index 00000000000..33814fb34f3 --- /dev/null +++ b/tests/mir-opt/gvn_on_unsafe_binder.test.GVN.diff @@ -0,0 +1,30 @@ +- // MIR for `test` before GVN ++ // MIR for `test` after GVN + + fn test() -> () { + let mut _0: (); + let _1: i32; + let mut _3: &i32; + scope 1 { + debug x => _1; + let _2: unsafe<'a> &'a i32; + scope 2 { + debug binder => _2; + } + } + + bb0: { + StorageLive(_1); + _1 = const 1_i32; + StorageLive(_2); + StorageLive(_3); + _3 = &_1; + _2 = wrap_binder!(move _3; unsafe<'a> &'a i32); + StorageDead(_3); + _0 = const (); + StorageDead(_2); + StorageDead(_1); + return; + } + } + diff --git a/tests/mir-opt/inline/exponential_runtime.rs b/tests/mir-opt/inline/exponential_runtime.rs index 1199ce4e558..62c1d8be1bf 100644 --- a/tests/mir-opt/inline/exponential_runtime.rs +++ b/tests/mir-opt/inline/exponential_runtime.rs @@ -87,10 +87,15 @@ fn main() { // CHECK-LABEL: fn main( // CHECK-NOT: inlined // CHECK: (inlined <() as G>::call) + // CHECK-NOT: inlined // CHECK: (inlined <() as F>::call) + // CHECK-NOT: inlined // CHECK: (inlined <() as E>::call) + // CHECK-NOT: inlined // CHECK: (inlined <() as D>::call) + // CHECK-NOT: inlined // CHECK: (inlined <() as C>::call) + // CHECK-NOT: inlined // CHECK: (inlined <() as B>::call) // CHECK-NOT: inlined <() as G>::call(); diff --git a/tests/mir-opt/inline/inline_diverging.h.Inline.panic-abort.diff b/tests/mir-opt/inline/inline_diverging.h.Inline.panic-abort.diff index 75fc2ea16e3..f099d763c3d 100644 --- a/tests/mir-opt/inline/inline_diverging.h.Inline.panic-abort.diff +++ b/tests/mir-opt/inline/inline_diverging.h.Inline.panic-abort.diff @@ -6,6 +6,7 @@ let _1: (!, !); + let mut _2: fn() -> ! {sleep}; + let mut _7: (); ++ let mut _8: (); + scope 1 (inlined call_twice::<!, fn() -> ! {sleep}>) { + debug f => _2; + let mut _3: &fn() -> ! {sleep}; @@ -17,6 +18,10 @@ + scope 3 { + debug b => _6; + } ++ scope 6 (inlined <fn() -> ! {sleep} as Fn<()>>::call - shim(fn() -> ! {sleep})) { ++ scope 7 (inlined sleep) { ++ } ++ } + } + scope 4 (inlined <fn() -> ! {sleep} as Fn<()>>::call - shim(fn() -> ! {sleep})) { + scope 5 (inlined sleep) { diff --git a/tests/mir-opt/inline/inline_diverging.h.Inline.panic-unwind.diff b/tests/mir-opt/inline/inline_diverging.h.Inline.panic-unwind.diff index 407cb24df67..c33e0810739 100644 --- a/tests/mir-opt/inline/inline_diverging.h.Inline.panic-unwind.diff +++ b/tests/mir-opt/inline/inline_diverging.h.Inline.panic-unwind.diff @@ -6,6 +6,7 @@ let _1: (!, !); + let mut _2: fn() -> ! {sleep}; + let mut _8: (); ++ let mut _9: (); + scope 1 (inlined call_twice::<!, fn() -> ! {sleep}>) { + debug f => _2; + let mut _3: &fn() -> ! {sleep}; @@ -18,6 +19,10 @@ + scope 3 { + debug b => _6; + } ++ scope 6 (inlined <fn() -> ! {sleep} as Fn<()>>::call - shim(fn() -> ! {sleep})) { ++ scope 7 (inlined sleep) { ++ } ++ } + } + scope 4 (inlined <fn() -> ! {sleep} as Fn<()>>::call - shim(fn() -> ! {sleep})) { + scope 5 (inlined sleep) { diff --git a/tests/mir-opt/inline_coroutine_body.run2-{closure#0}.Inline.panic-abort.diff b/tests/mir-opt/inline_coroutine_body.run2-{closure#0}.Inline.panic-abort.diff index 1e33e222b27..eb97af1e284 100644 --- a/tests/mir-opt/inline_coroutine_body.run2-{closure#0}.Inline.panic-abort.diff +++ b/tests/mir-opt/inline_coroutine_body.run2-{closure#0}.Inline.panic-abort.diff @@ -55,10 +55,46 @@ + let _26: (); + scope 9 { + } ++ scope 12 (inlined Pin::<&mut std::future::Ready<()>>::new_unchecked) { ++ } ++ scope 13 (inlined <std::future::Ready<()> as Future>::poll) { ++ let mut _42: (); ++ let mut _43: std::option::Option<()>; ++ let mut _44: &mut std::option::Option<()>; ++ let mut _45: &mut std::future::Ready<()>; ++ let mut _46: &mut std::pin::Pin<&mut std::future::Ready<()>>; ++ scope 14 (inlined <Pin<&mut std::future::Ready<()>> as DerefMut>::deref_mut) { ++ let mut _47: std::pin::Pin<&mut std::future::Ready<()>>; ++ scope 15 (inlined Pin::<&mut std::future::Ready<()>>::as_mut) { ++ let mut _48: &mut &mut std::future::Ready<()>; ++ scope 16 (inlined Pin::<&mut std::future::Ready<()>>::new_unchecked) { ++ } ++ scope 18 (inlined <&mut std::future::Ready<()> as DerefMut>::deref_mut) { ++ } ++ } ++ scope 17 (inlined Pin::<&mut std::future::Ready<()>>::get_mut) { ++ } ++ } ++ scope 19 (inlined Option::<()>::take) { ++ let mut _49: std::option::Option<()>; ++ scope 20 (inlined std::mem::replace::<Option<()>>) { ++ scope 21 { ++ } ++ } ++ } ++ scope 22 (inlined #[track_caller] Option::<()>::expect) { ++ let mut _50: isize; ++ let mut _51: !; ++ scope 23 { ++ } ++ } ++ } + } + scope 10 (inlined ready::<()>) { + let mut _41: std::option::Option<()>; + } ++ scope 11 (inlined <std::future::Ready<()> as IntoFuture>::into_future) { ++ } + } + } } @@ -113,7 +149,7 @@ + StorageLive(_40); + _33 = deref_copy (_8.0: &mut {async fn body of ActionPermit<'_, T>::perform()}); + _32 = discriminant((*_33)); -+ switchInt(move _32) -> [0: bb3, 1: bb13, 3: bb12, otherwise: bb8]; ++ switchInt(move _32) -> [0: bb3, 1: bb10, 3: bb9, otherwise: bb5]; } - bb3: { @@ -164,19 +200,16 @@ + _13 = std::future::Ready::<()>(move _41); + StorageDead(_41); + StorageDead(_14); -+ _12 = <std::future::Ready<()> as IntoFuture>::into_future(move _13) -> [return: bb4, unwind unreachable]; -+ } -+ - bb4: { -- StorageDead(_2); -- return; ++ _12 = move _13; + StorageDead(_13); + _36 = deref_copy (_8.0: &mut {async fn body of ActionPermit<'_, T>::perform()}); + (((*_36) as variant#3).1: std::future::Ready<()>) = move _12; -+ goto -> bb5; ++ goto -> bb4; + } + -+ bb5: { + bb4: { +- StorageDead(_2); +- return; + StorageLive(_17); + StorageLive(_18); + StorageLive(_19); @@ -185,10 +218,7 @@ + _37 = deref_copy (_8.0: &mut {async fn body of ActionPermit<'_, T>::perform()}); + _21 = &mut (((*_37) as variant#3).1: std::future::Ready<()>); + _20 = &mut (*_21); -+ _19 = Pin::<&mut std::future::Ready<()>>::new_unchecked(move _20) -> [return: bb6, unwind unreachable]; -+ } -+ -+ bb6: { ++ _19 = Pin::<&mut std::future::Ready<()>> { __pointer: copy _20 }; + StorageDead(_20); + StorageLive(_22); + StorageLive(_23); @@ -197,21 +227,36 @@ + _23 = move _24; + _22 = &mut (*_23); + StorageDead(_24); -+ _18 = <std::future::Ready<()> as Future>::poll(move _19, move _22) -> [return: bb7, unwind unreachable]; -+ } -+ -+ bb7: { -+ StorageDead(_22); -+ StorageDead(_19); -+ _25 = discriminant(_18); -+ switchInt(move _25) -> [0: bb10, 1: bb9, otherwise: bb8]; ++ StorageLive(_45); ++ StorageLive(_46); ++ StorageLive(_49); ++ StorageLive(_51); ++ StorageLive(_42); ++ StorageLive(_43); ++ StorageLive(_44); ++ _46 = &mut _19; ++ StorageLive(_47); ++ StorageLive(_48); ++ _48 = &mut (_19.0: &mut std::future::Ready<()>); ++ _45 = copy (_19.0: &mut std::future::Ready<()>); ++ StorageDead(_48); ++ _47 = Pin::<&mut std::future::Ready<()>> { __pointer: copy _45 }; ++ StorageDead(_47); ++ _44 = &mut ((*_45).0: std::option::Option<()>); ++ _49 = Option::<()>::None; ++ _43 = copy ((*_45).0: std::option::Option<()>); ++ ((*_45).0: std::option::Option<()>) = copy _49; ++ StorageDead(_44); ++ StorageLive(_50); ++ _50 = discriminant(_43); ++ switchInt(move _50) -> [0: bb11, 1: bb12, otherwise: bb5]; + } + -+ bb8: { ++ bb5: { + unreachable; + } + -+ bb9: { ++ bb6: { + _17 = const (); + StorageDead(_23); + StorageDead(_21); @@ -229,7 +274,7 @@ + goto -> bb2; + } + -+ bb10: { ++ bb7: { + StorageLive(_26); + _26 = copy ((_18 as Ready).0: ()); + _30 = copy _26; @@ -240,17 +285,17 @@ + StorageDead(_17); + StorageDead(_12); + _39 = deref_copy (_8.0: &mut {async fn body of ActionPermit<'_, T>::perform()}); -+ drop((((*_39) as variant#3).0: ActionPermit<'_, T>)) -> [return: bb11, unwind unreachable]; ++ drop((((*_39) as variant#3).0: ActionPermit<'_, T>)) -> [return: bb8, unwind unreachable]; + } + -+ bb11: { ++ bb8: { + _7 = Poll::<()>::Ready(move _30); + _40 = deref_copy (_8.0: &mut {async fn body of ActionPermit<'_, T>::perform()}); + discriminant((*_40)) = 1; + goto -> bb2; + } + -+ bb12: { ++ bb9: { + StorageLive(_12); + StorageLive(_28); + StorageLive(_29); @@ -259,11 +304,31 @@ + _31 = move _28; + StorageDead(_28); + _16 = const (); -+ goto -> bb5; ++ goto -> bb4; + } + -+ bb13: { -+ assert(const false, "`async fn` resumed after completion") -> [success: bb13, unwind unreachable]; ++ bb10: { ++ assert(const false, "`async fn` resumed after completion") -> [success: bb10, unwind unreachable]; ++ } ++ ++ bb11: { ++ _51 = option::expect_failed(const "`Ready` polled after completion") -> unwind unreachable; ++ } ++ ++ bb12: { ++ _42 = move ((_43 as Some).0: ()); ++ StorageDead(_50); ++ StorageDead(_43); ++ _18 = Poll::<()>::Ready(move _42); ++ StorageDead(_42); ++ StorageDead(_51); ++ StorageDead(_49); ++ StorageDead(_46); ++ StorageDead(_45); ++ StorageDead(_22); ++ StorageDead(_19); ++ _25 = discriminant(_18); ++ switchInt(move _25) -> [0: bb7, 1: bb6, otherwise: bb5]; } } diff --git a/tests/mir-opt/inline_coroutine_body.run2-{closure#0}.Inline.panic-unwind.diff b/tests/mir-opt/inline_coroutine_body.run2-{closure#0}.Inline.panic-unwind.diff index b1840beb3ef..eb757e09114 100644 --- a/tests/mir-opt/inline_coroutine_body.run2-{closure#0}.Inline.panic-unwind.diff +++ b/tests/mir-opt/inline_coroutine_body.run2-{closure#0}.Inline.panic-unwind.diff @@ -57,10 +57,46 @@ + let _26: (); + scope 9 { + } ++ scope 12 (inlined Pin::<&mut std::future::Ready<()>>::new_unchecked) { ++ } ++ scope 13 (inlined <std::future::Ready<()> as Future>::poll) { ++ let mut _44: (); ++ let mut _45: std::option::Option<()>; ++ let mut _46: &mut std::option::Option<()>; ++ let mut _47: &mut std::future::Ready<()>; ++ let mut _48: &mut std::pin::Pin<&mut std::future::Ready<()>>; ++ scope 14 (inlined <Pin<&mut std::future::Ready<()>> as DerefMut>::deref_mut) { ++ let mut _49: std::pin::Pin<&mut std::future::Ready<()>>; ++ scope 15 (inlined Pin::<&mut std::future::Ready<()>>::as_mut) { ++ let mut _50: &mut &mut std::future::Ready<()>; ++ scope 16 (inlined Pin::<&mut std::future::Ready<()>>::new_unchecked) { ++ } ++ scope 18 (inlined <&mut std::future::Ready<()> as DerefMut>::deref_mut) { ++ } ++ } ++ scope 17 (inlined Pin::<&mut std::future::Ready<()>>::get_mut) { ++ } ++ } ++ scope 19 (inlined Option::<()>::take) { ++ let mut _51: std::option::Option<()>; ++ scope 20 (inlined std::mem::replace::<Option<()>>) { ++ scope 21 { ++ } ++ } ++ } ++ scope 22 (inlined #[track_caller] Option::<()>::expect) { ++ let mut _52: isize; ++ let mut _53: !; ++ scope 23 { ++ } ++ } ++ } + } + scope 10 (inlined ready::<()>) { + let mut _43: std::option::Option<()>; + } ++ scope 11 (inlined <std::future::Ready<()> as IntoFuture>::into_future) { ++ } + } + } } @@ -117,7 +153,7 @@ + StorageLive(_42); + _33 = deref_copy (_8.0: &mut {async fn body of ActionPermit<'_, T>::perform()}); + _32 = discriminant((*_33)); -+ switchInt(move _32) -> [0: bb5, 1: bb22, 2: bb21, 3: bb20, otherwise: bb10]; ++ switchInt(move _32) -> [0: bb5, 1: bb15, 2: bb14, 3: bb13, otherwise: bb7]; } - bb3: { @@ -181,21 +217,16 @@ + _13 = std::future::Ready::<()>(move _43); + StorageDead(_43); + StorageDead(_14); -+ _12 = <std::future::Ready<()> as IntoFuture>::into_future(move _13) -> [return: bb6, unwind: bb17]; - } - -- bb5 (cleanup): { -- drop(_2) -> [return: bb6, unwind terminate(cleanup)]; -+ bb6: { ++ _12 = move _13; + StorageDead(_13); + _36 = deref_copy (_8.0: &mut {async fn body of ActionPermit<'_, T>::perform()}); + (((*_36) as variant#3).1: std::future::Ready<()>) = move _12; -+ goto -> bb7; ++ goto -> bb6; } -- bb6 (cleanup): { -- resume; -+ bb7: { +- bb5 (cleanup): { +- drop(_2) -> [return: bb6, unwind terminate(cleanup)]; ++ bb6: { + StorageLive(_17); + StorageLive(_18); + StorageLive(_19); @@ -204,10 +235,7 @@ + _37 = deref_copy (_8.0: &mut {async fn body of ActionPermit<'_, T>::perform()}); + _21 = &mut (((*_37) as variant#3).1: std::future::Ready<()>); + _20 = &mut (*_21); -+ _19 = Pin::<&mut std::future::Ready<()>>::new_unchecked(move _20) -> [return: bb8, unwind: bb15]; -+ } -+ -+ bb8: { ++ _19 = Pin::<&mut std::future::Ready<()>> { __pointer: copy _20 }; + StorageDead(_20); + StorageLive(_22); + StorageLive(_23); @@ -216,21 +244,38 @@ + _23 = move _24; + _22 = &mut (*_23); + StorageDead(_24); -+ _18 = <std::future::Ready<()> as Future>::poll(move _19, move _22) -> [return: bb9, unwind: bb14]; -+ } -+ -+ bb9: { -+ StorageDead(_22); -+ StorageDead(_19); -+ _25 = discriminant(_18); -+ switchInt(move _25) -> [0: bb12, 1: bb11, otherwise: bb10]; -+ } -+ -+ bb10: { ++ StorageLive(_47); ++ StorageLive(_48); ++ StorageLive(_51); ++ StorageLive(_53); ++ StorageLive(_44); ++ StorageLive(_45); ++ StorageLive(_46); ++ _48 = &mut _19; ++ StorageLive(_49); ++ StorageLive(_50); ++ _50 = &mut (_19.0: &mut std::future::Ready<()>); ++ _47 = copy (_19.0: &mut std::future::Ready<()>); ++ StorageDead(_50); ++ _49 = Pin::<&mut std::future::Ready<()>> { __pointer: copy _47 }; ++ StorageDead(_49); ++ _46 = &mut ((*_47).0: std::option::Option<()>); ++ _51 = Option::<()>::None; ++ _45 = copy ((*_47).0: std::option::Option<()>); ++ ((*_47).0: std::option::Option<()>) = copy _51; ++ StorageDead(_46); ++ StorageLive(_52); ++ _52 = discriminant(_45); ++ switchInt(move _52) -> [0: bb16, 1: bb17, otherwise: bb7]; + } + +- bb6 (cleanup): { +- resume; ++ bb7: { + unreachable; + } + -+ bb11: { ++ bb8: { + _17 = const (); + StorageDead(_23); + StorageDead(_21); @@ -248,7 +293,7 @@ + goto -> bb4; + } + -+ bb12: { ++ bb9: { + StorageLive(_26); + _26 = copy ((_18 as Ready).0: ()); + _30 = copy _26; @@ -259,54 +304,35 @@ + StorageDead(_17); + StorageDead(_12); + _39 = deref_copy (_8.0: &mut {async fn body of ActionPermit<'_, T>::perform()}); -+ drop((((*_39) as variant#3).0: ActionPermit<'_, T>)) -> [return: bb13, unwind: bb19]; ++ drop((((*_39) as variant#3).0: ActionPermit<'_, T>)) -> [return: bb10, unwind: bb12]; + } + -+ bb13: { ++ bb10: { + _7 = Poll::<()>::Ready(move _30); + _40 = deref_copy (_8.0: &mut {async fn body of ActionPermit<'_, T>::perform()}); + discriminant((*_40)) = 1; + goto -> bb4; + } + -+ bb14 (cleanup): { ++ bb11 (cleanup): { + StorageDead(_22); + StorageDead(_19); + StorageDead(_23); -+ goto -> bb16; -+ } -+ -+ bb15 (cleanup): { -+ StorageDead(_20); -+ StorageDead(_19); -+ goto -> bb16; -+ } -+ -+ bb16 (cleanup): { + StorageDead(_21); + StorageDead(_18); + StorageDead(_17); -+ goto -> bb18; -+ } -+ -+ bb17 (cleanup): { -+ StorageDead(_13); -+ goto -> bb18; -+ } -+ -+ bb18 (cleanup): { + StorageDead(_12); + _41 = deref_copy (_8.0: &mut {async fn body of ActionPermit<'_, T>::perform()}); -+ drop((((*_41) as variant#3).0: ActionPermit<'_, T>)) -> [return: bb19, unwind terminate(cleanup)]; ++ drop((((*_41) as variant#3).0: ActionPermit<'_, T>)) -> [return: bb12, unwind terminate(cleanup)]; + } + -+ bb19 (cleanup): { ++ bb12 (cleanup): { + _42 = deref_copy (_8.0: &mut {async fn body of ActionPermit<'_, T>::perform()}); + discriminant((*_42)) = 2; + goto -> bb2; + } + -+ bb20: { ++ bb13: { + StorageLive(_12); + StorageLive(_28); + StorageLive(_29); @@ -315,15 +341,35 @@ + _31 = move _28; + StorageDead(_28); + _16 = const (); -+ goto -> bb7; ++ goto -> bb6; + } + -+ bb21: { -+ assert(const false, "`async fn` resumed after panicking") -> [success: bb21, unwind: bb2]; ++ bb14: { ++ assert(const false, "`async fn` resumed after panicking") -> [success: bb14, unwind: bb2]; + } + -+ bb22: { -+ assert(const false, "`async fn` resumed after completion") -> [success: bb22, unwind: bb2]; ++ bb15: { ++ assert(const false, "`async fn` resumed after completion") -> [success: bb15, unwind: bb2]; ++ } ++ ++ bb16: { ++ _53 = option::expect_failed(const "`Ready` polled after completion") -> bb11; ++ } ++ ++ bb17: { ++ _44 = move ((_45 as Some).0: ()); ++ StorageDead(_52); ++ StorageDead(_45); ++ _18 = Poll::<()>::Ready(move _44); ++ StorageDead(_44); ++ StorageDead(_53); ++ StorageDead(_51); ++ StorageDead(_48); ++ StorageDead(_47); ++ StorageDead(_22); ++ StorageDead(_19); ++ _25 = discriminant(_18); ++ switchInt(move _25) -> [0: bb9, 1: bb8, otherwise: bb7]; } } diff --git a/tests/mir-opt/pre-codegen/loops.int_range.PreCodegen.after.mir b/tests/mir-opt/pre-codegen/loops.int_range.PreCodegen.after.mir index be69bbf10e7..1f9c464d633 100644 --- a/tests/mir-opt/pre-codegen/loops.int_range.PreCodegen.after.mir +++ b/tests/mir-opt/pre-codegen/loops.int_range.PreCodegen.after.mir @@ -26,6 +26,18 @@ fn int_range(_1: usize, _2: usize) -> () { let mut _12: usize; scope 6 { debug old => _11; + scope 8 (inlined <usize as Step>::forward_unchecked) { + debug start => _11; + debug n => const 1_usize; + scope 9 (inlined core::num::<impl usize>::unchecked_add) { + debug self => _11; + debug rhs => const 1_usize; + scope 10 (inlined core::ub_checks::check_language_ub) { + scope 11 (inlined core::ub_checks::check_language_ub::runtime) { + } + } + } + } } scope 7 (inlined std::cmp::impls::<impl PartialOrd for usize>::lt) { debug self => _6; @@ -50,7 +62,6 @@ fn int_range(_1: usize, _2: usize) -> () { bb1: { StorageLive(_13); _5 = &mut _4; - StorageLive(_11); StorageLive(_10); StorageLive(_6); _6 = &(_4.0: usize); @@ -70,7 +81,6 @@ fn int_range(_1: usize, _2: usize) -> () { StorageDead(_7); StorageDead(_6); StorageDead(_10); - StorageDead(_11); StorageDead(_13); StorageDead(_4); return; @@ -81,20 +91,16 @@ fn int_range(_1: usize, _2: usize) -> () { StorageDead(_6); _11 = copy (_4.0: usize); StorageLive(_12); - _12 = <usize as Step>::forward_unchecked(copy _11, const 1_usize) -> [return: bb4, unwind continue]; - } - - bb4: { + _12 = AddUnchecked(copy _11, const 1_usize); (_4.0: usize) = move _12; StorageDead(_12); _13 = Option::<usize>::Some(copy _11); StorageDead(_10); - StorageDead(_11); _14 = copy ((_13 as Some).0: usize); - _15 = opaque::<usize>(move _14) -> [return: bb5, unwind continue]; + _15 = opaque::<usize>(move _14) -> [return: bb4, unwind continue]; } - bb5: { + bb4: { StorageDead(_13); goto -> bb1; } diff --git a/tests/mir-opt/pre-codegen/mem_replace.mem_replace.PreCodegen.after.panic-abort.mir b/tests/mir-opt/pre-codegen/mem_replace.mem_replace.PreCodegen.after.panic-abort.mir index ed494f6e74c..958a06bcd34 100644 --- a/tests/mir-opt/pre-codegen/mem_replace.mem_replace.PreCodegen.after.panic-abort.mir +++ b/tests/mir-opt/pre-codegen/mem_replace.mem_replace.PreCodegen.after.panic-abort.mir @@ -6,10 +6,6 @@ fn mem_replace(_1: &mut u32, _2: u32) -> u32 { let mut _0: u32; scope 1 (inlined std::mem::replace::<u32>) { scope 2 { - scope 4 (inlined std::ptr::write::<u32>) { - } - } - scope 3 (inlined std::ptr::read::<u32>) { } } diff --git a/tests/mir-opt/pre-codegen/mem_replace.mem_replace.PreCodegen.after.panic-unwind.mir b/tests/mir-opt/pre-codegen/mem_replace.mem_replace.PreCodegen.after.panic-unwind.mir index ed494f6e74c..958a06bcd34 100644 --- a/tests/mir-opt/pre-codegen/mem_replace.mem_replace.PreCodegen.after.panic-unwind.mir +++ b/tests/mir-opt/pre-codegen/mem_replace.mem_replace.PreCodegen.after.panic-unwind.mir @@ -6,10 +6,6 @@ fn mem_replace(_1: &mut u32, _2: u32) -> u32 { let mut _0: u32; scope 1 (inlined std::mem::replace::<u32>) { scope 2 { - scope 4 (inlined std::ptr::write::<u32>) { - } - } - scope 3 (inlined std::ptr::read::<u32>) { } } diff --git a/tests/mir-opt/pre-codegen/range_iter.forward_loop.PreCodegen.after.panic-abort.mir b/tests/mir-opt/pre-codegen/range_iter.forward_loop.PreCodegen.after.panic-abort.mir index 5d33c33d73f..0aa37203c1b 100644 --- a/tests/mir-opt/pre-codegen/range_iter.forward_loop.PreCodegen.after.panic-abort.mir +++ b/tests/mir-opt/pre-codegen/range_iter.forward_loop.PreCodegen.after.panic-abort.mir @@ -23,6 +23,14 @@ fn forward_loop(_1: u32, _2: u32, _3: impl Fn(u32)) -> () { let _7: u32; let mut _8: u32; scope 6 { + scope 8 (inlined <u32 as Step>::forward_unchecked) { + scope 9 (inlined core::num::<impl u32>::unchecked_add) { + scope 10 (inlined core::ub_checks::check_language_ub) { + scope 11 (inlined core::ub_checks::check_language_ub::runtime) { + } + } + } + } } scope 7 (inlined std::cmp::impls::<impl PartialOrd for u32>::lt) { let mut _5: u32; @@ -41,7 +49,6 @@ fn forward_loop(_1: u32, _2: u32, _3: impl Fn(u32)) -> () { bb1: { StorageLive(_9); - StorageLive(_7); StorageLive(_6); StorageLive(_5); _5 = copy _4; @@ -52,7 +59,6 @@ fn forward_loop(_1: u32, _2: u32, _3: impl Fn(u32)) -> () { bb2: { StorageDead(_6); - StorageDead(_7); StorageDead(_9); StorageDead(_4); drop(_3) -> [return: bb3, unwind unreachable]; @@ -65,24 +71,20 @@ fn forward_loop(_1: u32, _2: u32, _3: impl Fn(u32)) -> () { bb4: { _7 = copy _4; StorageLive(_8); - _8 = <u32 as Step>::forward_unchecked(copy _7, const 1_usize) -> [return: bb5, unwind unreachable]; - } - - bb5: { + _8 = AddUnchecked(copy _7, const 1_u32); _4 = move _8; StorageDead(_8); _9 = Option::<u32>::Some(copy _7); StorageDead(_6); - StorageDead(_7); _10 = copy ((_9 as Some).0: u32); StorageLive(_11); _11 = &_3; StorageLive(_12); _12 = (copy _10,); - _13 = <impl Fn(u32) as Fn<(u32,)>>::call(move _11, move _12) -> [return: bb6, unwind unreachable]; + _13 = <impl Fn(u32) as Fn<(u32,)>>::call(move _11, move _12) -> [return: bb5, unwind unreachable]; } - bb6: { + bb5: { StorageDead(_12); StorageDead(_11); StorageDead(_9); diff --git a/tests/mir-opt/pre-codegen/range_iter.forward_loop.PreCodegen.after.panic-unwind.mir b/tests/mir-opt/pre-codegen/range_iter.forward_loop.PreCodegen.after.panic-unwind.mir index ded30a15520..699d8bc8fea 100644 --- a/tests/mir-opt/pre-codegen/range_iter.forward_loop.PreCodegen.after.panic-unwind.mir +++ b/tests/mir-opt/pre-codegen/range_iter.forward_loop.PreCodegen.after.panic-unwind.mir @@ -23,6 +23,14 @@ fn forward_loop(_1: u32, _2: u32, _3: impl Fn(u32)) -> () { let _7: u32; let mut _8: u32; scope 6 { + scope 8 (inlined <u32 as Step>::forward_unchecked) { + scope 9 (inlined core::num::<impl u32>::unchecked_add) { + scope 10 (inlined core::ub_checks::check_language_ub) { + scope 11 (inlined core::ub_checks::check_language_ub::runtime) { + } + } + } + } } scope 7 (inlined std::cmp::impls::<impl PartialOrd for u32>::lt) { let mut _5: u32; @@ -41,7 +49,6 @@ fn forward_loop(_1: u32, _2: u32, _3: impl Fn(u32)) -> () { bb1: { StorageLive(_9); - StorageLive(_7); StorageLive(_6); StorageLive(_5); _5 = copy _4; @@ -52,7 +59,6 @@ fn forward_loop(_1: u32, _2: u32, _3: impl Fn(u32)) -> () { bb2: { StorageDead(_6); - StorageDead(_7); StorageDead(_9); StorageDead(_4); drop(_3) -> [return: bb3, unwind continue]; @@ -65,35 +71,31 @@ fn forward_loop(_1: u32, _2: u32, _3: impl Fn(u32)) -> () { bb4: { _7 = copy _4; StorageLive(_8); - _8 = <u32 as Step>::forward_unchecked(copy _7, const 1_usize) -> [return: bb5, unwind: bb7]; - } - - bb5: { + _8 = AddUnchecked(copy _7, const 1_u32); _4 = move _8; StorageDead(_8); _9 = Option::<u32>::Some(copy _7); StorageDead(_6); - StorageDead(_7); _10 = copy ((_9 as Some).0: u32); StorageLive(_11); _11 = &_3; StorageLive(_12); _12 = (copy _10,); - _13 = <impl Fn(u32) as Fn<(u32,)>>::call(move _11, move _12) -> [return: bb6, unwind: bb7]; + _13 = <impl Fn(u32) as Fn<(u32,)>>::call(move _11, move _12) -> [return: bb5, unwind: bb6]; } - bb6: { + bb5: { StorageDead(_12); StorageDead(_11); StorageDead(_9); goto -> bb1; } - bb7 (cleanup): { - drop(_3) -> [return: bb8, unwind terminate(cleanup)]; + bb6 (cleanup): { + drop(_3) -> [return: bb7, unwind terminate(cleanup)]; } - bb8 (cleanup): { + bb7 (cleanup): { resume; } } diff --git a/tests/mir-opt/pre-codegen/range_iter.range_iter_next.PreCodegen.after.panic-abort.mir b/tests/mir-opt/pre-codegen/range_iter.range_iter_next.PreCodegen.after.panic-abort.mir index 2621ec67531..f3033d4a2fa 100644 --- a/tests/mir-opt/pre-codegen/range_iter.range_iter_next.PreCodegen.after.panic-abort.mir +++ b/tests/mir-opt/pre-codegen/range_iter.range_iter_next.PreCodegen.after.panic-abort.mir @@ -9,6 +9,14 @@ fn range_iter_next(_1: &mut std::ops::Range<u32>) -> Option<u32> { let _5: u32; let mut _6: u32; scope 3 { + scope 5 (inlined <u32 as Step>::forward_unchecked) { + scope 6 (inlined core::num::<impl u32>::unchecked_add) { + scope 7 (inlined core::ub_checks::check_language_ub) { + scope 8 (inlined core::ub_checks::check_language_ub::runtime) { + } + } + } + } } scope 4 (inlined std::cmp::impls::<impl PartialOrd for u32>::lt) { let mut _2: u32; @@ -18,7 +26,6 @@ fn range_iter_next(_1: &mut std::ops::Range<u32>) -> Option<u32> { } bb0: { - StorageLive(_5); StorageLive(_4); StorageLive(_2); _2 = copy ((*_1).0: u32); @@ -32,25 +39,21 @@ fn range_iter_next(_1: &mut std::ops::Range<u32>) -> Option<u32> { bb1: { _0 = const Option::<u32>::None; - goto -> bb4; + goto -> bb3; } bb2: { _5 = copy ((*_1).0: u32); StorageLive(_6); - _6 = <u32 as Step>::forward_unchecked(copy _5, const 1_usize) -> [return: bb3, unwind unreachable]; - } - - bb3: { + _6 = AddUnchecked(copy _5, const 1_u32); ((*_1).0: u32) = move _6; StorageDead(_6); _0 = Option::<u32>::Some(copy _5); - goto -> bb4; + goto -> bb3; } - bb4: { + bb3: { StorageDead(_4); - StorageDead(_5); return; } } diff --git a/tests/mir-opt/pre-codegen/range_iter.range_iter_next.PreCodegen.after.panic-unwind.mir b/tests/mir-opt/pre-codegen/range_iter.range_iter_next.PreCodegen.after.panic-unwind.mir index 338fb4b9523..f3033d4a2fa 100644 --- a/tests/mir-opt/pre-codegen/range_iter.range_iter_next.PreCodegen.after.panic-unwind.mir +++ b/tests/mir-opt/pre-codegen/range_iter.range_iter_next.PreCodegen.after.panic-unwind.mir @@ -9,6 +9,14 @@ fn range_iter_next(_1: &mut std::ops::Range<u32>) -> Option<u32> { let _5: u32; let mut _6: u32; scope 3 { + scope 5 (inlined <u32 as Step>::forward_unchecked) { + scope 6 (inlined core::num::<impl u32>::unchecked_add) { + scope 7 (inlined core::ub_checks::check_language_ub) { + scope 8 (inlined core::ub_checks::check_language_ub::runtime) { + } + } + } + } } scope 4 (inlined std::cmp::impls::<impl PartialOrd for u32>::lt) { let mut _2: u32; @@ -18,7 +26,6 @@ fn range_iter_next(_1: &mut std::ops::Range<u32>) -> Option<u32> { } bb0: { - StorageLive(_5); StorageLive(_4); StorageLive(_2); _2 = copy ((*_1).0: u32); @@ -32,25 +39,21 @@ fn range_iter_next(_1: &mut std::ops::Range<u32>) -> Option<u32> { bb1: { _0 = const Option::<u32>::None; - goto -> bb4; + goto -> bb3; } bb2: { _5 = copy ((*_1).0: u32); StorageLive(_6); - _6 = <u32 as Step>::forward_unchecked(copy _5, const 1_usize) -> [return: bb3, unwind continue]; - } - - bb3: { + _6 = AddUnchecked(copy _5, const 1_u32); ((*_1).0: u32) = move _6; StorageDead(_6); _0 = Option::<u32>::Some(copy _5); - goto -> bb4; + goto -> bb3; } - bb4: { + bb3: { StorageDead(_4); - StorageDead(_5); return; } } diff --git a/tests/mir-opt/pre-codegen/slice_iter.range_loop.PreCodegen.after.panic-abort.mir b/tests/mir-opt/pre-codegen/slice_iter.range_loop.PreCodegen.after.panic-abort.mir index 151783969dd..f8d11df5185 100644 --- a/tests/mir-opt/pre-codegen/slice_iter.range_loop.PreCodegen.after.panic-abort.mir +++ b/tests/mir-opt/pre-codegen/slice_iter.range_loop.PreCodegen.after.panic-abort.mir @@ -28,6 +28,14 @@ fn range_loop(_1: &[T], _2: impl Fn(usize, &T)) -> () { let _7: usize; let mut _8: usize; scope 7 { + scope 9 (inlined <usize as Step>::forward_unchecked) { + scope 10 (inlined core::num::<impl usize>::unchecked_add) { + scope 11 (inlined core::ub_checks::check_language_ub) { + scope 12 (inlined core::ub_checks::check_language_ub::runtime) { + } + } + } + } } scope 8 (inlined std::cmp::impls::<impl PartialOrd for usize>::lt) { let mut _5: usize; @@ -47,7 +55,6 @@ fn range_loop(_1: &[T], _2: impl Fn(usize, &T)) -> () { bb1: { StorageLive(_9); - StorageLive(_7); StorageLive(_6); StorageLive(_5); _5 = copy _4; @@ -58,7 +65,6 @@ fn range_loop(_1: &[T], _2: impl Fn(usize, &T)) -> () { bb2: { StorageDead(_6); - StorageDead(_7); StorageDead(_9); StorageDead(_4); drop(_2) -> [return: bb3, unwind unreachable]; @@ -71,30 +77,26 @@ fn range_loop(_1: &[T], _2: impl Fn(usize, &T)) -> () { bb4: { _7 = copy _4; StorageLive(_8); - _8 = <usize as Step>::forward_unchecked(copy _7, const 1_usize) -> [return: bb5, unwind unreachable]; - } - - bb5: { + _8 = AddUnchecked(copy _7, const 1_usize); _4 = move _8; StorageDead(_8); _9 = Option::<usize>::Some(copy _7); StorageDead(_6); - StorageDead(_7); _10 = copy ((_9 as Some).0: usize); _11 = Lt(copy _10, copy _3); - assert(move _11, "index out of bounds: the length is {} but the index is {}", copy _3, copy _10) -> [success: bb6, unwind unreachable]; + assert(move _11, "index out of bounds: the length is {} but the index is {}", copy _3, copy _10) -> [success: bb5, unwind unreachable]; } - bb6: { + bb5: { _12 = &(*_1)[_10]; StorageLive(_13); _13 = &_2; StorageLive(_14); _14 = (copy _10, copy _12); - _15 = <impl Fn(usize, &T) as Fn<(usize, &T)>>::call(move _13, move _14) -> [return: bb7, unwind unreachable]; + _15 = <impl Fn(usize, &T) as Fn<(usize, &T)>>::call(move _13, move _14) -> [return: bb6, unwind unreachable]; } - bb7: { + bb6: { StorageDead(_14); StorageDead(_13); StorageDead(_9); diff --git a/tests/mir-opt/pre-codegen/slice_iter.range_loop.PreCodegen.after.panic-unwind.mir b/tests/mir-opt/pre-codegen/slice_iter.range_loop.PreCodegen.after.panic-unwind.mir index 006329dc20d..2c249197894 100644 --- a/tests/mir-opt/pre-codegen/slice_iter.range_loop.PreCodegen.after.panic-unwind.mir +++ b/tests/mir-opt/pre-codegen/slice_iter.range_loop.PreCodegen.after.panic-unwind.mir @@ -28,6 +28,14 @@ fn range_loop(_1: &[T], _2: impl Fn(usize, &T)) -> () { let _7: usize; let mut _8: usize; scope 7 { + scope 9 (inlined <usize as Step>::forward_unchecked) { + scope 10 (inlined core::num::<impl usize>::unchecked_add) { + scope 11 (inlined core::ub_checks::check_language_ub) { + scope 12 (inlined core::ub_checks::check_language_ub::runtime) { + } + } + } + } } scope 8 (inlined std::cmp::impls::<impl PartialOrd for usize>::lt) { let mut _5: usize; @@ -47,7 +55,6 @@ fn range_loop(_1: &[T], _2: impl Fn(usize, &T)) -> () { bb1: { StorageLive(_9); - StorageLive(_7); StorageLive(_6); StorageLive(_5); _5 = copy _4; @@ -58,7 +65,6 @@ fn range_loop(_1: &[T], _2: impl Fn(usize, &T)) -> () { bb2: { StorageDead(_6); - StorageDead(_7); StorageDead(_9); StorageDead(_4); drop(_2) -> [return: bb3, unwind continue]; @@ -71,41 +77,37 @@ fn range_loop(_1: &[T], _2: impl Fn(usize, &T)) -> () { bb4: { _7 = copy _4; StorageLive(_8); - _8 = <usize as Step>::forward_unchecked(copy _7, const 1_usize) -> [return: bb5, unwind: bb8]; - } - - bb5: { + _8 = AddUnchecked(copy _7, const 1_usize); _4 = move _8; StorageDead(_8); _9 = Option::<usize>::Some(copy _7); StorageDead(_6); - StorageDead(_7); _10 = copy ((_9 as Some).0: usize); _11 = Lt(copy _10, copy _3); - assert(move _11, "index out of bounds: the length is {} but the index is {}", copy _3, copy _10) -> [success: bb6, unwind: bb8]; + assert(move _11, "index out of bounds: the length is {} but the index is {}", copy _3, copy _10) -> [success: bb5, unwind: bb7]; } - bb6: { + bb5: { _12 = &(*_1)[_10]; StorageLive(_13); _13 = &_2; StorageLive(_14); _14 = (copy _10, copy _12); - _15 = <impl Fn(usize, &T) as Fn<(usize, &T)>>::call(move _13, move _14) -> [return: bb7, unwind: bb8]; + _15 = <impl Fn(usize, &T) as Fn<(usize, &T)>>::call(move _13, move _14) -> [return: bb6, unwind: bb7]; } - bb7: { + bb6: { StorageDead(_14); StorageDead(_13); StorageDead(_9); goto -> bb1; } - bb8 (cleanup): { - drop(_2) -> [return: bb9, unwind terminate(cleanup)]; + bb7 (cleanup): { + drop(_2) -> [return: bb8, unwind terminate(cleanup)]; } - bb9 (cleanup): { + bb8 (cleanup): { resume; } } diff --git a/tests/pretty/hir-fn-params.pp b/tests/pretty/hir-fn-params.pp new file mode 100644 index 00000000000..3799c8a3c3b --- /dev/null +++ b/tests/pretty/hir-fn-params.pp @@ -0,0 +1,38 @@ +#[prelude_import] +use ::std::prelude::rust_2015::*; +#[macro_use] +extern crate std; +//@ pretty-compare-only +//@ pretty-mode:hir +//@ pp-exact:hir-fn-params.pp + +// This tests the pretty-printing of various kinds of function parameters. + +//--------------------------------------------------------------------------- +// Normal functions and methods. + +fn normal_fn(_: u32, a: u32) { } + +struct S; +impl S { + fn method(_: u32, a: u32) { } +} + +//--------------------------------------------------------------------------- +// More exotic forms, which get a different pretty-printing path. In the past, +// anonymous params and `_` params printed incorrectly, e.g. `fn(u32, _: u32)` +// was printed as `fn(: u32, : u32)`. +// +// Ideally we would also test invalid patterns, e.g. `fn(1: u32, &a: u32)`, +// because they had similar problems. But the pretty-printing tests currently +// can't contain compile errors. + +fn bare_fn(x: fn(u32, _: u32, a: u32)) { } + +extern "C" { + unsafe fn foreign_fn(_: u32, a: u32); +} + +trait T { + fn trait_fn(u32, _: u32, a: u32); +} diff --git a/tests/pretty/hir-fn-params.rs b/tests/pretty/hir-fn-params.rs new file mode 100644 index 00000000000..5ace5289d08 --- /dev/null +++ b/tests/pretty/hir-fn-params.rs @@ -0,0 +1,34 @@ +//@ pretty-compare-only +//@ pretty-mode:hir +//@ pp-exact:hir-fn-params.pp + +// This tests the pretty-printing of various kinds of function parameters. + +//--------------------------------------------------------------------------- +// Normal functions and methods. + +fn normal_fn(_: u32, a: u32) {} + +struct S; +impl S { + fn method(_: u32, a: u32) {} +} + +//--------------------------------------------------------------------------- +// More exotic forms, which get a different pretty-printing path. In the past, +// anonymous params and `_` params printed incorrectly, e.g. `fn(u32, _: u32)` +// was printed as `fn(: u32, : u32)`. +// +// Ideally we would also test invalid patterns, e.g. `fn(1: u32, &a: u32)`, +// because they had similar problems. But the pretty-printing tests currently +// can't contain compile errors. + +fn bare_fn(x: fn(u32, _: u32, a: u32)) {} + +extern "C" { + fn foreign_fn(_: u32, a: u32); +} + +trait T { + fn trait_fn(u32, _: u32, a: u32); +} diff --git a/tests/run-make/non-unicode-env/non_unicode_env.stderr b/tests/run-make/non-unicode-env/non_unicode_env.stderr index 1f260ac9c07..32868b13f74 100644 --- a/tests/run-make/non-unicode-env/non_unicode_env.stderr +++ b/tests/run-make/non-unicode-env/non_unicode_env.stderr @@ -3,16 +3,12 @@ error: environment variable `NON_UNICODE_VAR` is not a valid Unicode string | 2 | let _ = env!("NON_UNICODE_VAR"); | ^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: this error originates in the macro `env` (in Nightly builds, run with -Z macro-backtrace for more info) error: environment variable `NON_UNICODE_VAR` is not a valid Unicode string --> non_unicode_env.rs:3:13 | 3 | let _ = option_env!("NON_UNICODE_VAR"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: this error originates in the macro `option_env` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 2 previous errors diff --git a/tests/rustdoc-json/return-type-notation.rs b/tests/rustdoc-json/return-type-notation.rs new file mode 100644 index 00000000000..2219642bfc5 --- /dev/null +++ b/tests/rustdoc-json/return-type-notation.rs @@ -0,0 +1,18 @@ +//@ edition: 2021 +// ignore-tidy-linelength + +#![crate_type = "lib"] +#![feature(return_type_notation)] + +pub trait Foo { + async fn bar(); +} + +//@ is "$.index[*][?(@.name=='foo')].inner.function.generics.params[0].kind.type.bounds[0].trait_bound.trait.args.angle_bracketed.constraints[0].args" '"return_type_notation"' +//@ ismany "$.index[*][?(@.name=='foo')].inner.function.generics.where_predicates[*].bound_predicate.type.qualified_path.args" '"return_type_notation"' '"return_type_notation"' +pub fn foo<T: Foo<bar(..): Send>>() +where + <T as Foo>::bar(..): 'static, + T::bar(..): Sync, +{ +} diff --git a/tests/rustdoc-ui/doctest/relative-path-include-bytes-132203.edition2015.stdout b/tests/rustdoc-ui/doctest/relative-path-include-bytes-132203.edition2015.stdout index 13e142df837..ff26e7e3231 100644 --- a/tests/rustdoc-ui/doctest/relative-path-include-bytes-132203.edition2015.stdout +++ b/tests/rustdoc-ui/doctest/relative-path-include-bytes-132203.edition2015.stdout @@ -10,8 +10,6 @@ error: couldn't read `$DIR/relative-dir-empty-file`: $FILE_NOT_FOUND_MSG (os err | LL | let x = include_bytes!("relative-dir-empty-file"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: this error originates in the macro `include_bytes` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/rustdoc/return-type-notation.rs b/tests/rustdoc/return-type-notation.rs new file mode 100644 index 00000000000..405e98eb28d --- /dev/null +++ b/tests/rustdoc/return-type-notation.rs @@ -0,0 +1,18 @@ +//@ edition: 2021 + +#![crate_type = "lib"] +#![feature(return_type_notation)] + +pub trait Foo { + async fn bar(); +} + +//@ has "return_type_notation/fn.foo.html" +//@ has - '//pre[@class="rust item-decl"]' "pub fn foo<T: Foo<bar(..): Send>>()" +//@ has - '//pre[@class="rust item-decl"]' "where <T as Foo>::bar(..): 'static, T::bar(..): Sync" +pub fn foo<T: Foo<bar(..): Send>>() +where + <T as Foo>::bar(..): 'static, + T::bar(..): Sync, +{ +} diff --git a/tests/ui/abi/compatibility.rs b/tests/ui/abi/compatibility.rs index 01d90717107..64e65ece85d 100644 --- a/tests/ui/abi/compatibility.rs +++ b/tests/ui/abi/compatibility.rs @@ -40,6 +40,7 @@ //@ revisions: loongarch64 //@[loongarch64] compile-flags: --target loongarch64-unknown-linux-gnu //@[loongarch64] needs-llvm-components: loongarch +//@[loongarch64] min-llvm-version: 20 //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 diff --git a/tests/ui/alloc-error/alloc-error-handler-bad-signature-1.stderr b/tests/ui/alloc-error/alloc-error-handler-bad-signature-1.stderr index 80ff10e13d8..15314fac37b 100644 --- a/tests/ui/alloc-error/alloc-error-handler-bad-signature-1.stderr +++ b/tests/ui/alloc-error/alloc-error-handler-bad-signature-1.stderr @@ -18,7 +18,6 @@ LL | fn oom( | ^^^ LL | info: &Layout, | ------------- - = note: this error originates in the attribute macro `alloc_error_handler` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0308]: mismatched types --> $DIR/alloc-error-handler-bad-signature-1.rs:10:1 @@ -35,7 +34,6 @@ LL | | } | = note: expected type `!` found unit type `()` - = note: this error originates in the attribute macro `alloc_error_handler` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 2 previous errors diff --git a/tests/ui/alloc-error/alloc-error-handler-bad-signature-2.stderr b/tests/ui/alloc-error/alloc-error-handler-bad-signature-2.stderr index 7a495380f2b..2ab42638411 100644 --- a/tests/ui/alloc-error/alloc-error-handler-bad-signature-2.stderr +++ b/tests/ui/alloc-error/alloc-error-handler-bad-signature-2.stderr @@ -26,7 +26,6 @@ LL | fn oom( | ^^^ LL | info: Layout, | ------------ - = note: this error originates in the attribute macro `alloc_error_handler` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0308]: mismatched types --> $DIR/alloc-error-handler-bad-signature-2.rs:10:1 @@ -43,7 +42,6 @@ LL | | } | = note: expected type `!` found unit type `()` - = note: this error originates in the attribute macro `alloc_error_handler` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 2 previous errors diff --git a/tests/ui/alloc-error/alloc-error-handler-bad-signature-3.stderr b/tests/ui/alloc-error/alloc-error-handler-bad-signature-3.stderr index 3be219bdb06..3a410174f54 100644 --- a/tests/ui/alloc-error/alloc-error-handler-bad-signature-3.stderr +++ b/tests/ui/alloc-error/alloc-error-handler-bad-signature-3.stderr @@ -14,7 +14,6 @@ note: function defined here | LL | fn oom() -> ! { | ^^^ - = note: this error originates in the attribute macro `alloc_error_handler` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/allocator/not-an-allocator.stderr b/tests/ui/allocator/not-an-allocator.stderr index e1967b70013..079bf9334eb 100644 --- a/tests/ui/allocator/not-an-allocator.stderr +++ b/tests/ui/allocator/not-an-allocator.stderr @@ -7,7 +7,6 @@ LL | static A: usize = 0; | ^^^^^ the trait `GlobalAlloc` is not implemented for `usize` | = help: the trait `GlobalAlloc` is implemented for `System` - = note: this error originates in the attribute macro `global_allocator` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `usize: GlobalAlloc` is not satisfied --> $DIR/not-an-allocator.rs:2:11 @@ -19,7 +18,6 @@ LL | static A: usize = 0; | = help: the trait `GlobalAlloc` is implemented for `System` = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - = note: this error originates in the attribute macro `global_allocator` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `usize: GlobalAlloc` is not satisfied --> $DIR/not-an-allocator.rs:2:11 @@ -31,7 +29,6 @@ LL | static A: usize = 0; | = help: the trait `GlobalAlloc` is implemented for `System` = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - = note: this error originates in the attribute macro `global_allocator` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `usize: GlobalAlloc` is not satisfied --> $DIR/not-an-allocator.rs:2:11 @@ -43,7 +40,6 @@ LL | static A: usize = 0; | = help: the trait `GlobalAlloc` is implemented for `System` = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - = note: this error originates in the attribute macro `global_allocator` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 4 previous errors diff --git a/tests/ui/allocator/two-allocators.stderr b/tests/ui/allocator/two-allocators.stderr index 1eecbc0a97b..5308232a20b 100644 --- a/tests/ui/allocator/two-allocators.stderr +++ b/tests/ui/allocator/two-allocators.stderr @@ -7,8 +7,6 @@ LL | #[global_allocator] | ------------------- in this procedural macro expansion LL | static B: System = System; | ^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot define a new global allocator - | - = note: this error originates in the attribute macro `global_allocator` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/asm/ice-bad-err-span-in-template-129503.stderr b/tests/ui/asm/ice-bad-err-span-in-template-129503.stderr index ffa9362ed95..066959a052d 100644 --- a/tests/ui/asm/ice-bad-err-span-in-template-129503.stderr +++ b/tests/ui/asm/ice-bad-err-span-in-template-129503.stderr @@ -5,7 +5,6 @@ LL | asm!(concat!(r#"lJÆ�.�"#, "r} {}")); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ unmatched `}` in asm template string | = note: if you intended to print `}`, you can escape it using `}}` - = note: this error originates in the macro `concat` (in Nightly builds, run with -Z macro-backtrace for more info) error: invalid asm template string: unmatched `}` found --> $DIR/ice-bad-err-span-in-template-129503.rs:18:10 @@ -14,7 +13,6 @@ LL | asm!(concat!("abc", "r} {}")); | ^^^^^^^^^^^^^^^^^^^^^^^ unmatched `}` in asm template string | = note: if you intended to print `}`, you can escape it using `}}` - = note: this error originates in the macro `concat` (in Nightly builds, run with -Z macro-backtrace for more info) error: invalid asm template string: unmatched `}` found --> $DIR/ice-bad-err-span-in-template-129503.rs:24:19 diff --git a/tests/ui/asm/loongarch/bad-reg.loongarch64_lp64d.stderr b/tests/ui/asm/loongarch/bad-reg.loongarch64_lp64d.stderr index 0e544119650..c88f3af7642 100644 --- a/tests/ui/asm/loongarch/bad-reg.loongarch64_lp64d.stderr +++ b/tests/ui/asm/loongarch/bad-reg.loongarch64_lp64d.stderr @@ -1,35 +1,35 @@ error: invalid register `$r0`: constant zero cannot be used as an operand for inline asm - --> $DIR/bad-reg.rs:22:18 + --> $DIR/bad-reg.rs:23:18 | LL | asm!("", out("$r0") _); | ^^^^^^^^^^^^ error: invalid register `$tp`: reserved for TLS - --> $DIR/bad-reg.rs:24:18 + --> $DIR/bad-reg.rs:25:18 | LL | asm!("", out("$tp") _); | ^^^^^^^^^^^^ error: invalid register `$sp`: the stack pointer cannot be used as an operand for inline asm - --> $DIR/bad-reg.rs:26:18 + --> $DIR/bad-reg.rs:27:18 | LL | asm!("", out("$sp") _); | ^^^^^^^^^^^^ error: invalid register `$r21`: reserved by the ABI - --> $DIR/bad-reg.rs:28:18 + --> $DIR/bad-reg.rs:29:18 | LL | asm!("", out("$r21") _); | ^^^^^^^^^^^^^ error: invalid register `$fp`: the frame pointer cannot be used as an operand for inline asm - --> $DIR/bad-reg.rs:30:18 + --> $DIR/bad-reg.rs:31:18 | LL | asm!("", out("$fp") _); | ^^^^^^^^^^^^ error: invalid register `$r31`: $r31 is used internally by LLVM and cannot be used as an operand for inline asm - --> $DIR/bad-reg.rs:32:18 + --> $DIR/bad-reg.rs:33:18 | LL | asm!("", out("$r31") _); | ^^^^^^^^^^^^^ diff --git a/tests/ui/asm/loongarch/bad-reg.loongarch64_lp64s.stderr b/tests/ui/asm/loongarch/bad-reg.loongarch64_lp64s.stderr index 6d0410dc6a1..cb8e55a9722 100644 --- a/tests/ui/asm/loongarch/bad-reg.loongarch64_lp64s.stderr +++ b/tests/ui/asm/loongarch/bad-reg.loongarch64_lp64s.stderr @@ -1,59 +1,59 @@ error: invalid register `$r0`: constant zero cannot be used as an operand for inline asm - --> $DIR/bad-reg.rs:22:18 + --> $DIR/bad-reg.rs:23:18 | LL | asm!("", out("$r0") _); | ^^^^^^^^^^^^ error: invalid register `$tp`: reserved for TLS - --> $DIR/bad-reg.rs:24:18 + --> $DIR/bad-reg.rs:25:18 | LL | asm!("", out("$tp") _); | ^^^^^^^^^^^^ error: invalid register `$sp`: the stack pointer cannot be used as an operand for inline asm - --> $DIR/bad-reg.rs:26:18 + --> $DIR/bad-reg.rs:27:18 | LL | asm!("", out("$sp") _); | ^^^^^^^^^^^^ error: invalid register `$r21`: reserved by the ABI - --> $DIR/bad-reg.rs:28:18 + --> $DIR/bad-reg.rs:29:18 | LL | asm!("", out("$r21") _); | ^^^^^^^^^^^^^ error: invalid register `$fp`: the frame pointer cannot be used as an operand for inline asm - --> $DIR/bad-reg.rs:30:18 + --> $DIR/bad-reg.rs:31:18 | LL | asm!("", out("$fp") _); | ^^^^^^^^^^^^ error: invalid register `$r31`: $r31 is used internally by LLVM and cannot be used as an operand for inline asm - --> $DIR/bad-reg.rs:32:18 + --> $DIR/bad-reg.rs:33:18 | LL | asm!("", out("$r31") _); | ^^^^^^^^^^^^^ error: register class `freg` requires at least one of the following target features: d, f - --> $DIR/bad-reg.rs:36:26 + --> $DIR/bad-reg.rs:37:26 | LL | asm!("/* {} */", in(freg) f); | ^^^^^^^^^^ error: register class `freg` requires at least one of the following target features: d, f - --> $DIR/bad-reg.rs:38:26 + --> $DIR/bad-reg.rs:39:26 | LL | asm!("/* {} */", out(freg) _); | ^^^^^^^^^^^ error: register class `freg` requires at least one of the following target features: d, f - --> $DIR/bad-reg.rs:40:26 + --> $DIR/bad-reg.rs:41:26 | LL | asm!("/* {} */", in(freg) d); | ^^^^^^^^^^ error: register class `freg` requires at least one of the following target features: d, f - --> $DIR/bad-reg.rs:42:26 + --> $DIR/bad-reg.rs:43:26 | LL | asm!("/* {} */", out(freg) d); | ^^^^^^^^^^^ diff --git a/tests/ui/asm/loongarch/bad-reg.rs b/tests/ui/asm/loongarch/bad-reg.rs index 685b460bc92..db1c778e5a2 100644 --- a/tests/ui/asm/loongarch/bad-reg.rs +++ b/tests/ui/asm/loongarch/bad-reg.rs @@ -1,6 +1,7 @@ //@ add-core-stubs //@ needs-asm-support //@ revisions: loongarch64_lp64d loongarch64_lp64s +//@ min-llvm-version: 20 //@[loongarch64_lp64d] compile-flags: --target loongarch64-unknown-linux-gnu //@[loongarch64_lp64d] needs-llvm-components: loongarch //@[loongarch64_lp64s] compile-flags: --target loongarch64-unknown-none-softfloat diff --git a/tests/ui/asm/x86_64/goto.stderr b/tests/ui/asm/x86_64/goto.stderr index 8f89e2b1290..78b726b3f3d 100644 --- a/tests/ui/asm/x86_64/goto.stderr +++ b/tests/ui/asm/x86_64/goto.stderr @@ -17,7 +17,6 @@ note: the lint level is defined here | LL | #[warn(unreachable_code)] | ^^^^^^^^^^^^^^^^ - = note: this warning originates in the macro `unreachable` (in Nightly builds, run with -Z macro-backtrace for more info) warning: 1 warning emitted diff --git a/tests/ui/associated-type-bounds/return-type-notation/basic.without.stderr b/tests/ui/associated-type-bounds/return-type-notation/basic.without.stderr index 0a31cc67533..459f3ea1642 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/basic.without.stderr +++ b/tests/ui/associated-type-bounds/return-type-notation/basic.without.stderr @@ -15,6 +15,10 @@ note: required by a bound in `is_send` | LL | fn is_send(_: impl Send) {} | ^^^^ required by this bound in `is_send` +help: consider further restricting the associated type + | +LL | >() where <T as Foo>::method(..): Send { + | ++++++++++++++++++++++++++++++++++ error: aborting due to 1 previous error diff --git a/tests/ui/associated-type-bounds/return-type-notation/display.stderr b/tests/ui/associated-type-bounds/return-type-notation/display.stderr index b895d796952..a614089ce40 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/display.stderr +++ b/tests/ui/associated-type-bounds/return-type-notation/display.stderr @@ -11,6 +11,10 @@ note: required by a bound in `needs_trait` | LL | fn needs_trait(_: impl Trait) {} | ^^^^^ required by this bound in `needs_trait` +help: consider further restricting the associated type + | +LL | fn foo<T: Assoc>(t: T) where <T as Assoc>::method(..): Trait { + | +++++++++++++++++++++++++++++++++++++ error[E0277]: the trait bound `impl Sized { <T as Assoc>::method_with_lt(..) }: Trait` is not satisfied --> $DIR/display.rs:16:17 @@ -25,6 +29,10 @@ note: required by a bound in `needs_trait` | LL | fn needs_trait(_: impl Trait) {} | ^^^^^ required by this bound in `needs_trait` +help: consider further restricting the associated type + | +LL | fn foo<T: Assoc>(t: T) where <T as Assoc>::method_with_lt(..): Trait { + | +++++++++++++++++++++++++++++++++++++++++++++ error[E0277]: the trait bound `impl Sized: Trait` is not satisfied --> $DIR/display.rs:18:17 diff --git a/tests/ui/associated-type-bounds/return-type-notation/rendering.fixed b/tests/ui/associated-type-bounds/return-type-notation/rendering.fixed new file mode 100644 index 00000000000..72c174a0ca0 --- /dev/null +++ b/tests/ui/associated-type-bounds/return-type-notation/rendering.fixed @@ -0,0 +1,15 @@ +//@ run-rustfix + +#![allow(unused)] +#![feature(return_type_notation)] + +trait Foo { + fn missing() -> impl Sized; +} + +impl Foo for () { + //~^ ERROR not all trait items implemented, missing: `missing` +fn missing() -> impl Sized { todo!() } +} + +fn main() {} diff --git a/tests/ui/associated-type-bounds/return-type-notation/rendering.rs b/tests/ui/associated-type-bounds/return-type-notation/rendering.rs new file mode 100644 index 00000000000..4c9948d4c06 --- /dev/null +++ b/tests/ui/associated-type-bounds/return-type-notation/rendering.rs @@ -0,0 +1,14 @@ +//@ run-rustfix + +#![allow(unused)] +#![feature(return_type_notation)] + +trait Foo { + fn missing() -> impl Sized; +} + +impl Foo for () { + //~^ ERROR not all trait items implemented, missing: `missing` +} + +fn main() {} diff --git a/tests/ui/associated-type-bounds/return-type-notation/rendering.stderr b/tests/ui/associated-type-bounds/return-type-notation/rendering.stderr new file mode 100644 index 00000000000..62fdeb059dd --- /dev/null +++ b/tests/ui/associated-type-bounds/return-type-notation/rendering.stderr @@ -0,0 +1,12 @@ +error[E0046]: not all trait items implemented, missing: `missing` + --> $DIR/rendering.rs:10:1 + | +LL | fn missing() -> impl Sized; + | --------------------------- `missing` from trait +... +LL | impl Foo for () { + | ^^^^^^^^^^^^^^^ missing `missing` in implementation + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0046`. diff --git a/tests/ui/associated-types/issue-38821.stderr b/tests/ui/associated-types/issue-38821.stderr index dc919299710..8a19142b730 100644 --- a/tests/ui/associated-types/issue-38821.stderr +++ b/tests/ui/associated-types/issue-38821.stderr @@ -53,7 +53,6 @@ LL | impl<T: NotNull> IntoNullable for T { | ------- ^^^^^^^^^^^^ ^ | | | unsatisfied trait bound introduced here - = note: this error originates in the derive macro `Debug` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider further restricting the associated type | LL | Expr: Expression<SqlType=<Col::SqlType as IntoNullable>::Nullable>, <Col as Expression>::SqlType: NotNull, @@ -73,7 +72,6 @@ LL | impl<T: NotNull> IntoNullable for T { | | | unsatisfied trait bound introduced here = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - = note: this error originates in the derive macro `Debug` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider further restricting the associated type | LL | Expr: Expression<SqlType=<Col::SqlType as IntoNullable>::Nullable>, <Col as Expression>::SqlType: NotNull, @@ -92,7 +90,6 @@ LL | impl<T: NotNull> IntoNullable for T { | ------- ^^^^^^^^^^^^ ^ | | | unsatisfied trait bound introduced here - = note: this error originates in the derive macro `Debug` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `<Col as Expression>::SqlType: NotNull` is not satisfied --> $DIR/issue-38821.rs:23:10 @@ -108,7 +105,6 @@ LL | impl<T: NotNull> IntoNullable for T { | | | unsatisfied trait bound introduced here = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - = note: this error originates in the derive macro `Debug` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `<Col as Expression>::SqlType: NotNull` is not satisfied --> $DIR/issue-38821.rs:23:17 @@ -123,7 +119,6 @@ LL | impl<T: NotNull> IntoNullable for T { | ------- ^^^^^^^^^^^^ ^ | | | unsatisfied trait bound introduced here - = note: this error originates in the derive macro `Copy` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider further restricting the associated type | LL | Expr: Expression<SqlType=<Col::SqlType as IntoNullable>::Nullable>, <Col as Expression>::SqlType: NotNull, @@ -143,7 +138,6 @@ LL | impl<T: NotNull> IntoNullable for T { | | | unsatisfied trait bound introduced here = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - = note: this error originates in the derive macro `Copy` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider further restricting the associated type | LL | Expr: Expression<SqlType=<Col::SqlType as IntoNullable>::Nullable>, <Col as Expression>::SqlType: NotNull, @@ -162,7 +156,6 @@ LL | impl<T: NotNull> IntoNullable for T { | ------- ^^^^^^^^^^^^ ^ | | | unsatisfied trait bound introduced here - = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider further restricting the associated type | LL | Expr: Expression<SqlType=<Col::SqlType as IntoNullable>::Nullable>, <Col as Expression>::SqlType: NotNull, @@ -182,7 +175,6 @@ LL | impl<T: NotNull> IntoNullable for T { | | | unsatisfied trait bound introduced here = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider further restricting the associated type | LL | Expr: Expression<SqlType=<Col::SqlType as IntoNullable>::Nullable>, <Col as Expression>::SqlType: NotNull, @@ -201,7 +193,6 @@ LL | impl<T: NotNull> IntoNullable for T { | ------- ^^^^^^^^^^^^ ^ | | | unsatisfied trait bound introduced here - = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `<Col as Expression>::SqlType: NotNull` is not satisfied --> $DIR/issue-38821.rs:23:23 @@ -217,7 +208,6 @@ LL | impl<T: NotNull> IntoNullable for T { | | | unsatisfied trait bound introduced here = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `<Col as Expression>::SqlType: NotNull` is not satisfied --> $DIR/issue-38821.rs:23:10 @@ -233,7 +223,6 @@ LL | impl<T: NotNull> IntoNullable for T { | | | unsatisfied trait bound introduced here = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - = note: this error originates in the derive macro `Debug` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `<Col as Expression>::SqlType: NotNull` is not satisfied --> $DIR/issue-38821.rs:23:10 @@ -249,7 +238,6 @@ LL | impl<T: NotNull> IntoNullable for T { | | | unsatisfied trait bound introduced here = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - = note: this error originates in the derive macro `Debug` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `<Col as Expression>::SqlType: NotNull` is not satisfied --> $DIR/issue-38821.rs:23:23 @@ -265,7 +253,6 @@ LL | impl<T: NotNull> IntoNullable for T { | | | unsatisfied trait bound introduced here = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `<Col as Expression>::SqlType: NotNull` is not satisfied --> $DIR/issue-38821.rs:23:23 @@ -281,7 +268,6 @@ LL | impl<T: NotNull> IntoNullable for T { | | | unsatisfied trait bound introduced here = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `<Col as Expression>::SqlType: NotNull` is not satisfied --> $DIR/issue-38821.rs:23:10 @@ -297,7 +283,6 @@ LL | impl<T: NotNull> IntoNullable for T { | | | unsatisfied trait bound introduced here = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - = note: this error originates in the derive macro `Debug` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `<Col as Expression>::SqlType: NotNull` is not satisfied --> $DIR/issue-38821.rs:23:23 @@ -313,7 +298,6 @@ LL | impl<T: NotNull> IntoNullable for T { | | | unsatisfied trait bound introduced here = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 18 previous errors diff --git a/tests/ui/attributes/extented-attribute-macro-error.stderr b/tests/ui/attributes/extented-attribute-macro-error.stderr index 884f3c7b166..7b93b98f64c 100644 --- a/tests/ui/attributes/extented-attribute-macro-error.stderr +++ b/tests/ui/attributes/extented-attribute-macro-error.stderr @@ -3,8 +3,6 @@ error: couldn't read the file | LL | #![doc = include_str!("../not_existing_file.md")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: this error originates in the macro `include_str` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/attributes/outer-mod-attr-applies-only-to-first.rs b/tests/ui/attributes/outer-mod-attr-applies-only-to-first.rs new file mode 100644 index 00000000000..ec521c1afb5 --- /dev/null +++ b/tests/ui/attributes/outer-mod-attr-applies-only-to-first.rs @@ -0,0 +1,16 @@ +//! Regression test to check that outer attributes applied to the first module item is applied to +//! its attached module item only, and not also to other subsequent module items +//! +//! Commit: <https://github.com/rust-lang/rust/commit/7aee9f7b56f8d96f9444ebb1d06e32e024b81974> + +//@ check-pass +//@ compile-flags: --cfg=first +//@ no-auto-check-cfg + +#[cfg(first)] +mod hello {} + +#[cfg(not_set)] +mod hello {} + +fn main() {} diff --git a/tests/ui/borrowck/issue-114374-invalid-help-fmt-args.stderr b/tests/ui/borrowck/issue-114374-invalid-help-fmt-args.stderr index 3ee89d9734a..30f292f71a2 100644 --- a/tests/ui/borrowck/issue-114374-invalid-help-fmt-args.stderr +++ b/tests/ui/borrowck/issue-114374-invalid-help-fmt-args.stderr @@ -11,7 +11,6 @@ LL | bar(x); | = note: the result of `format_args!` can only be assigned directly if no placeholders in its arguments are used = note: to learn more, visit <https://doc.rust-lang.org/std/macro.format_args.html> - = note: this error originates in the macro `format_args` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0716]: temporary value dropped while borrowed --> $DIR/issue-114374-invalid-help-fmt-args.rs:10:15 @@ -26,7 +25,6 @@ LL | bar(foo); | = note: the result of `format_args!` can only be assigned directly if no placeholders in its arguments are used = note: to learn more, visit <https://doc.rust-lang.org/std/macro.format_args.html> - = note: this error originates in the macro `format_args` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 2 previous errors diff --git a/tests/ui/borrowck/issue-81899.stderr b/tests/ui/borrowck/issue-81899.stderr index 2e6e7511ec9..b5cd5e4abf3 100644 --- a/tests/ui/borrowck/issue-81899.stderr +++ b/tests/ui/borrowck/issue-81899.stderr @@ -9,7 +9,6 @@ note: inside `f::<{closure@$DIR/issue-81899.rs:4:31: 4:34}>` | LL | panic!() | ^^^^^^^^ the failure occurred here - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/issue-81899.rs:4:23 diff --git a/tests/ui/borrowck/issue-88434-minimal-example.stderr b/tests/ui/borrowck/issue-88434-minimal-example.stderr index c8ac13a3473..d9f3b4dcb90 100644 --- a/tests/ui/borrowck/issue-88434-minimal-example.stderr +++ b/tests/ui/borrowck/issue-88434-minimal-example.stderr @@ -9,7 +9,6 @@ note: inside `f::<{closure@$DIR/issue-88434-minimal-example.rs:3:25: 3:28}>` | LL | panic!() | ^^^^^^^^ the failure occurred here - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/issue-88434-minimal-example.rs:3:21 diff --git a/tests/ui/borrowck/issue-88434-removal-index-should-be-less.stderr b/tests/ui/borrowck/issue-88434-removal-index-should-be-less.stderr index 0041759609c..c82b5cf786d 100644 --- a/tests/ui/borrowck/issue-88434-removal-index-should-be-less.stderr +++ b/tests/ui/borrowck/issue-88434-removal-index-should-be-less.stderr @@ -9,7 +9,6 @@ note: inside `f::<{closure@$DIR/issue-88434-removal-index-should-be-less.rs:3:31 | LL | panic!() | ^^^^^^^^ the failure occurred here - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/issue-88434-removal-index-should-be-less.rs:3:23 diff --git a/tests/ui/cast/ptr-to-trait-obj-wrap.rs b/tests/ui/cast/ptr-to-trait-obj-wrap.rs index 6f9f6bddb99..9809ea80f95 100644 --- a/tests/ui/cast/ptr-to-trait-obj-wrap.rs +++ b/tests/ui/cast/ptr-to-trait-obj-wrap.rs @@ -2,7 +2,6 @@ // work. Note that the metadata doesn't change when a DST is wrapped in a // structure, so these casts *are* fine. // -// `unwrap` and `unwrap_nested` currently don't work due to a compiler limitation. //@ check-pass trait A {} diff --git a/tests/ui/check-cfg/target_feature.stderr b/tests/ui/check-cfg/target_feature.stderr index 5b82d3f539f..a9d67481ba1 100644 --- a/tests/ui/check-cfg/target_feature.stderr +++ b/tests/ui/check-cfg/target_feature.stderr @@ -60,6 +60,7 @@ LL | cfg!(target_feature = "_UNEXPECTED_VALUE"); `d32` `deflate-conversion` `dit` +`div32` `doloop` `dotprod` `dpb` @@ -133,8 +134,11 @@ LL | cfg!(target_feature = "_UNEXPECTED_VALUE"); `jsconv` `kl` `lahfsahf` +`lam-bh` +`lamcas` `lasx` `lbt` +`ld-seq-sa` `leoncasa` `lor` `lse` @@ -190,6 +194,7 @@ LL | cfg!(target_feature = "_UNEXPECTED_VALUE"); `reserve-x18` `rtm` `sb` +`scq` `sha` `sha2` `sha3` diff --git a/tests/ui/codemap_tests/issue-28308.stderr b/tests/ui/codemap_tests/issue-28308.stderr index efd8fa22fa5..7bc9e05dfc0 100644 --- a/tests/ui/codemap_tests/issue-28308.stderr +++ b/tests/ui/codemap_tests/issue-28308.stderr @@ -3,8 +3,6 @@ error[E0600]: cannot apply unary operator `!` to type `&'static str` | LL | assert!("foo"); | ^^^^^^^^^^^^^^ cannot apply unary operator `!` - | - = note: this error originates in the macro `assert` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/coherence/const-errs-dont-conflict-103369.stderr b/tests/ui/coherence/const-errs-dont-conflict-103369.stderr index 4acaaf22ae8..b2104299f65 100644 --- a/tests/ui/coherence/const-errs-dont-conflict-103369.stderr +++ b/tests/ui/coherence/const-errs-dont-conflict-103369.stderr @@ -9,7 +9,6 @@ note: inside `my_fn` | LL | panic!("Some error occurred"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the failure occurred here - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of constant value failed --> $DIR/const-errs-dont-conflict-103369.rs:7:25 @@ -22,7 +21,6 @@ note: inside `my_fn` | LL | panic!("Some error occurred"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the failure occurred here - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 2 previous errors diff --git a/tests/ui/coherence/warn-when-cycle-is-error-in-coherence.stderr b/tests/ui/coherence/warn-when-cycle-is-error-in-coherence.stderr index af4dbfcad0e..a9a99fb28d8 100644 --- a/tests/ui/coherence/warn-when-cycle-is-error-in-coherence.stderr +++ b/tests/ui/coherence/warn-when-cycle-is-error-in-coherence.stderr @@ -9,8 +9,6 @@ LL | | where LL | | T: Borrow<Q>, LL | | Q: ?Sized + PartialOrd, | |___________________________- first implementation here - | - = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/const-generics/adt_const_params/check-type-in-mir.rs b/tests/ui/const-generics/adt_const_params/check-type-in-mir.rs new file mode 100644 index 00000000000..bec485b001c --- /dev/null +++ b/tests/ui/const-generics/adt_const_params/check-type-in-mir.rs @@ -0,0 +1,16 @@ +// Ensure that we actually treat `N`'s type as `Invariant<'static>` in MIR typeck. + +#![feature(adt_const_params)] + +use std::marker::ConstParamTy; +use std::ops::Deref; + +#[derive(ConstParamTy, PartialEq, Eq)] +struct Invariant<'a>(<&'a () as Deref>::Target); + +fn test<'a, const N: Invariant<'static>>() { + let x: Invariant<'a> = N; + //~^ ERROR lifetime may not live long enough +} + +fn main() {} diff --git a/tests/ui/const-generics/adt_const_params/check-type-in-mir.stderr b/tests/ui/const-generics/adt_const_params/check-type-in-mir.stderr new file mode 100644 index 00000000000..7e265f33f35 --- /dev/null +++ b/tests/ui/const-generics/adt_const_params/check-type-in-mir.stderr @@ -0,0 +1,14 @@ +error: lifetime may not live long enough + --> $DIR/check-type-in-mir.rs:12:28 + | +LL | fn test<'a, const N: Invariant<'static>>() { + | -- lifetime `'a` defined here +LL | let x: Invariant<'a> = N; + | ^ assignment requires that `'a` must outlive `'static` + | + = note: requirement occurs because of the type `Invariant<'_>`, which makes the generic argument `'_` invariant + = note: the struct `Invariant<'a>` is invariant over the parameter `'a` + = help: see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance + +error: aborting due to 1 previous error + diff --git a/tests/ui/const-generics/adt_const_params/const_param_ty_impl_bad_field.stderr b/tests/ui/const-generics/adt_const_params/const_param_ty_impl_bad_field.stderr index 808a569fcad..a4e5736d834 100644 --- a/tests/ui/const-generics/adt_const_params/const_param_ty_impl_bad_field.stderr +++ b/tests/ui/const-generics/adt_const_params/const_param_ty_impl_bad_field.stderr @@ -15,8 +15,6 @@ LL | #[derive(std::marker::UnsizedConstParamTy, Eq, PartialEq)] LL | LL | struct CantParamDerive(NotParam); | -------- this field does not implement `ConstParamTy_` - | - = note: this error originates in the derive macro `std::marker::UnsizedConstParamTy` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 2 previous errors diff --git a/tests/ui/const-generics/adt_const_params/const_param_ty_impl_no_structural_eq.stderr b/tests/ui/const-generics/adt_const_params/const_param_ty_impl_no_structural_eq.stderr index 80d9942c591..b651cca3216 100644 --- a/tests/ui/const-generics/adt_const_params/const_param_ty_impl_no_structural_eq.stderr +++ b/tests/ui/const-generics/adt_const_params/const_param_ty_impl_no_structural_eq.stderr @@ -29,7 +29,6 @@ LL | #[derive(std::marker::UnsizedConstParamTy)] | note: required by a bound in `UnsizedConstParamTy` --> $SRC_DIR/core/src/marker.rs:LL:COL - = note: this error originates in the derive macro `std::marker::UnsizedConstParamTy` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `CantParamDerive` with `#[derive(Eq)]` | LL + #[derive(Eq)] @@ -44,7 +43,6 @@ LL | #[derive(std::marker::UnsizedConstParamTy)] | note: required by a bound in `UnsizedConstParamTy` --> $SRC_DIR/core/src/marker.rs:LL:COL - = note: this error originates in the derive macro `std::marker::UnsizedConstParamTy` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 4 previous errors diff --git a/tests/ui/const-generics/adt_const_params/nested_bad_const_param_ty.stderr b/tests/ui/const-generics/adt_const_params/nested_bad_const_param_ty.stderr index c2520f1d103..6b8d2394a86 100644 --- a/tests/ui/const-generics/adt_const_params/nested_bad_const_param_ty.stderr +++ b/tests/ui/const-generics/adt_const_params/nested_bad_const_param_ty.stderr @@ -12,7 +12,6 @@ note: the `ConstParamTy_` impl for `[*const u8; 1]` requires that `*const u8: Co | LL | struct Foo([*const u8; 1]); | ^^^^^^^^^^^^^^ - = note: this error originates in the derive macro `ConstParamTy` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0204]: the trait `ConstParamTy_` cannot be implemented for this type --> $DIR/nested_bad_const_param_ty.rs:11:10 @@ -28,7 +27,6 @@ note: the `ConstParamTy_` impl for `[*mut u8; 1]` requires that `*mut u8: ConstP | LL | struct Foo2([*mut u8; 1]); | ^^^^^^^^^^^^ - = note: this error originates in the derive macro `ConstParamTy` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0204]: the trait `ConstParamTy_` cannot be implemented for this type --> $DIR/nested_bad_const_param_ty.rs:16:10 @@ -44,7 +42,6 @@ note: the `ConstParamTy_` impl for `[fn(); 1]` requires that `fn(): ConstParamTy | LL | struct Foo3([fn(); 1]); | ^^^^^^^^^ - = note: this error originates in the derive macro `ConstParamTy` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0204]: the trait `ConstParamTy_` cannot be implemented for this type --> $DIR/nested_bad_const_param_ty.rs:6:10 @@ -60,7 +57,6 @@ note: the `ConstParamTy_` impl for `[*const u8; 1]` requires that `*const u8: Un | LL | struct Foo([*const u8; 1]); | ^^^^^^^^^^^^^^ - = note: this error originates in the derive macro `ConstParamTy` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0204]: the trait `ConstParamTy_` cannot be implemented for this type --> $DIR/nested_bad_const_param_ty.rs:11:10 @@ -76,7 +72,6 @@ note: the `ConstParamTy_` impl for `[*mut u8; 1]` requires that `*mut u8: Unsize | LL | struct Foo2([*mut u8; 1]); | ^^^^^^^^^^^^ - = note: this error originates in the derive macro `ConstParamTy` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0204]: the trait `ConstParamTy_` cannot be implemented for this type --> $DIR/nested_bad_const_param_ty.rs:16:10 @@ -92,7 +87,6 @@ note: the `ConstParamTy_` impl for `[fn(); 1]` requires that `fn(): UnsizedConst | LL | struct Foo3([fn(); 1]); | ^^^^^^^^^ - = note: this error originates in the derive macro `ConstParamTy` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 6 previous errors diff --git a/tests/ui/const-generics/adt_const_params/unsized_field-1.stderr b/tests/ui/const-generics/adt_const_params/unsized_field-1.stderr index 7a4f9b99c63..3089b30bd76 100644 --- a/tests/ui/const-generics/adt_const_params/unsized_field-1.stderr +++ b/tests/ui/const-generics/adt_const_params/unsized_field-1.stderr @@ -6,8 +6,6 @@ LL | #[derive(ConstParamTy, Eq, PartialEq)] LL | LL | struct A([u8]); | ---- this field does not implement `ConstParamTy_` - | - = note: this error originates in the derive macro `ConstParamTy` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0204]: the trait `ConstParamTy_` cannot be implemented for this type --> $DIR/unsized_field-1.rs:12:10 @@ -17,8 +15,6 @@ LL | #[derive(ConstParamTy, Eq, PartialEq)] LL | LL | struct B(&'static [u8]); | ------------- this field does not implement `ConstParamTy_` - | - = note: this error originates in the derive macro `ConstParamTy` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0204]: the trait `ConstParamTy_` cannot be implemented for this type --> $DIR/unsized_field-1.rs:16:10 @@ -28,8 +24,6 @@ LL | #[derive(ConstParamTy, Eq, PartialEq)] LL | LL | struct C(unsized_const_param::Foo); | ------------------------ this field does not implement `ConstParamTy_` - | - = note: this error originates in the derive macro `ConstParamTy` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 3 previous errors diff --git a/tests/ui/const-generics/adt_const_params/unsized_field-2.stderr b/tests/ui/const-generics/adt_const_params/unsized_field-2.stderr index 15acece538f..cef70ca0463 100644 --- a/tests/ui/const-generics/adt_const_params/unsized_field-2.stderr +++ b/tests/ui/const-generics/adt_const_params/unsized_field-2.stderr @@ -21,7 +21,6 @@ note: the `ConstParamTy_` impl for `GenericNotUnsizedParam<&'static [u8]>` requi | LL | struct A(unsized_const_param::GenericNotUnsizedParam<&'static [u8]>); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - = note: this error originates in the derive macro `std::marker::ConstParamTy` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error; 1 warning emitted diff --git a/tests/ui/const-generics/adt_const_params/unsizing-wfcheck-issue-126272.stderr b/tests/ui/const-generics/adt_const_params/unsizing-wfcheck-issue-126272.stderr index 72f3fd9de90..992a27c1c0e 100644 --- a/tests/ui/const-generics/adt_const_params/unsizing-wfcheck-issue-126272.stderr +++ b/tests/ui/const-generics/adt_const_params/unsizing-wfcheck-issue-126272.stderr @@ -26,8 +26,6 @@ LL | #[derive(Debug, PartialEq, Eq, ConstParamTy)] ... LL | nested: &'static Bar<dyn std::fmt::Debug>, | ----------------------------------------- this field does not implement `ConstParamTy_` - | - = note: this error originates in the derive macro `ConstParamTy` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0204]: the trait `ConstParamTy_` cannot be implemented for this type --> $DIR/unsizing-wfcheck-issue-126272.rs:8:32 @@ -53,7 +51,6 @@ note: the `ConstParamTy_` impl for `&'static Bar<(dyn Debug + 'static)>` require | LL | nested: &'static Bar<dyn std::fmt::Debug>, | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - = note: this error originates in the derive macro `ConstParamTy` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the size for values of type `(dyn Debug + 'static)` cannot be known at compilation time --> $DIR/unsizing-wfcheck-issue-126272.rs:12:5 @@ -76,7 +73,6 @@ LL | struct Bar<T>(T); = note: 2 redundant requirements hidden = note: required for `&&'static Bar<(dyn Debug + 'static)>` to implement `Debug` = note: required for the cast from `&&&'static Bar<(dyn Debug + 'static)>` to `&dyn Debug` - = note: this error originates in the derive macro `Debug` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0369]: binary operation `==` cannot be applied to type `&Bar<dyn Debug>` --> $DIR/unsizing-wfcheck-issue-126272.rs:12:5 @@ -86,8 +82,6 @@ LL | #[derive(Debug, PartialEq, Eq, ConstParamTy)] ... LL | nested: &'static Bar<dyn std::fmt::Debug>, | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `dyn Debug: Eq` is not satisfied --> $DIR/unsizing-wfcheck-issue-126272.rs:12:5 @@ -108,7 +102,6 @@ LL | #[derive(Debug, PartialEq, Eq, ConstParamTy)] = note: required for `&'static Bar<dyn Debug>` to implement `Eq` note: required by a bound in `AssertParamIsEq` --> $SRC_DIR/core/src/cmp.rs:LL:COL - = note: this error originates in the derive macro `Eq` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the size for values of type `dyn Debug` cannot be known at compilation time --> $DIR/unsizing-wfcheck-issue-126272.rs:12:5 @@ -132,7 +125,6 @@ LL | struct Bar<T>(T); | ^ - ...if indirection were used here: `Box<T>` | | | this could be changed to `T: ?Sized`... - = note: this error originates in the derive macro `Eq` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the size for values of type `(dyn Debug + 'static)` cannot be known at compilation time --> $DIR/unsizing-wfcheck-issue-126272.rs:26:33 diff --git a/tests/ui/const-generics/generic_const_parameter_types/check-type-in-mir.rs b/tests/ui/const-generics/generic_const_parameter_types/check-type-in-mir.rs new file mode 100644 index 00000000000..d3bc544ed6c --- /dev/null +++ b/tests/ui/const-generics/generic_const_parameter_types/check-type-in-mir.rs @@ -0,0 +1,12 @@ +// Ensure that we actually treat `N`'s type as `&'a u32` in MIR typeck. + +#![feature(unsized_const_params, adt_const_params, generic_const_parameter_types)] +//~^ WARN the feature `unsized_const_params` is incomplete +//~| WARN the feature `generic_const_parameter_types` is incomplete + +fn foo<'a, const N: &'a u32>() { + let b: &'static u32 = N; + //~^ ERROR lifetime may not live long enough +} + +fn main() {} diff --git a/tests/ui/const-generics/generic_const_parameter_types/check-type-in-mir.stderr b/tests/ui/const-generics/generic_const_parameter_types/check-type-in-mir.stderr new file mode 100644 index 00000000000..3dc7ce438fa --- /dev/null +++ b/tests/ui/const-generics/generic_const_parameter_types/check-type-in-mir.stderr @@ -0,0 +1,27 @@ +warning: the feature `unsized_const_params` is incomplete and may not be safe to use and/or cause compiler crashes + --> $DIR/check-type-in-mir.rs:3:12 + | +LL | #![feature(unsized_const_params, adt_const_params, generic_const_parameter_types)] + | ^^^^^^^^^^^^^^^^^^^^ + | + = note: see issue #95174 <https://github.com/rust-lang/rust/issues/95174> for more information + = note: `#[warn(incomplete_features)]` on by default + +warning: the feature `generic_const_parameter_types` is incomplete and may not be safe to use and/or cause compiler crashes + --> $DIR/check-type-in-mir.rs:3:52 + | +LL | #![feature(unsized_const_params, adt_const_params, generic_const_parameter_types)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: see issue #137626 <https://github.com/rust-lang/rust/issues/137626> for more information + +error: lifetime may not live long enough + --> $DIR/check-type-in-mir.rs:8:12 + | +LL | fn foo<'a, const N: &'a u32>() { + | -- lifetime `'a` defined here +LL | let b: &'static u32 = N; + | ^^^^^^^^^^^^ type annotation requires that `'a` must outlive `'static` + +error: aborting due to 1 previous error; 2 warnings emitted + diff --git a/tests/ui/const-ptr/forbidden_slices.stderr b/tests/ui/const-ptr/forbidden_slices.stderr index a4e9c972ceb..6f2da272ad3 100644 --- a/tests/ui/const-ptr/forbidden_slices.stderr +++ b/tests/ui/const-ptr/forbidden_slices.stderr @@ -109,7 +109,6 @@ note: inside `from_ptr_range::<'_, ()>` --> $SRC_DIR/core/src/slice/raw.rs:LL:COL note: inside `std::ptr::const_ptr::<impl *const ()>::offset_from_unsigned` --> $SRC_DIR/core/src/ptr/const_ptr.rs:LL:COL - = note: this error originates in the macro `assert` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: could not evaluate static initializer --> $DIR/forbidden_slices.rs:54:25 diff --git a/tests/ui/consts/const-blocks/trait-error.stderr b/tests/ui/consts/const-blocks/trait-error.stderr index 068720a53f6..58ddc047d03 100644 --- a/tests/ui/consts/const-blocks/trait-error.stderr +++ b/tests/ui/consts/const-blocks/trait-error.stderr @@ -13,7 +13,6 @@ note: required for `Foo<String>` to implement `Copy` LL | #[derive(Copy, Clone)] | ^^^^ unsatisfied trait bound introduced in this `derive` macro = note: the `Copy` trait is required because this value will be copied for each element of the array - = note: this error originates in the derive macro `Copy` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/consts/const-eval/const_panic-normalize-tabs-115498.stderr b/tests/ui/consts/const-eval/const_panic-normalize-tabs-115498.stderr index 64e227c4f45..fae971c09f2 100644 --- a/tests/ui/consts/const-eval/const_panic-normalize-tabs-115498.stderr +++ b/tests/ui/consts/const-eval/const_panic-normalize-tabs-115498.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of constant value failed | LL | struct Bug([u8; panic!{"\t"}]); | ^^^^^^^^^^^^ evaluation panicked: - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/consts/const-eval/const_panic.stderr b/tests/ui/consts/const-eval/const_panic.stderr index 0816b04faca..0874224e5f2 100644 --- a/tests/ui/consts/const-eval/const_panic.stderr +++ b/tests/ui/consts/const-eval/const_panic.stderr @@ -3,24 +3,18 @@ error[E0080]: evaluation of constant value failed | LL | const Z: () = std::panic!("cheese"); | ^^^^^^^^^^^^^^^^^^^^^ evaluation panicked: cheese - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `std::panic` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of constant value failed --> $DIR/const_panic.rs:9:16 | LL | const Z2: () = std::panic!(); | ^^^^^^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `std::panic` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of constant value failed --> $DIR/const_panic.rs:12:15 | LL | const Y: () = std::unreachable!(); | ^^^^^^^^^^^^^^^^^^^ evaluation panicked: internal error: entered unreachable code - | - = note: this error originates in the macro `$crate::panic::unreachable_2015` which comes from the expansion of the macro `std::unreachable` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of constant value failed --> $DIR/const_panic.rs:15:15 @@ -35,40 +29,30 @@ error[E0080]: evaluation of constant value failed | LL | const W: () = std::panic!(MSG); | ^^^^^^^^^^^^^^^^ evaluation panicked: hello - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `std::panic` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of constant value failed --> $DIR/const_panic.rs:21:16 | LL | const W2: () = std::panic!("{}", MSG); | ^^^^^^^^^^^^^^^^^^^^^^ evaluation panicked: hello - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `std::panic` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of constant value failed --> $DIR/const_panic.rs:24:20 | LL | const Z_CORE: () = core::panic!("cheese"); | ^^^^^^^^^^^^^^^^^^^^^^ evaluation panicked: cheese - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `core::panic` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of constant value failed --> $DIR/const_panic.rs:27:21 | LL | const Z2_CORE: () = core::panic!(); | ^^^^^^^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `core::panic` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of constant value failed --> $DIR/const_panic.rs:30:20 | LL | const Y_CORE: () = core::unreachable!(); | ^^^^^^^^^^^^^^^^^^^^ evaluation panicked: internal error: entered unreachable code - | - = note: this error originates in the macro `$crate::panic::unreachable_2015` which comes from the expansion of the macro `core::unreachable` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of constant value failed --> $DIR/const_panic.rs:33:20 @@ -83,16 +67,12 @@ error[E0080]: evaluation of constant value failed | LL | const W_CORE: () = core::panic!(MSG); | ^^^^^^^^^^^^^^^^^ evaluation panicked: hello - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `core::panic` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of constant value failed --> $DIR/const_panic.rs:39:21 | LL | const W2_CORE: () = core::panic!("{}", MSG); | ^^^^^^^^^^^^^^^^^^^^^^^ evaluation panicked: hello - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `core::panic` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 12 previous errors diff --git a/tests/ui/consts/const-eval/const_panic_2021.stderr b/tests/ui/consts/const-eval/const_panic_2021.stderr index 4faa2a1e4cf..1496df4445a 100644 --- a/tests/ui/consts/const-eval/const_panic_2021.stderr +++ b/tests/ui/consts/const-eval/const_panic_2021.stderr @@ -3,24 +3,18 @@ error[E0080]: evaluation of constant value failed | LL | const A: () = std::panic!("blåhaj"); | ^^^^^^^^^^^^^^^^^^^^^ evaluation panicked: blåhaj - | - = note: this error originates in the macro `$crate::panic::panic_2021` which comes from the expansion of the macro `std::panic` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of constant value failed --> $DIR/const_panic_2021.rs:9:15 | LL | const B: () = std::panic!(); | ^^^^^^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2021` which comes from the expansion of the macro `std::panic` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of constant value failed --> $DIR/const_panic_2021.rs:12:15 | LL | const C: () = std::unreachable!(); | ^^^^^^^^^^^^^^^^^^^ evaluation panicked: internal error: entered unreachable code - | - = note: this error originates in the macro `$crate::panic::unreachable_2021` which comes from the expansion of the macro `std::unreachable` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of constant value failed --> $DIR/const_panic_2021.rs:15:15 @@ -35,32 +29,24 @@ error[E0080]: evaluation of constant value failed | LL | const E: () = std::panic!("{}", MSG); | ^^^^^^^^^^^^^^^^^^^^^^ evaluation panicked: hello - | - = note: this error originates in the macro `$crate::panic::panic_2021` which comes from the expansion of the macro `std::panic` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of constant value failed --> $DIR/const_panic_2021.rs:21:20 | LL | const A_CORE: () = core::panic!("shark"); | ^^^^^^^^^^^^^^^^^^^^^ evaluation panicked: shark - | - = note: this error originates in the macro `$crate::panic::panic_2021` which comes from the expansion of the macro `core::panic` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of constant value failed --> $DIR/const_panic_2021.rs:24:20 | LL | const B_CORE: () = core::panic!(); | ^^^^^^^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2021` which comes from the expansion of the macro `core::panic` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of constant value failed --> $DIR/const_panic_2021.rs:27:20 | LL | const C_CORE: () = core::unreachable!(); | ^^^^^^^^^^^^^^^^^^^^ evaluation panicked: internal error: entered unreachable code - | - = note: this error originates in the macro `$crate::panic::unreachable_2021` which comes from the expansion of the macro `core::unreachable` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of constant value failed --> $DIR/const_panic_2021.rs:30:20 @@ -75,8 +61,6 @@ error[E0080]: evaluation of constant value failed | LL | const E_CORE: () = core::panic!("{}", MSG); | ^^^^^^^^^^^^^^^^^^^^^^^ evaluation panicked: hello - | - = note: this error originates in the macro `$crate::panic::panic_2021` which comes from the expansion of the macro `core::panic` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 10 previous errors diff --git a/tests/ui/consts/const-eval/const_panic_libcore_bin.stderr b/tests/ui/consts/const-eval/const_panic_libcore_bin.stderr index 11e70c48499..2acab711290 100644 --- a/tests/ui/consts/const-eval/const_panic_libcore_bin.stderr +++ b/tests/ui/consts/const-eval/const_panic_libcore_bin.stderr @@ -3,16 +3,12 @@ error[E0080]: evaluation of constant value failed | LL | const Z: () = panic!("cheese"); | ^^^^^^^^^^^^^^^^ evaluation panicked: cheese - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of constant value failed --> $DIR/const_panic_libcore_bin.rs:11:15 | LL | const Y: () = unreachable!(); | ^^^^^^^^^^^^^^ evaluation panicked: internal error: entered unreachable code - | - = note: this error originates in the macro `$crate::panic::unreachable_2015` which comes from the expansion of the macro `unreachable` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of constant value failed --> $DIR/const_panic_libcore_bin.rs:14:15 diff --git a/tests/ui/consts/const-eval/format.stderr b/tests/ui/consts/const-eval/format.stderr index af90acc2a26..e8d7bbcea09 100644 --- a/tests/ui/consts/const-eval/format.stderr +++ b/tests/ui/consts/const-eval/format.stderr @@ -5,7 +5,6 @@ LL | panic!("{:?}", 0); | ^^^^ | = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants - = note: this error originates in the macro `$crate::const_format_args` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0015]: cannot call non-const formatting macro in constant functions --> $DIR/format.rs:7:15 diff --git a/tests/ui/consts/const-eval/issue-85907.stderr b/tests/ui/consts/const-eval/issue-85907.stderr index 519227bc693..fa1bbf2187f 100644 --- a/tests/ui/consts/const-eval/issue-85907.stderr +++ b/tests/ui/consts/const-eval/issue-85907.stderr @@ -3,8 +3,6 @@ error: argument to `panic!()` in a const context must have type `&str` | LL | panic!(123); | ^^^^^^^^^^^ - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/consts/const-eval/panic-assoc-never-type.stderr b/tests/ui/consts/const-eval/panic-assoc-never-type.stderr index efdbbe5698f..71b33d8d0d5 100644 --- a/tests/ui/consts/const-eval/panic-assoc-never-type.stderr +++ b/tests/ui/consts/const-eval/panic-assoc-never-type.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of constant value failed | LL | const VOID: ! = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/panic-assoc-never-type.rs:14:13 diff --git a/tests/ui/consts/const-eval/panic-never-type.stderr b/tests/ui/consts/const-eval/panic-never-type.stderr index 30a320f8db2..1d9bba9aea2 100644 --- a/tests/ui/consts/const-eval/panic-never-type.stderr +++ b/tests/ui/consts/const-eval/panic-never-type.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of constant value failed | LL | const VOID: ! = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/consts/const-eval/unwind-abort.stderr b/tests/ui/consts/const-eval/unwind-abort.stderr index 96c0dd7c5e9..7d096c5d587 100644 --- a/tests/ui/consts/const-eval/unwind-abort.stderr +++ b/tests/ui/consts/const-eval/unwind-abort.stderr @@ -9,7 +9,6 @@ note: inside `foo` | LL | panic!() | ^^^^^^^^ the failure occurred here - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/consts/const-ptr-is-null.stderr b/tests/ui/consts/const-ptr-is-null.stderr index ff2db14a2f5..1a2be3b3cb1 100644 --- a/tests/ui/consts/const-ptr-is-null.stderr +++ b/tests/ui/consts/const-ptr-is-null.stderr @@ -8,7 +8,6 @@ note: inside `std::ptr::const_ptr::<impl *const i32>::is_null` --> $SRC_DIR/core/src/ptr/const_ptr.rs:LL:COL note: inside `std::ptr::const_ptr::<impl *const T>::is_null::compiletime` --> $SRC_DIR/core/src/ptr/const_ptr.rs:LL:COL - = note: this error originates in the macro `$crate::intrinsics::const_eval_select` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/consts/const_cmp_type_id.stderr b/tests/ui/consts/const_cmp_type_id.stderr index 2e9a8024eae..62f8d42c0e6 100644 --- a/tests/ui/consts/const_cmp_type_id.stderr +++ b/tests/ui/consts/const_cmp_type_id.stderr @@ -27,7 +27,6 @@ LL | let _a = TypeId::of::<u8>() < TypeId::of::<u16>(); note: impl defined here, but it is not `const` --> $SRC_DIR/core/src/any.rs:LL:COL = note: calls in constants are limited to constant functions, tuple structs and tuple variants - = note: this error originates in the derive macro `PartialOrd` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 3 previous errors diff --git a/tests/ui/consts/control-flow/assert.stderr b/tests/ui/consts/control-flow/assert.stderr index fc378f57fa4..3fa98b74bf6 100644 --- a/tests/ui/consts/control-flow/assert.stderr +++ b/tests/ui/consts/control-flow/assert.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of constant value failed | LL | const _: () = assert!(false); | ^^^^^^^^^^^^^^ evaluation panicked: assertion failed: false - | - = note: this error originates in the macro `assert` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/consts/issue-32829.stderr b/tests/ui/consts/issue-32829.stderr index 0cbc73cfaa3..542dce19151 100644 --- a/tests/ui/consts/issue-32829.stderr +++ b/tests/ui/consts/issue-32829.stderr @@ -3,8 +3,6 @@ error[E0080]: could not evaluate static initializer | LL | static S : u64 = { { panic!("foo"); 0 } }; | ^^^^^^^^^^^^^ evaluation panicked: foo - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/consts/issue-66693-panic-in-array-len.stderr b/tests/ui/consts/issue-66693-panic-in-array-len.stderr index 9cf5ad126f3..fdef515b6d4 100644 --- a/tests/ui/consts/issue-66693-panic-in-array-len.stderr +++ b/tests/ui/consts/issue-66693-panic-in-array-len.stderr @@ -3,16 +3,12 @@ error: argument to `panic!()` in a const context must have type `&str` | LL | let _ = [0i32; panic!(2f32)]; | ^^^^^^^^^^^^ - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of constant value failed --> $DIR/issue-66693-panic-in-array-len.rs:10:21 | LL | let _ = [false; panic!()]; | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 2 previous errors diff --git a/tests/ui/consts/issue-66693.stderr b/tests/ui/consts/issue-66693.stderr index 46f30a8cbab..ea657ec34bd 100644 --- a/tests/ui/consts/issue-66693.stderr +++ b/tests/ui/consts/issue-66693.stderr @@ -3,40 +3,30 @@ error: argument to `panic!()` in a const context must have type `&str` | LL | const _: () = panic!(1); | ^^^^^^^^^ - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) error: argument to `panic!()` in a const context must have type `&str` --> $DIR/issue-66693.rs:7:19 | LL | static _FOO: () = panic!(true); | ^^^^^^^^^^^^ - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of constant value failed --> $DIR/issue-66693.rs:16:15 | LL | const _: () = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: could not evaluate static initializer --> $DIR/issue-66693.rs:18:19 | LL | static _BAR: () = panic!("panic in static"); | ^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation panicked: panic in static - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) error: argument to `panic!()` in a const context must have type `&str` --> $DIR/issue-66693.rs:11:5 | LL | panic!(&1); | ^^^^^^^^^^ - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 5 previous errors diff --git a/tests/ui/consts/issue-76064.stderr b/tests/ui/consts/issue-76064.stderr index 55059220388..786d4213f1e 100644 --- a/tests/ui/consts/issue-76064.stderr +++ b/tests/ui/consts/issue-76064.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of constant value failed | LL | struct Bug([u8; panic!("panic")]); | ^^^^^^^^^^^^^^^ evaluation panicked: panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/consts/required-consts/collect-in-called-fn.noopt.stderr b/tests/ui/consts/required-consts/collect-in-called-fn.noopt.stderr index 08d0b338728..6812b3734ef 100644 --- a/tests/ui/consts/required-consts/collect-in-called-fn.noopt.stderr +++ b/tests/ui/consts/required-consts/collect-in-called-fn.noopt.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of `Fail::<i32>::C` failed | LL | const C: () = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/collect-in-called-fn.rs:19:17 diff --git a/tests/ui/consts/required-consts/collect-in-called-fn.opt.stderr b/tests/ui/consts/required-consts/collect-in-called-fn.opt.stderr index 08d0b338728..6812b3734ef 100644 --- a/tests/ui/consts/required-consts/collect-in-called-fn.opt.stderr +++ b/tests/ui/consts/required-consts/collect-in-called-fn.opt.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of `Fail::<i32>::C` failed | LL | const C: () = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/collect-in-called-fn.rs:19:17 diff --git a/tests/ui/consts/required-consts/collect-in-dead-closure.noopt.stderr b/tests/ui/consts/required-consts/collect-in-dead-closure.noopt.stderr index 41fe2cf84e4..661aea71604 100644 --- a/tests/ui/consts/required-consts/collect-in-dead-closure.noopt.stderr +++ b/tests/ui/consts/required-consts/collect-in-dead-closure.noopt.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of `Fail::<i32>::C` failed | LL | const C: () = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/collect-in-dead-closure.rs:17:17 diff --git a/tests/ui/consts/required-consts/collect-in-dead-closure.opt.stderr b/tests/ui/consts/required-consts/collect-in-dead-closure.opt.stderr index 41fe2cf84e4..661aea71604 100644 --- a/tests/ui/consts/required-consts/collect-in-dead-closure.opt.stderr +++ b/tests/ui/consts/required-consts/collect-in-dead-closure.opt.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of `Fail::<i32>::C` failed | LL | const C: () = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/collect-in-dead-closure.rs:17:17 diff --git a/tests/ui/consts/required-consts/collect-in-dead-drop.noopt.stderr b/tests/ui/consts/required-consts/collect-in-dead-drop.noopt.stderr index b62b25bd3aa..31e6b2f487f 100644 --- a/tests/ui/consts/required-consts/collect-in-dead-drop.noopt.stderr +++ b/tests/ui/consts/required-consts/collect-in-dead-drop.noopt.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of `Fail::<i32>::C` failed | LL | const C: () = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/collect-in-dead-drop.rs:16:17 diff --git a/tests/ui/consts/required-consts/collect-in-dead-drop.opt.stderr b/tests/ui/consts/required-consts/collect-in-dead-drop.opt.stderr index b62b25bd3aa..31e6b2f487f 100644 --- a/tests/ui/consts/required-consts/collect-in-dead-drop.opt.stderr +++ b/tests/ui/consts/required-consts/collect-in-dead-drop.opt.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of `Fail::<i32>::C` failed | LL | const C: () = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/collect-in-dead-drop.rs:16:17 diff --git a/tests/ui/consts/required-consts/collect-in-dead-fn-behind-assoc-type.noopt.stderr b/tests/ui/consts/required-consts/collect-in-dead-fn-behind-assoc-type.noopt.stderr index c8a7cf983c4..32dc1cb304b 100644 --- a/tests/ui/consts/required-consts/collect-in-dead-fn-behind-assoc-type.noopt.stderr +++ b/tests/ui/consts/required-consts/collect-in-dead-fn-behind-assoc-type.noopt.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of `Fail::<i32>::C` failed | LL | const C: () = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/collect-in-dead-fn-behind-assoc-type.rs:16:17 diff --git a/tests/ui/consts/required-consts/collect-in-dead-fn-behind-assoc-type.opt.stderr b/tests/ui/consts/required-consts/collect-in-dead-fn-behind-assoc-type.opt.stderr index c8a7cf983c4..32dc1cb304b 100644 --- a/tests/ui/consts/required-consts/collect-in-dead-fn-behind-assoc-type.opt.stderr +++ b/tests/ui/consts/required-consts/collect-in-dead-fn-behind-assoc-type.opt.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of `Fail::<i32>::C` failed | LL | const C: () = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/collect-in-dead-fn-behind-assoc-type.rs:16:17 diff --git a/tests/ui/consts/required-consts/collect-in-dead-fn-behind-generic.noopt.stderr b/tests/ui/consts/required-consts/collect-in-dead-fn-behind-generic.noopt.stderr index 1e68d66cf5e..d22cf579448 100644 --- a/tests/ui/consts/required-consts/collect-in-dead-fn-behind-generic.noopt.stderr +++ b/tests/ui/consts/required-consts/collect-in-dead-fn-behind-generic.noopt.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of `Fail::<i32>::C` failed | LL | const C: () = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/collect-in-dead-fn-behind-generic.rs:15:17 diff --git a/tests/ui/consts/required-consts/collect-in-dead-fn-behind-generic.opt.stderr b/tests/ui/consts/required-consts/collect-in-dead-fn-behind-generic.opt.stderr index 1e68d66cf5e..d22cf579448 100644 --- a/tests/ui/consts/required-consts/collect-in-dead-fn-behind-generic.opt.stderr +++ b/tests/ui/consts/required-consts/collect-in-dead-fn-behind-generic.opt.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of `Fail::<i32>::C` failed | LL | const C: () = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/collect-in-dead-fn-behind-generic.rs:15:17 diff --git a/tests/ui/consts/required-consts/collect-in-dead-fn-behind-opaque-type.noopt.stderr b/tests/ui/consts/required-consts/collect-in-dead-fn-behind-opaque-type.noopt.stderr index a9cc56fba45..91daa2f9bc3 100644 --- a/tests/ui/consts/required-consts/collect-in-dead-fn-behind-opaque-type.noopt.stderr +++ b/tests/ui/consts/required-consts/collect-in-dead-fn-behind-opaque-type.noopt.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of `m::Fail::<i32>::C` failed | LL | const C: () = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/collect-in-dead-fn-behind-opaque-type.rs:19:21 diff --git a/tests/ui/consts/required-consts/collect-in-dead-fn-behind-opaque-type.opt.stderr b/tests/ui/consts/required-consts/collect-in-dead-fn-behind-opaque-type.opt.stderr index a9cc56fba45..91daa2f9bc3 100644 --- a/tests/ui/consts/required-consts/collect-in-dead-fn-behind-opaque-type.opt.stderr +++ b/tests/ui/consts/required-consts/collect-in-dead-fn-behind-opaque-type.opt.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of `m::Fail::<i32>::C` failed | LL | const C: () = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/collect-in-dead-fn-behind-opaque-type.rs:19:21 diff --git a/tests/ui/consts/required-consts/collect-in-dead-fn.noopt.stderr b/tests/ui/consts/required-consts/collect-in-dead-fn.noopt.stderr index ec549561a17..d254fc60c0c 100644 --- a/tests/ui/consts/required-consts/collect-in-dead-fn.noopt.stderr +++ b/tests/ui/consts/required-consts/collect-in-dead-fn.noopt.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of `Fail::<i32>::C` failed | LL | const C: () = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/collect-in-dead-fn.rs:19:17 diff --git a/tests/ui/consts/required-consts/collect-in-dead-fn.opt.stderr b/tests/ui/consts/required-consts/collect-in-dead-fn.opt.stderr index ec549561a17..d254fc60c0c 100644 --- a/tests/ui/consts/required-consts/collect-in-dead-fn.opt.stderr +++ b/tests/ui/consts/required-consts/collect-in-dead-fn.opt.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of `Fail::<i32>::C` failed | LL | const C: () = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/collect-in-dead-fn.rs:19:17 diff --git a/tests/ui/consts/required-consts/collect-in-dead-fnptr-in-const.noopt.stderr b/tests/ui/consts/required-consts/collect-in-dead-fnptr-in-const.noopt.stderr index dfaf69d52b2..c14837ce442 100644 --- a/tests/ui/consts/required-consts/collect-in-dead-fnptr-in-const.noopt.stderr +++ b/tests/ui/consts/required-consts/collect-in-dead-fnptr-in-const.noopt.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of `Late::<i32>::FAIL` failed | LL | const FAIL: () = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/collect-in-dead-fnptr-in-const.rs:10:28 diff --git a/tests/ui/consts/required-consts/collect-in-dead-fnptr-in-const.opt.stderr b/tests/ui/consts/required-consts/collect-in-dead-fnptr-in-const.opt.stderr index dfaf69d52b2..c14837ce442 100644 --- a/tests/ui/consts/required-consts/collect-in-dead-fnptr-in-const.opt.stderr +++ b/tests/ui/consts/required-consts/collect-in-dead-fnptr-in-const.opt.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of `Late::<i32>::FAIL` failed | LL | const FAIL: () = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/collect-in-dead-fnptr-in-const.rs:10:28 diff --git a/tests/ui/consts/required-consts/collect-in-dead-fnptr.noopt.stderr b/tests/ui/consts/required-consts/collect-in-dead-fnptr.noopt.stderr index 7cbd423cdc0..284e1a70a20 100644 --- a/tests/ui/consts/required-consts/collect-in-dead-fnptr.noopt.stderr +++ b/tests/ui/consts/required-consts/collect-in-dead-fnptr.noopt.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of `Fail::<i32>::C` failed | LL | const C: () = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/collect-in-dead-fnptr.rs:18:17 diff --git a/tests/ui/consts/required-consts/collect-in-dead-fnptr.opt.stderr b/tests/ui/consts/required-consts/collect-in-dead-fnptr.opt.stderr index 7cbd423cdc0..284e1a70a20 100644 --- a/tests/ui/consts/required-consts/collect-in-dead-fnptr.opt.stderr +++ b/tests/ui/consts/required-consts/collect-in-dead-fnptr.opt.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of `Fail::<i32>::C` failed | LL | const C: () = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/collect-in-dead-fnptr.rs:18:17 diff --git a/tests/ui/consts/required-consts/collect-in-dead-move.noopt.stderr b/tests/ui/consts/required-consts/collect-in-dead-move.noopt.stderr index 58e9d7a2c9a..8b43c67c085 100644 --- a/tests/ui/consts/required-consts/collect-in-dead-move.noopt.stderr +++ b/tests/ui/consts/required-consts/collect-in-dead-move.noopt.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of `Fail::<i32>::C` failed | LL | const C: () = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/collect-in-dead-move.rs:16:17 diff --git a/tests/ui/consts/required-consts/collect-in-dead-move.opt.stderr b/tests/ui/consts/required-consts/collect-in-dead-move.opt.stderr index 58e9d7a2c9a..8b43c67c085 100644 --- a/tests/ui/consts/required-consts/collect-in-dead-move.opt.stderr +++ b/tests/ui/consts/required-consts/collect-in-dead-move.opt.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of `Fail::<i32>::C` failed | LL | const C: () = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/collect-in-dead-move.rs:16:17 diff --git a/tests/ui/consts/required-consts/collect-in-dead-vtable.noopt.stderr b/tests/ui/consts/required-consts/collect-in-dead-vtable.noopt.stderr index 6c78ca79fd6..4056f28541d 100644 --- a/tests/ui/consts/required-consts/collect-in-dead-vtable.noopt.stderr +++ b/tests/ui/consts/required-consts/collect-in-dead-vtable.noopt.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of `Fail::<i32>::C` failed | LL | const C: () = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/collect-in-dead-vtable.rs:22:21 diff --git a/tests/ui/consts/required-consts/collect-in-dead-vtable.opt.stderr b/tests/ui/consts/required-consts/collect-in-dead-vtable.opt.stderr index 6c78ca79fd6..4056f28541d 100644 --- a/tests/ui/consts/required-consts/collect-in-dead-vtable.opt.stderr +++ b/tests/ui/consts/required-consts/collect-in-dead-vtable.opt.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of `Fail::<i32>::C` failed | LL | const C: () = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/collect-in-dead-vtable.rs:22:21 diff --git a/tests/ui/consts/required-consts/collect-in-promoted-const.noopt.stderr b/tests/ui/consts/required-consts/collect-in-promoted-const.noopt.stderr index fd231e1101d..c5f3b0009f5 100644 --- a/tests/ui/consts/required-consts/collect-in-promoted-const.noopt.stderr +++ b/tests/ui/consts/required-consts/collect-in-promoted-const.noopt.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of `Fail::<i32>::C` failed | LL | const C: () = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/collect-in-promoted-const.rs:20:21 diff --git a/tests/ui/consts/required-consts/collect-in-promoted-const.opt.stderr b/tests/ui/consts/required-consts/collect-in-promoted-const.opt.stderr index 0f3f77769ad..6f36aaf314d 100644 --- a/tests/ui/consts/required-consts/collect-in-promoted-const.opt.stderr +++ b/tests/ui/consts/required-consts/collect-in-promoted-const.opt.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of `Fail::<T>::C` failed | LL | const C: () = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/collect-in-promoted-const.rs:20:21 @@ -17,8 +15,6 @@ error[E0080]: evaluation of `Fail::<i32>::C` failed | LL | const C: () = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/collect-in-promoted-const.rs:20:21 diff --git a/tests/ui/consts/required-consts/interpret-in-const-called-fn.noopt.stderr b/tests/ui/consts/required-consts/interpret-in-const-called-fn.noopt.stderr index d2145089028..9184df472c4 100644 --- a/tests/ui/consts/required-consts/interpret-in-const-called-fn.noopt.stderr +++ b/tests/ui/consts/required-consts/interpret-in-const-called-fn.noopt.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of `Fail::<i32>::C` failed | LL | const C: () = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/interpret-in-const-called-fn.rs:17:9 diff --git a/tests/ui/consts/required-consts/interpret-in-const-called-fn.opt.stderr b/tests/ui/consts/required-consts/interpret-in-const-called-fn.opt.stderr index d2145089028..9184df472c4 100644 --- a/tests/ui/consts/required-consts/interpret-in-const-called-fn.opt.stderr +++ b/tests/ui/consts/required-consts/interpret-in-const-called-fn.opt.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of `Fail::<i32>::C` failed | LL | const C: () = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/interpret-in-const-called-fn.rs:17:9 diff --git a/tests/ui/consts/required-consts/interpret-in-static.noopt.stderr b/tests/ui/consts/required-consts/interpret-in-static.noopt.stderr index f999bf370b8..aa778deb542 100644 --- a/tests/ui/consts/required-consts/interpret-in-static.noopt.stderr +++ b/tests/ui/consts/required-consts/interpret-in-static.noopt.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of `Fail::<i32>::C` failed | LL | const C: () = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/interpret-in-static.rs:16:9 diff --git a/tests/ui/consts/required-consts/interpret-in-static.opt.stderr b/tests/ui/consts/required-consts/interpret-in-static.opt.stderr index f999bf370b8..aa778deb542 100644 --- a/tests/ui/consts/required-consts/interpret-in-static.opt.stderr +++ b/tests/ui/consts/required-consts/interpret-in-static.opt.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of `Fail::<i32>::C` failed | LL | const C: () = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/interpret-in-static.rs:16:9 diff --git a/tests/ui/crate_type_flag.rs b/tests/ui/crate_type_flag.rs new file mode 100644 index 00000000000..4f3cfbae45d --- /dev/null +++ b/tests/ui/crate_type_flag.rs @@ -0,0 +1,4 @@ +//@ compile-flags: --crate-type dynlib +//@ error-pattern: unknown crate type: `dynlib`, expected one of: `lib`, `rlib`, `staticlib`, `dylib`, `cdylib`, `bin`, `proc-macro` + +fn main() {} diff --git a/tests/ui/crate_type_flag.stderr b/tests/ui/crate_type_flag.stderr new file mode 100644 index 00000000000..26a3e1fbd68 --- /dev/null +++ b/tests/ui/crate_type_flag.stderr @@ -0,0 +1,2 @@ +error: unknown crate type: `dynlib`, expected one of: `lib`, `rlib`, `staticlib`, `dylib`, `cdylib`, `bin`, `proc-macro` + diff --git a/tests/ui/custom_test_frameworks/mismatch.stderr b/tests/ui/custom_test_frameworks/mismatch.stderr index dad93cfbba4..c7798635fbf 100644 --- a/tests/ui/custom_test_frameworks/mismatch.stderr +++ b/tests/ui/custom_test_frameworks/mismatch.stderr @@ -7,7 +7,6 @@ LL | fn wrong_kind(){} | ^^^^^^^^^^^^^^^^^ the trait `Testable` is not implemented for `TestDescAndFn` | = note: required for the cast from `&TestDescAndFn` to `&dyn Testable` - = note: this error originates in the attribute macro `test` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/delegation/foreign-fn.rs b/tests/ui/delegation/foreign-fn.rs new file mode 100644 index 00000000000..1d221da29ce --- /dev/null +++ b/tests/ui/delegation/foreign-fn.rs @@ -0,0 +1,22 @@ +#![feature(fn_delegation)] +#![allow(incomplete_features)] +#![deny(unsafe_op_in_unsafe_fn)] +#![deny(unused_unsafe)] + +mod to_reuse { + unsafe extern "C" { + pub fn default_unsafe_foo(); + pub unsafe fn unsafe_foo(); + pub safe fn safe_foo(); + } +} + +reuse to_reuse::{default_unsafe_foo, unsafe_foo, safe_foo}; + +fn main() { + let _: extern "C" fn() = default_unsafe_foo; + //~^ ERROR mismatched types + let _: extern "C" fn() = unsafe_foo; + //~^ ERROR mismatched types + let _: extern "C" fn() = safe_foo; +} diff --git a/tests/ui/delegation/foreign-fn.stderr b/tests/ui/delegation/foreign-fn.stderr new file mode 100644 index 00000000000..f7d3dba4bb1 --- /dev/null +++ b/tests/ui/delegation/foreign-fn.stderr @@ -0,0 +1,27 @@ +error[E0308]: mismatched types + --> $DIR/foreign-fn.rs:17:30 + | +LL | let _: extern "C" fn() = default_unsafe_foo; + | --------------- ^^^^^^^^^^^^^^^^^^ expected safe fn, found unsafe fn + | | + | expected due to this + | + = note: expected fn pointer `extern "C" fn()` + found fn item `unsafe extern "C" fn() {default_unsafe_foo}` + = note: unsafe functions cannot be coerced into safe function pointers + +error[E0308]: mismatched types + --> $DIR/foreign-fn.rs:19:30 + | +LL | let _: extern "C" fn() = unsafe_foo; + | --------------- ^^^^^^^^^^ expected safe fn, found unsafe fn + | | + | expected due to this + | + = note: expected fn pointer `extern "C" fn()` + found fn item `unsafe extern "C" fn() {unsafe_foo}` + = note: unsafe functions cannot be coerced into safe function pointers + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0308`. diff --git a/tests/ui/derives/derives-span-Clone-enum-struct-variant.stderr b/tests/ui/derives/derives-span-Clone-enum-struct-variant.stderr index 2c8d9431646..9aeb3a8c03d 100644 --- a/tests/ui/derives/derives-span-Clone-enum-struct-variant.stderr +++ b/tests/ui/derives/derives-span-Clone-enum-struct-variant.stderr @@ -7,7 +7,6 @@ LL | #[derive(Clone)] LL | x: Error | ^^^^^^^^ the trait `Clone` is not implemented for `Error` | - = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Error` with `#[derive(Clone)]` | LL + #[derive(Clone)] diff --git a/tests/ui/derives/derives-span-Clone-enum.stderr b/tests/ui/derives/derives-span-Clone-enum.stderr index b683a8b8944..6b4f2241663 100644 --- a/tests/ui/derives/derives-span-Clone-enum.stderr +++ b/tests/ui/derives/derives-span-Clone-enum.stderr @@ -7,7 +7,6 @@ LL | #[derive(Clone)] LL | Error | ^^^^^ the trait `Clone` is not implemented for `Error` | - = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Error` with `#[derive(Clone)]` | LL + #[derive(Clone)] diff --git a/tests/ui/derives/derives-span-Clone-struct.stderr b/tests/ui/derives/derives-span-Clone-struct.stderr index 305a9275271..17e3f0eccf9 100644 --- a/tests/ui/derives/derives-span-Clone-struct.stderr +++ b/tests/ui/derives/derives-span-Clone-struct.stderr @@ -7,7 +7,6 @@ LL | struct Struct { LL | x: Error | ^^^^^^^^ the trait `Clone` is not implemented for `Error` | - = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Error` with `#[derive(Clone)]` | LL + #[derive(Clone)] diff --git a/tests/ui/derives/derives-span-Clone-tuple-struct.stderr b/tests/ui/derives/derives-span-Clone-tuple-struct.stderr index b636404ad9e..f8380d197b0 100644 --- a/tests/ui/derives/derives-span-Clone-tuple-struct.stderr +++ b/tests/ui/derives/derives-span-Clone-tuple-struct.stderr @@ -7,7 +7,6 @@ LL | struct Struct( LL | Error | ^^^^^ the trait `Clone` is not implemented for `Error` | - = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Error` with `#[derive(Clone)]` | LL + #[derive(Clone)] diff --git a/tests/ui/derives/derives-span-Debug-enum-struct-variant.stderr b/tests/ui/derives/derives-span-Debug-enum-struct-variant.stderr index 3f6c39bf939..a7f6d094681 100644 --- a/tests/ui/derives/derives-span-Debug-enum-struct-variant.stderr +++ b/tests/ui/derives/derives-span-Debug-enum-struct-variant.stderr @@ -9,7 +9,6 @@ LL | x: Error | = help: the trait `Debug` is not implemented for `Error` = note: add `#[derive(Debug)]` to `Error` or manually `impl Debug for Error` - = note: this error originates in the derive macro `Debug` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Error` with `#[derive(Debug)]` | LL + #[derive(Debug)] diff --git a/tests/ui/derives/derives-span-Debug-enum.stderr b/tests/ui/derives/derives-span-Debug-enum.stderr index eaeffaeb849..b3a58478159 100644 --- a/tests/ui/derives/derives-span-Debug-enum.stderr +++ b/tests/ui/derives/derives-span-Debug-enum.stderr @@ -9,7 +9,6 @@ LL | Error | = help: the trait `Debug` is not implemented for `Error` = note: add `#[derive(Debug)]` to `Error` or manually `impl Debug for Error` - = note: this error originates in the derive macro `Debug` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Error` with `#[derive(Debug)]` | LL + #[derive(Debug)] diff --git a/tests/ui/derives/derives-span-Debug-struct.stderr b/tests/ui/derives/derives-span-Debug-struct.stderr index 4a725e260de..c8ad652716c 100644 --- a/tests/ui/derives/derives-span-Debug-struct.stderr +++ b/tests/ui/derives/derives-span-Debug-struct.stderr @@ -9,7 +9,6 @@ LL | x: Error | = help: the trait `Debug` is not implemented for `Error` = note: add `#[derive(Debug)]` to `Error` or manually `impl Debug for Error` - = note: this error originates in the derive macro `Debug` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Error` with `#[derive(Debug)]` | LL + #[derive(Debug)] diff --git a/tests/ui/derives/derives-span-Debug-tuple-struct.stderr b/tests/ui/derives/derives-span-Debug-tuple-struct.stderr index 2f816e1c85b..dbece4d2091 100644 --- a/tests/ui/derives/derives-span-Debug-tuple-struct.stderr +++ b/tests/ui/derives/derives-span-Debug-tuple-struct.stderr @@ -9,7 +9,6 @@ LL | Error | = help: the trait `Debug` is not implemented for `Error` = note: add `#[derive(Debug)]` to `Error` or manually `impl Debug for Error` - = note: this error originates in the derive macro `Debug` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Error` with `#[derive(Debug)]` | LL + #[derive(Debug)] diff --git a/tests/ui/derives/derives-span-Default-struct.stderr b/tests/ui/derives/derives-span-Default-struct.stderr index 359b61528e1..442081f78ce 100644 --- a/tests/ui/derives/derives-span-Default-struct.stderr +++ b/tests/ui/derives/derives-span-Default-struct.stderr @@ -7,7 +7,6 @@ LL | struct Struct { LL | x: Error | ^^^^^^^^ the trait `Default` is not implemented for `Error` | - = note: this error originates in the derive macro `Default` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Error` with `#[derive(Default)]` | LL + #[derive(Default)] diff --git a/tests/ui/derives/derives-span-Default-tuple-struct.stderr b/tests/ui/derives/derives-span-Default-tuple-struct.stderr index 1ddb4ec3f64..e786ec1e9da 100644 --- a/tests/ui/derives/derives-span-Default-tuple-struct.stderr +++ b/tests/ui/derives/derives-span-Default-tuple-struct.stderr @@ -7,7 +7,6 @@ LL | struct Struct( LL | Error | ^^^^^ the trait `Default` is not implemented for `Error` | - = note: this error originates in the derive macro `Default` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Error` with `#[derive(Default)]` | LL + #[derive(Default)] diff --git a/tests/ui/derives/derives-span-Eq-enum-struct-variant.stderr b/tests/ui/derives/derives-span-Eq-enum-struct-variant.stderr index c9edc89e1bc..e0cb3c1b43d 100644 --- a/tests/ui/derives/derives-span-Eq-enum-struct-variant.stderr +++ b/tests/ui/derives/derives-span-Eq-enum-struct-variant.stderr @@ -9,7 +9,6 @@ LL | x: Error | note: required by a bound in `AssertParamIsEq` --> $SRC_DIR/core/src/cmp.rs:LL:COL - = note: this error originates in the derive macro `Eq` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Error` with `#[derive(Eq)]` | LL + #[derive(Eq)] diff --git a/tests/ui/derives/derives-span-Eq-enum.stderr b/tests/ui/derives/derives-span-Eq-enum.stderr index 7db13e97111..2f09b9ea385 100644 --- a/tests/ui/derives/derives-span-Eq-enum.stderr +++ b/tests/ui/derives/derives-span-Eq-enum.stderr @@ -9,7 +9,6 @@ LL | Error | note: required by a bound in `AssertParamIsEq` --> $SRC_DIR/core/src/cmp.rs:LL:COL - = note: this error originates in the derive macro `Eq` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Error` with `#[derive(Eq)]` | LL + #[derive(Eq)] diff --git a/tests/ui/derives/derives-span-Eq-struct.stderr b/tests/ui/derives/derives-span-Eq-struct.stderr index 36eeb89bde1..c16d9118e10 100644 --- a/tests/ui/derives/derives-span-Eq-struct.stderr +++ b/tests/ui/derives/derives-span-Eq-struct.stderr @@ -9,7 +9,6 @@ LL | x: Error | note: required by a bound in `AssertParamIsEq` --> $SRC_DIR/core/src/cmp.rs:LL:COL - = note: this error originates in the derive macro `Eq` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Error` with `#[derive(Eq)]` | LL + #[derive(Eq)] diff --git a/tests/ui/derives/derives-span-Eq-tuple-struct.stderr b/tests/ui/derives/derives-span-Eq-tuple-struct.stderr index 126d1053540..dac295eed91 100644 --- a/tests/ui/derives/derives-span-Eq-tuple-struct.stderr +++ b/tests/ui/derives/derives-span-Eq-tuple-struct.stderr @@ -9,7 +9,6 @@ LL | Error | note: required by a bound in `AssertParamIsEq` --> $SRC_DIR/core/src/cmp.rs:LL:COL - = note: this error originates in the derive macro `Eq` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Error` with `#[derive(Eq)]` | LL + #[derive(Eq)] diff --git a/tests/ui/derives/derives-span-Hash-enum-struct-variant.stderr b/tests/ui/derives/derives-span-Hash-enum-struct-variant.stderr index ae973228cac..9854b61d31b 100644 --- a/tests/ui/derives/derives-span-Hash-enum-struct-variant.stderr +++ b/tests/ui/derives/derives-span-Hash-enum-struct-variant.stderr @@ -7,7 +7,6 @@ LL | #[derive(Hash)] LL | x: Error | ^^^^^^^^ the trait `Hash` is not implemented for `Error` | - = note: this error originates in the derive macro `Hash` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Error` with `#[derive(Hash)]` | LL + #[derive(Hash)] diff --git a/tests/ui/derives/derives-span-Hash-enum.stderr b/tests/ui/derives/derives-span-Hash-enum.stderr index 85e26c84fa7..60e7d0cf1ff 100644 --- a/tests/ui/derives/derives-span-Hash-enum.stderr +++ b/tests/ui/derives/derives-span-Hash-enum.stderr @@ -7,7 +7,6 @@ LL | #[derive(Hash)] LL | Error | ^^^^^ the trait `Hash` is not implemented for `Error` | - = note: this error originates in the derive macro `Hash` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Error` with `#[derive(Hash)]` | LL + #[derive(Hash)] diff --git a/tests/ui/derives/derives-span-Hash-struct.stderr b/tests/ui/derives/derives-span-Hash-struct.stderr index f9a654b2df7..3851cf8ce8b 100644 --- a/tests/ui/derives/derives-span-Hash-struct.stderr +++ b/tests/ui/derives/derives-span-Hash-struct.stderr @@ -7,7 +7,6 @@ LL | struct Struct { LL | x: Error | ^^^^^^^^ the trait `Hash` is not implemented for `Error` | - = note: this error originates in the derive macro `Hash` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Error` with `#[derive(Hash)]` | LL + #[derive(Hash)] diff --git a/tests/ui/derives/derives-span-Hash-tuple-struct.stderr b/tests/ui/derives/derives-span-Hash-tuple-struct.stderr index 0a5fbe28658..e5a3e7a5566 100644 --- a/tests/ui/derives/derives-span-Hash-tuple-struct.stderr +++ b/tests/ui/derives/derives-span-Hash-tuple-struct.stderr @@ -7,7 +7,6 @@ LL | struct Struct( LL | Error | ^^^^^ the trait `Hash` is not implemented for `Error` | - = note: this error originates in the derive macro `Hash` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Error` with `#[derive(Hash)]` | LL + #[derive(Hash)] diff --git a/tests/ui/derives/derives-span-Ord-enum-struct-variant.stderr b/tests/ui/derives/derives-span-Ord-enum-struct-variant.stderr index 96ef59ca963..e253a9173fc 100644 --- a/tests/ui/derives/derives-span-Ord-enum-struct-variant.stderr +++ b/tests/ui/derives/derives-span-Ord-enum-struct-variant.stderr @@ -7,7 +7,6 @@ LL | #[derive(Ord,Eq,PartialOrd,PartialEq)] LL | x: Error | ^^^^^^^^ the trait `Ord` is not implemented for `Error` | - = note: this error originates in the derive macro `Ord` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Error` with `#[derive(Ord)]` | LL + #[derive(Ord)] diff --git a/tests/ui/derives/derives-span-Ord-enum.stderr b/tests/ui/derives/derives-span-Ord-enum.stderr index 7c75ecb6432..8a92458b51c 100644 --- a/tests/ui/derives/derives-span-Ord-enum.stderr +++ b/tests/ui/derives/derives-span-Ord-enum.stderr @@ -7,7 +7,6 @@ LL | #[derive(Ord,Eq,PartialOrd,PartialEq)] LL | Error | ^^^^^ the trait `Ord` is not implemented for `Error` | - = note: this error originates in the derive macro `Ord` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Error` with `#[derive(Ord)]` | LL + #[derive(Ord)] diff --git a/tests/ui/derives/derives-span-Ord-struct.stderr b/tests/ui/derives/derives-span-Ord-struct.stderr index 429e7e06f5d..ae110d51196 100644 --- a/tests/ui/derives/derives-span-Ord-struct.stderr +++ b/tests/ui/derives/derives-span-Ord-struct.stderr @@ -7,7 +7,6 @@ LL | struct Struct { LL | x: Error | ^^^^^^^^ the trait `Ord` is not implemented for `Error` | - = note: this error originates in the derive macro `Ord` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Error` with `#[derive(Ord)]` | LL + #[derive(Ord)] diff --git a/tests/ui/derives/derives-span-Ord-tuple-struct.stderr b/tests/ui/derives/derives-span-Ord-tuple-struct.stderr index a46133834c6..e2a6d5266b7 100644 --- a/tests/ui/derives/derives-span-Ord-tuple-struct.stderr +++ b/tests/ui/derives/derives-span-Ord-tuple-struct.stderr @@ -7,7 +7,6 @@ LL | struct Struct( LL | Error | ^^^^^ the trait `Ord` is not implemented for `Error` | - = note: this error originates in the derive macro `Ord` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Error` with `#[derive(Ord)]` | LL + #[derive(Ord)] diff --git a/tests/ui/derives/derives-span-PartialEq-enum-struct-variant.stderr b/tests/ui/derives/derives-span-PartialEq-enum-struct-variant.stderr index e88a523ef4f..09104289c64 100644 --- a/tests/ui/derives/derives-span-PartialEq-enum-struct-variant.stderr +++ b/tests/ui/derives/derives-span-PartialEq-enum-struct-variant.stderr @@ -12,7 +12,6 @@ note: an implementation of `PartialEq` might be missing for `Error` | LL | struct Error; | ^^^^^^^^^^^^ must implement `PartialEq` - = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Error` with `#[derive(PartialEq)]` | LL + #[derive(PartialEq)] diff --git a/tests/ui/derives/derives-span-PartialEq-enum.stderr b/tests/ui/derives/derives-span-PartialEq-enum.stderr index 80b225446b4..40dca92ef23 100644 --- a/tests/ui/derives/derives-span-PartialEq-enum.stderr +++ b/tests/ui/derives/derives-span-PartialEq-enum.stderr @@ -12,7 +12,6 @@ note: an implementation of `PartialEq` might be missing for `Error` | LL | struct Error; | ^^^^^^^^^^^^ must implement `PartialEq` - = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Error` with `#[derive(PartialEq)]` | LL + #[derive(PartialEq)] diff --git a/tests/ui/derives/derives-span-PartialEq-struct.stderr b/tests/ui/derives/derives-span-PartialEq-struct.stderr index d7fc3da46e0..cfd9fc41d06 100644 --- a/tests/ui/derives/derives-span-PartialEq-struct.stderr +++ b/tests/ui/derives/derives-span-PartialEq-struct.stderr @@ -12,7 +12,6 @@ note: an implementation of `PartialEq` might be missing for `Error` | LL | struct Error; | ^^^^^^^^^^^^ must implement `PartialEq` - = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Error` with `#[derive(PartialEq)]` | LL + #[derive(PartialEq)] diff --git a/tests/ui/derives/derives-span-PartialEq-tuple-struct.stderr b/tests/ui/derives/derives-span-PartialEq-tuple-struct.stderr index ea3920f406c..4e35cbb534d 100644 --- a/tests/ui/derives/derives-span-PartialEq-tuple-struct.stderr +++ b/tests/ui/derives/derives-span-PartialEq-tuple-struct.stderr @@ -12,7 +12,6 @@ note: an implementation of `PartialEq` might be missing for `Error` | LL | struct Error; | ^^^^^^^^^^^^ must implement `PartialEq` - = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Error` with `#[derive(PartialEq)]` | LL + #[derive(PartialEq)] diff --git a/tests/ui/derives/derives-span-PartialOrd-enum-struct-variant.stderr b/tests/ui/derives/derives-span-PartialOrd-enum-struct-variant.stderr index 3f83eb56aaf..7fe09d45cc1 100644 --- a/tests/ui/derives/derives-span-PartialOrd-enum-struct-variant.stderr +++ b/tests/ui/derives/derives-span-PartialOrd-enum-struct-variant.stderr @@ -8,7 +8,6 @@ LL | x: Error | ^^^^^^^^ no implementation for `Error < Error` and `Error > Error` | = help: the trait `PartialOrd` is not implemented for `Error` - = note: this error originates in the derive macro `PartialOrd` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Error` with `#[derive(PartialOrd)]` | LL + #[derive(PartialOrd)] diff --git a/tests/ui/derives/derives-span-PartialOrd-enum.stderr b/tests/ui/derives/derives-span-PartialOrd-enum.stderr index cf5915173c5..2a14e6e9618 100644 --- a/tests/ui/derives/derives-span-PartialOrd-enum.stderr +++ b/tests/ui/derives/derives-span-PartialOrd-enum.stderr @@ -8,7 +8,6 @@ LL | Error | ^^^^^ no implementation for `Error < Error` and `Error > Error` | = help: the trait `PartialOrd` is not implemented for `Error` - = note: this error originates in the derive macro `PartialOrd` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Error` with `#[derive(PartialOrd)]` | LL + #[derive(PartialOrd)] diff --git a/tests/ui/derives/derives-span-PartialOrd-struct.stderr b/tests/ui/derives/derives-span-PartialOrd-struct.stderr index de21a903b6c..0904e3ace8f 100644 --- a/tests/ui/derives/derives-span-PartialOrd-struct.stderr +++ b/tests/ui/derives/derives-span-PartialOrd-struct.stderr @@ -8,7 +8,6 @@ LL | x: Error | ^^^^^^^^ no implementation for `Error < Error` and `Error > Error` | = help: the trait `PartialOrd` is not implemented for `Error` - = note: this error originates in the derive macro `PartialOrd` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Error` with `#[derive(PartialOrd)]` | LL + #[derive(PartialOrd)] diff --git a/tests/ui/derives/derives-span-PartialOrd-tuple-struct.stderr b/tests/ui/derives/derives-span-PartialOrd-tuple-struct.stderr index 3050aeecc0d..501fea02e8e 100644 --- a/tests/ui/derives/derives-span-PartialOrd-tuple-struct.stderr +++ b/tests/ui/derives/derives-span-PartialOrd-tuple-struct.stderr @@ -8,7 +8,6 @@ LL | Error | ^^^^^ no implementation for `Error < Error` and `Error > Error` | = help: the trait `PartialOrd` is not implemented for `Error` - = note: this error originates in the derive macro `PartialOrd` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Error` with `#[derive(PartialOrd)]` | LL + #[derive(PartialOrd)] diff --git a/tests/ui/derives/deriving-copyclone.stderr b/tests/ui/derives/deriving-copyclone.stderr index c0c2215c04a..befff880280 100644 --- a/tests/ui/derives/deriving-copyclone.stderr +++ b/tests/ui/derives/deriving-copyclone.stderr @@ -16,7 +16,6 @@ note: required by a bound in `is_copy` | LL | fn is_copy<T: Copy>(_: T) {} | ^^^^ required by this bound in `is_copy` - = note: this error originates in the derive macro `Copy` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider borrowing here | LL | is_copy(B { a: 1, b: &C }); @@ -40,7 +39,6 @@ note: required by a bound in `is_clone` | LL | fn is_clone<T: Clone>(_: T) {} | ^^^^^ required by this bound in `is_clone` - = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider borrowing here | LL | is_clone(B { a: 1, b: &C }); @@ -64,7 +62,6 @@ note: required by a bound in `is_copy` | LL | fn is_copy<T: Copy>(_: T) {} | ^^^^ required by this bound in `is_copy` - = note: this error originates in the derive macro `Copy` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider borrowing here | LL | is_copy(B { a: 1, b: &D }); diff --git a/tests/ui/derives/deriving-no-inner-impl-error-message.stderr b/tests/ui/derives/deriving-no-inner-impl-error-message.stderr index ab99ba9fab5..294f700d9de 100644 --- a/tests/ui/derives/deriving-no-inner-impl-error-message.stderr +++ b/tests/ui/derives/deriving-no-inner-impl-error-message.stderr @@ -12,7 +12,6 @@ note: an implementation of `PartialEq` might be missing for `NoCloneOrEq` | LL | struct NoCloneOrEq; | ^^^^^^^^^^^^^^^^^^ must implement `PartialEq` - = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `NoCloneOrEq` with `#[derive(PartialEq)]` | LL + #[derive(PartialEq)] @@ -28,7 +27,6 @@ LL | struct C { LL | x: NoCloneOrEq | ^^^^^^^^^^^^^^ the trait `Clone` is not implemented for `NoCloneOrEq` | - = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `NoCloneOrEq` with `#[derive(Clone)]` | LL + #[derive(Clone)] diff --git a/tests/ui/derives/deriving-with-repr-packed-move-errors.stderr b/tests/ui/derives/deriving-with-repr-packed-move-errors.stderr index 2de4ee4eabd..68c3c8ae9ea 100644 --- a/tests/ui/derives/deriving-with-repr-packed-move-errors.stderr +++ b/tests/ui/derives/deriving-with-repr-packed-move-errors.stderr @@ -7,7 +7,6 @@ LL | struct StructA(String); | ^^^^^^ move occurs because `self.0` has type `String`, which does not implement the `Copy` trait | = note: `#[derive(Debug)]` triggers a move because taking references to the fields of a packed struct is undefined behaviour - = note: this error originates in the derive macro `Debug` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider cloning the value if the performance cost is acceptable | LL | struct StructA(String.clone()); @@ -22,7 +21,6 @@ LL | struct StructA(String); | ^^^^^^ move occurs because `self.0` has type `String`, which does not implement the `Copy` trait | = note: `#[derive(PartialEq)]` triggers a move because taking references to the fields of a packed struct is undefined behaviour - = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider cloning the value if the performance cost is acceptable | LL | struct StructA(String.clone()); @@ -37,7 +35,6 @@ LL | struct StructA(String); | ^^^^^^ move occurs because `other.0` has type `String`, which does not implement the `Copy` trait | = note: `#[derive(PartialEq)]` triggers a move because taking references to the fields of a packed struct is undefined behaviour - = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider cloning the value if the performance cost is acceptable | LL | struct StructA(String.clone()); @@ -52,7 +49,6 @@ LL | struct StructA(String); | ^^^^^^ move occurs because `self.0` has type `String`, which does not implement the `Copy` trait | = note: `#[derive(PartialOrd)]` triggers a move because taking references to the fields of a packed struct is undefined behaviour - = note: this error originates in the derive macro `PartialOrd` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider cloning the value if the performance cost is acceptable | LL | struct StructA(String.clone()); @@ -67,7 +63,6 @@ LL | struct StructA(String); | ^^^^^^ move occurs because `other.0` has type `String`, which does not implement the `Copy` trait | = note: `#[derive(PartialOrd)]` triggers a move because taking references to the fields of a packed struct is undefined behaviour - = note: this error originates in the derive macro `PartialOrd` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider cloning the value if the performance cost is acceptable | LL | struct StructA(String.clone()); @@ -82,7 +77,6 @@ LL | struct StructA(String); | ^^^^^^ move occurs because `self.0` has type `String`, which does not implement the `Copy` trait | = note: `#[derive(Ord)]` triggers a move because taking references to the fields of a packed struct is undefined behaviour - = note: this error originates in the derive macro `Ord` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider cloning the value if the performance cost is acceptable | LL | struct StructA(String.clone()); @@ -97,7 +91,6 @@ LL | struct StructA(String); | ^^^^^^ move occurs because `other.0` has type `String`, which does not implement the `Copy` trait | = note: `#[derive(Ord)]` triggers a move because taking references to the fields of a packed struct is undefined behaviour - = note: this error originates in the derive macro `Ord` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider cloning the value if the performance cost is acceptable | LL | struct StructA(String.clone()); @@ -112,7 +105,6 @@ LL | struct StructA(String); | ^^^^^^ move occurs because `self.0` has type `String`, which does not implement the `Copy` trait | = note: `#[derive(Hash)]` triggers a move because taking references to the fields of a packed struct is undefined behaviour - = note: this error originates in the derive macro `Hash` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider cloning the value if the performance cost is acceptable | LL | struct StructA(String.clone()); @@ -127,7 +119,6 @@ LL | struct StructA(String); | ^^^^^^ move occurs because `self.0` has type `String`, which does not implement the `Copy` trait | = note: `#[derive(Clone)]` triggers a move because taking references to the fields of a packed struct is undefined behaviour - = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider cloning the value if the performance cost is acceptable | LL | struct StructA(String.clone()); diff --git a/tests/ui/derives/deriving-with-repr-packed.stderr b/tests/ui/derives/deriving-with-repr-packed.stderr index 321ffb27eeb..5117f8d1112 100644 --- a/tests/ui/derives/deriving-with-repr-packed.stderr +++ b/tests/ui/derives/deriving-with-repr-packed.stderr @@ -16,7 +16,6 @@ LL | struct Y(usize); LL | struct X(Y); | - you could clone this value = note: `#[derive(Debug)]` triggers a move because taking references to the fields of a packed struct is undefined behaviour - = note: this error originates in the derive macro `Debug` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0161]: cannot move a value of type `[u8]` --> $DIR/deriving-with-repr-packed.rs:29:5 @@ -34,7 +33,6 @@ LL | data: [u8], | ^^^^^^^^^^ move occurs because `self.data` has type `[u8]`, which does not implement the `Copy` trait | = note: `#[derive(Debug)]` triggers a move because taking references to the fields of a packed struct is undefined behaviour - = note: this error originates in the derive macro `Debug` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0161]: cannot move a value of type `str` --> $DIR/deriving-with-repr-packed.rs:38:5 @@ -52,7 +50,6 @@ LL | data: str, | ^^^^^^^^^ move occurs because `self.data` has type `str`, which does not implement the `Copy` trait | = note: `#[derive(Debug)]` triggers a move because taking references to the fields of a packed struct is undefined behaviour - = note: this error originates in the derive macro `Debug` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 5 previous errors diff --git a/tests/ui/derives/duplicate-derive-copy-clone-diagnostics.stderr b/tests/ui/derives/duplicate-derive-copy-clone-diagnostics.stderr index f8e1db33f53..b9eb6194f6c 100644 --- a/tests/ui/derives/duplicate-derive-copy-clone-diagnostics.stderr +++ b/tests/ui/derives/duplicate-derive-copy-clone-diagnostics.stderr @@ -5,8 +5,6 @@ LL | #[derive(Copy, Clone)] | ---- first implementation here LL | #[derive(Copy, Clone)] | ^^^^ conflicting implementation for `E` - | - = note: this error originates in the derive macro `Copy` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0119]: conflicting implementations of trait `Clone` for type `E` --> $DIR/duplicate-derive-copy-clone-diagnostics.rs:6:16 @@ -15,8 +13,6 @@ LL | #[derive(Copy, Clone)] | ----- first implementation here LL | #[derive(Copy, Clone)] | ^^^^^ conflicting implementation for `E` - | - = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 2 previous errors diff --git a/tests/ui/derives/issue-97343.stderr b/tests/ui/derives/issue-97343.stderr index efb2fb70f5a..27691f57188 100644 --- a/tests/ui/derives/issue-97343.stderr +++ b/tests/ui/derives/issue-97343.stderr @@ -14,7 +14,6 @@ note: type parameter `Irrelevant` defined here | LL | pub struct Irrelevant<Irrelevant> { | ^^^^^^^^^^ - = note: this error originates in the derive macro `Debug` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/deriving/deriving-coerce-pointee-neg.stderr b/tests/ui/deriving/deriving-coerce-pointee-neg.stderr index d3d73132078..6c6e6312875 100644 --- a/tests/ui/deriving/deriving-coerce-pointee-neg.stderr +++ b/tests/ui/deriving/deriving-coerce-pointee-neg.stderr @@ -3,40 +3,30 @@ error[E0802]: `CoercePointee` can only be derived on `struct`s with `#[repr(tran | LL | #[derive(CoercePointee)] | ^^^^^^^^^^^^^ - | - = note: this error originates in the derive macro `CoercePointee` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0802]: `CoercePointee` can only be derived on `struct`s with at least one field --> $DIR/deriving-coerce-pointee-neg.rs:15:10 | LL | #[derive(CoercePointee)] | ^^^^^^^^^^^^^ - | - = note: this error originates in the derive macro `CoercePointee` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0802]: `CoercePointee` can only be derived on `struct`s with at least one field --> $DIR/deriving-coerce-pointee-neg.rs:22:10 | LL | #[derive(CoercePointee)] | ^^^^^^^^^^^^^ - | - = note: this error originates in the derive macro `CoercePointee` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0802]: `CoercePointee` can only be derived on `struct`s that are generic over at least one type --> $DIR/deriving-coerce-pointee-neg.rs:29:10 | LL | #[derive(CoercePointee)] | ^^^^^^^^^^^^^ - | - = note: this error originates in the derive macro `CoercePointee` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0802]: exactly one generic type parameter must be marked as `#[pointee]` to derive `CoercePointee` traits --> $DIR/deriving-coerce-pointee-neg.rs:34:10 | LL | #[derive(CoercePointee)] | ^^^^^^^^^^^^^ - | - = note: this error originates in the derive macro `CoercePointee` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0802]: only one type parameter can be marked as `#[pointee]` when deriving `CoercePointee` traits --> $DIR/deriving-coerce-pointee-neg.rs:43:39 @@ -126,8 +116,6 @@ LL | #[derive(CoercePointee)] ... LL | inner: std::rc::Rc<(i32, Box<T>)>, | --------------------------------- `Rc<(i32, Box<T>)>` must be a pointer, reference, or smart pointer that is allowed to be unsized - | - = note: this error originates in the derive macro `CoercePointee` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0375]: implementing `CoerceUnsized` does not allow multiple fields to be coerced --> $DIR/deriving-coerce-pointee-neg.rs:153:10 @@ -142,7 +130,6 @@ LL | inner1: Box<T>, | ^^^^^^^^^^^^^^ LL | inner2: Box<T>, | ^^^^^^^^^^^^^^ - = note: this error originates in the derive macro `CoercePointee` (in Nightly builds, run with -Z macro-backtrace for more info) error: for `UsingNonCoercePointeeData<T>` to have a valid implementation of `CoerceUnsized`, it must be possible to coerce the field of type `NotCoercePointeeData<T>` --> $DIR/deriving-coerce-pointee-neg.rs:164:10 @@ -152,8 +139,6 @@ LL | #[derive(CoercePointee)] LL | LL | struct UsingNonCoercePointeeData<T: ?Sized>(NotCoercePointeeData<T>); | ----------------------- `NotCoercePointeeData<T>` must be a pointer, reference, or smart pointer that is allowed to be unsized - | - = note: this error originates in the derive macro `CoercePointee` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0690]: transparent struct needs at most one field with non-trivial size or alignment, but has 2 --> $DIR/deriving-coerce-pointee-neg.rs:155:1 diff --git a/tests/ui/deriving/do-not-suggest-calling-fn-in-derive-macro.stderr b/tests/ui/deriving/do-not-suggest-calling-fn-in-derive-macro.stderr index 40464a49c34..af78f645463 100644 --- a/tests/ui/deriving/do-not-suggest-calling-fn-in-derive-macro.stderr +++ b/tests/ui/deriving/do-not-suggest-calling-fn-in-derive-macro.stderr @@ -6,8 +6,6 @@ LL | #[derive(PartialEq)] LL | pub struct Function { LL | callback: Rc<dyn Fn()>, | ^^^^^^^^^^^^^^^^^^^^^^ - | - = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/deriving/issue-103157.stderr b/tests/ui/deriving/issue-103157.stderr index 9754b0289c0..51d4d0a8974 100644 --- a/tests/ui/deriving/issue-103157.stderr +++ b/tests/ui/deriving/issue-103157.stderr @@ -20,7 +20,6 @@ LL | Float(Option<f64>), = note: required for `Option<f64>` to implement `Eq` note: required by a bound in `AssertParamIsEq` --> $SRC_DIR/core/src/cmp.rs:LL:COL - = note: this error originates in the derive macro `Eq` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/deriving/multiple-defaults.stderr b/tests/ui/deriving/multiple-defaults.stderr index 05fb6fecffa..a662ed248fe 100644 --- a/tests/ui/deriving/multiple-defaults.stderr +++ b/tests/ui/deriving/multiple-defaults.stderr @@ -11,7 +11,6 @@ LL | B, | - additional default | = note: only one variant can be default - = note: this error originates in the derive macro `Default` (in Nightly builds, run with -Z macro-backtrace for more info) error: multiple declared defaults --> $DIR/multiple-defaults.rs:18:10 @@ -26,7 +25,6 @@ LL | A, | - additional default | = note: only one variant can be default - = note: this error originates in the derive macro `Default` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0428]: the name `A` is defined multiple times --> $DIR/multiple-defaults.rs:23:5 diff --git a/tests/ui/diagnostic-width/tabs-trimming.stderr b/tests/ui/diagnostic-width/tabs-trimming.stderr index a896345bd70..e0d1c2d95a9 100644 --- a/tests/ui/diagnostic-width/tabs-trimming.stderr +++ b/tests/ui/diagnostic-width/tabs-trimming.stderr @@ -15,8 +15,6 @@ LL | ... v @ 1 | 2 | 3 => panic!("You gave me too little mon | | | binding initialized here in some conditions | binding declared here but left uninitialized - | - = note: this error originates in the macro `$crate::const_format_args` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 2 previous errors diff --git a/tests/ui/dupe-first-attr.rs b/tests/ui/dupe-first-attr.rs deleted file mode 100644 index c254df050c1..00000000000 --- a/tests/ui/dupe-first-attr.rs +++ /dev/null @@ -1,25 +0,0 @@ -//@ run-pass - -// Regression test for a problem with the first mod attribute -// being applied to every mod - - -#[cfg(target_os = "linux")] -mod hello {} - -#[cfg(target_os = "macos")] -mod hello {} - -#[cfg(target_os = "windows")] -mod hello {} - -#[cfg(target_os = "freebsd")] -mod hello {} - -#[cfg(target_os = "dragonfly")] -mod hello {} - -#[cfg(target_os = "android")] -mod hello {} - -fn main() {} diff --git a/tests/ui/duplicate_entry_error.rs b/tests/ui/duplicate_entry_error.rs deleted file mode 100644 index 5a25802c6e7..00000000000 --- a/tests/ui/duplicate_entry_error.rs +++ /dev/null @@ -1,18 +0,0 @@ -//@ normalize-stderr: "loaded from .*libstd-.*.rlib" -> "loaded from SYSROOT/libstd-*.rlib" -// note-pattern: first defined in crate `std`. - -// Test for issue #31788 and E0152 - -#![feature(lang_items)] - -extern crate core; - -use core::panic::PanicInfo; - -#[lang = "panic_impl"] -fn panic_impl(info: &PanicInfo) -> ! { -//~^ ERROR: found duplicate lang item `panic_impl` - loop {} -} - -fn main() {} diff --git a/tests/ui/dyn-compatibility/avoid-ice-on-warning-2.new.stderr b/tests/ui/dyn-compatibility/avoid-ice-on-warning-2.new.stderr index 87207d607e2..4c4cb45293f 100644 --- a/tests/ui/dyn-compatibility/avoid-ice-on-warning-2.new.stderr +++ b/tests/ui/dyn-compatibility/avoid-ice-on-warning-2.new.stderr @@ -4,7 +4,7 @@ error[E0782]: expected a type, found a trait LL | fn id<F>(f: Copy) -> usize { | ^^^^ | - = note: `Copy` it is dyn-incompatible, so it can't be `dyn` + = note: `Copy` is dyn-incompatible, otherwise a trait object could be used help: use a new generic type parameter, constrained by `Copy` | LL - fn id<F>(f: Copy) -> usize { diff --git a/tests/ui/dyn-compatibility/avoid-ice-on-warning-3.new.stderr b/tests/ui/dyn-compatibility/avoid-ice-on-warning-3.new.stderr index 6075e313f4e..d3208d07e91 100644 --- a/tests/ui/dyn-compatibility/avoid-ice-on-warning-3.new.stderr +++ b/tests/ui/dyn-compatibility/avoid-ice-on-warning-3.new.stderr @@ -4,7 +4,7 @@ error[E0782]: expected a type, found a trait LL | trait A { fn g(b: B) -> B; } | ^ | - = note: `B` it is dyn-incompatible, so it can't be `dyn` + = note: `B` is dyn-incompatible, otherwise a trait object could be used help: use a new generic type parameter, constrained by `B` | LL - trait A { fn g(b: B) -> B; } @@ -32,7 +32,7 @@ error[E0782]: expected a type, found a trait LL | trait B { fn f(a: A) -> A; } | ^ | - = note: `A` it is dyn-incompatible, so it can't be `dyn` + = note: `A` is dyn-incompatible, otherwise a trait object could be used help: use a new generic type parameter, constrained by `A` | LL - trait B { fn f(a: A) -> A; } diff --git a/tests/ui/env-macro/env-escaped-var.stderr b/tests/ui/env-macro/env-escaped-var.stderr index 53a2ead6742..65d53a7fa1f 100644 --- a/tests/ui/env-macro/env-escaped-var.stderr +++ b/tests/ui/env-macro/env-escaped-var.stderr @@ -5,7 +5,6 @@ LL | env!("\t"); | ^^^^^^^^^^ | = help: use `std::env::var("\t")` to read the variable at run time - = note: this error originates in the macro `env` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/env-macro/env-not-defined-custom.stderr b/tests/ui/env-macro/env-not-defined-custom.stderr index 70c41bcc52e..638f261e48e 100644 --- a/tests/ui/env-macro/env-not-defined-custom.stderr +++ b/tests/ui/env-macro/env-not-defined-custom.stderr @@ -3,8 +3,6 @@ error: my error message | LL | fn main() { env!("__HOPEFULLY_NOT_DEFINED__", "my error message"); } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: this error originates in the macro `env` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/env-macro/env-not-defined-default.stderr b/tests/ui/env-macro/env-not-defined-default.stderr index efd7fdb4e53..77ba00e45c1 100644 --- a/tests/ui/env-macro/env-not-defined-default.stderr +++ b/tests/ui/env-macro/env-not-defined-default.stderr @@ -5,7 +5,6 @@ LL | env!("CARGO__HOPEFULLY_NOT_DEFINED__"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: Cargo sets build script variables at run time. Use `std::env::var("CARGO__HOPEFULLY_NOT_DEFINED__")` instead - = note: this error originates in the macro `env` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/env-macro/error-recovery-issue-55897.stderr b/tests/ui/env-macro/error-recovery-issue-55897.stderr index f1cacf5420e..3d9ef56c502 100644 --- a/tests/ui/env-macro/error-recovery-issue-55897.stderr +++ b/tests/ui/env-macro/error-recovery-issue-55897.stderr @@ -5,7 +5,6 @@ LL | include!(concat!(env!("NON_EXISTENT"), "/data.rs")); | ^^^^^^^^^^^^^^^^^^^^ | = help: use `std::env::var("NON_EXISTENT")` to read the variable at run time - = note: this error originates in the macro `env` (in Nightly builds, run with -Z macro-backtrace for more info) error: suffixes on string literals are invalid --> $DIR/error-recovery-issue-55897.rs:15:22 diff --git a/tests/ui/env-macro/name-whitespace-issue-110547.stderr b/tests/ui/env-macro/name-whitespace-issue-110547.stderr index 5f34904d4ae..f29c5dbf8d1 100644 --- a/tests/ui/env-macro/name-whitespace-issue-110547.stderr +++ b/tests/ui/env-macro/name-whitespace-issue-110547.stderr @@ -5,7 +5,6 @@ LL | env!{"\t"}; | ^^^^^^^^^^ | = help: use `std::env::var("\t")` to read the variable at run time - = note: this error originates in the macro `env` (in Nightly builds, run with -Z macro-backtrace for more info) error: environment variable `\t` not defined at compile time --> $DIR/name-whitespace-issue-110547.rs:5:5 @@ -14,7 +13,6 @@ LL | env!("\t"); | ^^^^^^^^^^ | = help: use `std::env::var("\t")` to read the variable at run time - = note: this error originates in the macro `env` (in Nightly builds, run with -Z macro-backtrace for more info) error: environment variable `\u{2069}` not defined at compile time --> $DIR/name-whitespace-issue-110547.rs:6:5 @@ -23,7 +21,6 @@ LL | env!("\u{2069}"); | ^^^^^^^^^^^^^^^^ | = help: use `std::env::var("\u{2069}")` to read the variable at run time - = note: this error originates in the macro `env` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 3 previous errors diff --git a/tests/ui/error-codes/E0152-duplicate-lang-items.rs b/tests/ui/error-codes/E0152-duplicate-lang-items.rs new file mode 100644 index 00000000000..089810b1ad2 --- /dev/null +++ b/tests/ui/error-codes/E0152-duplicate-lang-items.rs @@ -0,0 +1,20 @@ +//! Validates the correct printing of E0152 in the case of duplicate "lang_item" function +//! definitions. +//! +//! Issue: <https://github.com/rust-lang/rust/issues/31788> + +//@ error-pattern: first defined in crate `std` +//@ normalize-stderr: "loaded from .*libstd-.*.rlib" -> "loaded from SYSROOT/libstd-*.rlib" +#![feature(lang_items)] + +extern crate core; + +use core::panic::PanicInfo; + +#[lang = "panic_impl"] +fn panic_impl(info: &PanicInfo) -> ! { + //~^ ERROR: found duplicate lang item `panic_impl` + loop {} +} + +fn main() {} diff --git a/tests/ui/duplicate_entry_error.stderr b/tests/ui/error-codes/E0152-duplicate-lang-items.stderr index 958e9c7527d..3c3d64322f3 100644 --- a/tests/ui/duplicate_entry_error.stderr +++ b/tests/ui/error-codes/E0152-duplicate-lang-items.stderr @@ -1,5 +1,5 @@ error[E0152]: found duplicate lang item `panic_impl` - --> $DIR/duplicate_entry_error.rs:13:1 + --> $DIR/E0152-duplicate-lang-items.rs:15:1 | LL | / fn panic_impl(info: &PanicInfo) -> ! { LL | | @@ -7,9 +7,9 @@ LL | | loop {} LL | | } | |_^ | - = note: the lang item is first defined in crate `std` (which `duplicate_entry_error` depends on) + = note: the lang item is first defined in crate `std` (which `E0152_duplicate_lang_items` depends on) = note: first definition in `std` loaded from SYSROOT/libstd-*.rlib - = note: second definition in the local crate (`duplicate_entry_error`) + = note: second definition in the local crate (`E0152_duplicate_lang_items`) error: aborting due to 1 previous error diff --git a/tests/ui/error-codes/E0184.stderr b/tests/ui/error-codes/E0184.stderr index 625c6685a61..1a7df9ac095 100644 --- a/tests/ui/error-codes/E0184.stderr +++ b/tests/ui/error-codes/E0184.stderr @@ -3,8 +3,6 @@ error[E0184]: the trait `Copy` cannot be implemented for this type; the type has | LL | #[derive(Copy)] | ^^^^ `Copy` not allowed on types with destructors - | - = note: this error originates in the derive macro `Copy` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/duplicate-label-E0381-issue-129274.rs b/tests/ui/error-codes/E0381-duplicated-label.rs index b2156e630c8..84a85caa65d 100644 --- a/tests/ui/duplicate-label-E0381-issue-129274.rs +++ b/tests/ui/error-codes/E0381-duplicated-label.rs @@ -1,3 +1,6 @@ +//! Regression test for duplicated label in E0381 error message. +//! +//! Issue: <https://github.com/rust-lang/rust/issues/129274> fn main() { fn test() { loop { diff --git a/tests/ui/duplicate-label-E0381-issue-129274.stderr b/tests/ui/error-codes/E0381-duplicated-label.stderr index 7f8bddb17c5..36e6d966f09 100644 --- a/tests/ui/duplicate-label-E0381-issue-129274.stderr +++ b/tests/ui/error-codes/E0381-duplicated-label.stderr @@ -1,5 +1,5 @@ error[E0381]: used binding `blah` is possibly-uninitialized - --> $DIR/duplicate-label-E0381-issue-129274.rs:8:33 + --> $DIR/E0381-duplicated-label.rs:11:33 | LL | let blah: Option<String>; | ---- binding declared here but left uninitialized diff --git a/tests/ui/exclusive-drop-and-copy.stderr b/tests/ui/exclusive-drop-and-copy.stderr index 546079422a7..340ca89c396 100644 --- a/tests/ui/exclusive-drop-and-copy.stderr +++ b/tests/ui/exclusive-drop-and-copy.stderr @@ -3,16 +3,12 @@ error[E0184]: the trait `Copy` cannot be implemented for this type; the type has | LL | #[derive(Copy, Clone)] | ^^^^ `Copy` not allowed on types with destructors - | - = note: this error originates in the derive macro `Copy` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0184]: the trait `Copy` cannot be implemented for this type; the type has a destructor --> $DIR/exclusive-drop-and-copy.rs:10:10 | LL | #[derive(Copy, Clone)] | ^^^^ `Copy` not allowed on types with destructors - | - = note: this error originates in the derive macro `Copy` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 2 previous errors diff --git a/tests/ui/explicit-tail-calls/ctfe-tail-call-panic.stderr b/tests/ui/explicit-tail-calls/ctfe-tail-call-panic.stderr index ef71722a0ab..3bdd09e9683 100644 --- a/tests/ui/explicit-tail-calls/ctfe-tail-call-panic.stderr +++ b/tests/ui/explicit-tail-calls/ctfe-tail-call-panic.stderr @@ -9,7 +9,6 @@ note: inside `g` | LL | panic!() | ^^^^^^^^ the failure occurred here - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/feature-gates/feature-gate-concat_idents2.stderr b/tests/ui/feature-gates/feature-gate-concat_idents2.stderr index 2052813ea4a..b42a1d999e4 100644 --- a/tests/ui/feature-gates/feature-gate-concat_idents2.stderr +++ b/tests/ui/feature-gates/feature-gate-concat_idents2.stderr @@ -13,8 +13,6 @@ error[E0425]: cannot find value `ab` in this scope | LL | concat_idents!(a, b); | ^^^^^^^^^^^^^^^^^^^^ not found in this scope - | - = note: this error originates in the macro `concat_idents` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 2 previous errors diff --git a/tests/ui/fmt/format-args-capture-first-literal-is-macro.stderr b/tests/ui/fmt/format-args-capture-first-literal-is-macro.stderr index e399361579f..e9b2e83c288 100644 --- a/tests/ui/fmt/format-args-capture-first-literal-is-macro.stderr +++ b/tests/ui/fmt/format-args-capture-first-literal-is-macro.stderr @@ -24,7 +24,6 @@ LL | format!(concat!("{a}")); | = note: did you intend to capture a variable `a` from the surrounding scope? = note: to avoid ambiguity, `format_args!` cannot capture variables when the format string is expanded from a macro - = note: this error originates in the macro `concat` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 3 previous errors diff --git a/tests/ui/fmt/format-args-capture-from-pm-first-arg-macro.stderr b/tests/ui/fmt/format-args-capture-from-pm-first-arg-macro.stderr index 950dea721e2..e7ed2a76e6a 100644 --- a/tests/ui/fmt/format-args-capture-from-pm-first-arg-macro.stderr +++ b/tests/ui/fmt/format-args-capture-from-pm-first-arg-macro.stderr @@ -6,7 +6,6 @@ LL | format_string_proc_macro::bad_format_args_captures!(); | = note: did you intend to capture a variable `x` from the surrounding scope? = note: to avoid ambiguity, `format_args!` cannot capture variables when the format string is expanded from a macro - = note: this error originates in the macro `concat` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/fmt/format-args-capture-macro-hygiene.stderr b/tests/ui/fmt/format-args-capture-macro-hygiene.stderr index 1b5fbd2af34..47ef581629e 100644 --- a/tests/ui/fmt/format-args-capture-macro-hygiene.stderr +++ b/tests/ui/fmt/format-args-capture-macro-hygiene.stderr @@ -6,7 +6,6 @@ LL | format!(concat!("{foo}")); | = note: did you intend to capture a variable `foo` from the surrounding scope? = note: to avoid ambiguity, `format_args!` cannot capture variables when the format string is expanded from a macro - = note: this error originates in the macro `concat` (in Nightly builds, run with -Z macro-backtrace for more info) error: there is no argument named `bar` --> $DIR/format-args-capture-macro-hygiene.rs:16:13 @@ -16,7 +15,6 @@ LL | format!(concat!("{ba", "r} {}"), 1); | = note: did you intend to capture a variable `bar` from the surrounding scope? = note: to avoid ambiguity, `format_args!` cannot capture variables when the format string is expanded from a macro - = note: this error originates in the macro `concat` (in Nightly builds, run with -Z macro-backtrace for more info) error: there is no argument named `foo` --> $DIR/format-args-capture-macro-hygiene.rs:7:13 diff --git a/tests/ui/fmt/format-expanded-string.stderr b/tests/ui/fmt/format-expanded-string.stderr index 26ce7f26958..ab5baaf3789 100644 --- a/tests/ui/fmt/format-expanded-string.stderr +++ b/tests/ui/fmt/format-expanded-string.stderr @@ -5,7 +5,6 @@ LL | format!(concat!("abc}")); | ^^^^^^^^^^^^^^^ unmatched `}` in format string | = note: if you intended to print `}`, you can escape it using `}}` - = note: this error originates in the macro `concat` (in Nightly builds, run with -Z macro-backtrace for more info) error: invalid format string: unmatched `}` found --> $DIR/format-expanded-string.rs:22:34 diff --git a/tests/ui/fmt/ifmt-bad-format-args.stderr b/tests/ui/fmt/ifmt-bad-format-args.stderr index 2db280c5e2a..d458f2bc05b 100644 --- a/tests/ui/fmt/ifmt-bad-format-args.stderr +++ b/tests/ui/fmt/ifmt-bad-format-args.stderr @@ -3,8 +3,6 @@ error: requires at least a format string argument | LL | format_args!(); | ^^^^^^^^^^^^^^ - | - = note: this error originates in the macro `format_args` (in Nightly builds, run with -Z macro-backtrace for more info) error: format argument must be a string literal --> $DIR/ifmt-bad-format-args.rs:3:18 diff --git a/tests/ui/fmt/issue-86085.stderr b/tests/ui/fmt/issue-86085.stderr index f325a3ce293..4cc19ec4365 100644 --- a/tests/ui/fmt/issue-86085.stderr +++ b/tests/ui/fmt/issue-86085.stderr @@ -5,7 +5,6 @@ LL | format ! ( concat ! ( r#"lJÆ�.�"# , "r} {}" ) ) ; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ unmatched `}` in format string | = note: if you intended to print `}`, you can escape it using `}}` - = note: this error originates in the macro `concat` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/fmt/issue-91556.stderr b/tests/ui/fmt/issue-91556.stderr index 52917fb8c42..69f3779b93c 100644 --- a/tests/ui/fmt/issue-91556.stderr +++ b/tests/ui/fmt/issue-91556.stderr @@ -5,7 +5,6 @@ LL | let _ = format!(concat!("{0}𝖳𝖾𝗌𝗍{"), i); | ^^^^^^^^^^^^^^^^^^^ expected `}` in format string | = note: if you intended to print `{`, you can escape it using `{{` - = note: this error originates in the macro `concat` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/fmt/raw-idents.stderr b/tests/ui/fmt/raw-idents.stderr index 2ddc114d286..178340cf57e 100644 --- a/tests/ui/fmt/raw-idents.stderr +++ b/tests/ui/fmt/raw-idents.stderr @@ -27,7 +27,6 @@ LL | println!(concat!("{r#", "type}")); | ^^^^^^^^^^^^^^^^^^^^^^^ raw identifier used here in format string | = note: identifiers in format strings can be keywords and don't need to be prefixed with `r#` - = note: this error originates in the macro `concat` (in Nightly builds, run with -Z macro-backtrace for more info) error: invalid format string: raw identifiers are not supported --> $DIR/raw-idents.rs:11:16 diff --git a/tests/ui/fmt/respanned-literal-issue-106191.stderr b/tests/ui/fmt/respanned-literal-issue-106191.stderr index 17ab29e799b..5c9e538aa0c 100644 --- a/tests/ui/fmt/respanned-literal-issue-106191.stderr +++ b/tests/ui/fmt/respanned-literal-issue-106191.stderr @@ -13,7 +13,6 @@ LL | format_args!(r#concat!("¡ {")); | ^^^^^^^^^^^^^^^^^^^^^^^ expected `}` in format string | = note: if you intended to print `{`, you can escape it using `{{` - = note: this error originates in the macro `concat` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 2 previous errors diff --git a/tests/ui/generic-associated-types/impl_bounds.stderr b/tests/ui/generic-associated-types/impl_bounds.stderr index 291f0ade439..231c0dd89c5 100644 --- a/tests/ui/generic-associated-types/impl_bounds.stderr +++ b/tests/ui/generic-associated-types/impl_bounds.stderr @@ -41,7 +41,6 @@ LL | trait Foo { ... LL | type C where Self: Clone; | ^ this trait's associated type doesn't have the requirement `Fooy<T>: Copy` - = note: this error originates in the derive macro `Copy` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider restricting type parameter `T` with trait `Copy` | LL | impl<T: std::marker::Copy> Foo for Fooy<T> { @@ -66,7 +65,6 @@ LL | trait Foo { ... LL | fn d() where Self: Clone; | ^ this trait's method doesn't have the requirement `Fooy<T>: Copy` - = note: this error originates in the derive macro `Copy` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider restricting type parameter `T` with trait `Copy` | LL | impl<T: std::marker::Copy> Foo for Fooy<T> { diff --git a/tests/ui/generic-const-items/def-site-eval.fail.stderr b/tests/ui/generic-const-items/def-site-eval.fail.stderr index 1ba4455c7be..fa07f385522 100644 --- a/tests/ui/generic-const-items/def-site-eval.fail.stderr +++ b/tests/ui/generic-const-items/def-site-eval.fail.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of `_::<'_>` failed | LL | const _<'_a>: () = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/generics/post_monomorphization_error_backtrace.stderr b/tests/ui/generics/post_monomorphization_error_backtrace.stderr index 1366d5491f4..96aa04ee359 100644 --- a/tests/ui/generics/post_monomorphization_error_backtrace.stderr +++ b/tests/ui/generics/post_monomorphization_error_backtrace.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of `assert_zst::F::<u32>::V` failed | LL | const V: () = assert!(std::mem::size_of::<T>() == 0); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation panicked: assertion failed: std::mem::size_of::<T>() == 0 - | - = note: this error originates in the macro `assert` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/post_monomorphization_error_backtrace.rs:14:5 @@ -23,8 +21,6 @@ error[E0080]: evaluation of `assert_zst::F::<i32>::V` failed | LL | const V: () = assert!(std::mem::size_of::<T>() == 0); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation panicked: assertion failed: std::mem::size_of::<T>() == 0 - | - = note: this error originates in the macro `assert` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/post_monomorphization_error_backtrace.rs:14:5 diff --git a/tests/ui/include-macros/mismatched-types.stderr b/tests/ui/include-macros/mismatched-types.stderr index 9bc0e64464e..8d541966a6a 100644 --- a/tests/ui/include-macros/mismatched-types.stderr +++ b/tests/ui/include-macros/mismatched-types.stderr @@ -11,7 +11,6 @@ LL | let b: &[u8] = include_str!("file.txt"); | = note: expected reference `&[u8]` found reference `&'static str` - = note: this error originates in the macro `include_str` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0308]: mismatched types --> $DIR/mismatched-types.rs:3:19 @@ -23,7 +22,6 @@ LL | let s: &str = include_bytes!("file.txt"); | = note: expected reference `&str` found reference `&'static [u8; 0]` - = note: this error originates in the macro `include_bytes` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 2 previous errors diff --git a/tests/ui/include-macros/parent_dir.stderr b/tests/ui/include-macros/parent_dir.stderr index d0a1f4fd3b9..4ee6fe104b0 100644 --- a/tests/ui/include-macros/parent_dir.stderr +++ b/tests/ui/include-macros/parent_dir.stderr @@ -4,7 +4,6 @@ error: couldn't read `$DIR/include-macros/file.txt`: $FILE_NOT_FOUND_MSG LL | let _ = include_str!("include-macros/file.txt"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | - = note: this error originates in the macro `include_str` (in Nightly builds, run with -Z macro-backtrace for more info) help: there is a file with the same name in a different directory | LL - let _ = include_str!("include-macros/file.txt"); @@ -17,7 +16,6 @@ error: couldn't read `$DIR/hello.rs`: $FILE_NOT_FOUND_MSG LL | let _ = include_str!("hello.rs"); | ^^^^^^^^^^^^^^^^^^^^^^^^ | - = note: this error originates in the macro `include_str` (in Nightly builds, run with -Z macro-backtrace for more info) help: there is a file with the same name in a different directory | LL | let _ = include_str!("../hello.rs"); @@ -29,7 +27,6 @@ error: couldn't read `$DIR/../../data.bin`: $FILE_NOT_FOUND_MSG LL | let _ = include_bytes!("../../data.bin"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | - = note: this error originates in the macro `include_bytes` (in Nightly builds, run with -Z macro-backtrace for more info) help: there is a file with the same name in a different directory | LL - let _ = include_bytes!("../../data.bin"); @@ -42,7 +39,6 @@ error: couldn't read `$DIR/tests/ui/include-macros/file.txt`: $FILE_NOT_FOUND_MS LL | let _ = include_str!("tests/ui/include-macros/file.txt"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | - = note: this error originates in the macro `include_str` (in Nightly builds, run with -Z macro-backtrace for more info) help: there is a file with the same name in a different directory | LL - let _ = include_str!("tests/ui/include-macros/file.txt"); diff --git a/tests/ui/inline-const/const-expr-generic-err.stderr b/tests/ui/inline-const/const-expr-generic-err.stderr index e67c0b28e02..a40e8bceb36 100644 --- a/tests/ui/inline-const/const-expr-generic-err.stderr +++ b/tests/ui/inline-const/const-expr-generic-err.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of `foo::<i32>::{constant#0}` failed | LL | const { assert!(std::mem::size_of::<T>() == 0); } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation panicked: assertion failed: std::mem::size_of::<T>() == 0 - | - = note: this error originates in the macro `assert` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/const-expr-generic-err.rs:4:5 diff --git a/tests/ui/inline-const/required-const.stderr b/tests/ui/inline-const/required-const.stderr index a6c630b5477..2f618e54ed3 100644 --- a/tests/ui/inline-const/required-const.stderr +++ b/tests/ui/inline-const/required-const.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of `foo::<i32>::{constant#0}` failed | LL | const { panic!() } | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/required-const.rs:6:9 diff --git a/tests/ui/invalid-compile-flags/crate-type-flag.empty_crate_type.stderr b/tests/ui/invalid-compile-flags/crate-type-flag.empty_crate_type.stderr index 0f8772024df..4ab816d30f6 100644 --- a/tests/ui/invalid-compile-flags/crate-type-flag.empty_crate_type.stderr +++ b/tests/ui/invalid-compile-flags/crate-type-flag.empty_crate_type.stderr @@ -1,2 +1,2 @@ -error: unknown crate type: `` +error: unknown crate type: ``, expected one of: `lib`, `rlib`, `staticlib`, `dylib`, `cdylib`, `bin`, `proc-macro` diff --git a/tests/ui/invalid-compile-flags/crate-type-flag.proc_underscore_macro.stderr b/tests/ui/invalid-compile-flags/crate-type-flag.proc_underscore_macro.stderr index a4a97416996..91cc66801f1 100644 --- a/tests/ui/invalid-compile-flags/crate-type-flag.proc_underscore_macro.stderr +++ b/tests/ui/invalid-compile-flags/crate-type-flag.proc_underscore_macro.stderr @@ -1,2 +1,2 @@ -error: unknown crate type: `proc_macro` +error: unknown crate type: `proc_macro`, expected one of: `lib`, `rlib`, `staticlib`, `dylib`, `cdylib`, `bin`, `proc-macro` diff --git a/tests/ui/invalid-compile-flags/crate-type-flag.rs b/tests/ui/invalid-compile-flags/crate-type-flag.rs index 07d853b3307..01014307149 100644 --- a/tests/ui/invalid-compile-flags/crate-type-flag.rs +++ b/tests/ui/invalid-compile-flags/crate-type-flag.rs @@ -45,16 +45,16 @@ // `proc-macro` is accepted, but `proc_macro` is not. //@ revisions: proc_underscore_macro //@[proc_underscore_macro] compile-flags: --crate-type=proc_macro -//@[proc_underscore_macro] error-pattern: "unknown crate type: `proc_macro`" +//@[proc_underscore_macro] error-pattern: unknown crate type: `proc_macro` // Empty `--crate-type` not accepted. //@ revisions: empty_crate_type //@[empty_crate_type] compile-flags: --crate-type= -//@[empty_crate_type] error-pattern: "unknown crate type: ``" +//@[empty_crate_type] error-pattern: unknown crate type: `` // Random unknown crate type. Also check that we can handle non-ASCII. //@ revisions: unknown //@[unknown] compile-flags: --crate-type=🤡 -//@[unknown] error-pattern: "unknown crate type: `🤡`" +//@[unknown] error-pattern: unknown crate type: `🤡` fn main() {} diff --git a/tests/ui/invalid-compile-flags/crate-type-flag.unknown.stderr b/tests/ui/invalid-compile-flags/crate-type-flag.unknown.stderr index 7fb0f09a1af..ec202e171f0 100644 --- a/tests/ui/invalid-compile-flags/crate-type-flag.unknown.stderr +++ b/tests/ui/invalid-compile-flags/crate-type-flag.unknown.stderr @@ -1,2 +1,2 @@ -error: unknown crate type: `🤡` +error: unknown crate type: `🤡`, expected one of: `lib`, `rlib`, `staticlib`, `dylib`, `cdylib`, `bin`, `proc-macro` diff --git a/tests/ui/issues/issue-14091-2.stderr b/tests/ui/issues/issue-14091-2.stderr index ac894767059..d573a0917be 100644 --- a/tests/ui/issues/issue-14091-2.stderr +++ b/tests/ui/issues/issue-14091-2.stderr @@ -11,7 +11,6 @@ LL | pub struct BytePos(pub u32); | ^^^^^^^^^^^^^^^^^^ must implement `Not` note: the trait `Not` must be implemented --> $SRC_DIR/core/src/ops/bit.rs:LL:COL - = note: this error originates in the macro `assert` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/issues/issue-21160.stderr b/tests/ui/issues/issue-21160.stderr index 892a4530ebc..f1145a0a7c1 100644 --- a/tests/ui/issues/issue-21160.stderr +++ b/tests/ui/issues/issue-21160.stderr @@ -6,7 +6,6 @@ LL | #[derive(Hash)] LL | struct Foo(Bar); | ^^^ the trait `Hash` is not implemented for `Bar` | - = note: this error originates in the derive macro `Hash` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Bar` with `#[derive(Hash)]` | LL + #[derive(Hash)] diff --git a/tests/ui/issues/issue-27340.stderr b/tests/ui/issues/issue-27340.stderr index 61ae660f4cf..d5ff29a618b 100644 --- a/tests/ui/issues/issue-27340.stderr +++ b/tests/ui/issues/issue-27340.stderr @@ -6,8 +6,6 @@ LL | #[derive(Copy, Clone)] LL | LL | struct Bar(Foo); | --- this field does not implement `Copy` - | - = note: this error originates in the derive macro `Copy` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `Foo: Clone` is not satisfied --> $DIR/issue-27340.rs:4:12 @@ -20,7 +18,6 @@ LL | struct Bar(Foo); | note: required by a bound in `AssertParamIsClone` --> $SRC_DIR/core/src/clone.rs:LL:COL - = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Foo` with `#[derive(Clone)]` | LL + #[derive(Clone)] diff --git a/tests/ui/issues/issue-27592.stderr b/tests/ui/issues/issue-27592.stderr index 1205a8b656b..c8649d82d74 100644 --- a/tests/ui/issues/issue-27592.stderr +++ b/tests/ui/issues/issue-27592.stderr @@ -6,16 +6,12 @@ LL | write(|| format_args!("{}", String::from("Hello world"))); | | | | | temporary value created here | returns a value referencing data owned by the current function - | - = note: this error originates in the macro `format_args` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0515]: cannot return reference to temporary value --> $DIR/issue-27592.rs:16:14 | LL | write(|| format_args!("{}", String::from("Hello world"))); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ returns a reference to data owned by the current function - | - = note: this error originates in the macro `format_args` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 2 previous errors diff --git a/tests/ui/issues/issue-32950.stderr b/tests/ui/issues/issue-32950.stderr index f6635d982e4..3cdf35af1d8 100644 --- a/tests/ui/issues/issue-32950.stderr +++ b/tests/ui/issues/issue-32950.stderr @@ -9,8 +9,6 @@ error[E0412]: cannot find type `FooBar` in this scope | LL | concat_idents!(Foo, Bar) | ^^^^^^^^^^^^^^^^^^^^^^^^ not found in this scope - | - = note: this error originates in the macro `concat_idents` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 2 previous errors diff --git a/tests/ui/issues/issue-34229.stderr b/tests/ui/issues/issue-34229.stderr index e6aa0d25934..2385284de0b 100644 --- a/tests/ui/issues/issue-34229.stderr +++ b/tests/ui/issues/issue-34229.stderr @@ -7,7 +7,6 @@ LL | #[derive(PartialEq, PartialOrd)] struct Nope(Comparable); | in this derive macro expansion | = help: the trait `PartialOrd` is not implemented for `Comparable` - = note: this error originates in the derive macro `PartialOrd` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Comparable` with `#[derive(PartialOrd)]` | LL | #[derive(PartialEq)] #[derive(PartialOrd)] diff --git a/tests/ui/issues/issue-76191.stderr b/tests/ui/issues/issue-76191.stderr index de08fc4ed0d..ac1bdfaa847 100644 --- a/tests/ui/issues/issue-76191.stderr +++ b/tests/ui/issues/issue-76191.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of constant value failed | LL | const RANGE2: RangeInclusive<i32> = panic!(); | ^^^^^^^^ evaluation panicked: explicit panic - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0308]: mismatched types --> $DIR/issue-76191.rs:14:9 diff --git a/tests/ui/lint/test-inner-fn.stderr b/tests/ui/lint/test-inner-fn.stderr index 7a32bc86bf7..bf476a45f77 100644 --- a/tests/ui/lint/test-inner-fn.stderr +++ b/tests/ui/lint/test-inner-fn.stderr @@ -5,15 +5,12 @@ LL | #[test] | ^^^^^^^ | = note: requested on the command line with `-D unnameable-test-items` - = note: this error originates in the attribute macro `test` (in Nightly builds, run with -Z macro-backtrace for more info) error: cannot test inner items --> $DIR/test-inner-fn.rs:13:9 | LL | #[test] | ^^^^^^^ - | - = note: this error originates in the attribute macro `test` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 2 previous errors diff --git a/tests/ui/lint/unused/unused-field-in-pat-field.rs b/tests/ui/lint/unused/unused-field-in-pat-field.rs new file mode 100644 index 00000000000..34959a1023f --- /dev/null +++ b/tests/ui/lint/unused/unused-field-in-pat-field.rs @@ -0,0 +1,21 @@ +//@ check-pass + +// Ensure we collect lint levels from pat fields in structs. + +#![deny(unused_variables)] + +pub struct Foo { + bar: u32, + baz: u32, +} + +pub fn test(foo: Foo) { + let Foo { + #[allow(unused_variables)] + bar, + #[allow(unused_variables)] + baz, + } = foo; +} + +fn main() {} diff --git a/tests/ui/macros/builtin-env-issue-114010.stderr b/tests/ui/macros/builtin-env-issue-114010.stderr index 0da42089cce..2751160e2d4 100644 --- a/tests/ui/macros/builtin-env-issue-114010.stderr +++ b/tests/ui/macros/builtin-env-issue-114010.stderr @@ -5,7 +5,6 @@ LL | env![r#"oopsie"#]; | ^^^^^^^^^^^^^^^^^ | = help: use `std::env::var(r#"oopsie"#)` to read the variable at run time - = note: this error originates in the macro `env` (in Nightly builds, run with -Z macro-backtrace for more info) error: environment variable `a""a` not defined at compile time --> $DIR/builtin-env-issue-114010.rs:7:1 @@ -14,7 +13,6 @@ LL | env![r#"a""a"#]; | ^^^^^^^^^^^^^^^ | = help: use `std::env::var(r#"a""a"#)` to read the variable at run time - = note: this error originates in the macro `env` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 2 previous errors diff --git a/tests/ui/macros/cfg.stderr b/tests/ui/macros/cfg.stderr index 53326914865..ad3f9b188dd 100644 --- a/tests/ui/macros/cfg.stderr +++ b/tests/ui/macros/cfg.stderr @@ -3,8 +3,6 @@ error: macro requires a cfg-pattern as an argument | LL | cfg!(); | ^^^^^^ cfg-pattern required - | - = note: this error originates in the macro `cfg` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0565]: literal in `cfg` predicate value must be a boolean --> $DIR/cfg.rs:3:10 @@ -23,8 +21,6 @@ error: expected 1 cfg-pattern | LL | cfg!(foo, bar); | ^^^^^^^^^^^^^^ - | - = note: this error originates in the macro `cfg` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 4 previous errors diff --git a/tests/ui/macros/macros-nonfatal-errors.stderr b/tests/ui/macros/macros-nonfatal-errors.stderr index fd5e41986a8..44194b506a4 100644 --- a/tests/ui/macros/macros-nonfatal-errors.stderr +++ b/tests/ui/macros/macros-nonfatal-errors.stderr @@ -57,7 +57,6 @@ LL | | Bar, LL | | } | |_- this enum needs a unit variant marked with `#[default]` | - = note: this error originates in the derive macro `Default` (in Nightly builds, run with -Z macro-backtrace for more info) help: make this unit variant default by placing `#[default]` on it | LL | #[default] Foo, @@ -77,8 +76,6 @@ LL | | Foo(i32), LL | | Bar(i32), LL | | } | |_- this enum needs a unit variant marked with `#[default]` - | - = note: this error originates in the derive macro `Default` (in Nightly builds, run with -Z macro-backtrace for more info) error: multiple declared defaults --> $DIR/macros-nonfatal-errors.rs:54:10 @@ -96,7 +93,6 @@ LL | Baz, | --- additional default | = note: only one variant can be default - = note: this error originates in the derive macro `Default` (in Nightly builds, run with -Z macro-backtrace for more info) error: `#[default]` attribute does not accept a value --> $DIR/macros-nonfatal-errors.rs:66:5 @@ -200,7 +196,6 @@ LL | env!("RUST_HOPEFULLY_THIS_DOESNT_EXIST"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: use `std::env::var("RUST_HOPEFULLY_THIS_DOESNT_EXIST")` to read the variable at run time - = note: this error originates in the macro `env` (in Nightly builds, run with -Z macro-backtrace for more info) error: format argument must be a string literal --> $DIR/macros-nonfatal-errors.rs:114:13 @@ -230,8 +225,6 @@ error: couldn't read `$DIR/i'd be quite surprised if a file with this name exist | LL | include_str!("i'd be quite surprised if a file with this name existed"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: this error originates in the macro `include_str` (in Nightly builds, run with -Z macro-backtrace for more info) error: argument must be a string literal --> $DIR/macros-nonfatal-errors.rs:120:20 @@ -244,8 +237,6 @@ error: couldn't read `$DIR/i'd be quite surprised if a file with this name exist | LL | include_bytes!("i'd be quite surprised if a file with this name existed"); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: this error originates in the macro `include_bytes` (in Nightly builds, run with -Z macro-backtrace for more info) error: trace_macros! accepts only `true` or `false` --> $DIR/macros-nonfatal-errors.rs:123:5 diff --git a/tests/ui/macros/not-utf8.stderr b/tests/ui/macros/not-utf8.stderr index be028816e0f..d466d5087d4 100644 --- a/tests/ui/macros/not-utf8.stderr +++ b/tests/ui/macros/not-utf8.stderr @@ -9,7 +9,6 @@ note: byte `193` is not valid utf-8 | LL | �|�␂!5�cc␕␂�Ӻi��WWj�ȥ�'�}�␒�J�ȉ��W�␞O�@����␜w�V���LO����␔[ ␃_�'���SQ�~ذ��ų&��- ��lN~��!@␌ _#���kQ��h�␝�:�␜␇� | ^ - = note: this error originates in the macro `include` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/macros/unreachable-format-args.edition_2015.stderr b/tests/ui/macros/unreachable-format-args.edition_2015.stderr index 6a133d5e406..9104848a58b 100644 --- a/tests/ui/macros/unreachable-format-args.edition_2015.stderr +++ b/tests/ui/macros/unreachable-format-args.edition_2015.stderr @@ -6,7 +6,6 @@ LL | unreachable!("x is {x} and y is {y}", y = 0); | = note: did you intend to capture a variable `x` from the surrounding scope? = note: to avoid ambiguity, `format_args!` cannot capture variables when the format string is expanded from a macro - = note: this error originates in the macro `$crate::concat` which comes from the expansion of the macro `unreachable` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/malformed/malformed-derive-entry.stderr b/tests/ui/malformed/malformed-derive-entry.stderr index 3059d75d718..02036e8d4c9 100644 --- a/tests/ui/malformed/malformed-derive-entry.stderr +++ b/tests/ui/malformed/malformed-derive-entry.stderr @@ -24,7 +24,6 @@ LL | #[derive(Copy(Bad))] | note: required by a bound in `Copy` --> $SRC_DIR/core/src/marker.rs:LL:COL - = note: this error originates in the derive macro `Copy` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Test1` with `#[derive(Clone)]` | LL + #[derive(Clone)] @@ -39,7 +38,6 @@ LL | #[derive(Copy="bad")] | note: required by a bound in `Copy` --> $SRC_DIR/core/src/marker.rs:LL:COL - = note: this error originates in the derive macro `Copy` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Test2` with `#[derive(Clone)]` | LL + #[derive(Clone)] diff --git a/tests/ui/never_type/fallback-closure-wrap.fallback.stderr b/tests/ui/never_type/fallback-closure-wrap.fallback.stderr index ac99a1fc24c..afb929454c7 100644 --- a/tests/ui/never_type/fallback-closure-wrap.fallback.stderr +++ b/tests/ui/never_type/fallback-closure-wrap.fallback.stderr @@ -9,7 +9,6 @@ LL | panic!("Can't connect to server."); = note: expected unit type `()` found type `!` = note: required for the cast from `Box<{closure@$DIR/fallback-closure-wrap.rs:18:40: 18:47}>` to `Box<dyn FnMut()>` - = note: this error originates in the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/parser/shebang/issue-71471-ignore-tidy.stderr b/tests/ui/parser/shebang/issue-71471-ignore-tidy.stderr index 41cd4fb93fa..cdd36ba4cae 100644 --- a/tests/ui/parser/shebang/issue-71471-ignore-tidy.stderr +++ b/tests/ui/parser/shebang/issue-71471-ignore-tidy.stderr @@ -3,6 +3,9 @@ error: expected `[`, found `B` | LL | #!B | ^ expected `[` + | + = note: the token sequence `#!` here looks like the start of a shebang interpreter directive but it is not + = help: if you meant this to be a shebang interpreter directive, move it to the very start of the file error: aborting due to 1 previous error diff --git a/tests/ui/parser/shebang/shebang-must-start-file.stderr b/tests/ui/parser/shebang/shebang-must-start-file.stderr index 56991c96b7a..cf897d07780 100644 --- a/tests/ui/parser/shebang/shebang-must-start-file.stderr +++ b/tests/ui/parser/shebang/shebang-must-start-file.stderr @@ -3,6 +3,9 @@ error: expected `[`, found `/` | LL | #!/bin/bash | ^ expected `[` + | + = note: the token sequence `#!` here looks like the start of a shebang interpreter directive but it is not + = help: if you meant this to be a shebang interpreter directive, move it to the very start of the file error: aborting due to 1 previous error diff --git a/tests/ui/parser/shebang/shebang-split.rs b/tests/ui/parser/shebang/shebang-split.rs new file mode 100644 index 00000000000..470bb669143 --- /dev/null +++ b/tests/ui/parser/shebang/shebang-split.rs @@ -0,0 +1,5 @@ +// empty line +# !/bin/env + +// checks that diagnostics for shebang lookalikes is not present +//@ error-pattern: expected `[`\n\n diff --git a/tests/ui/parser/shebang/shebang-split.stderr b/tests/ui/parser/shebang/shebang-split.stderr new file mode 100644 index 00000000000..804df1f0086 --- /dev/null +++ b/tests/ui/parser/shebang/shebang-split.stderr @@ -0,0 +1,8 @@ +error: expected `[`, found `/` + --> $DIR/shebang-split.rs:2:4 + | +LL | # !/bin/env + | ^ expected `[` + +error: aborting due to 1 previous error + diff --git a/tests/ui/pattern/check-struct-pat-fields-stability-issue-138319.rs b/tests/ui/pattern/check-struct-pat-fields-stability-issue-138319.rs new file mode 100644 index 00000000000..b951c6d92ee --- /dev/null +++ b/tests/ui/pattern/check-struct-pat-fields-stability-issue-138319.rs @@ -0,0 +1,12 @@ +//@ check-pass +struct Point { + #[deprecated = "x is deprecated"] + _x: i32, + _y: i32, +} + +fn main() { + let p = Point { _x: 1, _y: 2 }; //~ WARNING use of deprecated field `Point::_x` + // Before fix, it report an warning + let Point { #[expect(deprecated)]_x, .. } = p; +} diff --git a/tests/ui/pattern/check-struct-pat-fields-stability-issue-138319.stderr b/tests/ui/pattern/check-struct-pat-fields-stability-issue-138319.stderr new file mode 100644 index 00000000000..707eb58e547 --- /dev/null +++ b/tests/ui/pattern/check-struct-pat-fields-stability-issue-138319.stderr @@ -0,0 +1,10 @@ +warning: use of deprecated field `Point::_x`: x is deprecated + --> $DIR/check-struct-pat-fields-stability-issue-138319.rs:9:21 + | +LL | let p = Point { _x: 1, _y: 2 }; + | ^^^^^ + | + = note: `#[warn(deprecated)]` on by default + +warning: 1 warning emitted + diff --git a/tests/ui/pattern/deref-patterns/dont-ice-on-slice-in-deref-pat-in-closure.rs b/tests/ui/pattern/deref-patterns/dont-ice-on-slice-in-deref-pat-in-closure.rs new file mode 100644 index 00000000000..e1a37b9c65f --- /dev/null +++ b/tests/ui/pattern/deref-patterns/dont-ice-on-slice-in-deref-pat-in-closure.rs @@ -0,0 +1,15 @@ +//@ check-pass +//! Regression test for ICE in `rustc_hir_typeck::expr_use_visitor` on nesting a slice pattern +//! inside a deref pattern inside a closure: rust-lang/rust#125059 + +#![feature(deref_patterns)] +#![allow(incomplete_features, unused)] + +fn simple_vec(vec: Vec<u32>) -> u32 { + (|| match Vec::<u32>::new() { + deref!([]) => 100, + _ => 2000, + })() +} + +fn main() {} diff --git a/tests/ui/proc-macro/issue-104884-trait-impl-sugg-err.stderr b/tests/ui/proc-macro/issue-104884-trait-impl-sugg-err.stderr index 0fe560afcb5..c12c8d03361 100644 --- a/tests/ui/proc-macro/issue-104884-trait-impl-sugg-err.stderr +++ b/tests/ui/proc-macro/issue-104884-trait-impl-sugg-err.stderr @@ -7,7 +7,6 @@ LL | #[derive(PartialOrd, AddImpl)] = help: the trait `PartialEq` is not implemented for `PriorityQueue<T>` note: required by a bound in `PartialOrd` --> $SRC_DIR/core/src/cmp.rs:LL:COL - = note: this error originates in the derive macro `PartialOrd` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `PriorityQueue<T>: Eq` is not satisfied --> $DIR/issue-104884-trait-impl-sugg-err.rs:13:22 @@ -32,7 +31,6 @@ LL | #[derive(PartialOrd, AddImpl)] | ^^^^^^^^^^ unsatisfied trait bound introduced in this `derive` macro note: required by a bound in `Ord` --> $SRC_DIR/core/src/cmp.rs:LL:COL - = note: this error originates in the derive macro `AddImpl` which comes from the expansion of the derive macro `PartialOrd` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: can't compare `BinaryHeap<PriorityQueueEntry<T>>` with `_` --> $DIR/issue-104884-trait-impl-sugg-err.rs:20:25 @@ -44,7 +42,6 @@ LL | struct PriorityQueue<T>(BinaryHeap<PriorityQueueEntry<T>>); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ no implementation for `BinaryHeap<PriorityQueueEntry<T>> < _` and `BinaryHeap<PriorityQueueEntry<T>> > _` | = help: the trait `PartialOrd<_>` is not implemented for `BinaryHeap<PriorityQueueEntry<T>>` - = note: this error originates in the derive macro `PartialOrd` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0599]: no method named `cmp` found for struct `BinaryHeap<PriorityQueueEntry<T>>` in the current scope --> $DIR/issue-104884-trait-impl-sugg-err.rs:13:22 diff --git a/tests/ui/proc-macro/quote/not-quotable.stderr b/tests/ui/proc-macro/quote/not-quotable.stderr index e349b2dce53..62a02638e54 100644 --- a/tests/ui/proc-macro/quote/not-quotable.stderr +++ b/tests/ui/proc-macro/quote/not-quotable.stderr @@ -17,7 +17,6 @@ LL | let _ = quote! { $ip }; Rc<T> bool and 24 others - = note: this error originates in the macro `quote` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/range/range_traits-1.stderr b/tests/ui/range/range_traits-1.stderr index 617afc99530..ab1035778cd 100644 --- a/tests/ui/range/range_traits-1.stderr +++ b/tests/ui/range/range_traits-1.stderr @@ -8,7 +8,6 @@ LL | a: Range<usize>, | ^^^^^^^^^^^^^^^ no implementation for `std::ops::Range<usize> < std::ops::Range<usize>` and `std::ops::Range<usize> > std::ops::Range<usize>` | = help: the trait `PartialOrd` is not implemented for `std::ops::Range<usize>` - = note: this error originates in the derive macro `PartialOrd` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: can't compare `std::ops::RangeTo<usize>` with `std::ops::RangeTo<usize>` --> $DIR/range_traits-1.rs:8:5 @@ -20,7 +19,6 @@ LL | b: RangeTo<usize>, | ^^^^^^^^^^^^^^^^^ no implementation for `std::ops::RangeTo<usize> < std::ops::RangeTo<usize>` and `std::ops::RangeTo<usize> > std::ops::RangeTo<usize>` | = help: the trait `PartialOrd` is not implemented for `std::ops::RangeTo<usize>` - = note: this error originates in the derive macro `PartialOrd` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: can't compare `std::ops::RangeFrom<usize>` with `std::ops::RangeFrom<usize>` --> $DIR/range_traits-1.rs:11:5 @@ -32,7 +30,6 @@ LL | c: RangeFrom<usize>, | ^^^^^^^^^^^^^^^^^^^ no implementation for `std::ops::RangeFrom<usize> < std::ops::RangeFrom<usize>` and `std::ops::RangeFrom<usize> > std::ops::RangeFrom<usize>` | = help: the trait `PartialOrd` is not implemented for `std::ops::RangeFrom<usize>` - = note: this error originates in the derive macro `PartialOrd` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: can't compare `std::ops::RangeFull` with `std::ops::RangeFull` --> $DIR/range_traits-1.rs:14:5 @@ -44,7 +41,6 @@ LL | d: RangeFull, | ^^^^^^^^^^^^ no implementation for `std::ops::RangeFull < std::ops::RangeFull` and `std::ops::RangeFull > std::ops::RangeFull` | = help: the trait `PartialOrd` is not implemented for `std::ops::RangeFull` - = note: this error originates in the derive macro `PartialOrd` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: can't compare `std::ops::RangeInclusive<usize>` with `std::ops::RangeInclusive<usize>` --> $DIR/range_traits-1.rs:17:5 @@ -56,7 +52,6 @@ LL | e: RangeInclusive<usize>, | ^^^^^^^^^^^^^^^^^^^^^^^^ no implementation for `std::ops::RangeInclusive<usize> < std::ops::RangeInclusive<usize>` and `std::ops::RangeInclusive<usize> > std::ops::RangeInclusive<usize>` | = help: the trait `PartialOrd` is not implemented for `std::ops::RangeInclusive<usize>` - = note: this error originates in the derive macro `PartialOrd` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: can't compare `std::ops::RangeToInclusive<usize>` with `std::ops::RangeToInclusive<usize>` --> $DIR/range_traits-1.rs:20:5 @@ -68,7 +63,6 @@ LL | f: RangeToInclusive<usize>, | ^^^^^^^^^^^^^^^^^^^^^^^^^^ no implementation for `std::ops::RangeToInclusive<usize> < std::ops::RangeToInclusive<usize>` and `std::ops::RangeToInclusive<usize> > std::ops::RangeToInclusive<usize>` | = help: the trait `PartialOrd` is not implemented for `std::ops::RangeToInclusive<usize>` - = note: this error originates in the derive macro `PartialOrd` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `std::ops::Range<usize>: Ord` is not satisfied --> $DIR/range_traits-1.rs:5:5 @@ -78,8 +72,6 @@ LL | #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] LL | struct AllTheRanges { LL | a: Range<usize>, | ^^^^^^^^^^^^^^^ the trait `Ord` is not implemented for `std::ops::Range<usize>` - | - = note: this error originates in the derive macro `Ord` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `std::ops::RangeTo<usize>: Ord` is not satisfied --> $DIR/range_traits-1.rs:8:5 @@ -89,8 +81,6 @@ LL | #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] ... LL | b: RangeTo<usize>, | ^^^^^^^^^^^^^^^^^ the trait `Ord` is not implemented for `std::ops::RangeTo<usize>` - | - = note: this error originates in the derive macro `Ord` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `std::ops::RangeFrom<usize>: Ord` is not satisfied --> $DIR/range_traits-1.rs:11:5 @@ -100,8 +90,6 @@ LL | #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] ... LL | c: RangeFrom<usize>, | ^^^^^^^^^^^^^^^^^^^ the trait `Ord` is not implemented for `std::ops::RangeFrom<usize>` - | - = note: this error originates in the derive macro `Ord` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `std::ops::RangeFull: Ord` is not satisfied --> $DIR/range_traits-1.rs:14:5 @@ -111,8 +99,6 @@ LL | #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] ... LL | d: RangeFull, | ^^^^^^^^^^^^ the trait `Ord` is not implemented for `std::ops::RangeFull` - | - = note: this error originates in the derive macro `Ord` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `std::ops::RangeInclusive<usize>: Ord` is not satisfied --> $DIR/range_traits-1.rs:17:5 @@ -122,8 +108,6 @@ LL | #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] ... LL | e: RangeInclusive<usize>, | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Ord` is not implemented for `std::ops::RangeInclusive<usize>` - | - = note: this error originates in the derive macro `Ord` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: the trait bound `std::ops::RangeToInclusive<usize>: Ord` is not satisfied --> $DIR/range_traits-1.rs:20:5 @@ -133,8 +117,6 @@ LL | #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] ... LL | f: RangeToInclusive<usize>, | ^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Ord` is not implemented for `std::ops::RangeToInclusive<usize>` - | - = note: this error originates in the derive macro `Ord` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 12 previous errors diff --git a/tests/ui/range/range_traits-2.stderr b/tests/ui/range/range_traits-2.stderr index 04778eecf56..2001c85c434 100644 --- a/tests/ui/range/range_traits-2.stderr +++ b/tests/ui/range/range_traits-2.stderr @@ -5,8 +5,6 @@ LL | #[derive(Copy, Clone)] | ^^^^ LL | struct R(Range<usize>); | ------------ this field does not implement `Copy` - | - = note: this error originates in the derive macro `Copy` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/range/range_traits-3.stderr b/tests/ui/range/range_traits-3.stderr index 094cc146b6c..71210379c79 100644 --- a/tests/ui/range/range_traits-3.stderr +++ b/tests/ui/range/range_traits-3.stderr @@ -5,8 +5,6 @@ LL | #[derive(Copy, Clone)] | ^^^^ LL | struct R(RangeFrom<usize>); | ---------------- this field does not implement `Copy` - | - = note: this error originates in the derive macro `Copy` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/range/range_traits-6.stderr b/tests/ui/range/range_traits-6.stderr index 7c66d1c749c..a58022ef7e4 100644 --- a/tests/ui/range/range_traits-6.stderr +++ b/tests/ui/range/range_traits-6.stderr @@ -5,8 +5,6 @@ LL | #[derive(Copy, Clone)] | ^^^^ LL | struct R(RangeInclusive<usize>); | --------------------- this field does not implement `Copy` - | - = note: this error originates in the derive macro `Copy` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/resolve/multiple_definitions_attribute_merging.stderr b/tests/ui/resolve/multiple_definitions_attribute_merging.stderr index ac6307c7a69..10ce68e506e 100644 --- a/tests/ui/resolve/multiple_definitions_attribute_merging.stderr +++ b/tests/ui/resolve/multiple_definitions_attribute_merging.stderr @@ -15,8 +15,8 @@ LL | #[derive(PartialEq)] LL | #[repr(C)] LL | struct Dealigned<T>(u8, T); | ^ - | - = + + Box<dyn Any> query stack during panic: #0 [mir_built] building MIR for `<impl at $DIR/multiple_definitions_attribute_merging.rs:15:10: 15:19>::eq` diff --git a/tests/ui/resolve/proc_macro_generated_packed.stderr b/tests/ui/resolve/proc_macro_generated_packed.stderr index 8b700595034..47de5be82dd 100644 --- a/tests/ui/resolve/proc_macro_generated_packed.stderr +++ b/tests/ui/resolve/proc_macro_generated_packed.stderr @@ -6,8 +6,8 @@ LL | #[derive(PartialEq)] ... LL | struct Dealigned<T>(u8, T); | ^ - | - = + + Box<dyn Any> query stack during panic: #0 [mir_built] building MIR for `<impl at $DIR/proc_macro_generated_packed.rs:15:10: 15:19>::eq` diff --git a/tests/ui/rfcs/rfc-1937-termination-trait/termination-trait-test-wrong-type.stderr b/tests/ui/rfcs/rfc-1937-termination-trait/termination-trait-test-wrong-type.stderr index 0a703367d96..b89c5e8dda8 100644 --- a/tests/ui/rfcs/rfc-1937-termination-trait/termination-trait-test-wrong-type.stderr +++ b/tests/ui/rfcs/rfc-1937-termination-trait/termination-trait-test-wrong-type.stderr @@ -9,7 +9,6 @@ LL | fn can_parse_zero_as_f32() -> Result<f32, ParseFloatError> { = note: required for `Result<f32, ParseFloatError>` to implement `Termination` note: required by a bound in `assert_test_result` --> $SRC_DIR/test/src/lib.rs:LL:COL - = note: this error originates in the attribute macro `test` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/rust-2021/ice-return-unsized-can-impl-2.stderr b/tests/ui/rust-2021/ice-return-unsized-can-impl-2.stderr index f2942820e28..75718c94b19 100644 --- a/tests/ui/rust-2021/ice-return-unsized-can-impl-2.stderr +++ b/tests/ui/rust-2021/ice-return-unsized-can-impl-2.stderr @@ -4,7 +4,7 @@ error[E0782]: expected a type, found a trait LL | fn concrete(b: B) -> B; | ^ | - = note: `B` it is dyn-incompatible, so it can't be `dyn` + = note: `B` is dyn-incompatible, otherwise a trait object could be used help: use a new generic type parameter, constrained by `B` | LL - fn concrete(b: B) -> B; @@ -32,7 +32,7 @@ error[E0782]: expected a type, found a trait LL | fn f(a: A) -> A; | ^ | - = note: `A` it is dyn-incompatible, so it can't be `dyn` + = note: `A` is dyn-incompatible, otherwise a trait object could be used help: use a new generic type parameter, constrained by `A` | LL - fn f(a: A) -> A; diff --git a/tests/ui/rust-2021/ice-return-unsized-can-impl.stderr b/tests/ui/rust-2021/ice-return-unsized-can-impl.stderr index cfee506e29b..284232cf4f4 100644 --- a/tests/ui/rust-2021/ice-return-unsized-can-impl.stderr +++ b/tests/ui/rust-2021/ice-return-unsized-can-impl.stderr @@ -4,7 +4,7 @@ error[E0782]: expected a type, found a trait LL | fn g(new: B) -> B; | ^ | - = note: `B` it is dyn-incompatible, so it can't be `dyn` + = note: `B` is dyn-incompatible, otherwise a trait object could be used help: use a new generic type parameter, constrained by `B` | LL - fn g(new: B) -> B; diff --git a/tests/ui/rust-2021/ice-unsized-fn-params-2.stderr b/tests/ui/rust-2021/ice-unsized-fn-params-2.stderr index 7f837bbe50f..630bbc2b905 100644 --- a/tests/ui/rust-2021/ice-unsized-fn-params-2.stderr +++ b/tests/ui/rust-2021/ice-unsized-fn-params-2.stderr @@ -4,7 +4,7 @@ error[E0782]: expected a type, found a trait LL | fn guard(_s: Copy) -> bool { | ^^^^ | - = note: `Copy` it is dyn-incompatible, so it can't be `dyn` + = note: `Copy` is dyn-incompatible, otherwise a trait object could be used help: use a new generic type parameter, constrained by `Copy` | LL - fn guard(_s: Copy) -> bool { diff --git a/tests/ui/rust-2021/ice-unsized-fn-params.stderr b/tests/ui/rust-2021/ice-unsized-fn-params.stderr index 4d900711ed6..57708031d6b 100644 --- a/tests/ui/rust-2021/ice-unsized-fn-params.stderr +++ b/tests/ui/rust-2021/ice-unsized-fn-params.stderr @@ -4,7 +4,7 @@ error[E0782]: expected a type, found a trait LL | fn g(b: B) -> B; | ^ | - = note: `B` it is dyn-incompatible, so it can't be `dyn` + = note: `B` is dyn-incompatible, otherwise a trait object could be used help: use a new generic type parameter, constrained by `B` | LL - fn g(b: B) -> B; @@ -32,7 +32,7 @@ error[E0782]: expected a type, found a trait LL | fn f(a: A) -> A; | ^ | - = note: `A` it is dyn-incompatible, so it can't be `dyn` + = note: `A` is dyn-incompatible, otherwise a trait object could be used help: use a new generic type parameter, constrained by `A` | LL - fn f(a: A) -> A; diff --git a/tests/ui/simd/array-trait.stderr b/tests/ui/simd/array-trait.stderr index 2d2a11f25ad..299f0ad96ae 100644 --- a/tests/ui/simd/array-trait.stderr +++ b/tests/ui/simd/array-trait.stderr @@ -22,8 +22,6 @@ LL | #[derive(Copy, Clone)] | ----- in this derive macro expansion LL | pub struct T<S: Simd>([S::Lane; S::SIZE]); | ^^^^^^^^^^^^^^^^^^ - | - = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 3 previous errors diff --git a/tests/ui/simd/const-err-trumps-simd-err.stderr b/tests/ui/simd/const-err-trumps-simd-err.stderr index e88c277885e..a0f1c664a4f 100644 --- a/tests/ui/simd/const-err-trumps-simd-err.stderr +++ b/tests/ui/simd/const-err-trumps-simd-err.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of `get_elem::<4>::{constant#0}` failed | LL | const { assert!(LANE < 4); } // the error should be here... | ^^^^^^^^^^^^^^^^^ evaluation panicked: assertion failed: LANE < 4 - | - = note: this error originates in the macro `assert` (in Nightly builds, run with -Z macro-backtrace for more info) note: erroneous constant encountered --> $DIR/const-err-trumps-simd-err.rs:16:5 diff --git a/tests/ui/span/E0204.stderr b/tests/ui/span/E0204.stderr index 3a0afb541ba..fe375b94781 100644 --- a/tests/ui/span/E0204.stderr +++ b/tests/ui/span/E0204.stderr @@ -15,8 +15,6 @@ LL | #[derive(Copy)] LL | struct Foo2<'a> { LL | ty: &'a mut bool, | ---------------- this field does not implement `Copy` - | - = note: this error originates in the derive macro `Copy` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0204]: the trait `Copy` cannot be implemented for this type --> $DIR/E0204.rs:17:15 @@ -35,8 +33,6 @@ LL | #[derive(Copy)] LL | enum EFoo2<'a> { LL | Bar(&'a mut bool), | ------------ this field does not implement `Copy` - | - = note: this error originates in the derive macro `Copy` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 4 previous errors diff --git a/tests/ui/stability-attribute/check-stability-issue-138319.rs b/tests/ui/stability-attribute/check-stability-issue-138319.rs new file mode 100644 index 00000000000..5440e0cad94 --- /dev/null +++ b/tests/ui/stability-attribute/check-stability-issue-138319.rs @@ -0,0 +1,39 @@ +//@ check-pass +fn _foo() { + _Bar { //~ WARNING use of deprecated struct `_Bar`: reason + #[expect(deprecated)] + foo: 0, + }; +} + +#[deprecated = "reason"] +struct _Bar { + foo: u32, +} + +fn _foo2() { + #[expect(deprecated)] + _Bar2 { + foo2: 0, + }; +} + +#[deprecated = "reason"] +struct _Bar2 { + foo2: u32, +} + +fn _foo3() { + _Bar3 { + #[expect(deprecated)] + foo3: 0, + }; +} + +struct _Bar3 { + #[deprecated = "reason"] + foo3: u32, +} + + +fn main() {} diff --git a/tests/ui/stability-attribute/check-stability-issue-138319.stderr b/tests/ui/stability-attribute/check-stability-issue-138319.stderr new file mode 100644 index 00000000000..4a2c3554a1e --- /dev/null +++ b/tests/ui/stability-attribute/check-stability-issue-138319.stderr @@ -0,0 +1,10 @@ +warning: use of deprecated struct `_Bar`: reason + --> $DIR/check-stability-issue-138319.rs:3:5 + | +LL | _Bar { + | ^^^^ + | + = note: `#[warn(deprecated)]` on by default + +warning: 1 warning emitted + diff --git a/tests/ui/structs/default-field-values/failures.stderr b/tests/ui/structs/default-field-values/failures.stderr index 50553816462..58f7baee4b2 100644 --- a/tests/ui/structs/default-field-values/failures.stderr +++ b/tests/ui/structs/default-field-values/failures.stderr @@ -21,7 +21,6 @@ LL | pub struct Bar { LL | pub bar: S, | ^^^^^^^^^^ the trait `Default` is not implemented for `S` | - = note: this error originates in the derive macro `Default` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `S` with `#[derive(Default)]` | LL + #[derive(Default)] diff --git a/tests/ui/structs/default-field-values/invalid-const.stderr b/tests/ui/structs/default-field-values/invalid-const.stderr index 56d20d8d711..030bdbfcc3e 100644 --- a/tests/ui/structs/default-field-values/invalid-const.stderr +++ b/tests/ui/structs/default-field-values/invalid-const.stderr @@ -3,8 +3,6 @@ error[E0080]: evaluation of constant value failed | LL | pub bax: u8 = panic!("asdf"), | ^^^^^^^^^^^^^^ evaluation panicked: asdf - | - = note: this error originates in the macro `$crate::panic::panic_2015` which comes from the expansion of the macro `panic` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of `Baz::<C>::bat::{constant#0}` failed --> $DIR/invalid-const.rs:11:19 diff --git a/tests/ui/suggestions/derive-clone-for-eq.stderr b/tests/ui/suggestions/derive-clone-for-eq.stderr index eae0b0ae817..eb0355853da 100644 --- a/tests/ui/suggestions/derive-clone-for-eq.stderr +++ b/tests/ui/suggestions/derive-clone-for-eq.stderr @@ -13,7 +13,6 @@ LL | impl<T: Clone, U> PartialEq<U> for Struct<T> | unsatisfied trait bound introduced here note: required by a bound in `Eq` --> $SRC_DIR/core/src/cmp.rs:LL:COL - = note: this error originates in the derive macro `Eq` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider restricting type parameter `T` with trait `Clone` | LL | pub struct Struct<T: std::clone::Clone>(T); diff --git a/tests/ui/suggestions/derive-macro-missing-bounds.stderr b/tests/ui/suggestions/derive-macro-missing-bounds.stderr index 37a5f4932ff..68c8204d1e1 100644 --- a/tests/ui/suggestions/derive-macro-missing-bounds.stderr +++ b/tests/ui/suggestions/derive-macro-missing-bounds.stderr @@ -8,7 +8,6 @@ LL | struct Outer<T>(Inner<T>); | = help: the trait `Debug` is not implemented for `a::Inner<T>` = note: add `#[derive(Debug)]` to `a::Inner<T>` or manually `impl Debug for a::Inner<T>` - = note: this error originates in the derive macro `Debug` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `a::Inner<T>` with `#[derive(Debug)]` | LL + #[derive(Debug)] @@ -37,7 +36,6 @@ LL | impl<T: Debug + Trait> Debug for Inner<T> { = note: 1 redundant requirement hidden = note: required for `&c::Inner<T>` to implement `Debug` = note: required for the cast from `&&c::Inner<T>` to `&dyn Debug` - = note: this error originates in the derive macro `Debug` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider restricting type parameter `T` with trait `Trait` | LL | struct Outer<T: c::Trait>(Inner<T>); @@ -59,7 +57,6 @@ LL | impl<T> Debug for Inner<T> where T: Debug, T: Trait { = note: 1 redundant requirement hidden = note: required for `&d::Inner<T>` to implement `Debug` = note: required for the cast from `&&d::Inner<T>` to `&dyn Debug` - = note: this error originates in the derive macro `Debug` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider restricting type parameter `T` with trait `Trait` | LL | struct Outer<T: d::Trait>(Inner<T>); @@ -81,7 +78,6 @@ LL | impl<T> Debug for Inner<T> where T: Debug + Trait { = note: 1 redundant requirement hidden = note: required for `&e::Inner<T>` to implement `Debug` = note: required for the cast from `&&e::Inner<T>` to `&dyn Debug` - = note: this error originates in the derive macro `Debug` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider restricting type parameter `T` with trait `Trait` | LL | struct Outer<T: e::Trait>(Inner<T>); @@ -103,7 +99,6 @@ LL | impl<T: Debug> Debug for Inner<T> where T: Trait { = note: 1 redundant requirement hidden = note: required for `&f::Inner<T>` to implement `Debug` = note: required for the cast from `&&f::Inner<T>` to `&dyn Debug` - = note: this error originates in the derive macro `Debug` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider restricting type parameter `T` with trait `Trait` | LL | struct Outer<T: f::Trait>(Inner<T>); diff --git a/tests/ui/suggestions/dyn-incompatible-trait-should-use-self-2021-without-dyn.stderr b/tests/ui/suggestions/dyn-incompatible-trait-should-use-self-2021-without-dyn.stderr index 20aa227d10f..7b0fd979991 100644 --- a/tests/ui/suggestions/dyn-incompatible-trait-should-use-self-2021-without-dyn.stderr +++ b/tests/ui/suggestions/dyn-incompatible-trait-should-use-self-2021-without-dyn.stderr @@ -4,7 +4,7 @@ error[E0782]: expected a type, found a trait LL | fn f(a: A) -> A; | ^ | - = note: `A` it is dyn-incompatible, so it can't be `dyn` + = note: `A` is dyn-incompatible, otherwise a trait object could be used help: use a new generic type parameter, constrained by `A` | LL - fn f(a: A) -> A; @@ -32,7 +32,7 @@ error[E0782]: expected a type, found a trait LL | fn f(b: B) -> B; | ^ | - = note: `B` it is dyn-incompatible, so it can't be `dyn` + = note: `B` is dyn-incompatible, otherwise a trait object could be used help: use a new generic type parameter, constrained by `B` | LL - fn f(b: B) -> B; @@ -60,7 +60,7 @@ error[E0782]: expected a type, found a trait LL | fn f(&self, c: C) -> C; | ^ | - = note: `C` it is dyn-incompatible, so it can't be `dyn` + = note: `C` is dyn-incompatible, otherwise a trait object could be used help: use a new generic type parameter, constrained by `C` | LL - fn f(&self, c: C) -> C; diff --git a/tests/ui/suggestions/missing-bound-in-derive-copy-impl-2.stderr b/tests/ui/suggestions/missing-bound-in-derive-copy-impl-2.stderr index 4408fe0a0a4..a48dd30d008 100644 --- a/tests/ui/suggestions/missing-bound-in-derive-copy-impl-2.stderr +++ b/tests/ui/suggestions/missing-bound-in-derive-copy-impl-2.stderr @@ -31,7 +31,6 @@ LL | #[derive(Debug, Copy, Clone)] LL | pub struct Vector2<T: Debug + Copy + Clone> { | ---- unsatisfied trait bound introduced in this `derive` macro = note: required for the cast from `&Vector2<K>` to `&dyn Debug` - = note: this error originates in the derive macro `Debug` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider further restricting type parameter `K` with trait `Copy` | LL | pub struct AABB<K: Debug + std::marker::Copy> { @@ -51,7 +50,6 @@ note: required by a bound in `Vector2` | LL | pub struct Vector2<T: Debug + Copy + Clone> { | ^^^^ required by this bound in `Vector2` - = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider further restricting type parameter `K` with trait `Copy` | LL | pub struct AABB<K: Debug + std::marker::Copy> { @@ -73,7 +71,6 @@ LL | #[derive(Debug, Copy, Clone)] | ^^^^^ LL | pub struct Vector2<T: Debug + Copy + Clone> { | ---- unsatisfied trait bound introduced in this `derive` macro - = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider further restricting type parameter `K` with trait `Copy` | LL | pub struct AABB<K: Debug + std::marker::Copy> { diff --git a/tests/ui/suggestions/missing-bound-in-derive-copy-impl-3.stderr b/tests/ui/suggestions/missing-bound-in-derive-copy-impl-3.stderr index 1bbf6f66ab2..3f8b6f93e1f 100644 --- a/tests/ui/suggestions/missing-bound-in-derive-copy-impl-3.stderr +++ b/tests/ui/suggestions/missing-bound-in-derive-copy-impl-3.stderr @@ -12,7 +12,6 @@ note: the `Copy` impl for `Vector2<K>` requires that `K: Debug` | LL | pub loc: Vector2<K>, | ^^^^^^^^^^ - = note: this error originates in the derive macro `Copy` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider further restricting type parameter `K` with trait `Debug` | LL | pub struct AABB<K: Copy + Debug>{ @@ -43,7 +42,6 @@ LL | pub struct AABB<K: Copy>{ LL | pub loc: Vector2<K>, | ^^^^^^^^^^^^^^^^^^^ `K` cannot be formatted using `{:?}` because it doesn't implement `Debug` | - = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider further restricting type parameter `K` with trait `Debug` | LL | pub struct AABB<K: Copy + std::fmt::Debug>{ @@ -58,7 +56,6 @@ LL | #[derive(Debug, Copy, Clone)] LL | pub size: Vector2<K> | ^^^^^^^^^^^^^^^^^^^^ `K` cannot be formatted using `{:?}` because it doesn't implement `Debug` | - = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider further restricting type parameter `K` with trait `Debug` | LL | pub struct AABB<K: Copy + std::fmt::Debug>{ diff --git a/tests/ui/suggestions/missing-bound-in-derive-copy-impl.stderr b/tests/ui/suggestions/missing-bound-in-derive-copy-impl.stderr index 8b5cced4c4a..3766e3e2c7b 100644 --- a/tests/ui/suggestions/missing-bound-in-derive-copy-impl.stderr +++ b/tests/ui/suggestions/missing-bound-in-derive-copy-impl.stderr @@ -12,7 +12,6 @@ note: the `Copy` impl for `Vector2<K>` requires that `K: Debug` | LL | pub loc: Vector2<K>, | ^^^^^^^^^^ - = note: this error originates in the derive macro `Copy` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider restricting type parameter `K` with trait `Debug` | LL | pub struct AABB<K: Debug> { @@ -67,7 +66,6 @@ LL | #[derive(Debug, Copy, Clone)] LL | pub struct Vector2<T: Debug + Copy + Clone> { | ---- unsatisfied trait bound introduced in this `derive` macro = note: required for the cast from `&Vector2<K>` to `&dyn Debug` - = note: this error originates in the derive macro `Debug` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider restricting type parameter `K` with trait `Copy` | LL | pub struct AABB<K: std::marker::Copy> { @@ -82,7 +80,6 @@ LL | pub struct AABB<K> { LL | pub loc: Vector2<K>, | ^^^^^^^^^^^^^^^^^^^ `K` cannot be formatted using `{:?}` because it doesn't implement `Debug` | - = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider restricting type parameter `K` with trait `Debug` | LL | pub struct AABB<K: std::fmt::Debug> { @@ -102,7 +99,6 @@ note: required by a bound in `Vector2` | LL | pub struct Vector2<T: Debug + Copy + Clone> { | ^^^^ required by this bound in `Vector2` - = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider restricting type parameter `K` with trait `Copy` | LL | pub struct AABB<K: std::marker::Copy> { @@ -117,7 +113,6 @@ LL | #[derive(Debug, Copy, Clone)] LL | pub size: Vector2<K>, | ^^^^^^^^^^^^^^^^^^^^ `K` cannot be formatted using `{:?}` because it doesn't implement `Debug` | - = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider restricting type parameter `K` with trait `Debug` | LL | pub struct AABB<K: std::fmt::Debug> { @@ -139,7 +134,6 @@ LL | #[derive(Debug, Copy, Clone)] | ^^^^^ LL | pub struct Vector2<T: Debug + Copy + Clone> { | ---- unsatisfied trait bound introduced in this `derive` macro - = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider restricting type parameter `K` with trait `Copy` | LL | pub struct AABB<K: std::marker::Copy> { diff --git a/tests/ui/test-attrs/custom-test-frameworks/issue-107454.stderr b/tests/ui/test-attrs/custom-test-frameworks/issue-107454.stderr index 6ac79924d80..1b1a59ec582 100644 --- a/tests/ui/test-attrs/custom-test-frameworks/issue-107454.stderr +++ b/tests/ui/test-attrs/custom-test-frameworks/issue-107454.stderr @@ -9,7 +9,6 @@ note: the lint level is defined here | LL | #![deny(unnameable_test_items)] | ^^^^^^^^^^^^^^^^^^^^^ - = note: this error originates in the attribute macro `test_case` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/test-attrs/issue-12997-2.stderr b/tests/ui/test-attrs/issue-12997-2.stderr index bc84ff413df..1123630a4a1 100644 --- a/tests/ui/test-attrs/issue-12997-2.stderr +++ b/tests/ui/test-attrs/issue-12997-2.stderr @@ -14,7 +14,6 @@ note: function defined here | LL | fn bar(x: isize) { } | ^^^ -------- - = note: this error originates in the attribute macro `bench` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/test-attrs/test-function-signature.stderr b/tests/ui/test-attrs/test-function-signature.stderr index abdb30dc931..c025163c0bd 100644 --- a/tests/ui/test-attrs/test-function-signature.stderr +++ b/tests/ui/test-attrs/test-function-signature.stderr @@ -32,7 +32,6 @@ LL | fn bar() -> i32 { | note: required by a bound in `assert_test_result` --> $SRC_DIR/test/src/lib.rs:LL:COL - = note: this error originates in the attribute macro `test` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 5 previous errors diff --git a/tests/ui/traits/const-traits/const_derives/derive-const-gate.stderr b/tests/ui/traits/const-traits/const_derives/derive-const-gate.stderr index fae871a4c85..202210a2e65 100644 --- a/tests/ui/traits/const-traits/const_derives/derive-const-gate.stderr +++ b/tests/ui/traits/const-traits/const_derives/derive-const-gate.stderr @@ -15,7 +15,6 @@ LL | #[derive_const(Default)] | = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` = note: adding a non-const method body in the future would be a breaking change - = note: this error originates in the derive macro `Default` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 2 previous errors diff --git a/tests/ui/traits/const-traits/const_derives/derive-const-non-const-type.stderr b/tests/ui/traits/const-traits/const_derives/derive-const-non-const-type.stderr index 64564de2a0c..27f4bcf46ef 100644 --- a/tests/ui/traits/const-traits/const_derives/derive-const-non-const-type.stderr +++ b/tests/ui/traits/const-traits/const_derives/derive-const-non-const-type.stderr @@ -6,7 +6,6 @@ LL | #[derive_const(Default)] | = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` = note: adding a non-const method body in the future would be a breaking change - = note: this error originates in the derive macro `Default` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0015]: cannot call non-const associated function `<A as Default>::default` in constant functions --> $DIR/derive-const-non-const-type.rs:11:14 @@ -17,7 +16,6 @@ LL | pub struct S(A); | ^ | = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants - = note: this error originates in the derive macro `Default` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 2 previous errors diff --git a/tests/ui/traits/const-traits/const_derives/derive-const-use.stderr b/tests/ui/traits/const-traits/const_derives/derive-const-use.stderr index 9ad3b0c1617..8297911a3f3 100644 --- a/tests/ui/traits/const-traits/const_derives/derive-const-use.stderr +++ b/tests/ui/traits/const-traits/const_derives/derive-const-use.stderr @@ -27,7 +27,6 @@ LL | #[derive_const(Default, PartialEq)] | = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` = note: adding a non-const method body in the future would be a breaking change - = note: this error originates in the derive macro `Default` (in Nightly builds, run with -Z macro-backtrace for more info) error: const `impl` for trait `PartialEq` which is not marked with `#[const_trait]` --> $DIR/derive-const-use.rs:11:12 @@ -46,7 +45,6 @@ LL | #[derive_const(Default, PartialEq)] | = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` = note: adding a non-const method body in the future would be a breaking change - = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0015]: cannot call non-const associated function `<S as Default>::default` in constants --> $DIR/derive-const-use.rs:18:35 @@ -73,7 +71,6 @@ LL | pub struct S((), A); | ^^ | = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants - = note: this error originates in the derive macro `Default` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0015]: cannot call non-const associated function `<A as Default>::default` in constant functions --> $DIR/derive-const-use.rs:16:18 @@ -84,7 +81,6 @@ LL | pub struct S((), A); | ^ | = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants - = note: this error originates in the derive macro `Default` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0015]: cannot call non-const operator in constant functions --> $DIR/derive-const-use.rs:16:14 @@ -95,7 +91,6 @@ LL | pub struct S((), A); | ^^ | = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants - = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0015]: cannot call non-const operator in constant functions --> $DIR/derive-const-use.rs:16:18 @@ -106,7 +101,6 @@ LL | pub struct S((), A); | ^ | = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants - = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 12 previous errors diff --git a/tests/ui/traits/const-traits/const_derives/derive-const-with-params.stderr b/tests/ui/traits/const-traits/const_derives/derive-const-with-params.stderr index 6b1405712ef..d1dbf62d566 100644 --- a/tests/ui/traits/const-traits/const_derives/derive-const-with-params.stderr +++ b/tests/ui/traits/const-traits/const_derives/derive-const-with-params.stderr @@ -6,7 +6,6 @@ LL | #[derive_const(PartialEq)] | = note: marking a trait with `#[const_trait]` ensures all default method bodies are `const` = note: adding a non-const method body in the future would be a breaking change - = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) error: `~const` can only be applied to `#[const_trait]` traits | @@ -22,7 +21,6 @@ LL | pub struct Reverse<T>(T); | ^ | = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants - = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0015]: cannot call non-const operator in constant functions --> $DIR/derive-const-with-params.rs:11:5 diff --git a/tests/ui/traits/issue-106072.stderr b/tests/ui/traits/issue-106072.stderr index 3e0d6d88086..815787c3bfe 100644 --- a/tests/ui/traits/issue-106072.stderr +++ b/tests/ui/traits/issue-106072.stderr @@ -13,8 +13,6 @@ error[E0782]: expected a type, found a trait | LL | #[derive(Clone)] | ^^^^^ - | - = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0782]: expected a type, found a trait --> $DIR/issue-106072.rs:1:10 @@ -23,7 +21,6 @@ LL | #[derive(Clone)] | ^^^^^ | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 3 previous errors diff --git a/tests/ui/traits/issue-50480.stderr b/tests/ui/traits/issue-50480.stderr index d3c11238ede..ed8c74e9bdd 100644 --- a/tests/ui/traits/issue-50480.stderr +++ b/tests/ui/traits/issue-50480.stderr @@ -79,8 +79,6 @@ LL | struct Foo(N, NotDefined, <i32 as Iterator>::Item, Vec<i32>, String); | -------- ------ this field does not implement `Copy` | | | this field does not implement `Copy` - | - = note: this error originates in the derive macro `Copy` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0204]: the trait `Copy` cannot be implemented for this type --> $DIR/issue-50480.rs:11:17 @@ -92,8 +90,6 @@ LL | struct Bar<T>(T, N, NotDefined, <i32 as Iterator>::Item, Vec<i32>, String); | -------- ------ this field does not implement `Copy` | | | this field does not implement `Copy` - | - = note: this error originates in the derive macro `Copy` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: `i32` is not an iterator --> $DIR/issue-50480.rs:14:33 @@ -118,7 +114,6 @@ LL | #[derive(Clone, Copy)] | ^^^^^ `i32` is not an iterator | = help: the trait `Iterator` is not implemented for `i32` - = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: `i32` is not an iterator --> $DIR/issue-50480.rs:14:33 @@ -130,7 +125,6 @@ LL | struct Bar<T>(T, N, NotDefined, <i32 as Iterator>::Item, Vec<i32>, String); | ^^^^^^^^^^^^^^^^^^^^^^^ `i32` is not an iterator | = help: the trait `Iterator` is not implemented for `i32` - = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 13 previous errors diff --git a/tests/ui/traits/issue-71136.stderr b/tests/ui/traits/issue-71136.stderr index 2c03c6bf08e..cd891c88c9f 100644 --- a/tests/ui/traits/issue-71136.stderr +++ b/tests/ui/traits/issue-71136.stderr @@ -8,7 +8,6 @@ LL | the_foos: Vec<Foo>, | ^^^^^^^^^^^^^^^^^^ the trait `Clone` is not implemented for `Foo` | = note: required for `Vec<Foo>` to implement `Clone` - = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Foo` with `#[derive(Clone)]` | LL + #[derive(Clone)] diff --git a/tests/ui/traits/issue-79458.stderr b/tests/ui/traits/issue-79458.stderr index c80efbe9287..9e53ec8cc90 100644 --- a/tests/ui/traits/issue-79458.stderr +++ b/tests/ui/traits/issue-79458.stderr @@ -9,7 +9,6 @@ LL | bar: &'a mut T | = help: the trait `Clone` is implemented for `&T` = note: `Clone` is implemented for `&T`, but not for `&mut T` - = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/traits/next-solver/global-cache-and-parallel-frontend.stderr b/tests/ui/traits/next-solver/global-cache-and-parallel-frontend.stderr index da269bbeae4..290b1df1665 100644 --- a/tests/ui/traits/next-solver/global-cache-and-parallel-frontend.stderr +++ b/tests/ui/traits/next-solver/global-cache-and-parallel-frontend.stderr @@ -13,7 +13,6 @@ LL | impl<T: Clone, U> PartialEq<U> for Struct<T> | unsatisfied trait bound introduced here note: required by a bound in `Eq` --> $SRC_DIR/core/src/cmp.rs:LL:COL - = note: this error originates in the derive macro `Eq` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider restricting type parameter `T` with trait `Clone` | LL | pub struct Struct<T: std::clone::Clone>(T); diff --git a/tests/ui/transmutability/uninhabited.stderr b/tests/ui/transmutability/uninhabited.stderr index 39f8bf19c36..4c5c4107a85 100644 --- a/tests/ui/transmutability/uninhabited.stderr +++ b/tests/ui/transmutability/uninhabited.stderr @@ -3,24 +3,18 @@ error[E0080]: evaluation of constant value failed | LL | assert!(false); | ^^^^^^^^^^^^^^ evaluation panicked: assertion failed: false - | - = note: this error originates in the macro `assert` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of constant value failed --> $DIR/uninhabited.rs:63:9 | LL | assert!(false); | ^^^^^^^^^^^^^^ evaluation panicked: assertion failed: false - | - = note: this error originates in the macro `assert` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0080]: evaluation of constant value failed --> $DIR/uninhabited.rs:87:9 | LL | assert!(false); | ^^^^^^^^^^^^^^ evaluation panicked: assertion failed: false - | - = note: this error originates in the macro `assert` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0277]: `()` cannot be safely transmuted into `void::Void` --> $DIR/uninhabited.rs:29:41 diff --git a/tests/ui/type/pattern_types/derives.stderr b/tests/ui/type/pattern_types/derives.stderr index 9d4baef621b..f59617ebc45 100644 --- a/tests/ui/type/pattern_types/derives.stderr +++ b/tests/ui/type/pattern_types/derives.stderr @@ -6,8 +6,6 @@ LL | #[derive(Clone, Copy, PartialEq)] LL | #[repr(transparent)] LL | struct Nanoseconds(NanoI32); | ^^^^^^^ - | - = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) error: aborting due to 1 previous error diff --git a/tests/ui/typeck/cyclic_type_ice.stderr b/tests/ui/typeck/cyclic_type_ice.stderr index 4dc02a53c02..645766becbf 100644 --- a/tests/ui/typeck/cyclic_type_ice.stderr +++ b/tests/ui/typeck/cyclic_type_ice.stderr @@ -23,7 +23,7 @@ LL | let f = |_, _| (); help: provide the argument | LL - f(f); -LL + f(/* */, /* */); +LL + f(/* _ */, /* _ */); | error: aborting due to 2 previous errors diff --git a/tests/ui/union/union-derive-clone.stderr b/tests/ui/union/union-derive-clone.stderr index a2b81f0dba1..679ab6a38e4 100644 --- a/tests/ui/union/union-derive-clone.stderr +++ b/tests/ui/union/union-derive-clone.stderr @@ -6,7 +6,6 @@ LL | #[derive(Clone)] | note: required by a bound in `AssertParamIsCopy` --> $SRC_DIR/core/src/clone.rs:LL:COL - = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `U1` with `#[derive(Copy)]` | LL + #[derive(Copy)] diff --git a/tests/ui/union/union-derive-eq.current.stderr b/tests/ui/union/union-derive-eq.current.stderr index 151ceebe1ba..a0339687dad 100644 --- a/tests/ui/union/union-derive-eq.current.stderr +++ b/tests/ui/union/union-derive-eq.current.stderr @@ -9,7 +9,6 @@ LL | a: PartialEqNotEq, | note: required by a bound in `AssertParamIsEq` --> $SRC_DIR/core/src/cmp.rs:LL:COL - = note: this error originates in the derive macro `Eq` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `PartialEqNotEq` with `#[derive(Eq)]` | LL + #[derive(Eq)] diff --git a/tests/ui/union/union-derive-eq.next.stderr b/tests/ui/union/union-derive-eq.next.stderr index 151ceebe1ba..a0339687dad 100644 --- a/tests/ui/union/union-derive-eq.next.stderr +++ b/tests/ui/union/union-derive-eq.next.stderr @@ -9,7 +9,6 @@ LL | a: PartialEqNotEq, | note: required by a bound in `AssertParamIsEq` --> $SRC_DIR/core/src/cmp.rs:LL:COL - = note: this error originates in the derive macro `Eq` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `PartialEqNotEq` with `#[derive(Eq)]` | LL + #[derive(Eq)] diff --git a/triagebot.toml b/triagebot.toml index 84aae8a5179..293ad259910 100644 --- a/triagebot.toml +++ b/triagebot.toml @@ -1081,6 +1081,8 @@ warn_non_default_branch.enable = true contributing_url = "https://rustc-dev-guide.rust-lang.org/getting-started.html" users_on_vacation = [ "jyn514", + "ChrisDenton", + "jieyouxu", ] [[assign.warn_non_default_branch.exceptions]] @@ -1115,7 +1117,6 @@ compiler = [ "@wesleywiser", ] libs = [ - "@cuviper", "@Mark-Simulacrum", "@Amanieu", "@Noratrieb", |
