diff options
697 files changed, 10402 insertions, 7241 deletions
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dc8ac539a3a..e92afc14c20 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -182,11 +182,6 @@ jobs: - name: install MinGW run: src/ci/scripts/install-mingw.sh - # Workaround for spurious ci failures after mingw install - # see https://rust-lang.zulipchat.com/#narrow/channel/242791-t-infra/topic/Spurious.20bors.20CI.20failures/near/528915775 - - name: ensure home dir exists - run: mkdir -p ~ - - name: install ninja run: src/ci/scripts/install-ninja.sh diff --git a/Cargo.lock b/Cargo.lock index 7d2fca8bb3f..b7fc2de20b5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -216,7 +216,7 @@ dependencies = [ "memchr", "serde", "serde_derive", - "winnow 0.7.11", + "winnow 0.7.12", ] [[package]] @@ -384,7 +384,7 @@ dependencies = [ name = "cargo-miri" version = "0.1.0" dependencies = [ - "cargo_metadata 0.19.2", + "cargo_metadata 0.21.0", "directories", "rustc-build-sysroot", "rustc_tools_util 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", @@ -403,13 +403,38 @@ dependencies = [ ] [[package]] +name = "cargo-platform" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84982c6c0ae343635a3a4ee6dedef965513735c8b183caa7289fa6e27399ebd4" +dependencies = [ + "serde", +] + +[[package]] +name = "cargo-util-schemas" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dc1a6f7b5651af85774ae5a34b4e8be397d9cf4bc063b7e6dbd99a841837830" +dependencies = [ + "semver", + "serde", + "serde-untagged", + "serde-value", + "thiserror 2.0.12", + "toml 0.8.23", + "unicode-xid", + "url", +] + +[[package]] name = "cargo_metadata" version = "0.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2d886547e41f740c616ae73108f6eb70afe6d940c7bc697cb30f13daec073037" dependencies = [ "camino", - "cargo-platform", + "cargo-platform 0.1.9", "semver", "serde", "serde_json", @@ -423,7 +448,22 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd5eb614ed4c27c5d706420e4320fbe3216ab31fa1c33cd8246ac36dae4479ba" dependencies = [ "camino", - "cargo-platform", + "cargo-platform 0.1.9", + "semver", + "serde", + "serde_json", + "thiserror 2.0.12", +] + +[[package]] +name = "cargo_metadata" +version = "0.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5cfca2aaa699835ba88faf58a06342a314a950d2b9686165e038286c30316868" +dependencies = [ + "camino", + "cargo-platform 0.2.0", + "cargo-util-schemas", "semver", "serde", "serde_json", @@ -470,23 +510,12 @@ dependencies = [ [[package]] name = "chrono-tz" -version = "0.10.3" +version = "0.10.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "efdce149c370f133a071ca8ef6ea340b7b88748ab0810097a9e2976eaa34b4f3" +checksum = "a6139a8597ed92cf816dfb33f5dd6cf0bb93a6adc938f11039f371bc5bcd26c3" dependencies = [ "chrono", - "chrono-tz-build", - "phf", -] - -[[package]] -name = "chrono-tz-build" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f10f8c9340e31fc120ff885fcdb54a0b48e474bbd77cab557f0c30a3e569402" -dependencies = [ - "parse-zoneinfo", - "phf_codegen", + "phf 0.12.1", ] [[package]] @@ -501,9 +530,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.40" +version = "4.5.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40b6887a1d8685cebccf115538db5c0efe625ccac9696ad45c409d96566e910f" +checksum = "be92d32e80243a54711e5d7ce823c35c41c9d929dc4ab58e1276f625841aadf9" dependencies = [ "clap_builder", "clap_derive", @@ -521,9 +550,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.40" +version = "4.5.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0c66c08ce9f0c698cbce5c0279d0bb6ac936d8674174fe48f736533b964f59e" +checksum = "707eab41e9622f9139419d573eca0900137718000c517d47da73045f54331c3d" dependencies = [ "anstream", "anstyle", @@ -533,9 +562,9 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.5.40" +version = "4.5.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2c7947ae4cc3d851207c1adb5b5e260ff0cca11446b1d6d1423788e442257ce" +checksum = "ef4f52386a59ca4c860f7393bcf8abd8dfd91ecccc0f774635ff68e92eeef491" dependencies = [ "heck 0.5.0", "proc-macro2", @@ -572,7 +601,7 @@ dependencies = [ "tempfile", "termize", "toml 0.7.8", - "ui_test 0.30.2", + "ui_test", "walkdir", ] @@ -715,6 +744,15 @@ dependencies = [ ] [[package]] +name = "colored" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fde0e0ec90c9dfb3b4b1a0891a7dcd0e2bffde2f7efed5fe7c9bb00e5bfb915e" +dependencies = [ + "windows-sys 0.59.0", +] + +[[package]] name = "comma" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -727,7 +765,7 @@ dependencies = [ "anstyle-svg", "build_helper", "camino", - "colored", + "colored 2.2.0", "diff", "getopts", "glob", @@ -798,9 +836,9 @@ dependencies = [ [[package]] name = "crc32fast" -version = "1.4.2" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a97769d94ddab943e4510d138150169a2758b5ef3eb191a9ee688de3e23ef7b3" +checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" dependencies = [ "cfg-if", ] @@ -989,9 +1027,9 @@ dependencies = [ [[package]] name = "derive_setters" -version = "0.1.7" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9c848e86c87e5cc305313041c5677d4d95d60baa71cf95e5f6ea2554bb629ff" +checksum = "ae5c625eda104c228c06ecaf988d1c60e542176bd7a490e60eeda3493244c0c9" dependencies = [ "darling", "proc-macro2", @@ -1155,6 +1193,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" [[package]] +name = "erased-serde" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e004d887f51fcb9fef17317a2f3525c887d8aa3f4f50fed920816a688284a5b7" +dependencies = [ + "serde", + "typeid", +] + +[[package]] name = "errno" version = "0.3.13" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -1842,17 +1890,16 @@ dependencies = [ [[package]] name = "ipc-channel" -version = "0.19.0" +version = "0.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fb8251fb7bcd9ccd3725ed8deae9fe7db8e586495c9eb5b0c52e6233e5e75ea" +checksum = "5b1c98b70019c830a1fc39cecfe1f60ff99c4122f0a189697c810c90ec545c14" dependencies = [ "bincode", "crossbeam-channel", "fnv", - "lazy_static", "libc", "mio", - "rand 0.8.5", + "rand 0.9.1", "serde", "tempfile", "uuid", @@ -2045,9 +2092,9 @@ checksum = "f9fbbcab51052fe104eb5e5d351cf728d30a5be1fe14d9be8a3b097481fb97de" [[package]] name = "libredox" -version = "0.1.4" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1580801010e535496706ba011c15f8532df6b42297d2e471fec38ceadd8c0638" +checksum = "4488594b9328dee448adb906d8b126d9b7deb7cf5c22161ee591610bb1be83c0" dependencies = [ "bitflags", "libc", @@ -2157,7 +2204,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c7a7213d12e1864c0f002f52c2923d4556935a43dec5e71355c2760e0f6e7a18" dependencies = [ "log", - "phf", + "phf 0.11.3", "phf_codegen", "string_cache", "string_cache_codegen", @@ -2196,9 +2243,9 @@ dependencies = [ [[package]] name = "measureme" -version = "12.0.1" +version = "12.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "570a507d8948a66a97f42cbbaf8a6bb9516a51017d4ee949502ad7a10a864395" +checksum = "6ebd1ebda747ae161a4a377bf93f87e18d46faad2331cc0c7d25b84b1d445f49" dependencies = [ "log", "memmap2", @@ -2251,7 +2298,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78bed444cc8a2160f01cbcf811ef18cac863ad68ae8ca62092e8db51d51c761c" dependencies = [ "libc", - "log", "wasi 0.11.1+wasi-snapshot-preview1", "windows-sys 0.59.0", ] @@ -2274,7 +2320,7 @@ dependencies = [ "capstone", "chrono", "chrono-tz", - "colored", + "colored 3.0.0", "directories", "getrandom 0.3.3", "ipc-channel", @@ -2291,7 +2337,7 @@ dependencies = [ "smallvec", "tempfile", "tikv-jemalloc-sys", - "ui_test 0.29.2", + "ui_test", ] [[package]] @@ -2572,6 +2618,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" [[package]] +name = "ordered-float" +version = "2.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68f19d67e5a2795c94e73e0bb1cc1a7edeb2e28efd39e2e1c9b7a40c1108b11c" +dependencies = [ + "num-traits", +] + +[[package]] name = "overload" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -2633,15 +2688,6 @@ dependencies = [ ] [[package]] -name = "parse-zoneinfo" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f2a05b18d44e2957b88f96ba460715e295bc1d7510468a2f3d3b44535d26c24" -dependencies = [ - "regex", -] - -[[package]] name = "pathdiff" version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -2712,7 +2758,16 @@ version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" dependencies = [ - "phf_shared", + "phf_shared 0.11.3", +] + +[[package]] +name = "phf" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "913273894cec178f401a31ec4b656318d95473527be05c0752cc41cdc32be8b7" +dependencies = [ + "phf_shared 0.12.1", ] [[package]] @@ -2722,7 +2777,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aef8048c789fa5e851558d709946d6d79a8ff88c0440c587967f8e94bfb1216a" dependencies = [ "phf_generator", - "phf_shared", + "phf_shared 0.11.3", ] [[package]] @@ -2731,7 +2786,7 @@ version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" dependencies = [ - "phf_shared", + "phf_shared 0.11.3", "rand 0.8.5", ] @@ -2745,6 +2800,15 @@ dependencies = [ ] [[package]] +name = "phf_shared" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06005508882fb681fd97892ecff4b7fd0fee13ef1aa569f8695dae7ab9099981" +dependencies = [ + "siphasher", +] + +[[package]] name = "pin-project-lite" version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -4752,15 +4816,15 @@ dependencies = [ [[package]] name = "rustix" -version = "1.0.7" +version = "1.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c71e83d6afe7ff64890ec6b71d6a69bb8a610ab78ce364b3352876bb4c801266" +checksum = "11181fbabf243db407ef8df94a6ce0b2f9a733bd8be4ad02b4eda9602296cac8" dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys", - "windows-sys 0.59.0", + "windows-sys 0.60.2", ] [[package]] @@ -4848,6 +4912,27 @@ dependencies = [ ] [[package]] +name = "serde-untagged" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "299d9c19d7d466db4ab10addd5703e4c615dec2a5a16dbbafe191045e87ee66e" +dependencies = [ + "erased-serde", + "serde", + "typeid", +] + +[[package]] +name = "serde-value" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3a1a3341211875ef120e117ea7fd5228530ae7e7036a779fdc9117be6b3282c" +dependencies = [ + "ordered-float", + "serde", +] + +[[package]] name = "serde_derive" version = "1.0.219" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -4860,9 +4945,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.140" +version = "1.0.141" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373" +checksum = "30b9eff21ebe718216c6ec64e1d9ac57087aad11efc64e32002bce4a0d4c03d3" dependencies = [ "itoa", "memchr", @@ -4946,16 +5031,6 @@ dependencies = [ [[package]] name = "spanned" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86af297923fbcfd107c20a189a6e9c872160df71a7190ae4a7a6c5dce4b2feb6" -dependencies = [ - "bstr", - "color-eyre", -] - -[[package]] -name = "spanned" version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c92d4b0c055fde758f086eb4a6e73410247df8a3837fd606d2caeeaf72aa566d" @@ -5027,7 +5102,7 @@ checksum = "bf776ba3fa74f83bf4b63c3dcbbf82173db2632ed8452cb2d891d33f459de70f" dependencies = [ "new_debug_unreachable", "parking_lot", - "phf_shared", + "phf_shared 0.11.3", "precomputed-hash", "serde", ] @@ -5039,7 +5114,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c711928715f1fe0fe509c53b43e993a9a557babc2d0a3567d0a3006f1ac931a0" dependencies = [ "phf_generator", - "phf_shared", + "phf_shared 0.11.3", "proc-macro2", "quote", ] @@ -5104,9 +5179,9 @@ dependencies = [ [[package]] name = "sysinfo" -version = "0.36.0" +version = "0.36.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aab138f5c1bb35231de19049060a87977ad23e04f2303e953bc5c2947ac7dec4" +checksum = "252800745060e7b9ffb7b2badbd8b31cfa4aa2e61af879d0a3bf2a317c20217d" dependencies = [ "libc", "objc2-core-foundation", @@ -5411,7 +5486,7 @@ dependencies = [ "serde_spanned", "toml_datetime", "toml_write", - "winnow 0.7.11", + "winnow 0.7.12", ] [[package]] @@ -5532,6 +5607,12 @@ dependencies = [ ] [[package]] +name = "typeid" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" + +[[package]] name = "typenum" version = "1.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -5554,32 +5635,6 @@ checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971" [[package]] name = "ui_test" -version = "0.29.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1211b1111c752c73b33073d2958072be08825fd97c9ab4d83444da361a06634b" -dependencies = [ - "annotate-snippets 0.11.5", - "anyhow", - "bstr", - "cargo-platform", - "cargo_metadata 0.18.1", - "color-eyre", - "colored", - "comma", - "crossbeam-channel", - "indicatif", - "levenshtein", - "prettydiff", - "regex", - "rustc_version", - "rustfix", - "serde", - "serde_json", - "spanned 0.3.0", -] - -[[package]] -name = "ui_test" version = "0.30.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b56a6897cc4bb6f8daf1939b0b39cd9645856997f46f4d0b3e3cb7122dfe9251" @@ -5587,10 +5642,10 @@ dependencies = [ "annotate-snippets 0.11.5", "anyhow", "bstr", - "cargo-platform", + "cargo-platform 0.1.9", "cargo_metadata 0.18.1", "color-eyre", - "colored", + "colored 2.2.0", "comma", "crossbeam-channel", "indicatif", @@ -5601,7 +5656,7 @@ dependencies = [ "rustfix", "serde", "serde_json", - "spanned 0.4.1", + "spanned", ] [[package]] @@ -5829,9 +5884,9 @@ dependencies = [ [[package]] name = "wasi-preview1-component-adapter-provider" -version = "34.0.1" +version = "34.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aafa1e6af9a954a4bcf6ef420c33355d0ce84ddc6afbcba7bb6f05126f9120ae" +checksum = "33696c5f1ff1e083de9f36c3da471abd736362bc173e093f8b0b1ed5a387e39b" [[package]] name = "wasm-bindgen" @@ -6475,9 +6530,9 @@ dependencies = [ [[package]] name = "winnow" -version = "0.7.11" +version = "0.7.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74c7b26e3480b707944fc872477815d29a8e429d2f93a1ce000f5fa84a15cbcd" +checksum = "f3edebf492c8125044983378ecb5766203ad3b4c2f7a922bd7dd207f6d443e95" dependencies = [ "memchr", ] diff --git a/compiler/rustc_abi/src/lib.rs b/compiler/rustc_abi/src/lib.rs index de4b5a46c81..5bd73502d98 100644 --- a/compiler/rustc_abi/src/lib.rs +++ b/compiler/rustc_abi/src/lib.rs @@ -43,7 +43,7 @@ use std::fmt; #[cfg(feature = "nightly")] use std::iter::Step; use std::num::{NonZeroUsize, ParseIntError}; -use std::ops::{Add, AddAssign, Deref, Mul, RangeInclusive, Sub}; +use std::ops::{Add, AddAssign, Deref, Mul, RangeFull, RangeInclusive, Sub}; use std::str::FromStr; use bitflags::bitflags; @@ -1391,12 +1391,45 @@ impl WrappingRange { } /// Returns `true` if `size` completely fills the range. + /// + /// Note that this is *not* the same as `self == WrappingRange::full(size)`. + /// Niche calculations can produce full ranges which are not the canonical one; + /// for example `Option<NonZero<u16>>` gets `valid_range: (..=0) | (1..)`. #[inline] fn is_full_for(&self, size: Size) -> bool { let max_value = size.unsigned_int_max(); debug_assert!(self.start <= max_value && self.end <= max_value); self.start == (self.end.wrapping_add(1) & max_value) } + + /// Checks whether this range is considered non-wrapping when the values are + /// interpreted as *unsigned* numbers of width `size`. + /// + /// Returns `Ok(true)` if there's no wrap-around, `Ok(false)` if there is, + /// and `Err(..)` if the range is full so it depends how you think about it. + #[inline] + pub fn no_unsigned_wraparound(&self, size: Size) -> Result<bool, RangeFull> { + if self.is_full_for(size) { Err(..) } else { Ok(self.start <= self.end) } + } + + /// Checks whether this range is considered non-wrapping when the values are + /// interpreted as *signed* numbers of width `size`. + /// + /// This is heavily dependent on the `size`, as `100..=200` does wrap when + /// interpreted as `i8`, but doesn't when interpreted as `i16`. + /// + /// Returns `Ok(true)` if there's no wrap-around, `Ok(false)` if there is, + /// and `Err(..)` if the range is full so it depends how you think about it. + #[inline] + pub fn no_signed_wraparound(&self, size: Size) -> Result<bool, RangeFull> { + if self.is_full_for(size) { + Err(..) + } else { + let start: i128 = size.sign_extend(self.start); + let end: i128 = size.sign_extend(self.end); + Ok(start <= end) + } + } } impl fmt::Debug for WrappingRange { diff --git a/compiler/rustc_ast_lowering/messages.ftl b/compiler/rustc_ast_lowering/messages.ftl index c6472fd45fa..370b15d2871 100644 --- a/compiler/rustc_ast_lowering/messages.ftl +++ b/compiler/rustc_ast_lowering/messages.ftl @@ -127,9 +127,6 @@ ast_lowering_misplaced_impl_trait = `impl Trait` is not allowed in {$position} .note = `impl Trait` is only allowed in arguments and return types of functions and methods -ast_lowering_misplaced_relax_trait_bound = - `?Trait` bounds are only permitted at the point where a type parameter is declared - ast_lowering_never_pattern_with_body = a never pattern is always unreachable .label = this will never be executed diff --git a/compiler/rustc_ast_lowering/src/errors.rs b/compiler/rustc_ast_lowering/src/errors.rs index b444324ef91..83f3a976e83 100644 --- a/compiler/rustc_ast_lowering/src/errors.rs +++ b/compiler/rustc_ast_lowering/src/errors.rs @@ -325,13 +325,6 @@ pub(crate) struct MisplacedDoubleDot { } #[derive(Diagnostic)] -#[diag(ast_lowering_misplaced_relax_trait_bound)] -pub(crate) struct MisplacedRelaxTraitBound { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] #[diag(ast_lowering_match_arm_with_no_body)] pub(crate) struct MatchArmWithNoBody { #[primary_span] diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index abd70c7517c..ddf01b69e7f 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -16,14 +16,11 @@ use smallvec::{SmallVec, smallvec}; use thin_vec::ThinVec; use tracing::instrument; -use super::errors::{ - InvalidAbi, InvalidAbiSuggestion, MisplacedRelaxTraitBound, TupleStructWithDefault, - UnionWithDefault, -}; +use super::errors::{InvalidAbi, InvalidAbiSuggestion, TupleStructWithDefault, UnionWithDefault}; use super::stability::{enabled_names, gate_unstable_abi}; use super::{ AstOwner, FnDeclKind, ImplTraitContext, ImplTraitPosition, LoweringContext, ParamMode, - ResolverAstLoweringExt, + RelaxedBoundForbiddenReason, RelaxedBoundPolicy, ResolverAstLoweringExt, }; pub(super) struct ItemLowerer<'a, 'hir> { @@ -435,6 +432,7 @@ impl<'hir> LoweringContext<'_, 'hir> { |this| { let bounds = this.lower_param_bounds( bounds, + RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::SuperTrait), ImplTraitContext::Disallowed(ImplTraitPosition::Bound), ); let items = this.arena.alloc_from_iter( @@ -455,6 +453,7 @@ impl<'hir> LoweringContext<'_, 'hir> { |this| { this.lower_param_bounds( bounds, + RelaxedBoundPolicy::Allowed, ImplTraitContext::Disallowed(ImplTraitPosition::Bound), ) }, @@ -940,6 +939,7 @@ impl<'hir> LoweringContext<'_, 'hir> { hir::TraitItemKind::Type( this.lower_param_bounds( bounds, + RelaxedBoundPolicy::Allowed, ImplTraitContext::Disallowed(ImplTraitPosition::Generic), ), ty, @@ -1677,61 +1677,6 @@ impl<'hir> LoweringContext<'_, 'hir> { assert!(self.impl_trait_defs.is_empty()); assert!(self.impl_trait_bounds.is_empty()); - // Error if `?Trait` bounds in where clauses don't refer directly to type parameters. - // Note: we used to clone these bounds directly onto the type parameter (and avoid lowering - // these into hir when we lower thee where clauses), but this makes it quite difficult to - // keep track of the Span info. Now, `<dyn HirTyLowerer>::add_implicit_sized_bound` - // checks both param bounds and where clauses for `?Sized`. - for pred in &generics.where_clause.predicates { - let WherePredicateKind::BoundPredicate(bound_pred) = &pred.kind else { - continue; - }; - let compute_is_param = || { - // Check if the where clause type is a plain type parameter. - match self - .resolver - .get_partial_res(bound_pred.bounded_ty.id) - .and_then(|r| r.full_res()) - { - Some(Res::Def(DefKind::TyParam, def_id)) - if bound_pred.bound_generic_params.is_empty() => - { - generics - .params - .iter() - .any(|p| def_id == self.local_def_id(p.id).to_def_id()) - } - // Either the `bounded_ty` is not a plain type parameter, or - // it's not found in the generic type parameters list. - _ => false, - } - }; - // We only need to compute this once per `WherePredicate`, but don't - // need to compute this at all unless there is a Maybe bound. - let mut is_param: Option<bool> = None; - for bound in &bound_pred.bounds { - if !matches!( - *bound, - GenericBound::Trait(PolyTraitRef { - modifiers: TraitBoundModifiers { polarity: BoundPolarity::Maybe(_), .. }, - .. - }) - ) { - continue; - } - let is_param = *is_param.get_or_insert_with(compute_is_param); - if !is_param && !self.tcx.features().more_maybe_bounds() { - self.tcx - .sess - .create_feature_err( - MisplacedRelaxTraitBound { span: bound.span() }, - sym::more_maybe_bounds, - ) - .emit(); - } - } - } - let mut predicates: SmallVec<[hir::WherePredicate<'hir>; 4]> = SmallVec::new(); predicates.extend(generics.params.iter().filter_map(|param| { self.lower_generic_bound_predicate( @@ -1741,6 +1686,7 @@ impl<'hir> LoweringContext<'_, 'hir> { ¶m.bounds, param.colon_span, generics.span, + RelaxedBoundPolicy::Allowed, itctx, PredicateOrigin::GenericParam, ) @@ -1750,7 +1696,7 @@ impl<'hir> LoweringContext<'_, 'hir> { .where_clause .predicates .iter() - .map(|predicate| self.lower_where_predicate(predicate)), + .map(|predicate| self.lower_where_predicate(predicate, &generics.params)), ); let mut params: SmallVec<[hir::GenericParam<'hir>; 4]> = self @@ -1827,6 +1773,7 @@ impl<'hir> LoweringContext<'_, 'hir> { bounds: &[GenericBound], colon_span: Option<Span>, parent_span: Span, + rbp: RelaxedBoundPolicy<'_>, itctx: ImplTraitContext, origin: PredicateOrigin, ) -> Option<hir::WherePredicate<'hir>> { @@ -1835,7 +1782,7 @@ impl<'hir> LoweringContext<'_, 'hir> { return None; } - let bounds = self.lower_param_bounds(bounds, itctx); + let bounds = self.lower_param_bounds(bounds, rbp, itctx); let param_span = ident.span; @@ -1887,7 +1834,11 @@ impl<'hir> LoweringContext<'_, 'hir> { Some(hir::WherePredicate { hir_id, span, kind }) } - fn lower_where_predicate(&mut self, pred: &WherePredicate) -> hir::WherePredicate<'hir> { + fn lower_where_predicate( + &mut self, + pred: &WherePredicate, + params: &[ast::GenericParam], + ) -> hir::WherePredicate<'hir> { let hir_id = self.lower_node_id(pred.id); let span = self.lower_span(pred.span); self.lower_attrs(hir_id, &pred.attrs, span); @@ -1896,17 +1847,29 @@ impl<'hir> LoweringContext<'_, 'hir> { bound_generic_params, bounded_ty, bounds, - }) => hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate { - bound_generic_params: self - .lower_generic_params(bound_generic_params, hir::GenericParamSource::Binder), - bounded_ty: self - .lower_ty(bounded_ty, ImplTraitContext::Disallowed(ImplTraitPosition::Bound)), - bounds: self.lower_param_bounds( - bounds, - ImplTraitContext::Disallowed(ImplTraitPosition::Bound), - ), - origin: PredicateOrigin::WhereClause, - }), + }) => { + let rbp = if bound_generic_params.is_empty() { + RelaxedBoundPolicy::AllowedIfOnTyParam(bounded_ty.id, params) + } else { + RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::LateBoundVarsInScope) + }; + hir::WherePredicateKind::BoundPredicate(hir::WhereBoundPredicate { + bound_generic_params: self.lower_generic_params( + bound_generic_params, + hir::GenericParamSource::Binder, + ), + bounded_ty: self.lower_ty( + bounded_ty, + ImplTraitContext::Disallowed(ImplTraitPosition::Bound), + ), + bounds: self.lower_param_bounds( + bounds, + rbp, + ImplTraitContext::Disallowed(ImplTraitPosition::Bound), + ), + origin: PredicateOrigin::WhereClause, + }) + } WherePredicateKind::RegionPredicate(WhereRegionPredicate { lifetime, bounds }) => { hir::WherePredicateKind::RegionPredicate(hir::WhereRegionPredicate { lifetime: self.lower_lifetime( @@ -1916,6 +1879,7 @@ impl<'hir> LoweringContext<'_, 'hir> { ), bounds: self.lower_param_bounds( bounds, + RelaxedBoundPolicy::Allowed, ImplTraitContext::Disallowed(ImplTraitPosition::Bound), ), in_where_clause: true, diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 1c96a375035..9aef189a29d 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -53,8 +53,8 @@ use rustc_hir::def::{DefKind, LifetimeRes, Namespace, PartialRes, PerNS, Res}; use rustc_hir::def_id::{CRATE_DEF_ID, LOCAL_CRATE, LocalDefId}; use rustc_hir::lints::DelayedLint; use rustc_hir::{ - self as hir, AngleBrackets, ConstArg, GenericArg, HirId, ItemLocalMap, LangItem, - LifetimeSource, LifetimeSyntax, ParamName, TraitCandidate, + self as hir, AngleBrackets, ConstArg, GenericArg, HirId, ItemLocalMap, LifetimeSource, + LifetimeSyntax, ParamName, TraitCandidate, }; use rustc_index::{Idx, IndexSlice, IndexVec}; use rustc_macros::extension; @@ -281,6 +281,24 @@ impl ResolverAstLowering { } } +/// How relaxed bounds `?Trait` should be treated. +/// +/// Relaxed bounds should only be allowed in places where we later +/// (namely during HIR ty lowering) perform *sized elaboration*. +#[derive(Clone, Copy, Debug)] +enum RelaxedBoundPolicy<'a> { + Allowed, + AllowedIfOnTyParam(NodeId, &'a [ast::GenericParam]), + Forbidden(RelaxedBoundForbiddenReason), +} + +#[derive(Clone, Copy, Debug)] +enum RelaxedBoundForbiddenReason { + TraitObjectTy, + SuperTrait, + LateBoundVarsInScope, +} + /// Context of `impl Trait` in code, which determines whether it is allowed in an HIR subtree, /// and if so, what meaning it has. #[derive(Debug, Copy, Clone, PartialEq, Eq)] @@ -856,25 +874,32 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { /// name resolver owing to lifetime elision; this also populates the resolver's node-id->def-id /// map, so that later calls to `opt_node_id_to_def_id` that refer to these extra lifetime /// parameters will be successful. - #[instrument(level = "debug", skip(self))] + #[instrument(level = "debug", skip(self), ret)] #[inline] fn lower_lifetime_binder( &mut self, binder: NodeId, generic_params: &[GenericParam], ) -> &'hir [hir::GenericParam<'hir>] { - let mut generic_params: Vec<_> = self - .lower_generic_params_mut(generic_params, hir::GenericParamSource::Binder) - .collect(); + // Start by creating params for extra lifetimes params, as this creates the definitions + // that may be referred to by the AST inside `generic_params`. let extra_lifetimes = self.resolver.extra_lifetime_params(binder); debug!(?extra_lifetimes); - generic_params.extend(extra_lifetimes.into_iter().filter_map(|(ident, node_id, res)| { - self.lifetime_res_to_generic_param(ident, node_id, res, hir::GenericParamSource::Binder) - })); - let generic_params = self.arena.alloc_from_iter(generic_params); - debug!(?generic_params); - - generic_params + let extra_lifetimes: Vec<_> = extra_lifetimes + .into_iter() + .filter_map(|(ident, node_id, res)| { + self.lifetime_res_to_generic_param( + ident, + node_id, + res, + hir::GenericParamSource::Binder, + ) + }) + .collect(); + let arena = self.arena; + let explicit_generic_params = + self.lower_generic_params_mut(generic_params, hir::GenericParamSource::Binder); + arena.alloc_from_iter(explicit_generic_params.chain(extra_lifetimes.into_iter())) } fn with_dyn_type_scope<T>(&mut self, in_scope: bool, f: impl FnOnce(&mut Self) -> T) -> T { @@ -1084,10 +1109,9 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { &*self.arena.alloc(self.ty(constraint.span, hir::TyKind::Err(guar))); hir::AssocItemConstraintKind::Equality { term: err_ty.into() } } else { - // Desugar `AssocTy: Bounds` into an assoc type binding where the - // later desugars into a trait predicate. - let bounds = self.lower_param_bounds(bounds, itctx); - + // FIXME(#135229): These should be forbidden! + let bounds = + self.lower_param_bounds(bounds, RelaxedBoundPolicy::Allowed, itctx); hir::AssocItemConstraintKind::Bound { bounds } } } @@ -1216,6 +1240,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { span: t.span, parens: ast::Parens::No, }, + RelaxedBoundPolicy::Forbidden(RelaxedBoundForbiddenReason::TraitObjectTy), itctx, ); let bounds = this.arena.alloc_from_iter([bound]); @@ -1271,7 +1296,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { parenthesized: hir::GenericArgsParentheses::No, span_ext: span, }); - let path = self.make_lang_item_qpath(LangItem::Pin, span, Some(args)); + let path = self.make_lang_item_qpath(hir::LangItem::Pin, span, Some(args)); hir::TyKind::Path(path) } TyKind::FnPtr(f) => { @@ -1332,7 +1357,13 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { // takes care of rejecting invalid modifier combinations and // const trait bounds in trait object types. GenericBound::Trait(ty) => { - let trait_ref = this.lower_poly_trait_ref(ty, itctx); + let trait_ref = this.lower_poly_trait_ref( + ty, + RelaxedBoundPolicy::Forbidden( + RelaxedBoundForbiddenReason::TraitObjectTy, + ), + itctx, + ); Some(trait_ref) } GenericBound::Outlives(lifetime) => { @@ -1387,9 +1418,9 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } path } - ImplTraitContext::InBinding => { - hir::TyKind::TraitAscription(self.lower_param_bounds(bounds, itctx)) - } + ImplTraitContext::InBinding => hir::TyKind::TraitAscription( + self.lower_param_bounds(bounds, RelaxedBoundPolicy::Allowed, itctx), + ), ImplTraitContext::FeatureGated(position, feature) => { let guar = self .tcx @@ -1505,7 +1536,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::OpaqueTy, span, None); self.lower_opaque_inner(opaque_ty_node_id, origin, opaque_ty_span, |this| { - this.lower_param_bounds(bounds, itctx) + this.lower_param_bounds(bounds, RelaxedBoundPolicy::Allowed, itctx) }) } @@ -1799,10 +1830,13 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { fn lower_param_bound( &mut self, tpb: &GenericBound, + rbp: RelaxedBoundPolicy<'_>, itctx: ImplTraitContext, ) -> hir::GenericBound<'hir> { match tpb { - GenericBound::Trait(p) => hir::GenericBound::Trait(self.lower_poly_trait_ref(p, itctx)), + GenericBound::Trait(p) => { + hir::GenericBound::Trait(self.lower_poly_trait_ref(p, rbp, itctx)) + } GenericBound::Outlives(lifetime) => hir::GenericBound::Outlives(self.lower_lifetime( lifetime, LifetimeSource::OutlivesBound, @@ -2017,21 +2051,93 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { #[instrument(level = "debug", skip(self))] fn lower_poly_trait_ref( &mut self, - p: &PolyTraitRef, + PolyTraitRef { bound_generic_params, modifiers, trait_ref, span, parens: _ }: &PolyTraitRef, + rbp: RelaxedBoundPolicy<'_>, itctx: ImplTraitContext, ) -> hir::PolyTraitRef<'hir> { let bound_generic_params = - self.lower_lifetime_binder(p.trait_ref.ref_id, &p.bound_generic_params); - let trait_ref = self.lower_trait_ref(p.modifiers, &p.trait_ref, itctx); - let modifiers = self.lower_trait_bound_modifiers(p.modifiers); + self.lower_lifetime_binder(trait_ref.ref_id, bound_generic_params); + let trait_ref = self.lower_trait_ref(*modifiers, trait_ref, itctx); + let modifiers = self.lower_trait_bound_modifiers(*modifiers); + + if let ast::BoundPolarity::Maybe(_) = modifiers.polarity { + self.validate_relaxed_bound(trait_ref, *span, rbp); + } + hir::PolyTraitRef { bound_generic_params, modifiers, trait_ref, - span: self.lower_span(p.span), + span: self.lower_span(*span), } } + fn validate_relaxed_bound( + &self, + trait_ref: hir::TraitRef<'_>, + span: Span, + rbp: RelaxedBoundPolicy<'_>, + ) { + // Even though feature `more_maybe_bounds` bypasses the given policy and (currently) enables + // relaxed bounds in every conceivable position[^1], we don't want to advertise it to the user + // (via a feature gate) since it's super internal. Besides this, it'd be quite distracting. + // + // [^1]: Strictly speaking, this is incorrect (at the very least for `Sized`) because it's + // no longer fully consistent with default trait elaboration in HIR ty lowering. + + match rbp { + RelaxedBoundPolicy::Allowed => return, + RelaxedBoundPolicy::AllowedIfOnTyParam(id, params) => { + if let Some(res) = self.resolver.get_partial_res(id).and_then(|r| r.full_res()) + && let Res::Def(DefKind::TyParam, def_id) = res + && params.iter().any(|p| def_id == self.local_def_id(p.id).to_def_id()) + { + return; + } + if self.tcx.features().more_maybe_bounds() { + return; + } + } + RelaxedBoundPolicy::Forbidden(reason) => { + if self.tcx.features().more_maybe_bounds() { + return; + } + + match reason { + RelaxedBoundForbiddenReason::TraitObjectTy => { + self.dcx().span_err( + span, + "relaxed bounds are not permitted in trait object types", + ); + return; + } + RelaxedBoundForbiddenReason::SuperTrait => { + let mut diag = self.dcx().struct_span_err( + span, + "relaxed bounds are not permitted in supertrait bounds", + ); + if let Some(def_id) = trait_ref.trait_def_id() + && self.tcx.is_lang_item(def_id, hir::LangItem::Sized) + { + diag.note("traits are `?Sized` by default"); + } + diag.emit(); + return; + } + RelaxedBoundForbiddenReason::LateBoundVarsInScope => {} + }; + } + } + + self.dcx() + .struct_span_err(span, "this relaxed bound is not permitted here") + .with_note( + "in this context, relaxed bounds are only allowed on \ + type parameters defined by the closest item", + ) + .emit(); + } + fn lower_mt(&mut self, mt: &MutTy, itctx: ImplTraitContext) -> hir::MutTy<'hir> { hir::MutTy { ty: self.lower_ty(&mt.ty, itctx), mutbl: mt.mutbl } } @@ -2040,17 +2146,19 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { fn lower_param_bounds( &mut self, bounds: &[GenericBound], + rbp: RelaxedBoundPolicy<'_>, itctx: ImplTraitContext, ) -> hir::GenericBounds<'hir> { - self.arena.alloc_from_iter(self.lower_param_bounds_mut(bounds, itctx)) + self.arena.alloc_from_iter(self.lower_param_bounds_mut(bounds, rbp, itctx)) } fn lower_param_bounds_mut( &mut self, bounds: &[GenericBound], + rbp: RelaxedBoundPolicy<'_>, itctx: ImplTraitContext, ) -> impl Iterator<Item = hir::GenericBound<'hir>> { - bounds.iter().map(move |bound| self.lower_param_bound(bound, itctx)) + bounds.iter().map(move |bound| self.lower_param_bound(bound, rbp, itctx)) } #[instrument(level = "debug", skip(self), ret)] @@ -2084,6 +2192,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { bounds, /* colon_span */ None, span, + RelaxedBoundPolicy::Allowed, ImplTraitContext::Universal, hir::PredicateOrigin::ImplTrait, ); diff --git a/compiler/rustc_ast_passes/messages.ftl b/compiler/rustc_ast_passes/messages.ftl index e419154d65d..af93d55c898 100644 --- a/compiler/rustc_ast_passes/messages.ftl +++ b/compiler/rustc_ast_passes/messages.ftl @@ -212,11 +212,6 @@ ast_passes_nomangle_ascii = `#[no_mangle]` requires ASCII identifier ast_passes_obsolete_auto = `impl Trait for .. {"{}"}` is an obsolete syntax .help = use `auto trait Trait {"{}"}` instead -ast_passes_optional_trait_object = `?Trait` is not permitted in trait object types - -ast_passes_optional_trait_supertrait = `?Trait` is not permitted in supertraits - .note = traits are `?{$path_str}` by default - ast_passes_out_of_order_params = {$param_ord} parameters must be declared prior to {$max_param} parameters .suggestion = reorder the parameters: lifetimes, then consts and types diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs index c69250c0305..a08dae11153 100644 --- a/compiler/rustc_ast_passes/src/ast_validation.rs +++ b/compiler/rustc_ast_passes/src/ast_validation.rs @@ -1381,29 +1381,6 @@ impl<'a> Visitor<'a> for AstValidator<'a> { match bound { GenericBound::Trait(trait_ref) => { match (ctxt, trait_ref.modifiers.constness, trait_ref.modifiers.polarity) { - (BoundKind::SuperTraits, BoundConstness::Never, BoundPolarity::Maybe(_)) - if !self.features.more_maybe_bounds() => - { - self.sess - .create_feature_err( - errors::OptionalTraitSupertrait { - span: trait_ref.span, - path_str: pprust::path_to_string(&trait_ref.trait_ref.path), - }, - sym::more_maybe_bounds, - ) - .emit(); - } - (BoundKind::TraitObject, BoundConstness::Never, BoundPolarity::Maybe(_)) - if !self.features.more_maybe_bounds() => - { - self.sess - .create_feature_err( - errors::OptionalTraitObject { span: trait_ref.span }, - sym::more_maybe_bounds, - ) - .emit(); - } ( BoundKind::TraitObject, BoundConstness::Always(_), diff --git a/compiler/rustc_ast_passes/src/errors.rs b/compiler/rustc_ast_passes/src/errors.rs index c1ebd025c7a..fd4b2528541 100644 --- a/compiler/rustc_ast_passes/src/errors.rs +++ b/compiler/rustc_ast_passes/src/errors.rs @@ -567,22 +567,6 @@ pub(crate) struct NestedLifetimes { } #[derive(Diagnostic)] -#[diag(ast_passes_optional_trait_supertrait)] -#[note] -pub(crate) struct OptionalTraitSupertrait { - #[primary_span] - pub span: Span, - pub path_str: String, -} - -#[derive(Diagnostic)] -#[diag(ast_passes_optional_trait_object)] -pub(crate) struct OptionalTraitObject { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] #[diag(ast_passes_const_bound_trait_object)] pub(crate) struct ConstBoundTraitObject { #[primary_span] diff --git a/compiler/rustc_attr_data_structures/src/encode_cross_crate.rs b/compiler/rustc_attr_data_structures/src/encode_cross_crate.rs index 8a3eb2ac845..86d9ddba4d2 100644 --- a/compiler/rustc_attr_data_structures/src/encode_cross_crate.rs +++ b/compiler/rustc_attr_data_structures/src/encode_cross_crate.rs @@ -41,9 +41,9 @@ impl AttributeKind { Fundamental { .. } => Yes, Ignore { .. } => No, Inline(..) => No, - LinkName { .. } => Yes, + LinkName { .. } => Yes, // Needed for rustdoc LinkOrdinal { .. } => No, - LinkSection { .. } => No, + LinkSection { .. } => Yes, // Needed for rustdoc LoopMatch(..) => No, MacroTransparency(..) => Yes, Marker(..) => No, @@ -51,8 +51,8 @@ impl AttributeKind { MustUse { .. } => Yes, Naked(..) => No, NoImplicitPrelude(..) => No, - NoMangle(..) => No, - NonExhaustive(..) => Yes, + NoMangle(..) => Yes, // Needed for rustdoc + NonExhaustive(..) => Yes, // Needed for rustdoc OmitGdbPrettyPrinterSection => No, Optimize(..) => No, ParenSugar(..) => No, diff --git a/compiler/rustc_attr_data_structures/src/lib.rs b/compiler/rustc_attr_data_structures/src/lib.rs index 8f8ce575a18..ecca0e39063 100644 --- a/compiler/rustc_attr_data_structures/src/lib.rs +++ b/compiler/rustc_attr_data_structures/src/lib.rs @@ -24,7 +24,7 @@ use rustc_ast::token::CommentKind; use rustc_ast::{AttrStyle, IntTy, UintTy}; use rustc_ast_pretty::pp::Printer; use rustc_span::hygiene::Transparency; -use rustc_span::{Span, Symbol}; +use rustc_span::{ErrorGuaranteed, Span, Symbol}; pub use stability::*; use thin_vec::ThinVec; pub use version::*; @@ -170,7 +170,7 @@ macro_rules! print_tup { } print_tup!(A B C D E F G H); -print_skip!(Span, ()); +print_skip!(Span, (), ErrorGuaranteed); print_disp!(u16, bool, NonZero<u32>); print_debug!(Symbol, UintTy, IntTy, Align, AttrStyle, CommentKind, Transparency); diff --git a/compiler/rustc_attr_data_structures/src/stability.rs b/compiler/rustc_attr_data_structures/src/stability.rs index 218e771c745..bd31c062117 100644 --- a/compiler/rustc_attr_data_structures/src/stability.rs +++ b/compiler/rustc_attr_data_structures/src/stability.rs @@ -1,7 +1,7 @@ use std::num::NonZero; use rustc_macros::{Decodable, Encodable, HashStable_Generic, PrintAttribute}; -use rustc_span::{Symbol, sym}; +use rustc_span::{ErrorGuaranteed, Symbol, sym}; use crate::{PrintAttribute, RustcVersion}; @@ -153,7 +153,7 @@ pub enum StableSince { /// Stabilized in the upcoming version, whatever number that is. Current, /// Failed to parse a stabilization version. - Err, + Err(ErrorGuaranteed), } impl StabilityLevel { diff --git a/compiler/rustc_attr_parsing/src/attributes/stability.rs b/compiler/rustc_attr_parsing/src/attributes/stability.rs index 8f405e5aad9..59337749c87 100644 --- a/compiler/rustc_attr_parsing/src/attributes/stability.rs +++ b/compiler/rustc_attr_parsing/src/attributes/stability.rs @@ -292,12 +292,12 @@ pub(crate) fn parse_stability<S: Stage>( } else if let Some(version) = parse_version(since) { StableSince::Version(version) } else { - cx.emit_err(session_diagnostics::InvalidSince { span: cx.attr_span }); - StableSince::Err + let err = cx.emit_err(session_diagnostics::InvalidSince { span: cx.attr_span }); + StableSince::Err(err) } } else { - cx.emit_err(session_diagnostics::MissingSince { span: cx.attr_span }); - StableSince::Err + let err = cx.emit_err(session_diagnostics::MissingSince { span: cx.attr_span }); + StableSince::Err(err) }; match feature { diff --git a/compiler/rustc_codegen_cranelift/example/float-minmax-pass.rs b/compiler/rustc_codegen_cranelift/example/float-minmax-pass.rs index ad46e18c11c..b7491b7e522 100644 --- a/compiler/rustc_codegen_cranelift/example/float-minmax-pass.rs +++ b/compiler/rustc_codegen_cranelift/example/float-minmax-pass.rs @@ -11,6 +11,12 @@ #[derive(Copy, Clone, PartialEq, Debug)] struct f32x4(pub [f32; 4]); +impl f32x4 { + fn into_array(self) -> [f32; 4] { + unsafe { std::mem::transmute(self) } + } +} + use std::intrinsics::simd::*; fn main() { @@ -29,22 +35,22 @@ fn main() { unsafe { let min0 = simd_fmin(x, y); let min1 = simd_fmin(y, x); - assert_eq!(min0, min1); + assert_eq!(min0.into_array(), min1.into_array()); let e = f32x4([1.0, 1.0, 3.0, 3.0]); - assert_eq!(min0, e); + assert_eq!(min0.into_array(), e.into_array()); let minn = simd_fmin(x, n); - assert_eq!(minn, x); + assert_eq!(minn.into_array(), x.into_array()); let minn = simd_fmin(y, n); - assert_eq!(minn, y); + assert_eq!(minn.into_array(), y.into_array()); let max0 = simd_fmax(x, y); let max1 = simd_fmax(y, x); - assert_eq!(max0, max1); + assert_eq!(max0.into_array(), max1.into_array()); let e = f32x4([2.0, 2.0, 4.0, 4.0]); - assert_eq!(max0, e); + assert_eq!(max0.into_array(), e.into_array()); let maxn = simd_fmax(x, n); - assert_eq!(maxn, x); + assert_eq!(maxn.into_array(), x.into_array()); let maxn = simd_fmax(y, n); - assert_eq!(maxn, y); + assert_eq!(maxn.into_array(), y.into_array()); } } diff --git a/compiler/rustc_codegen_cranelift/example/mini_core_hello_world.rs b/compiler/rustc_codegen_cranelift/example/mini_core_hello_world.rs index 246bd3104ec..86602c6b2a3 100644 --- a/compiler/rustc_codegen_cranelift/example/mini_core_hello_world.rs +++ b/compiler/rustc_codegen_cranelift/example/mini_core_hello_world.rs @@ -348,7 +348,8 @@ fn main() { struct V([f64; 2]); let f = V([0.0, 1.0]); - let _a = f.0[0]; + let fp = (&raw const f) as *const [f64; 2]; + let _a = (unsafe { &*fp })[0]; stack_val_align(); } diff --git a/compiler/rustc_codegen_gcc/.github/workflows/m68k.yml b/compiler/rustc_codegen_gcc/.github/workflows/m68k.yml index 245bee7f2a3..759d0d59e26 100644 --- a/compiler/rustc_codegen_gcc/.github/workflows/m68k.yml +++ b/compiler/rustc_codegen_gcc/.github/workflows/m68k.yml @@ -14,8 +14,6 @@ permissions: env: # Enable backtraces for easier debugging RUST_BACKTRACE: 1 - # TODO: remove when confish.sh is removed. - OVERWRITE_TARGET_TRIPLE: m68k-unknown-linux-gnu jobs: build: @@ -59,14 +57,12 @@ jobs: - name: Setup path to libgccjit run: | - sudo dpkg -i gcc-m68k-15.deb + sudo dpkg --force-overwrite -i gcc-m68k-15.deb echo 'gcc-path = "/usr/lib/"' > config.toml - name: Set env run: | echo "workspace="$GITHUB_WORKSPACE >> $GITHUB_ENV - - #- name: Cache rust repository ## We only clone the rust repository for rustc tests @@ -86,16 +82,20 @@ jobs: - name: Build sample project with target defined as JSON spec run: | ./y.sh prepare --only-libcore --cross - ./y.sh build --sysroot --features compiler_builtins/no-f16-f128 --target-triple m68k-unknown-linux-gnu --target ${{ github.workspace }}/target_specs/m68k-unknown-linux-gnu.json - ./y.sh cargo build --manifest-path=./tests/hello-world/Cargo.toml --target ${{ github.workspace }}/target_specs/m68k-unknown-linux-gnu.json + ./y.sh build --sysroot --features compiler-builtins-no-f16-f128 --target-triple m68k-unknown-linux-gnu --target ${{ github.workspace }}/target_specs/m68k-unknown-linux-gnu.json + CG_RUSTFLAGS="-Clinker=m68k-unknown-linux-gnu-gcc" ./y.sh cargo build --manifest-path=./tests/hello-world/Cargo.toml --target ${{ github.workspace }}/target_specs/m68k-unknown-linux-gnu.json ./y.sh clean all - name: Build run: | ./y.sh prepare --only-libcore --cross - ./y.sh build --sysroot --features compiler_builtins/no-f16-f128 --target-triple m68k-unknown-linux-gnu - ./y.sh test --mini-tests - CG_GCC_TEST_TARGET=m68k-unknown-linux-gnu ./y.sh test --cargo-tests + ./y.sh build --sysroot --features compiler-builtins-no-f16-f128 --target-triple m68k-unknown-linux-gnu + ./y.sh test --mini-tests --target-triple m68k-unknown-linux-gnu + # FIXME: since https://github.com/rust-lang/rust/pull/140809, we cannot run programs for architectures not + # supported by the object crate, since this adds a dependency on symbols.o for the panic runtime. + # And as such, a wrong order of the object files in the linker command now fails with an undefined reference + # to some symbols like __rustc::rust_panic. + #CG_GCC_TEST_TARGET=m68k-unknown-linux-gnu ./y.sh test --cargo-tests --target-triple m68k-unknown-linux-gnu ./y.sh clean all - name: Prepare dependencies @@ -104,9 +104,23 @@ jobs: git config --global user.name "User" ./y.sh prepare --cross - - name: Run tests - run: | - ./y.sh test --release --clean --build-sysroot --sysroot-features compiler_builtins/no-f16-f128 ${{ matrix.commands }} + # FIXME: We cannot run programs for architectures not supported by the object crate. See comment above. + #- name: Run tests + #run: | + #./y.sh test --target-triple m68k-unknown-linux-gnu --release --clean --build-sysroot --sysroot-features compiler-builtins-no-f16-f128 ${{ matrix.commands }} + + # FIXME: We cannot run programs for architectures not supported by the object crate. See comment above. + #- name: Run Hello World! + #run: | + #./y.sh build --target-triple m68k-unknown-linux-gnu + + #vm_dir=$(pwd)/vm + #cd tests/hello-world + #CG_RUSTFLAGS="-Clinker=m68k-unknown-linux-gnu-gcc" ../../y.sh cargo build --target m68k-unknown-linux-gnu + #sudo cp target/m68k-unknown-linux-gnu/debug/hello_world $vm_dir/home/ + #sudo chroot $vm_dir qemu-m68k-static /home/hello_world > hello_world_stdout + #expected_output="40" + #test $(cat hello_world_stdout) == $expected_output || (echo "Output differs. Actual output: $(cat hello_world_stdout)"; exit 1) # Summary job for the merge queue. # ALL THE PREVIOUS JOBS NEED TO BE ADDED TO THE `needs` SECTION OF THIS JOB! diff --git a/compiler/rustc_codegen_gcc/.github/workflows/release.yml b/compiler/rustc_codegen_gcc/.github/workflows/release.yml index 1d8eaf9a141..b7e2583aad3 100644 --- a/compiler/rustc_codegen_gcc/.github/workflows/release.yml +++ b/compiler/rustc_codegen_gcc/.github/workflows/release.yml @@ -78,7 +78,8 @@ jobs: - name: Run tests run: | # FIXME(antoyo): we cannot enable LTO for stdarch tests currently because of some failing LTO tests using proc-macros. - echo -n 'lto = "fat"' >> build_system/build_sysroot/Cargo.toml + # FIXME(antoyo): this should probably not be needed since we embed the LTO bitcode. + printf '[profile.release]\nlto = "fat"\n' >> build/build_sysroot/sysroot_src/library/Cargo.toml EMBED_LTO_BITCODE=1 ./y.sh test --release --clean --release-sysroot --build-sysroot --keep-lto-tests ${{ matrix.commands }} - name: Run y.sh cargo build diff --git a/compiler/rustc_codegen_gcc/build_system/build_sysroot/Cargo.lock b/compiler/rustc_codegen_gcc/build_system/build_sysroot/Cargo.lock deleted file mode 100644 index 0c75977ee79..00000000000 --- a/compiler/rustc_codegen_gcc/build_system/build_sysroot/Cargo.lock +++ /dev/null @@ -1,502 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 4 - -[[package]] -name = "addr2line" -version = "0.24.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfbe277e56a376000877090da837660b4427aad530e3028d44e0bffe4f89a1c1" -dependencies = [ - "compiler_builtins", - "gimli", - "rustc-std-workspace-alloc", - "rustc-std-workspace-core", -] - -[[package]] -name = "adler2" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627" -dependencies = [ - "compiler_builtins", - "rustc-std-workspace-core", -] - -[[package]] -name = "alloc" -version = "0.0.0" -dependencies = [ - "compiler_builtins", - "core", -] - -[[package]] -name = "alloctests" -version = "0.0.0" -dependencies = [ - "rand", - "rand_xorshift", -] - -[[package]] -name = "cc" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aeb932158bd710538c73702db6945cb68a8fb08c519e6e12706b94263b36db8" -dependencies = [ - "shlex", -] - -[[package]] -name = "cfg-if" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" -dependencies = [ - "compiler_builtins", - "rustc-std-workspace-core", -] - -[[package]] -name = "compiler_builtins" -version = "0.1.160" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6376049cfa92c0aa8b9ac95fae22184b981c658208d4ed8a1dc553cd83612895" -dependencies = [ - "cc", - "rustc-std-workspace-core", -] - -[[package]] -name = "core" -version = "0.0.0" - -[[package]] -name = "coretests" -version = "0.0.0" -dependencies = [ - "rand", - "rand_xorshift", -] - -[[package]] -name = "dlmalloc" -version = "0.2.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8cff88b751e7a276c4ab0e222c3f355190adc6dde9ce39c851db39da34990df7" -dependencies = [ - "cfg-if", - "compiler_builtins", - "libc", - "rustc-std-workspace-core", - "windows-sys", -] - -[[package]] -name = "fortanix-sgx-abi" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57cafc2274c10fab234f176b25903ce17e690fca7597090d50880e047a0389c5" -dependencies = [ - "compiler_builtins", - "rustc-std-workspace-core", -] - -[[package]] -name = "getopts" -version = "0.2.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14dbbfd5c71d70241ecf9e6f13737f7b5ce823821063188d7e46c41d371eebd5" -dependencies = [ - "rustc-std-workspace-core", - "rustc-std-workspace-std", - "unicode-width", -] - -[[package]] -name = "gimli" -version = "0.31.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f" -dependencies = [ - "compiler_builtins", - "rustc-std-workspace-alloc", - "rustc-std-workspace-core", -] - -[[package]] -name = "hashbrown" -version = "0.15.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "84b26c544d002229e640969970a2e74021aadf6e2f96372b9c58eff97de08eb3" -dependencies = [ - "compiler_builtins", - "rustc-std-workspace-alloc", - "rustc-std-workspace-core", -] - -[[package]] -name = "hermit-abi" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f154ce46856750ed433c8649605bf7ed2de3bc35fd9d2a9f30cddd873c80cb08" -dependencies = [ - "compiler_builtins", - "rustc-std-workspace-alloc", - "rustc-std-workspace-core", -] - -[[package]] -name = "libc" -version = "0.2.172" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d750af042f7ef4f724306de029d18836c26c1765a54a6a3f094cbd23a7267ffa" -dependencies = [ - "rustc-std-workspace-core", -] - -[[package]] -name = "memchr" -version = "2.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" -dependencies = [ - "compiler_builtins", - "rustc-std-workspace-core", -] - -[[package]] -name = "miniz_oxide" -version = "0.8.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3be647b768db090acb35d5ec5db2b0e1f1de11133ca123b9eacf5137868f892a" -dependencies = [ - "adler2", - "compiler_builtins", - "rustc-std-workspace-alloc", - "rustc-std-workspace-core", -] - -[[package]] -name = "object" -version = "0.36.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62948e14d923ea95ea2c7c86c71013138b66525b86bdc08d2dcc262bdb497b87" -dependencies = [ - "compiler_builtins", - "memchr", - "rustc-std-workspace-alloc", - "rustc-std-workspace-core", -] - -[[package]] -name = "panic_abort" -version = "0.0.0" -dependencies = [ - "alloc", - "compiler_builtins", - "core", - "libc", -] - -[[package]] -name = "panic_unwind" -version = "0.0.0" -dependencies = [ - "alloc", - "cfg-if", - "compiler_builtins", - "core", - "libc", - "unwind", -] - -[[package]] -name = "proc_macro" -version = "0.0.0" -dependencies = [ - "core", - "rustc-literal-escaper", - "std", -] - -[[package]] -name = "profiler_builtins" -version = "0.0.0" -dependencies = [ - "cc", -] - -[[package]] -name = "r-efi" -version = "5.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74765f6d916ee2faa39bc8e68e4f3ed8949b48cccdac59983d287a7cb71ce9c5" -dependencies = [ - "compiler_builtins", - "rustc-std-workspace-core", -] - -[[package]] -name = "r-efi-alloc" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e43c53ff1a01d423d1cb762fd991de07d32965ff0ca2e4f80444ac7804198203" -dependencies = [ - "compiler_builtins", - "r-efi", - "rustc-std-workspace-core", -] - -[[package]] -name = "rand" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fbfd9d094a40bf3ae768db9361049ace4c0e04a4fd6b359518bd7b73a73dd97" -dependencies = [ - "rand_core", -] - -[[package]] -name = "rand_core" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38" - -[[package]] -name = "rand_xorshift" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a" -dependencies = [ - "rand_core", -] - -[[package]] -name = "rustc-demangle" -version = "0.1.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" -dependencies = [ - "compiler_builtins", - "rustc-std-workspace-core", -] - -[[package]] -name = "rustc-literal-escaper" -version = "0.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0041b6238913c41fe704213a4a9329e2f685a156d1781998128b4149c230ad04" -dependencies = [ - "rustc-std-workspace-std", -] - -[[package]] -name = "rustc-std-workspace-alloc" -version = "1.99.0" -dependencies = [ - "alloc", -] - -[[package]] -name = "rustc-std-workspace-core" -version = "1.99.0" -dependencies = [ - "core", -] - -[[package]] -name = "rustc-std-workspace-std" -version = "1.99.0" -dependencies = [ - "std", -] - -[[package]] -name = "shlex" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" - -[[package]] -name = "std" -version = "0.0.0" -dependencies = [ - "addr2line", - "alloc", - "cfg-if", - "compiler_builtins", - "core", - "dlmalloc", - "fortanix-sgx-abi", - "hashbrown", - "hermit-abi", - "libc", - "miniz_oxide", - "object", - "panic_abort", - "panic_unwind", - "r-efi", - "r-efi-alloc", - "rand", - "rand_xorshift", - "rustc-demangle", - "std_detect", - "unwind", - "wasi", - "windows-targets 0.0.0", -] - -[[package]] -name = "std_detect" -version = "0.1.5" -dependencies = [ - "cfg-if", - "compiler_builtins", - "libc", - "rustc-std-workspace-alloc", - "rustc-std-workspace-core", -] - -[[package]] -name = "sysroot" -version = "0.0.0" -dependencies = [ - "proc_macro", - "profiler_builtins", - "std", - "test", -] - -[[package]] -name = "test" -version = "0.0.0" -dependencies = [ - "core", - "getopts", - "libc", - "std", -] - -[[package]] -name = "unicode-width" -version = "0.1.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" -dependencies = [ - "compiler_builtins", - "rustc-std-workspace-core", - "rustc-std-workspace-std", -] - -[[package]] -name = "unwind" -version = "0.0.0" -dependencies = [ - "cfg-if", - "compiler_builtins", - "core", - "libc", - "unwinding", -] - -[[package]] -name = "unwinding" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8393f2782b6060a807337ff353780c1ca15206f9ba2424df18cb6e733bd7b345" -dependencies = [ - "compiler_builtins", - "gimli", - "rustc-std-workspace-core", -] - -[[package]] -name = "wasi" -version = "0.11.0+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" -dependencies = [ - "compiler_builtins", - "rustc-std-workspace-alloc", - "rustc-std-workspace-core", -] - -[[package]] -name = "windows-sys" -version = "0.59.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" -dependencies = [ - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-targets" -version = "0.0.0" - -[[package]] -name = "windows-targets" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" -dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" - -[[package]] -name = "windows_i686_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" - -[[package]] -name = "windows_i686_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" diff --git a/compiler/rustc_codegen_gcc/build_system/build_sysroot/Cargo.toml b/compiler/rustc_codegen_gcc/build_system/build_sysroot/Cargo.toml deleted file mode 100644 index 29a3bcec304..00000000000 --- a/compiler/rustc_codegen_gcc/build_system/build_sysroot/Cargo.toml +++ /dev/null @@ -1,39 +0,0 @@ -[package] -authors = ["rustc_codegen_gcc devs"] -name = "sysroot" -version = "0.0.0" -resolver = "2" - -[dependencies] -core = { path = "./sysroot_src/library/core" } -compiler_builtins = { path = "./sysroot_src/library/compiler-builtins/compiler-builtins" } -alloc = { path = "./sysroot_src/library/alloc" } -std = { path = "./sysroot_src/library/std", features = ["panic_unwind", "backtrace"] } -test = { path = "./sysroot_src/library/test" } -proc_macro = { path = "./sysroot_src/library/proc_macro" } - -[patch.crates-io] -rustc-std-workspace-core = { path = "./sysroot_src/library/rustc-std-workspace-core" } -rustc-std-workspace-alloc = { path = "./sysroot_src/library/rustc-std-workspace-alloc" } -rustc-std-workspace-std = { path = "./sysroot_src/library/rustc-std-workspace-std" } -compiler_builtins = { path = "./sysroot_src/library/compiler-builtins/compiler-builtins" } - -# For compiler-builtins we always use a high number of codegen units. -# The goal here is to place every single intrinsic into its own object -# file to avoid symbol clashes with the system libgcc if possible. Note -# that this number doesn't actually produce this many object files, we -# just don't create more than this number of object files. -# -# It's a bit of a bummer that we have to pass this here, unfortunately. -# Ideally this would be specified through an env var to Cargo so Cargo -# knows how many CGUs are for this specific crate, but for now -# per-crate configuration isn't specifiable in the environment. -[profile.dev.package.compiler_builtins] -codegen-units = 10000 - -[profile.release.package.compiler_builtins] -codegen-units = 10000 - -[profile.release] -debug = "limited" -#lto = "fat" # TODO(antoyo): re-enable when the failing LTO tests regarding proc-macros are fixed. diff --git a/compiler/rustc_codegen_gcc/build_system/build_sysroot/lib.rs b/compiler/rustc_codegen_gcc/build_system/build_sysroot/lib.rs deleted file mode 100644 index 0c9ac1ac8e4..00000000000 --- a/compiler/rustc_codegen_gcc/build_system/build_sysroot/lib.rs +++ /dev/null @@ -1 +0,0 @@ -#![no_std] diff --git a/compiler/rustc_codegen_gcc/build_system/src/build.rs b/compiler/rustc_codegen_gcc/build_system/src/build.rs index ecc4c1b2fe2..94b40319f4a 100644 --- a/compiler/rustc_codegen_gcc/build_system/src/build.rs +++ b/compiler/rustc_codegen_gcc/build_system/src/build.rs @@ -5,7 +5,7 @@ use std::path::Path; use crate::config::{Channel, ConfigInfo}; use crate::utils::{ - copy_file, create_dir, get_sysroot_dir, run_command, run_command_with_output_and_env, walk_dir, + create_dir, get_sysroot_dir, run_command, run_command_with_output_and_env, walk_dir, }; #[derive(Default)] @@ -53,11 +53,11 @@ impl BuildArg { } } -fn cleanup_sysroot_previous_build(start_dir: &Path) { +fn cleanup_sysroot_previous_build(library_dir: &Path) { // Cleanup for previous run // Clean target dir except for build scripts and incremental cache let _ = walk_dir( - start_dir.join("target"), + library_dir.join("target"), &mut |dir: &Path| { for top in &["debug", "release"] { let _ = fs::remove_dir_all(dir.join(top).join("build")); @@ -95,31 +95,13 @@ fn cleanup_sysroot_previous_build(start_dir: &Path) { &mut |_| Ok(()), false, ); - - let _ = fs::remove_file(start_dir.join("Cargo.lock")); - let _ = fs::remove_file(start_dir.join("test_target/Cargo.lock")); - let _ = fs::remove_dir_all(start_dir.join("sysroot")); -} - -pub fn create_build_sysroot_content(start_dir: &Path) -> Result<(), String> { - if !start_dir.is_dir() { - create_dir(start_dir)?; - } - copy_file("build_system/build_sysroot/Cargo.toml", start_dir.join("Cargo.toml"))?; - copy_file("build_system/build_sysroot/Cargo.lock", start_dir.join("Cargo.lock"))?; - - let src_dir = start_dir.join("src"); - if !src_dir.is_dir() { - create_dir(&src_dir)?; - } - copy_file("build_system/build_sysroot/lib.rs", start_dir.join("src/lib.rs")) } pub fn build_sysroot(env: &HashMap<String, String>, config: &ConfigInfo) -> Result<(), String> { let start_dir = get_sysroot_dir(); - cleanup_sysroot_previous_build(&start_dir); - create_build_sysroot_content(&start_dir)?; + let library_dir = start_dir.join("sysroot_src").join("library"); + cleanup_sysroot_previous_build(&library_dir); // Builds libs let mut rustflags = env.get("RUSTFLAGS").cloned().unwrap_or_default(); @@ -157,9 +139,13 @@ pub fn build_sysroot(env: &HashMap<String, String>, config: &ConfigInfo) -> Resu rustflags.push_str(&cg_rustflags); } + args.push(&"--features"); + args.push(&"backtrace"); + let mut env = env.clone(); env.insert("RUSTFLAGS".to_string(), rustflags); - run_command_with_output_and_env(&args, Some(&start_dir), Some(&env))?; + let sysroot_dir = library_dir.join("sysroot"); + run_command_with_output_and_env(&args, Some(&sysroot_dir), Some(&env))?; // Copy files to sysroot let sysroot_path = start_dir.join(format!("sysroot/lib/rustlib/{}/lib/", config.target_triple)); @@ -169,7 +155,7 @@ pub fn build_sysroot(env: &HashMap<String, String>, config: &ConfigInfo) -> Resu run_command(&[&"cp", &"-r", &dir_to_copy, &sysroot_path], None).map(|_| ()) }; walk_dir( - start_dir.join(format!("target/{}/{}/deps", config.target_triple, channel)), + library_dir.join(format!("target/{}/{}/deps", config.target_triple, channel)), &mut copier.clone(), &mut copier, false, @@ -178,7 +164,7 @@ pub fn build_sysroot(env: &HashMap<String, String>, config: &ConfigInfo) -> Resu // Copy the source files to the sysroot (Rust for Linux needs this). let sysroot_src_path = start_dir.join("sysroot/lib/rustlib/src/rust"); create_dir(&sysroot_src_path)?; - run_command(&[&"cp", &"-r", &start_dir.join("sysroot_src/library/"), &sysroot_src_path], None)?; + run_command(&[&"cp", &"-r", &library_dir, &sysroot_src_path], None)?; Ok(()) } diff --git a/compiler/rustc_codegen_gcc/build_system/src/config.rs b/compiler/rustc_codegen_gcc/build_system/src/config.rs index 650c030ca53..a5f802e293a 100644 --- a/compiler/rustc_codegen_gcc/build_system/src/config.rs +++ b/compiler/rustc_codegen_gcc/build_system/src/config.rs @@ -352,11 +352,6 @@ impl ConfigInfo { None => return Err("no host found".to_string()), }; - if self.target_triple.is_empty() - && let Some(overwrite) = env.get("OVERWRITE_TARGET_TRIPLE") - { - self.target_triple = overwrite.clone(); - } if self.target_triple.is_empty() { self.target_triple = self.host_triple.clone(); } diff --git a/compiler/rustc_codegen_gcc/build_system/src/utils.rs b/compiler/rustc_codegen_gcc/build_system/src/utils.rs index d77707d5f17..fc948c54b24 100644 --- a/compiler/rustc_codegen_gcc/build_system/src/utils.rs +++ b/compiler/rustc_codegen_gcc/build_system/src/utils.rs @@ -303,19 +303,6 @@ pub fn create_dir<P: AsRef<Path>>(path: P) -> Result<(), String> { }) } -pub fn copy_file<F: AsRef<Path>, T: AsRef<Path>>(from: F, to: T) -> Result<(), String> { - fs::copy(&from, &to) - .map_err(|error| { - format!( - "Failed to copy file `{}` into `{}`: {:?}", - from.as_ref().display(), - to.as_ref().display(), - error - ) - }) - .map(|_| ()) -} - /// This function differs from `git_clone` in how it handles *where* the repository will be cloned. /// In `git_clone`, it is cloned in the provided path. In this function, the path you provide is /// the parent folder. So if you pass "a" as folder and try to clone "b.git", it will be cloned into diff --git a/compiler/rustc_codegen_gcc/doc/tips.md b/compiler/rustc_codegen_gcc/doc/tips.md index 86c22db186e..e62c3402a29 100644 --- a/compiler/rustc_codegen_gcc/doc/tips.md +++ b/compiler/rustc_codegen_gcc/doc/tips.md @@ -62,14 +62,14 @@ generate it in [gimple.md](./doc/gimple.md). * Run `./y.sh prepare --cross` so that the sysroot is patched for the cross-compiling case. * Set the path to the cross-compiling libgccjit in `gcc-path` (in `config.toml`). - * Make sure you have the linker for your target (for instance `m68k-unknown-linux-gnu-gcc`) in your `$PATH`. Currently, the linker name is hardcoded as being `$TARGET-gcc`. Specify the target when building the sysroot: `./y.sh build --sysroot --target-triple m68k-unknown-linux-gnu`. - * Build your project by specifying the target: `OVERWRITE_TARGET_TRIPLE=m68k-unknown-linux-gnu ../y.sh cargo build --target m68k-unknown-linux-gnu`. + * Make sure you have the linker for your target (for instance `m68k-unknown-linux-gnu-gcc`) in your `$PATH`. You can specify which linker to use via `CG_RUSTFLAGS="-Clinker=<linker>"`, for instance: `CG_RUSTFLAGS="-Clinker=m68k-unknown-linux-gnu-gcc"`. Specify the target when building the sysroot: `./y.sh build --sysroot --target-triple m68k-unknown-linux-gnu`. + * Build your project by specifying the target and the linker to use: `CG_RUSTFLAGS="-Clinker=m68k-unknown-linux-gnu-gcc" ../y.sh cargo build --target m68k-unknown-linux-gnu`. If the target is not yet supported by the Rust compiler, create a [target specification file](https://docs.rust-embedded.org/embedonomicon/custom-target.html) (note that the `arch` specified in this file must be supported by the rust compiler). Then, you can use it the following way: * Add the target specification file using `--target` as an **absolute** path to build the sysroot: `./y.sh build --sysroot --target-triple m68k-unknown-linux-gnu --target $(pwd)/m68k-unknown-linux-gnu.json` - * Build your project by specifying the target specification file: `OVERWRITE_TARGET_TRIPLE=m68k-unknown-linux-gnu ../y.sh cargo build --target path/to/m68k-unknown-linux-gnu.json`. + * Build your project by specifying the target specification file: `../y.sh cargo build --target path/to/m68k-unknown-linux-gnu.json`. If you get the following error: diff --git a/compiler/rustc_codegen_gcc/example/mini_core_hello_world.rs b/compiler/rustc_codegen_gcc/example/mini_core_hello_world.rs index 6b6f71edaf8..85489f850e2 100644 --- a/compiler/rustc_codegen_gcc/example/mini_core_hello_world.rs +++ b/compiler/rustc_codegen_gcc/example/mini_core_hello_world.rs @@ -6,7 +6,7 @@ )] #![no_core] #![allow(dead_code, internal_features, non_camel_case_types)] -#![rustfmt::skip] +#![rustfmt_skip] extern crate mini_core; @@ -198,10 +198,17 @@ fn main() { assert_eq!(intrinsics::align_of::<u16>() as u8, 2); assert_eq!(intrinsics::align_of_val(&a) as u8, intrinsics::align_of::<&str>() as u8); - assert!(!const { intrinsics::needs_drop::<u8>() }); - assert!(!const { intrinsics::needs_drop::<[u8]>() }); - assert!(const { intrinsics::needs_drop::<NoisyDrop>() }); - assert!(const { intrinsics::needs_drop::<NoisyDropUnsized>() }); + /* + * TODO: re-enable in the next sync. + let u8_needs_drop = const { intrinsics::needs_drop::<u8>() }; + assert!(!u8_needs_drop); + let slice_needs_drop = const { intrinsics::needs_drop::<[u8]>() }; + assert!(!slice_needs_drop); + let noisy_drop = const { intrinsics::needs_drop::<NoisyDrop>() }; + assert!(noisy_drop); + let noisy_unsized_drop = const { intrinsics::needs_drop::<NoisyDropUnsized>() }; + assert!(noisy_unsized_drop); + */ Unique { pointer: 0 as *const &str, diff --git a/compiler/rustc_codegen_gcc/rust-toolchain b/compiler/rustc_codegen_gcc/rust-toolchain index bccbc6cd2c5..2fe8ec4647f 100644 --- a/compiler/rustc_codegen_gcc/rust-toolchain +++ b/compiler/rustc_codegen_gcc/rust-toolchain @@ -1,3 +1,3 @@ [toolchain] -channel = "nightly-2025-06-28" +channel = "nightly-2025-07-04" components = ["rust-src", "rustc-dev", "llvm-tools-preview"] diff --git a/compiler/rustc_codegen_gcc/src/builder.rs b/compiler/rustc_codegen_gcc/src/builder.rs index 28d1ec7d895..a4ec4bf8dea 100644 --- a/compiler/rustc_codegen_gcc/src/builder.rs +++ b/compiler/rustc_codegen_gcc/src/builder.rs @@ -971,7 +971,11 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { fn volatile_load(&mut self, ty: Type<'gcc>, ptr: RValue<'gcc>) -> RValue<'gcc> { let ptr = self.context.new_cast(self.location, ptr, ty.make_volatile().make_pointer()); - ptr.dereference(self.location).to_rvalue() + // (FractalFir): We insert a local here, to ensure this volatile load can't move across + // blocks. + let local = self.current_func().new_local(self.location, ty, "volatile_tmp"); + self.block.add_assignment(self.location, local, ptr.dereference(self.location).to_rvalue()); + local.to_rvalue() } fn atomic_load( diff --git a/compiler/rustc_codegen_gcc/src/lib.rs b/compiler/rustc_codegen_gcc/src/lib.rs index d81bcc59775..af416929ea7 100644 --- a/compiler/rustc_codegen_gcc/src/lib.rs +++ b/compiler/rustc_codegen_gcc/src/lib.rs @@ -273,6 +273,10 @@ fn new_context<'gcc, 'tcx>(tcx: TyCtxt<'tcx>) -> Context<'gcc> { } impl ExtraBackendMethods for GccCodegenBackend { + fn supports_parallel(&self) -> bool { + false + } + fn codegen_allocator( &self, tcx: TyCtxt<'_>, @@ -341,8 +345,7 @@ impl Deref for SyncContext { } unsafe impl Send for SyncContext {} -// FIXME(antoyo): that shouldn't be Sync. Parallel compilation is currently disabled with "-Zno-parallel-llvm". -// TODO: disable it here by returning false in CodegenBackend::supports_parallel(). +// FIXME(antoyo): that shouldn't be Sync. Parallel compilation is currently disabled with "CodegenBackend::supports_parallel()". unsafe impl Sync for SyncContext {} impl WriteBackendMethods for GccCodegenBackend { diff --git a/compiler/rustc_codegen_gcc/src/mono_item.rs b/compiler/rustc_codegen_gcc/src/mono_item.rs index 51f35cbdee4..ff188c437da 100644 --- a/compiler/rustc_codegen_gcc/src/mono_item.rs +++ b/compiler/rustc_codegen_gcc/src/mono_item.rs @@ -64,7 +64,7 @@ impl<'gcc, 'tcx> PreDefineCodegenMethods<'tcx> for CodegenCx<'gcc, 'tcx> { if linkage != Linkage::Internal && self.tcx.is_compiler_builtins(LOCAL_CRATE) { #[cfg(feature = "master")] decl.add_attribute(FnAttribute::Visibility(gccjit::Visibility::Hidden)); - } else { + } else if visibility != Visibility::Default { #[cfg(feature = "master")] decl.add_attribute(FnAttribute::Visibility(base::visibility_to_gcc(visibility))); } diff --git a/compiler/rustc_codegen_gcc/tests/failing-ui-tests.txt b/compiler/rustc_codegen_gcc/tests/failing-ui-tests.txt index 544d0bfc710..6979c04d534 100644 --- a/compiler/rustc_codegen_gcc/tests/failing-ui-tests.txt +++ b/compiler/rustc_codegen_gcc/tests/failing-ui-tests.txt @@ -80,3 +80,5 @@ tests/ui/uninhabited/uninhabited-transparent-return-abi.rs tests/ui/coroutine/panic-drops-resume.rs tests/ui/coroutine/panic-drops.rs tests/ui/coroutine/panic-safe.rs +tests/ui/process/nofile-limit.rs +tests/ui/simd/intrinsic/generic-arithmetic-pass.rs diff --git a/compiler/rustc_codegen_gcc/tests/run/asm.rs b/compiler/rustc_codegen_gcc/tests/run/asm.rs index 2dbf43be664..9b15a28d829 100644 --- a/compiler/rustc_codegen_gcc/tests/run/asm.rs +++ b/compiler/rustc_codegen_gcc/tests/run/asm.rs @@ -16,6 +16,7 @@ add_asm: ret" ); +#[cfg(target_arch = "x86_64")] extern "C" { fn add_asm(a: i64, b: i64) -> i64; } diff --git a/compiler/rustc_codegen_gcc/tests/run/float.rs b/compiler/rustc_codegen_gcc/tests/run/float.rs index 424fa1cf4ad..df555f383fe 100644 --- a/compiler/rustc_codegen_gcc/tests/run/float.rs +++ b/compiler/rustc_codegen_gcc/tests/run/float.rs @@ -3,8 +3,6 @@ // Run-time: // status: 0 -#![feature(const_black_box)] - fn main() { use std::hint::black_box; @@ -15,14 +13,14 @@ fn main() { }}; } - check!(i32, (black_box(0.0f32) as i32)); + check!(i32, black_box(0.0f32) as i32); - check!(u64, (black_box(f32::NAN) as u64)); - check!(u128, (black_box(f32::NAN) as u128)); + check!(u64, black_box(f32::NAN) as u64); + check!(u128, black_box(f32::NAN) as u128); - check!(i64, (black_box(f64::NAN) as i64)); - check!(u64, (black_box(f64::NAN) as u64)); + check!(i64, black_box(f64::NAN) as i64); + check!(u64, black_box(f64::NAN) as u64); - check!(i16, (black_box(f32::MIN) as i16)); - check!(i16, (black_box(f32::MAX) as i16)); + check!(i16, black_box(f32::MIN) as i16); + check!(i16, black_box(f32::MAX) as i16); } diff --git a/compiler/rustc_codegen_gcc/tests/run/int.rs b/compiler/rustc_codegen_gcc/tests/run/int.rs index 47b5dea46f8..e20ecc23679 100644 --- a/compiler/rustc_codegen_gcc/tests/run/int.rs +++ b/compiler/rustc_codegen_gcc/tests/run/int.rs @@ -3,8 +3,6 @@ // Run-time: // status: 0 -#![feature(const_black_box)] - fn main() { use std::hint::black_box; diff --git a/compiler/rustc_codegen_gcc/tests/run/volatile.rs b/compiler/rustc_codegen_gcc/tests/run/volatile.rs index 8b043312593..94a7bdc5c06 100644 --- a/compiler/rustc_codegen_gcc/tests/run/volatile.rs +++ b/compiler/rustc_codegen_gcc/tests/run/volatile.rs @@ -5,13 +5,14 @@ use std::mem::MaybeUninit; +#[allow(dead_code)] #[derive(Debug)] struct Struct { pointer: *const (), func: unsafe fn(*const ()), } -fn func(ptr: *const ()) { +fn func(_ptr: *const ()) { } fn main() { diff --git a/compiler/rustc_codegen_gcc/tests/run/volatile2.rs b/compiler/rustc_codegen_gcc/tests/run/volatile2.rs index a177b817ab3..bdcb8259878 100644 --- a/compiler/rustc_codegen_gcc/tests/run/volatile2.rs +++ b/compiler/rustc_codegen_gcc/tests/run/volatile2.rs @@ -6,8 +6,6 @@ mod libc { #[link(name = "c")] extern "C" { - pub fn puts(s: *const u8) -> i32; - pub fn sigaction(signum: i32, act: *const sigaction, oldact: *mut sigaction) -> i32; pub fn mmap(addr: *mut (), len: usize, prot: i32, flags: i32, fd: i32, offset: i64) -> *mut (); pub fn mprotect(addr: *mut (), len: usize, prot: i32) -> i32; @@ -61,7 +59,7 @@ fn main() { panic!("error: mmap failed"); } - let p_count = (&mut COUNT) as *mut u32; + let p_count = (&raw mut COUNT) as *mut u32; p_count.write_volatile(0); // Trigger segfaults @@ -94,7 +92,7 @@ fn main() { } unsafe extern "C" fn segv_handler(_: i32, _: *mut (), _: *mut ()) { - let p_count = (&mut COUNT) as *mut u32; + let p_count = (&raw mut COUNT) as *mut u32; p_count.write_volatile(p_count.read_volatile() + 1); let count = p_count.read_volatile(); diff --git a/compiler/rustc_codegen_llvm/src/back/lto.rs b/compiler/rustc_codegen_llvm/src/back/lto.rs index 655e1c95373..84302009da9 100644 --- a/compiler/rustc_codegen_llvm/src/back/lto.rs +++ b/compiler/rustc_codegen_llvm/src/back/lto.rs @@ -654,6 +654,7 @@ pub(crate) fn run_pass_manager( // We then run the llvm_optimize function a second time, to optimize the code which we generated // in the enzyme differentiation pass. let enable_ad = config.autodiff.contains(&config::AutoDiff::Enable); + let enable_gpu = config.offload.contains(&config::Offload::Enable); let stage = if thin { write::AutodiffStage::PreAD } else { @@ -668,6 +669,12 @@ pub(crate) fn run_pass_manager( write::llvm_optimize(cgcx, dcx, module, None, config, opt_level, opt_stage, stage)?; } + if enable_gpu && !thin { + let cx = + SimpleCx::new(module.module_llvm.llmod(), &module.module_llvm.llcx, cgcx.pointer_size); + crate::builder::gpu_offload::handle_gpu_code(cgcx, &cx); + } + if cfg!(llvm_enzyme) && enable_ad && !thin { let cx = SimpleCx::new(module.module_llvm.llmod(), &module.module_llvm.llcx, cgcx.pointer_size); diff --git a/compiler/rustc_codegen_llvm/src/back/owned_target_machine.rs b/compiler/rustc_codegen_llvm/src/back/owned_target_machine.rs index dfde4595590..8e82013e94a 100644 --- a/compiler/rustc_codegen_llvm/src/back/owned_target_machine.rs +++ b/compiler/rustc_codegen_llvm/src/back/owned_target_machine.rs @@ -39,6 +39,7 @@ impl OwnedTargetMachine { debug_info_compression: &CStr, use_emulated_tls: bool, args_cstr_buff: &[u8], + use_wasm_eh: bool, ) -> Result<Self, LlvmError<'static>> { assert!(args_cstr_buff.len() > 0); assert!( @@ -72,6 +73,7 @@ impl OwnedTargetMachine { use_emulated_tls, args_cstr_buff.as_ptr() as *const c_char, args_cstr_buff.len(), + use_wasm_eh, ) }; diff --git a/compiler/rustc_codegen_llvm/src/back/write.rs b/compiler/rustc_codegen_llvm/src/back/write.rs index 68279008c03..6f8fba2a30d 100644 --- a/compiler/rustc_codegen_llvm/src/back/write.rs +++ b/compiler/rustc_codegen_llvm/src/back/write.rs @@ -15,6 +15,7 @@ use rustc_codegen_ssa::back::write::{ BitcodeSection, CodegenContext, EmitObj, ModuleConfig, TargetMachineFactoryConfig, TargetMachineFactoryFn, }; +use rustc_codegen_ssa::base::wants_wasm_eh; use rustc_codegen_ssa::traits::*; use rustc_codegen_ssa::{CompiledModule, ModuleCodegen, ModuleKind}; use rustc_data_structures::profiling::SelfProfilerRef; @@ -285,6 +286,8 @@ pub(crate) fn target_machine_factory( let file_name_display_preference = sess.filename_display_preference(RemapPathScopeComponents::DEBUGINFO); + let use_wasm_eh = wants_wasm_eh(sess); + Arc::new(move |config: TargetMachineFactoryConfig| { let path_to_cstring_helper = |path: Option<PathBuf>| -> CString { let path = path.unwrap_or_default(); @@ -321,6 +324,7 @@ pub(crate) fn target_machine_factory( &debuginfo_compression, use_emulated_tls, &args_cstr_buff, + use_wasm_eh, ) }) } diff --git a/compiler/rustc_codegen_llvm/src/builder.rs b/compiler/rustc_codegen_llvm/src/builder.rs index 514923ad6f3..0ade9edb0d2 100644 --- a/compiler/rustc_codegen_llvm/src/builder.rs +++ b/compiler/rustc_codegen_llvm/src/builder.rs @@ -3,6 +3,7 @@ use std::ops::Deref; use std::{iter, ptr}; pub(crate) mod autodiff; +pub(crate) mod gpu_offload; use libc::{c_char, c_uint, size_t}; use rustc_abi as abi; @@ -117,6 +118,74 @@ impl<'a, 'll, CX: Borrow<SCx<'ll>>> GenericBuilder<'a, 'll, CX> { } bx } + + // The generic builder has less functionality and thus (unlike the other alloca) we can not + // easily jump to the beginning of the function to place our allocas there. We trust the user + // to manually do that. FIXME(offload): improve the genericCx and add more llvm wrappers to + // handle this. + pub(crate) fn direct_alloca(&mut self, ty: &'ll Type, align: Align, name: &str) -> &'ll Value { + let val = unsafe { + let alloca = llvm::LLVMBuildAlloca(self.llbuilder, ty, UNNAMED); + llvm::LLVMSetAlignment(alloca, align.bytes() as c_uint); + // Cast to default addrspace if necessary + llvm::LLVMBuildPointerCast(self.llbuilder, alloca, self.cx.type_ptr(), UNNAMED) + }; + if name != "" { + let name = std::ffi::CString::new(name).unwrap(); + llvm::set_value_name(val, &name.as_bytes()); + } + val + } + + pub(crate) fn inbounds_gep( + &mut self, + ty: &'ll Type, + ptr: &'ll Value, + indices: &[&'ll Value], + ) -> &'ll Value { + unsafe { + llvm::LLVMBuildGEPWithNoWrapFlags( + self.llbuilder, + ty, + ptr, + indices.as_ptr(), + indices.len() as c_uint, + UNNAMED, + GEPNoWrapFlags::InBounds, + ) + } + } + + pub(crate) fn store(&mut self, val: &'ll Value, ptr: &'ll Value, align: Align) -> &'ll Value { + debug!("Store {:?} -> {:?}", val, ptr); + assert_eq!(self.cx.type_kind(self.cx.val_ty(ptr)), TypeKind::Pointer); + unsafe { + let store = llvm::LLVMBuildStore(self.llbuilder, val, ptr); + llvm::LLVMSetAlignment(store, align.bytes() as c_uint); + store + } + } + + pub(crate) fn load(&mut self, ty: &'ll Type, ptr: &'ll Value, align: Align) -> &'ll Value { + unsafe { + let load = llvm::LLVMBuildLoad2(self.llbuilder, ty, ptr, UNNAMED); + llvm::LLVMSetAlignment(load, align.bytes() as c_uint); + load + } + } + + fn memset(&mut self, ptr: &'ll Value, fill_byte: &'ll Value, size: &'ll Value, align: Align) { + unsafe { + llvm::LLVMRustBuildMemSet( + self.llbuilder, + ptr, + align.bytes() as c_uint, + fill_byte, + size, + false, + ); + } + } } /// Empty string, to be used where LLVM expects an instruction name, indicating diff --git a/compiler/rustc_codegen_llvm/src/builder/gpu_offload.rs b/compiler/rustc_codegen_llvm/src/builder/gpu_offload.rs new file mode 100644 index 00000000000..1280ab1442a --- /dev/null +++ b/compiler/rustc_codegen_llvm/src/builder/gpu_offload.rs @@ -0,0 +1,439 @@ +use std::ffi::CString; + +use llvm::Linkage::*; +use rustc_abi::Align; +use rustc_codegen_ssa::back::write::CodegenContext; +use rustc_codegen_ssa::traits::BaseTypeCodegenMethods; + +use crate::builder::SBuilder; +use crate::common::AsCCharPtr; +use crate::llvm::AttributePlace::Function; +use crate::llvm::{self, Linkage, Type, Value}; +use crate::{LlvmCodegenBackend, SimpleCx, attributes}; + +pub(crate) fn handle_gpu_code<'ll>( + _cgcx: &CodegenContext<LlvmCodegenBackend>, + cx: &'ll SimpleCx<'_>, +) { + // The offload memory transfer type for each kernel + let mut o_types = vec![]; + let mut kernels = vec![]; + let offload_entry_ty = add_tgt_offload_entry(&cx); + for num in 0..9 { + let kernel = cx.get_function(&format!("kernel_{num}")); + if let Some(kernel) = kernel { + o_types.push(gen_define_handling(&cx, kernel, offload_entry_ty, num)); + kernels.push(kernel); + } + } + + gen_call_handling(&cx, &kernels, &o_types); +} + +// What is our @1 here? A magic global, used in our data_{begin/update/end}_mapper: +// @0 = private unnamed_addr constant [23 x i8] c";unknown;unknown;0;0;;\00", align 1 +// @1 = private unnamed_addr constant %struct.ident_t { i32 0, i32 2, i32 0, i32 22, ptr @0 }, align 8 +fn generate_at_one<'ll>(cx: &'ll SimpleCx<'_>) -> &'ll llvm::Value { + // @0 = private unnamed_addr constant [23 x i8] c";unknown;unknown;0;0;;\00", align 1 + let unknown_txt = ";unknown;unknown;0;0;;"; + let c_entry_name = CString::new(unknown_txt).unwrap(); + let c_val = c_entry_name.as_bytes_with_nul(); + let initializer = crate::common::bytes_in_context(cx.llcx, c_val); + let at_zero = add_unnamed_global(&cx, &"", initializer, PrivateLinkage); + llvm::set_alignment(at_zero, Align::ONE); + + // @1 = private unnamed_addr constant %struct.ident_t { i32 0, i32 2, i32 0, i32 22, ptr @0 }, align 8 + let struct_ident_ty = cx.type_named_struct("struct.ident_t"); + let struct_elems = vec![ + cx.get_const_i32(0), + cx.get_const_i32(2), + cx.get_const_i32(0), + cx.get_const_i32(22), + at_zero, + ]; + let struct_elems_ty: Vec<_> = struct_elems.iter().map(|&x| cx.val_ty(x)).collect(); + let initializer = crate::common::named_struct(struct_ident_ty, &struct_elems); + cx.set_struct_body(struct_ident_ty, &struct_elems_ty, false); + let at_one = add_unnamed_global(&cx, &"", initializer, PrivateLinkage); + llvm::set_alignment(at_one, Align::EIGHT); + at_one +} + +pub(crate) fn add_tgt_offload_entry<'ll>(cx: &'ll SimpleCx<'_>) -> &'ll llvm::Type { + let offload_entry_ty = cx.type_named_struct("struct.__tgt_offload_entry"); + let tptr = cx.type_ptr(); + let ti64 = cx.type_i64(); + let ti32 = cx.type_i32(); + let ti16 = cx.type_i16(); + // For each kernel to run on the gpu, we will later generate one entry of this type. + // copied from LLVM + // typedef struct { + // uint64_t Reserved; + // uint16_t Version; + // uint16_t Kind; + // uint32_t Flags; Flags associated with the entry (see Target Region Entry Flags) + // void *Address; Address of global symbol within device image (function or global) + // char *SymbolName; + // uint64_t Size; Size of the entry info (0 if it is a function) + // uint64_t Data; + // void *AuxAddr; + // } __tgt_offload_entry; + let entry_elements = vec![ti64, ti16, ti16, ti32, tptr, tptr, ti64, ti64, tptr]; + cx.set_struct_body(offload_entry_ty, &entry_elements, false); + offload_entry_ty +} + +fn gen_tgt_kernel_global<'ll>(cx: &'ll SimpleCx<'_>) { + let kernel_arguments_ty = cx.type_named_struct("struct.__tgt_kernel_arguments"); + let tptr = cx.type_ptr(); + let ti64 = cx.type_i64(); + let ti32 = cx.type_i32(); + let tarr = cx.type_array(ti32, 3); + + // Taken from the LLVM APITypes.h declaration: + //struct KernelArgsTy { + // uint32_t Version = 0; // Version of this struct for ABI compatibility. + // uint32_t NumArgs = 0; // Number of arguments in each input pointer. + // void **ArgBasePtrs = + // nullptr; // Base pointer of each argument (e.g. a struct). + // void **ArgPtrs = nullptr; // Pointer to the argument data. + // int64_t *ArgSizes = nullptr; // Size of the argument data in bytes. + // int64_t *ArgTypes = nullptr; // Type of the data (e.g. to / from). + // void **ArgNames = nullptr; // Name of the data for debugging, possibly null. + // void **ArgMappers = nullptr; // User-defined mappers, possibly null. + // uint64_t Tripcount = + // 0; // Tripcount for the teams / distribute loop, 0 otherwise. + // struct { + // uint64_t NoWait : 1; // Was this kernel spawned with a `nowait` clause. + // uint64_t IsCUDA : 1; // Was this kernel spawned via CUDA. + // uint64_t Unused : 62; + // } Flags = {0, 0, 0}; + // // The number of teams (for x,y,z dimension). + // uint32_t NumTeams[3] = {0, 0, 0}; + // // The number of threads (for x,y,z dimension). + // uint32_t ThreadLimit[3] = {0, 0, 0}; + // uint32_t DynCGroupMem = 0; // Amount of dynamic cgroup memory requested. + //}; + let kernel_elements = + vec![ti32, ti32, tptr, tptr, tptr, tptr, tptr, tptr, ti64, ti64, tarr, tarr, ti32]; + + cx.set_struct_body(kernel_arguments_ty, &kernel_elements, false); + // For now we don't handle kernels, so for now we just add a global dummy + // to make sure that the __tgt_offload_entry is defined and handled correctly. + cx.declare_global("my_struct_global2", kernel_arguments_ty); +} + +fn gen_tgt_data_mappers<'ll>( + cx: &'ll SimpleCx<'_>, +) -> (&'ll llvm::Value, &'ll llvm::Value, &'ll llvm::Value, &'ll llvm::Type) { + let tptr = cx.type_ptr(); + let ti64 = cx.type_i64(); + let ti32 = cx.type_i32(); + + let args = vec![tptr, ti64, ti32, tptr, tptr, tptr, tptr, tptr, tptr]; + let mapper_fn_ty = cx.type_func(&args, cx.type_void()); + let mapper_begin = "__tgt_target_data_begin_mapper"; + let mapper_update = "__tgt_target_data_update_mapper"; + let mapper_end = "__tgt_target_data_end_mapper"; + let begin_mapper_decl = declare_offload_fn(&cx, mapper_begin, mapper_fn_ty); + let update_mapper_decl = declare_offload_fn(&cx, mapper_update, mapper_fn_ty); + let end_mapper_decl = declare_offload_fn(&cx, mapper_end, mapper_fn_ty); + + let nounwind = llvm::AttributeKind::NoUnwind.create_attr(cx.llcx); + attributes::apply_to_llfn(begin_mapper_decl, Function, &[nounwind]); + attributes::apply_to_llfn(update_mapper_decl, Function, &[nounwind]); + attributes::apply_to_llfn(end_mapper_decl, Function, &[nounwind]); + + (begin_mapper_decl, update_mapper_decl, end_mapper_decl, mapper_fn_ty) +} + +fn add_priv_unnamed_arr<'ll>(cx: &SimpleCx<'ll>, name: &str, vals: &[u64]) -> &'ll llvm::Value { + let ti64 = cx.type_i64(); + let mut size_val = Vec::with_capacity(vals.len()); + for &val in vals { + size_val.push(cx.get_const_i64(val)); + } + let initializer = cx.const_array(ti64, &size_val); + add_unnamed_global(cx, name, initializer, PrivateLinkage) +} + +pub(crate) fn add_unnamed_global<'ll>( + cx: &SimpleCx<'ll>, + name: &str, + initializer: &'ll llvm::Value, + l: Linkage, +) -> &'ll llvm::Value { + let llglobal = add_global(cx, name, initializer, l); + llvm::LLVMSetUnnamedAddress(llglobal, llvm::UnnamedAddr::Global); + llglobal +} + +pub(crate) fn add_global<'ll>( + cx: &SimpleCx<'ll>, + name: &str, + initializer: &'ll llvm::Value, + l: Linkage, +) -> &'ll llvm::Value { + let c_name = CString::new(name).unwrap(); + let llglobal: &'ll llvm::Value = llvm::add_global(cx.llmod, cx.val_ty(initializer), &c_name); + llvm::set_global_constant(llglobal, true); + llvm::set_linkage(llglobal, l); + llvm::set_initializer(llglobal, initializer); + llglobal +} + +fn gen_define_handling<'ll>( + cx: &'ll SimpleCx<'_>, + kernel: &'ll llvm::Value, + offload_entry_ty: &'ll llvm::Type, + num: i64, +) -> &'ll llvm::Value { + let types = cx.func_params_types(cx.get_type_of_global(kernel)); + // It seems like non-pointer values are automatically mapped. So here, we focus on pointer (or + // reference) types. + let num_ptr_types = types + .iter() + .map(|&x| matches!(cx.type_kind(x), rustc_codegen_ssa::common::TypeKind::Pointer)) + .count(); + + // We do not know their size anymore at this level, so hardcode a placeholder. + // A follow-up pr will track these from the frontend, where we still have Rust types. + // Then, we will be able to figure out that e.g. `&[f32;256]` will result in 4*256 bytes. + // I decided that 1024 bytes is a great placeholder value for now. + add_priv_unnamed_arr(&cx, &format!(".offload_sizes.{num}"), &vec![1024; num_ptr_types]); + // Here we figure out whether something needs to be copied to the gpu (=1), from the gpu (=2), + // or both to and from the gpu (=3). Other values shouldn't affect us for now. + // A non-mutable reference or pointer will be 1, an array that's not read, but fully overwritten + // will be 2. For now, everything is 3, until we have our frontend set up. + let o_types = + add_priv_unnamed_arr(&cx, &format!(".offload_maptypes.{num}"), &vec![3; num_ptr_types]); + // Next: For each function, generate these three entries. A weak constant, + // the llvm.rodata entry name, and the omp_offloading_entries value + + let name = format!(".kernel_{num}.region_id"); + let initializer = cx.get_const_i8(0); + let region_id = add_unnamed_global(&cx, &name, initializer, WeakAnyLinkage); + + let c_entry_name = CString::new(format!("kernel_{num}")).unwrap(); + let c_val = c_entry_name.as_bytes_with_nul(); + let offload_entry_name = format!(".offloading.entry_name.{num}"); + + let initializer = crate::common::bytes_in_context(cx.llcx, c_val); + let llglobal = add_unnamed_global(&cx, &offload_entry_name, initializer, InternalLinkage); + llvm::set_alignment(llglobal, Align::ONE); + llvm::set_section(llglobal, c".llvm.rodata.offloading"); + + // Not actively used yet, for calling real kernels + let name = format!(".offloading.entry.kernel_{num}"); + + // See the __tgt_offload_entry documentation above. + let reserved = cx.get_const_i64(0); + let version = cx.get_const_i16(1); + let kind = cx.get_const_i16(1); + let flags = cx.get_const_i32(0); + let size = cx.get_const_i64(0); + let data = cx.get_const_i64(0); + let aux_addr = cx.const_null(cx.type_ptr()); + let elems = vec![reserved, version, kind, flags, region_id, llglobal, size, data, aux_addr]; + + let initializer = crate::common::named_struct(offload_entry_ty, &elems); + let c_name = CString::new(name).unwrap(); + let llglobal = llvm::add_global(cx.llmod, offload_entry_ty, &c_name); + llvm::set_global_constant(llglobal, true); + llvm::set_linkage(llglobal, WeakAnyLinkage); + llvm::set_initializer(llglobal, initializer); + llvm::set_alignment(llglobal, Align::ONE); + let c_section_name = CString::new(".omp_offloading_entries").unwrap(); + llvm::set_section(llglobal, &c_section_name); + o_types +} + +fn declare_offload_fn<'ll>( + cx: &'ll SimpleCx<'_>, + name: &str, + ty: &'ll llvm::Type, +) -> &'ll llvm::Value { + crate::declare::declare_simple_fn( + cx, + name, + llvm::CallConv::CCallConv, + llvm::UnnamedAddr::No, + llvm::Visibility::Default, + ty, + ) +} + +// For each kernel *call*, we now use some of our previous declared globals to move data to and from +// the gpu. We don't have a proper frontend yet, so we assume that every call to a kernel function +// from main is intended to run on the GPU. For now, we only handle the data transfer part of it. +// If two consecutive kernels use the same memory, we still move it to the host and back to the gpu. +// Since in our frontend users (by default) don't have to specify data transfer, this is something +// we should optimize in the future! We also assume that everything should be copied back and forth, +// but sometimes we can directly zero-allocate on the device and only move back, or if something is +// immutable, we might only copy it to the device, but not back. +// +// Current steps: +// 0. Alloca some variables for the following steps +// 1. set insert point before kernel call. +// 2. generate all the GEPS and stores, to be used in 3) +// 3. generate __tgt_target_data_begin calls to move data to the GPU +// +// unchanged: keep kernel call. Later move the kernel to the GPU +// +// 4. set insert point after kernel call. +// 5. generate all the GEPS and stores, to be used in 6) +// 6. generate __tgt_target_data_end calls to move data from the GPU +fn gen_call_handling<'ll>( + cx: &'ll SimpleCx<'_>, + _kernels: &[&'ll llvm::Value], + o_types: &[&'ll llvm::Value], +) { + // %struct.__tgt_bin_desc = type { i32, ptr, ptr, ptr } + let tptr = cx.type_ptr(); + let ti32 = cx.type_i32(); + let tgt_bin_desc_ty = vec![ti32, tptr, tptr, tptr]; + let tgt_bin_desc = cx.type_named_struct("struct.__tgt_bin_desc"); + cx.set_struct_body(tgt_bin_desc, &tgt_bin_desc_ty, false); + + gen_tgt_kernel_global(&cx); + let (begin_mapper_decl, _, end_mapper_decl, fn_ty) = gen_tgt_data_mappers(&cx); + + let main_fn = cx.get_function("main"); + let Some(main_fn) = main_fn else { return }; + let kernel_name = "kernel_1"; + let call = unsafe { + llvm::LLVMRustGetFunctionCall(main_fn, kernel_name.as_c_char_ptr(), kernel_name.len()) + }; + let Some(kernel_call) = call else { + return; + }; + let kernel_call_bb = unsafe { llvm::LLVMGetInstructionParent(kernel_call) }; + let called = unsafe { llvm::LLVMGetCalledValue(kernel_call).unwrap() }; + let mut builder = SBuilder::build(cx, kernel_call_bb); + + let types = cx.func_params_types(cx.get_type_of_global(called)); + let num_args = types.len() as u64; + + // Step 0) + // %struct.__tgt_bin_desc = type { i32, ptr, ptr, ptr } + // %6 = alloca %struct.__tgt_bin_desc, align 8 + unsafe { llvm::LLVMRustPositionBuilderPastAllocas(builder.llbuilder, main_fn) }; + + let tgt_bin_desc_alloca = builder.direct_alloca(tgt_bin_desc, Align::EIGHT, "EmptyDesc"); + + let ty = cx.type_array(cx.type_ptr(), num_args); + // Baseptr are just the input pointer to the kernel, stored in a local alloca + let a1 = builder.direct_alloca(ty, Align::EIGHT, ".offload_baseptrs"); + // Ptrs are the result of a gep into the baseptr, at least for our trivial types. + let a2 = builder.direct_alloca(ty, Align::EIGHT, ".offload_ptrs"); + // These represent the sizes in bytes, e.g. the entry for `&[f64; 16]` will be 8*16. + let ty2 = cx.type_array(cx.type_i64(), num_args); + let a4 = builder.direct_alloca(ty2, Align::EIGHT, ".offload_sizes"); + // Now we allocate once per function param, a copy to be passed to one of our maps. + let mut vals = vec![]; + let mut geps = vec![]; + let i32_0 = cx.get_const_i32(0); + for (index, in_ty) in types.iter().enumerate() { + // get function arg, store it into the alloca, and read it. + let p = llvm::get_param(called, index as u32); + let name = llvm::get_value_name(p); + let name = str::from_utf8(&name).unwrap(); + let arg_name = format!("{name}.addr"); + let alloca = builder.direct_alloca(in_ty, Align::EIGHT, &arg_name); + + builder.store(p, alloca, Align::EIGHT); + let val = builder.load(in_ty, alloca, Align::EIGHT); + let gep = builder.inbounds_gep(cx.type_f32(), val, &[i32_0]); + vals.push(val); + geps.push(gep); + } + + // Step 1) + unsafe { llvm::LLVMRustPositionBefore(builder.llbuilder, kernel_call) }; + builder.memset(tgt_bin_desc_alloca, cx.get_const_i8(0), cx.get_const_i64(32), Align::EIGHT); + + let mapper_fn_ty = cx.type_func(&[cx.type_ptr()], cx.type_void()); + let register_lib_decl = declare_offload_fn(&cx, "__tgt_register_lib", mapper_fn_ty); + let unregister_lib_decl = declare_offload_fn(&cx, "__tgt_unregister_lib", mapper_fn_ty); + let init_ty = cx.type_func(&[], cx.type_void()); + let init_rtls_decl = declare_offload_fn(cx, "__tgt_init_all_rtls", init_ty); + + // call void @__tgt_register_lib(ptr noundef %6) + builder.call(mapper_fn_ty, register_lib_decl, &[tgt_bin_desc_alloca], None); + // call void @__tgt_init_all_rtls() + builder.call(init_ty, init_rtls_decl, &[], None); + + for i in 0..num_args { + let idx = cx.get_const_i32(i); + let gep1 = builder.inbounds_gep(ty, a1, &[i32_0, idx]); + builder.store(vals[i as usize], gep1, Align::EIGHT); + let gep2 = builder.inbounds_gep(ty, a2, &[i32_0, idx]); + builder.store(geps[i as usize], gep2, Align::EIGHT); + let gep3 = builder.inbounds_gep(ty2, a4, &[i32_0, idx]); + // As mentioned above, we don't use Rust type information yet. So for now we will just + // assume that we have 1024 bytes, 256 f32 values. + // FIXME(offload): write an offload frontend and handle arbitrary types. + builder.store(cx.get_const_i64(1024), gep3, Align::EIGHT); + } + + // For now we have a very simplistic indexing scheme into our + // offload_{baseptrs,ptrs,sizes}. We will probably improve this along with our gpu frontend pr. + fn get_geps<'a, 'll>( + builder: &mut SBuilder<'a, 'll>, + cx: &'ll SimpleCx<'ll>, + ty: &'ll Type, + ty2: &'ll Type, + a1: &'ll Value, + a2: &'ll Value, + a4: &'ll Value, + ) -> (&'ll Value, &'ll Value, &'ll Value) { + let i32_0 = cx.get_const_i32(0); + + let gep1 = builder.inbounds_gep(ty, a1, &[i32_0, i32_0]); + let gep2 = builder.inbounds_gep(ty, a2, &[i32_0, i32_0]); + let gep3 = builder.inbounds_gep(ty2, a4, &[i32_0, i32_0]); + (gep1, gep2, gep3) + } + + fn generate_mapper_call<'a, 'll>( + builder: &mut SBuilder<'a, 'll>, + cx: &'ll SimpleCx<'ll>, + geps: (&'ll Value, &'ll Value, &'ll Value), + o_type: &'ll Value, + fn_to_call: &'ll Value, + fn_ty: &'ll Type, + num_args: u64, + s_ident_t: &'ll Value, + ) { + let nullptr = cx.const_null(cx.type_ptr()); + let i64_max = cx.get_const_i64(u64::MAX); + let num_args = cx.get_const_i32(num_args); + let args = + vec![s_ident_t, i64_max, num_args, geps.0, geps.1, geps.2, o_type, nullptr, nullptr]; + builder.call(fn_ty, fn_to_call, &args, None); + } + + // Step 2) + let s_ident_t = generate_at_one(&cx); + let o = o_types[0]; + let geps = get_geps(&mut builder, &cx, ty, ty2, a1, a2, a4); + generate_mapper_call(&mut builder, &cx, geps, o, begin_mapper_decl, fn_ty, num_args, s_ident_t); + + // Step 3) + // Here we will add code for the actual kernel launches in a follow-up PR. + // FIXME(offload): launch kernels + + // Step 4) + unsafe { llvm::LLVMRustPositionAfter(builder.llbuilder, kernel_call) }; + + let geps = get_geps(&mut builder, &cx, ty, ty2, a1, a2, a4); + generate_mapper_call(&mut builder, &cx, geps, o, end_mapper_decl, fn_ty, num_args, s_ident_t); + + builder.call(mapper_fn_ty, unregister_lib_decl, &[tgt_bin_desc_alloca], None); + + // With this we generated the following begin and end mappers. We could easily generate the + // update mapper in an update. + // call void @__tgt_target_data_begin_mapper(ptr @1, i64 -1, i32 3, ptr %27, ptr %28, ptr %29, ptr @.offload_maptypes, ptr null, ptr null) + // call void @__tgt_target_data_update_mapper(ptr @1, i64 -1, i32 2, ptr %46, ptr %47, ptr %48, ptr @.offload_maptypes.1, ptr null, ptr null) + // call void @__tgt_target_data_end_mapper(ptr @1, i64 -1, i32 3, ptr %49, ptr %50, ptr %51, ptr @.offload_maptypes, ptr null, ptr null) +} diff --git a/compiler/rustc_codegen_llvm/src/common.rs b/compiler/rustc_codegen_llvm/src/common.rs index f9ab96b5789..f29fefb66f0 100644 --- a/compiler/rustc_codegen_llvm/src/common.rs +++ b/compiler/rustc_codegen_llvm/src/common.rs @@ -118,6 +118,10 @@ impl<'ll, CX: Borrow<SCx<'ll>>> GenericCx<'ll, CX> { r } } + + pub(crate) fn const_null(&self, t: &'ll Type) -> &'ll Value { + unsafe { llvm::LLVMConstNull(t) } + } } impl<'ll, 'tcx> ConstCodegenMethods for CodegenCx<'ll, 'tcx> { @@ -377,6 +381,11 @@ pub(crate) fn bytes_in_context<'ll>(llcx: &'ll llvm::Context, bytes: &[u8]) -> & } } +pub(crate) fn named_struct<'ll>(ty: &'ll Type, elts: &[&'ll Value]) -> &'ll Value { + let len = c_uint::try_from(elts.len()).expect("LLVMConstStructInContext elements len overflow"); + unsafe { llvm::LLVMConstNamedStruct(ty, elts.as_ptr(), len) } +} + fn struct_in_context<'ll>( llcx: &'ll llvm::Context, elts: &[&'ll Value], diff --git a/compiler/rustc_codegen_llvm/src/context.rs b/compiler/rustc_codegen_llvm/src/context.rs index 6a23becaa96..ee77774c688 100644 --- a/compiler/rustc_codegen_llvm/src/context.rs +++ b/compiler/rustc_codegen_llvm/src/context.rs @@ -207,11 +207,16 @@ pub(crate) unsafe fn create_module<'ll>( // LLVM 21 updated the default layout on nvptx: https://github.com/llvm/llvm-project/pull/124961 target_data_layout = target_data_layout.replace("e-p6:32:32-i64", "e-i64"); } + if sess.target.arch == "amdgpu" { + // LLVM 21 adds the address width for address space 8. + // See https://github.com/llvm/llvm-project/pull/139419 + target_data_layout = target_data_layout.replace("p8:128:128:128:48", "p8:128:128") + } } // Ensure the data-layout values hardcoded remain the defaults. { - let tm = crate::back::write::create_informational_target_machine(tcx.sess, false); + let tm = crate::back::write::create_informational_target_machine(sess, false); unsafe { llvm::LLVMRustSetDataLayoutFromTargetMachine(llmod, tm.raw()); } @@ -680,6 +685,22 @@ impl<'ll, CX: Borrow<SCx<'ll>>> GenericCx<'ll, CX> { unsafe { llvm::LLVMConstInt(ty, val, llvm::False) } } + pub(crate) fn get_const_i64(&self, n: u64) -> &'ll Value { + self.get_const_int(self.type_i64(), n) + } + + pub(crate) fn get_const_i32(&self, n: u64) -> &'ll Value { + self.get_const_int(self.type_i32(), n) + } + + pub(crate) fn get_const_i16(&self, n: u64) -> &'ll Value { + self.get_const_int(self.type_i16(), n) + } + + pub(crate) fn get_const_i8(&self, n: u64) -> &'ll Value { + self.get_const_int(self.type_i8(), n) + } + pub(crate) fn get_function(&self, name: &str) -> Option<&'ll Value> { let name = SmallCStr::new(name); unsafe { llvm::LLVMGetNamedFunction((**self).borrow().llmod, name.as_ptr()) } diff --git a/compiler/rustc_codegen_llvm/src/declare.rs b/compiler/rustc_codegen_llvm/src/declare.rs index eb75716d768..960a895a203 100644 --- a/compiler/rustc_codegen_llvm/src/declare.rs +++ b/compiler/rustc_codegen_llvm/src/declare.rs @@ -215,7 +215,9 @@ impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> { llfn } +} +impl<'ll, CX: Borrow<SCx<'ll>>> GenericCx<'ll, CX> { /// Declare a global with an intention to define it. /// /// Use this function when you intend to define a global. This function will @@ -234,13 +236,13 @@ impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> { /// /// Use this function when you intend to define a global without a name. pub(crate) fn define_private_global(&self, ty: &'ll Type) -> &'ll Value { - unsafe { llvm::LLVMRustInsertPrivateGlobal(self.llmod, ty) } + unsafe { llvm::LLVMRustInsertPrivateGlobal(self.llmod(), ty) } } /// Gets declared value by name. pub(crate) fn get_declared_value(&self, name: &str) -> Option<&'ll Value> { debug!("get_declared_value(name={:?})", name); - unsafe { llvm::LLVMRustGetNamedValue(self.llmod, name.as_c_char_ptr(), name.len()) } + unsafe { llvm::LLVMRustGetNamedValue(self.llmod(), name.as_c_char_ptr(), name.len()) } } /// Gets defined or externally defined (AvailableExternally linkage) value by diff --git a/compiler/rustc_codegen_llvm/src/lib.rs b/compiler/rustc_codegen_llvm/src/lib.rs index 6db4e122ad6..aaf21f9ada9 100644 --- a/compiler/rustc_codegen_llvm/src/lib.rs +++ b/compiler/rustc_codegen_llvm/src/lib.rs @@ -412,6 +412,20 @@ impl ModuleLlvm { } } + fn tm_from_cgcx( + cgcx: &CodegenContext<LlvmCodegenBackend>, + name: &str, + dcx: DiagCtxtHandle<'_>, + ) -> Result<OwnedTargetMachine, FatalError> { + let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, name); + match (cgcx.tm_factory)(tm_factory_config) { + Ok(m) => Ok(m), + Err(e) => { + return Err(dcx.emit_almost_fatal(ParseTargetMachineConfig(e))); + } + } + } + fn parse( cgcx: &CodegenContext<LlvmCodegenBackend>, name: &CStr, @@ -421,13 +435,7 @@ impl ModuleLlvm { unsafe { let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names); let llmod_raw = back::lto::parse_module(llcx, name, buffer, dcx)?; - let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, name.to_str().unwrap()); - let tm = match (cgcx.tm_factory)(tm_factory_config) { - Ok(m) => m, - Err(e) => { - return Err(dcx.emit_almost_fatal(ParseTargetMachineConfig(e))); - } - }; + let tm = ModuleLlvm::tm_from_cgcx(cgcx, name.to_str().unwrap(), dcx)?; Ok(ModuleLlvm { llmod_raw, llcx, tm: ManuallyDrop::new(tm) }) } diff --git a/compiler/rustc_codegen_llvm/src/llvm/enzyme_ffi.rs b/compiler/rustc_codegen_llvm/src/llvm/enzyme_ffi.rs index c696b8d8ff2..56d756e52cc 100644 --- a/compiler/rustc_codegen_llvm/src/llvm/enzyme_ffi.rs +++ b/compiler/rustc_codegen_llvm/src/llvm/enzyme_ffi.rs @@ -4,7 +4,7 @@ use libc::{c_char, c_uint}; use super::MetadataKindId; use super::ffi::{AttributeKind, BasicBlock, Metadata, Module, Type, Value}; -use crate::llvm::Bool; +use crate::llvm::{Bool, Builder}; #[link(name = "llvm-wrapper", kind = "static")] unsafe extern "C" { @@ -31,6 +31,14 @@ unsafe extern "C" { index: c_uint, kind: AttributeKind, ); + pub(crate) fn LLVMRustPositionBefore<'a>(B: &'a Builder<'_>, I: &'a Value); + pub(crate) fn LLVMRustPositionAfter<'a>(B: &'a Builder<'_>, I: &'a Value); + pub(crate) fn LLVMRustGetFunctionCall( + F: &Value, + name: *const c_char, + NameLen: libc::size_t, + ) -> Option<&Value>; + } unsafe extern "C" { diff --git a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs index 0b1e632cbc4..edfb29dd1be 100644 --- a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs +++ b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs @@ -1138,6 +1138,11 @@ unsafe extern "C" { Count: c_uint, Packed: Bool, ) -> &'a Value; + pub(crate) fn LLVMConstNamedStruct<'a>( + StructTy: &'a Type, + ConstantVals: *const &'a Value, + Count: c_uint, + ) -> &'a Value; pub(crate) fn LLVMConstVector(ScalarConstantVals: *const &Value, Size: c_uint) -> &Value; // Constant expressions @@ -1217,6 +1222,8 @@ unsafe extern "C" { ) -> &'a BasicBlock; // Operations on instructions + pub(crate) fn LLVMGetInstructionParent(Inst: &Value) -> &BasicBlock; + pub(crate) fn LLVMGetCalledValue(CallInst: &Value) -> Option<&Value>; pub(crate) fn LLVMIsAInstruction(Val: &Value) -> Option<&Value>; pub(crate) fn LLVMGetFirstBasicBlock(Fn: &Value) -> &BasicBlock; pub(crate) fn LLVMGetOperand(Val: &Value, Index: c_uint) -> Option<&Value>; @@ -2425,6 +2432,7 @@ unsafe extern "C" { UseEmulatedTls: bool, ArgsCstrBuff: *const c_char, ArgsCstrBuffLen: usize, + UseWasmEH: bool, ) -> *mut TargetMachine; pub(crate) fn LLVMRustDisposeTargetMachine(T: *mut TargetMachine); @@ -2556,6 +2564,7 @@ unsafe extern "C" { pub(crate) fn LLVMRustSetDataLayoutFromTargetMachine<'a>(M: &'a Module, TM: &'a TargetMachine); + pub(crate) fn LLVMRustPositionBuilderPastAllocas<'a>(B: &Builder<'a>, Fn: &'a Value); pub(crate) fn LLVMRustPositionBuilderAtStart<'a>(B: &Builder<'a>, BB: &'a BasicBlock); pub(crate) fn LLVMRustSetModulePICLevel(M: &Module); diff --git a/compiler/rustc_codegen_ssa/src/back/write.rs b/compiler/rustc_codegen_ssa/src/back/write.rs index 50a7cba300b..24e0a4eb533 100644 --- a/compiler/rustc_codegen_ssa/src/back/write.rs +++ b/compiler/rustc_codegen_ssa/src/back/write.rs @@ -120,6 +120,7 @@ pub struct ModuleConfig { pub emit_lifetime_markers: bool, pub llvm_plugins: Vec<String>, pub autodiff: Vec<config::AutoDiff>, + pub offload: Vec<config::Offload>, } impl ModuleConfig { @@ -268,6 +269,7 @@ impl ModuleConfig { emit_lifetime_markers: sess.emit_lifetime_markers(), llvm_plugins: if_regular!(sess.opts.unstable_opts.llvm_plugins.clone(), vec![]), autodiff: if_regular!(sess.opts.unstable_opts.autodiff.clone(), vec![]), + offload: if_regular!(sess.opts.unstable_opts.offload.clone(), vec![]), } } diff --git a/compiler/rustc_codegen_ssa/src/mir/operand.rs b/compiler/rustc_codegen_ssa/src/mir/operand.rs index b0d191528a8..06bedaaa4a2 100644 --- a/compiler/rustc_codegen_ssa/src/mir/operand.rs +++ b/compiler/rustc_codegen_ssa/src/mir/operand.rs @@ -329,20 +329,11 @@ impl<'a, 'tcx, V: CodegenObject> OperandRef<'tcx, V> { let offset = self.layout.fields.offset(i); if !bx.is_backend_ref(self.layout) && bx.is_backend_ref(field) { - if let BackendRepr::SimdVector { count, .. } = self.layout.backend_repr - && let BackendRepr::Memory { sized: true } = field.backend_repr - && count.is_power_of_two() - { - assert_eq!(field.size, self.layout.size); - // This is being deprecated, but for now stdarch still needs it for - // Newtype vector of array, e.g. #[repr(simd)] struct S([i32; 4]); - let place = PlaceRef::alloca(bx, field); - self.val.store(bx, place.val.with_type(self.layout)); - return bx.load_operand(place); - } else { - // Part of https://github.com/rust-lang/compiler-team/issues/838 - bug!("Non-ref type {self:?} cannot project to ref field type {field:?}"); - } + // Part of https://github.com/rust-lang/compiler-team/issues/838 + span_bug!( + fx.mir.span, + "Non-ref type {self:?} cannot project to ref field type {field:?}", + ); } let val = if field.is_zst() { @@ -486,6 +477,7 @@ impl<'a, 'tcx, V: CodegenObject> OperandRef<'tcx, V> { // value and the variant index match, since that's all `Niche` can encode. let relative_max = niche_variants.end().as_u32() - niche_variants.start().as_u32(); + let niche_start_const = bx.cx().const_uint_big(tag_llty, niche_start); // We have a subrange `niche_start..=niche_end` inside `range`. // If the value of the tag is inside this subrange, it's a @@ -511,35 +503,88 @@ impl<'a, 'tcx, V: CodegenObject> OperandRef<'tcx, V> { // } 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 is_niche = bx.icmp(IntPredicate::IntEQ, tag, niche_start_const); 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)); + // With multiple niched variants we'll have to actually compute + // the variant index from the stored tag. + // + // However, there's still one small optimization we can often do for + // determining *whether* a tag value is a natural value or a niched + // variant. The general algorithm involves a subtraction that often + // wraps in practice, making it tricky to analyse. However, in cases + // where there are few enough possible values of the tag that it doesn't + // need to wrap around, we can instead just look for the contiguous + // tag values on the end of the range with a single comparison. + // + // For example, take the type `enum Demo { A, B, Untagged(bool) }`. + // The `bool` is {0, 1}, and the two other variants are given the + // tags {2, 3} respectively. That means the `tag_range` is + // `[0, 3]`, which doesn't wrap as unsigned (nor as signed), so + // we can test for the niched variants with just `>= 2`. + // + // That means we're looking either for the niche values *above* + // the natural values of the untagged variant: + // + // niche_start niche_end + // | | + // v v + // MIN -------------+---------------------------+---------- MAX + // ^ | is niche | + // | +---------------------------+ + // | | + // tag_range.start tag_range.end + // + // Or *below* the natural values: + // + // niche_start niche_end + // | | + // v v + // MIN ----+-----------------------+---------------------- MAX + // | is niche | ^ + // +-----------------------+ | + // | | + // tag_range.start tag_range.end + // + // With those two options and having the flexibility to choose + // between a signed or unsigned comparison on the tag, that + // covers most realistic scenarios. The tests have a (contrived) + // example of a 1-byte enum with over 128 niched variants which + // wraps both as signed as unsigned, though, and for something + // like that we're stuck with the general algorithm. + + let tag_range = tag_scalar.valid_range(&dl); + let tag_size = tag_scalar.size(&dl); + let niche_end = u128::from(relative_max).wrapping_add(niche_start); + let niche_end = tag_size.truncate(niche_end); + + let relative_discr = bx.sub(tag, niche_start_const); 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), - ); - - // Thanks to parameter attributes and load metadata, LLVM already knows - // the general valid range of the tag. It's possible, though, for there - // to be an impossible value *in the middle*, which those ranges don't - // communicate, so it's worth an `assume` to let the optimizer know. - if niche_variants.contains(&untagged_variant) - && bx.cx().sess().opts.optimize != OptLevel::No - { - let impossible = - u64::from(untagged_variant.as_u32() - niche_variants.start().as_u32()); - let impossible = bx.cx().const_uint(tag_llty, impossible); - let ne = bx.icmp(IntPredicate::IntNE, relative_discr, impossible); - bx.assume(ne); - } + let is_niche = if tag_range.no_unsigned_wraparound(tag_size) == Ok(true) { + if niche_start == tag_range.start { + let niche_end_const = bx.cx().const_uint_big(tag_llty, niche_end); + bx.icmp(IntPredicate::IntULE, tag, niche_end_const) + } else { + assert_eq!(niche_end, tag_range.end); + bx.icmp(IntPredicate::IntUGE, tag, niche_start_const) + } + } else if tag_range.no_signed_wraparound(tag_size) == Ok(true) { + if niche_start == tag_range.start { + let niche_end_const = bx.cx().const_uint_big(tag_llty, niche_end); + bx.icmp(IntPredicate::IntSLE, tag, niche_end_const) + } else { + assert_eq!(niche_end, tag_range.end); + bx.icmp(IntPredicate::IntSGE, tag, niche_start_const) + } + } else { + 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) }; @@ -550,11 +595,24 @@ impl<'a, 'tcx, V: CodegenObject> OperandRef<'tcx, V> { 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), - ); + let untagged_variant_const = + bx.cx().const_uint(cast_to, u64::from(untagged_variant.as_u32())); + + // Thanks to parameter attributes and load metadata, LLVM already knows + // the general valid range of the tag. It's possible, though, for there + // to be an impossible value *in the middle*, which those ranges don't + // communicate, so it's worth an `assume` to let the optimizer know. + // Most importantly, this means when optimizing a variant test like + // `SELECT(is_niche, complex, CONST) == CONST` it's ok to simplify that + // to `!is_niche` because the `complex` part can't possibly match. + if niche_variants.contains(&untagged_variant) + && bx.cx().sess().opts.optimize != OptLevel::No + { + let ne = bx.icmp(IntPredicate::IntNE, tagged_discr, untagged_variant_const); + bx.assume(ne); + } + + let discr = bx.select(is_niche, tagged_discr, untagged_variant_const); // In principle we could insert assumes on the possible range of `discr`, but // currently in LLVM this isn't worth it because the original `tag` will diff --git a/compiler/rustc_codegen_ssa/src/mir/rvalue.rs b/compiler/rustc_codegen_ssa/src/mir/rvalue.rs index 2587e89417a..e872f8434e5 100644 --- a/compiler/rustc_codegen_ssa/src/mir/rvalue.rs +++ b/compiler/rustc_codegen_ssa/src/mir/rvalue.rs @@ -630,7 +630,17 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { OperandRef { val: OperandValue::Immediate(static_), layout } } mir::Rvalue::Use(ref operand) => self.codegen_operand(bx, operand), - mir::Rvalue::Repeat(..) => bug!("{rvalue:?} in codegen_rvalue_operand"), + mir::Rvalue::Repeat(ref elem, len_const) => { + // All arrays have `BackendRepr::Memory`, so only the ZST cases + // end up here. Anything else forces the destination local to be + // `Memory`, and thus ends up handled in `codegen_rvalue` instead. + let operand = self.codegen_operand(bx, elem); + let array_ty = Ty::new_array_with_const_len(bx.tcx(), operand.layout.ty, len_const); + let array_ty = self.monomorphize(array_ty); + let array_layout = bx.layout_of(array_ty); + assert!(array_layout.is_zst()); + OperandRef { val: OperandValue::ZeroSized, layout: array_layout } + } mir::Rvalue::Aggregate(ref kind, ref fields) => { let (variant_index, active_field_index) = match **kind { mir::AggregateKind::Adt(_, variant_index, _, _, active_field_index) => { @@ -1000,12 +1010,10 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { mir::Rvalue::NullaryOp(..) | mir::Rvalue::ThreadLocalRef(_) | mir::Rvalue::Use(..) | + mir::Rvalue::Repeat(..) | // (*) mir::Rvalue::Aggregate(..) | // (*) mir::Rvalue::WrapUnsafeBinder(..) => // (*) true, - // Arrays are always aggregates, so it's not worth checking anything here. - // (If it's really `[(); N]` or `[T; 0]` and we use the place path, fine.) - mir::Rvalue::Repeat(..) => false, } // (*) this is only true if the type is suitable diff --git a/compiler/rustc_codegen_ssa/src/target_features.rs b/compiler/rustc_codegen_ssa/src/target_features.rs index 53df99993f0..def4ec13e87 100644 --- a/compiler/rustc_codegen_ssa/src/target_features.rs +++ b/compiler/rustc_codegen_ssa/src/target_features.rs @@ -149,14 +149,14 @@ fn parse_rust_feature_flag<'a>( if let Some(base_feature) = feature.strip_prefix('+') { // Skip features that are not target features, but rustc features. if RUSTC_SPECIFIC_FEATURES.contains(&base_feature) { - return; + continue; } callback(base_feature, sess.target.implied_target_features(base_feature), true) } else if let Some(base_feature) = feature.strip_prefix('-') { // Skip features that are not target features, but rustc features. if RUSTC_SPECIFIC_FEATURES.contains(&base_feature) { - return; + continue; } // If `f1` implies `f2`, then `!f2` implies `!f1` -- this is standard logical diff --git a/compiler/rustc_const_eval/src/const_eval/error.rs b/compiler/rustc_const_eval/src/const_eval/error.rs index 3e880d02001..e00fb2c1eaf 100644 --- a/compiler/rustc_const_eval/src/const_eval/error.rs +++ b/compiler/rustc_const_eval/src/const_eval/error.rs @@ -2,17 +2,17 @@ use std::mem; use rustc_errors::{Diag, DiagArgName, DiagArgValue, DiagMessage, IntoDiagArg}; use rustc_middle::mir::AssertKind; -use rustc_middle::mir::interpret::{AllocId, Provenance, ReportedErrorInfo}; +use rustc_middle::mir::interpret::{AllocId, Provenance, ReportedErrorInfo, UndefinedBehaviorInfo}; use rustc_middle::query::TyCtxtAt; +use rustc_middle::ty::ConstInt; use rustc_middle::ty::layout::LayoutError; -use rustc_middle::ty::{ConstInt, TyCtxt}; use rustc_span::{Span, Symbol}; use super::CompileTimeMachine; use crate::errors::{self, FrameNote, ReportErrorExt}; use crate::interpret::{ - CtfeProvenance, ErrorHandled, Frame, InterpErrorInfo, InterpErrorKind, MachineStopType, - Pointer, err_inval, err_machine_stop, + CtfeProvenance, ErrorHandled, Frame, InterpCx, InterpErrorInfo, InterpErrorKind, + MachineStopType, Pointer, err_inval, err_machine_stop, }; /// The CTFE machine has some custom error kinds. @@ -163,7 +163,7 @@ pub fn get_span_and_frames<'tcx>( /// You can use it to add a stacktrace of current execution according to /// `get_span_and_frames` or just give context on where the const eval error happened. pub(super) fn report<'tcx, C, F>( - tcx: TyCtxt<'tcx>, + ecx: &InterpCx<'tcx, CompileTimeMachine<'tcx>>, error: InterpErrorKind<'tcx>, span: Span, get_span_and_frames: C, @@ -173,6 +173,7 @@ where C: FnOnce() -> (Span, Vec<FrameNote>), F: FnOnce(&mut Diag<'_>, Span, Vec<FrameNote>), { + let tcx = ecx.tcx.tcx; // Special handling for certain errors match error { // Don't emit a new diagnostic for these errors, they are already reported elsewhere or @@ -198,6 +199,20 @@ where InterpErrorKind::ResourceExhaustion(_) | InterpErrorKind::InvalidProgram(_) ); + if let InterpErrorKind::UndefinedBehavior(UndefinedBehaviorInfo::InvalidUninitBytes( + Some((alloc_id, _access)), + )) = error + { + let bytes = ecx.print_alloc_bytes_for_diagnostics(alloc_id); + let info = ecx.get_alloc_info(alloc_id); + let raw_bytes = errors::RawBytesNote { + size: info.size.bytes(), + align: info.align.bytes(), + bytes, + }; + err.subdiagnostic(raw_bytes); + } + error.add_args(&mut err); mk(&mut err, span, frames); diff --git a/compiler/rustc_const_eval/src/const_eval/eval_queries.rs b/compiler/rustc_const_eval/src/const_eval/eval_queries.rs index ce72d59b8b0..f584f6c948e 100644 --- a/compiler/rustc_const_eval/src/const_eval/eval_queries.rs +++ b/compiler/rustc_const_eval/src/const_eval/eval_queries.rs @@ -411,7 +411,7 @@ fn report_eval_error<'tcx>( let instance = with_no_trimmed_paths!(cid.instance.to_string()); super::report( - *ecx.tcx, + ecx, error, DUMMY_SP, || super::get_span_and_frames(ecx.tcx, ecx.stack()), @@ -451,7 +451,7 @@ fn report_validation_error<'tcx>( errors::RawBytesNote { size: info.size.bytes(), align: info.align.bytes(), bytes }; crate::const_eval::report( - *ecx.tcx, + ecx, error, DUMMY_SP, || crate::const_eval::get_span_and_frames(ecx.tcx, ecx.stack()), diff --git a/compiler/rustc_const_eval/src/interpret/cast.rs b/compiler/rustc_const_eval/src/interpret/cast.rs index 7a73d70fc85..de4fbc7b475 100644 --- a/compiler/rustc_const_eval/src/interpret/cast.rs +++ b/compiler/rustc_const_eval/src/interpret/cast.rs @@ -17,6 +17,7 @@ use super::{ throw_ub_custom, }; use crate::fluent_generated as fluent; +use crate::interpret::Writeable; impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { pub fn cast( @@ -358,7 +359,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { fn unsize_into_ptr( &mut self, src: &OpTy<'tcx, M::Provenance>, - dest: &PlaceTy<'tcx, M::Provenance>, + dest: &impl Writeable<'tcx, M::Provenance>, // The pointee types source_ty: Ty<'tcx>, cast_ty: Ty<'tcx>, @@ -455,7 +456,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { &mut self, src: &OpTy<'tcx, M::Provenance>, cast_ty: TyAndLayout<'tcx>, - dest: &PlaceTy<'tcx, M::Provenance>, + dest: &impl Writeable<'tcx, M::Provenance>, ) -> InterpResult<'tcx> { trace!("Unsizing {:?} of type {} into {}", *src, src.layout.ty, cast_ty.ty); match (src.layout.ty.kind(), cast_ty.ty.kind()) { @@ -496,7 +497,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { self.cur_span(), "unsize_into: invalid conversion: {:?} -> {:?}", src.layout, - dest.layout + dest.layout() ) } } diff --git a/compiler/rustc_const_eval/src/interpret/memory.rs b/compiler/rustc_const_eval/src/interpret/memory.rs index 47228de5213..20c8e983cea 100644 --- a/compiler/rustc_const_eval/src/interpret/memory.rs +++ b/compiler/rustc_const_eval/src/interpret/memory.rs @@ -67,8 +67,8 @@ pub enum AllocKind { LiveData, /// A function allocation (that fn ptrs point to). Function, - /// A (symbolic) vtable allocation. - VTable, + /// A "virtual" allocation, used for vtables and TypeId. + Virtual, /// A dead allocation. Dead, } @@ -950,11 +950,9 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { let (size, align) = global_alloc.size_and_align(*self.tcx, self.typing_env); let mutbl = global_alloc.mutability(*self.tcx, self.typing_env); let kind = match global_alloc { - GlobalAlloc::TypeId { .. } - | GlobalAlloc::Static { .. } - | GlobalAlloc::Memory { .. } => AllocKind::LiveData, + GlobalAlloc::Static { .. } | GlobalAlloc::Memory { .. } => AllocKind::LiveData, GlobalAlloc::Function { .. } => bug!("We already checked function pointers above"), - GlobalAlloc::VTable { .. } => AllocKind::VTable, + GlobalAlloc::VTable { .. } | GlobalAlloc::TypeId { .. } => AllocKind::Virtual, }; return AllocInfo::new(size, align, kind, mutbl); } diff --git a/compiler/rustc_const_eval/src/interpret/validity.rs b/compiler/rustc_const_eval/src/interpret/validity.rs index 62f591ceaa9..693b3782960 100644 --- a/compiler/rustc_const_eval/src/interpret/validity.rs +++ b/compiler/rustc_const_eval/src/interpret/validity.rs @@ -394,7 +394,7 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValidityVisitor<'rt, 'tcx, M> { interp_ok(try_validation!( self.ecx.read_immediate(val), self.path, - Ub(InvalidUninitBytes(None)) => + Ub(InvalidUninitBytes(_)) => Uninit { expected }, // The `Unsup` cases can only occur during CTFE Unsup(ReadPointerAsInt(_)) => diff --git a/compiler/rustc_error_codes/src/error_codes/E0203.md b/compiler/rustc_error_codes/src/error_codes/E0203.md index 1edb519275f..a4dceedbf1f 100644 --- a/compiler/rustc_error_codes/src/error_codes/E0203.md +++ b/compiler/rustc_error_codes/src/error_codes/E0203.md @@ -1,15 +1,15 @@ -Having multiple relaxed default bounds is unsupported. +Having duplicate relaxed default bounds is unsupported. Erroneous code example: ```compile_fail,E0203 -struct Bad<T: ?Sized + ?Send>{ - inner: T +struct Bad<T: ?Sized + ?Sized>{ + inner: T, } ``` -Here the type `T` cannot have a relaxed bound for multiple default traits -(`Sized` and `Send`). This can be fixed by only using one relaxed bound. +Here the type parameter `T` cannot have duplicate relaxed bounds for default +trait `Sized`. This can be fixed by only using one relaxed bound: ``` struct Good<T: ?Sized>{ diff --git a/compiler/rustc_errors/src/diagnostic.rs b/compiler/rustc_errors/src/diagnostic.rs index a128f8d31a1..96c7ba6ed27 100644 --- a/compiler/rustc_errors/src/diagnostic.rs +++ b/compiler/rustc_errors/src/diagnostic.rs @@ -1421,7 +1421,7 @@ impl<'a, G: EmissionGuarantee> Diag<'a, G> { /// /// See `emit` and `delay_as_bug` for details. #[track_caller] - pub fn emit_unless(mut self, delay: bool) -> G::EmitResult { + pub fn emit_unless_delay(mut self, delay: bool) -> G::EmitResult { if delay { self.downgrade_to_delayed_bug(); } diff --git a/compiler/rustc_hir/src/target.rs b/compiler/rustc_hir/src/target.rs index 601898023fc..d617f44f8d8 100644 --- a/compiler/rustc_hir/src/target.rs +++ b/compiler/rustc_hir/src/target.rs @@ -41,7 +41,7 @@ pub enum Target { Union, Trait, TraitAlias, - Impl, + Impl { of_trait: bool }, Expression, Statement, Arm, @@ -51,7 +51,7 @@ pub enum Target { ForeignFn, ForeignStatic, ForeignTy, - GenericParam(GenericParamKind), + GenericParam { kind: GenericParamKind, has_default: bool }, MacroDef, Param, PatField, @@ -86,14 +86,14 @@ impl Target { | Target::Union | Target::Trait | Target::TraitAlias - | Target::Impl + | Target::Impl { .. } | Target::Expression | Target::Statement | Target::Arm | Target::ForeignFn | Target::ForeignStatic | Target::ForeignTy - | Target::GenericParam(_) + | Target::GenericParam { .. } | Target::MacroDef | Target::Param | Target::PatField @@ -119,7 +119,7 @@ impl Target { ItemKind::Union(..) => Target::Union, ItemKind::Trait(..) => Target::Trait, ItemKind::TraitAlias(..) => Target::TraitAlias, - ItemKind::Impl { .. } => Target::Impl, + ItemKind::Impl(imp_) => Target::Impl { of_trait: imp_.of_trait.is_some() }, } } @@ -141,7 +141,7 @@ impl Target { DefKind::Union => Target::Union, DefKind::Trait => Target::Trait, DefKind::TraitAlias => Target::TraitAlias, - DefKind::Impl { .. } => Target::Impl, + DefKind::Impl { of_trait } => Target::Impl { of_trait }, _ => panic!("impossible case reached"), } } @@ -169,11 +169,17 @@ impl Target { pub fn from_generic_param(generic_param: &hir::GenericParam<'_>) -> Target { match generic_param.kind { - hir::GenericParamKind::Type { .. } => Target::GenericParam(GenericParamKind::Type), + hir::GenericParamKind::Type { default, .. } => Target::GenericParam { + kind: GenericParamKind::Type, + has_default: default.is_some(), + }, hir::GenericParamKind::Lifetime { .. } => { - Target::GenericParam(GenericParamKind::Lifetime) + Target::GenericParam { kind: GenericParamKind::Lifetime, has_default: false } } - hir::GenericParamKind::Const { .. } => Target::GenericParam(GenericParamKind::Const), + hir::GenericParamKind::Const { default, .. } => Target::GenericParam { + kind: GenericParamKind::Const, + has_default: default.is_some(), + }, } } @@ -196,7 +202,8 @@ impl Target { Target::Union => "union", Target::Trait => "trait", Target::TraitAlias => "trait alias", - Target::Impl => "implementation block", + Target::Impl { of_trait: false } => "inherent implementation block", + Target::Impl { of_trait: true } => "trait implementation block", Target::Expression => "expression", Target::Statement => "statement", Target::Arm => "match arm", @@ -210,7 +217,7 @@ impl Target { Target::ForeignFn => "foreign function", Target::ForeignStatic => "foreign static item", Target::ForeignTy => "foreign type", - Target::GenericParam(kind) => match kind { + Target::GenericParam { kind, has_default: _ } => match kind { GenericParamKind::Type => "type parameter", GenericParamKind::Lifetime => "lifetime parameter", GenericParamKind::Const => "const parameter", diff --git a/compiler/rustc_hir_analysis/messages.ftl b/compiler/rustc_hir_analysis/messages.ftl index e38ca9e80ce..2428c1aa29f 100644 --- a/compiler/rustc_hir_analysis/messages.ftl +++ b/compiler/rustc_hir_analysis/messages.ftl @@ -371,9 +371,6 @@ hir_analysis_missing_type_params = *[other] parameters } must be specified on the object type -hir_analysis_multiple_relaxed_default_bounds = - type parameter has more than one relaxed default bound, only one is supported - hir_analysis_must_be_name_of_associated_function = must be a name of an associated function hir_analysis_must_implement_not_function = not a function @@ -448,8 +445,6 @@ hir_analysis_parenthesized_fn_trait_expansion = hir_analysis_placeholder_not_allowed_item_signatures = the placeholder `_` is not allowed within types on item signatures for {$kind} .label = not allowed in type signatures -hir_analysis_pointee_sized_trait_object = `PointeeSized` cannot be used with trait objects - hir_analysis_precise_capture_self_alias = `Self` can't be captured in `use<...>` precise captures list, since it is an alias .label = `Self` is not a generic argument, but an alias to the type of the {$what} 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 87db80f2423..e24426f9fed 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs @@ -1173,7 +1173,7 @@ fn check_region_bounds_on_impl_item<'tcx>( bounds_span, where_span, }) - .emit_unless(delay); + .emit_unless_delay(delay); Err(reported) } @@ -1481,7 +1481,7 @@ fn compare_self_type<'tcx>( } else { err.note_trait_signature(trait_m.name(), trait_m.signature(tcx)); } - return Err(err.emit_unless(delay)); + return Err(err.emit_unless_delay(delay)); } (true, false) => { @@ -1502,7 +1502,7 @@ fn compare_self_type<'tcx>( err.note_trait_signature(trait_m.name(), trait_m.signature(tcx)); } - return Err(err.emit_unless(delay)); + return Err(err.emit_unless_delay(delay)); } } @@ -1662,7 +1662,7 @@ fn compare_number_of_generics<'tcx>( err.span_label(*span, "`impl Trait` introduces an implicit type parameter"); } - let reported = err.emit_unless(delay); + let reported = err.emit_unless_delay(delay); err_occurred = Some(reported); } } @@ -1745,7 +1745,7 @@ fn compare_number_of_method_arguments<'tcx>( ), ); - return Err(err.emit_unless(delay)); + return Err(err.emit_unless_delay(delay)); } Ok(()) @@ -1872,7 +1872,7 @@ fn compare_synthetic_generics<'tcx>( ); }; } - error_found = Some(err.emit_unless(delay)); + error_found = Some(err.emit_unless_delay(delay)); } } if let Some(reported) = error_found { Err(reported) } else { Ok(()) } @@ -1974,7 +1974,7 @@ fn compare_generic_param_kinds<'tcx>( err.span_label(impl_header_span, ""); err.span_label(param_impl_span, make_param_message("found", param_impl)); - let reported = err.emit_unless(delay); + let reported = err.emit_unless_delay(delay); return Err(reported); } } diff --git a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs index f2f1560d8b2..cc53919626e 100644 --- a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs @@ -267,20 +267,16 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen match predicate.kind { hir::WherePredicateKind::BoundPredicate(bound_pred) => { let ty = icx.lowerer().lower_ty_maybe_return_type_notation(bound_pred.bounded_ty); - let bound_vars = tcx.late_bound_vars(predicate.hir_id); - // Keep the type around in a dummy predicate, in case of no bounds. - // That way, `where Ty:` is not a complete noop (see #53696) and `Ty` - // is still checked for WF. + + // This is a `where Ty:` (sic!). if bound_pred.bounds.is_empty() { if let ty::Param(_) = ty.kind() { - // This is a `where T:`, which can be in the HIR from the - // transformation that moves `?Sized` to `T`'s declaration. - // We can skip the predicate because type parameters are - // trivially WF, but also we *should*, to avoid exposing - // users who never wrote `where Type:,` themselves, to - // compiler/tooling bugs from not handling WF predicates. + // We can skip the predicate because type parameters are trivially WF. } else { + // Keep the type around in a dummy predicate. That way, it's not a complete + // noop (see #53696) and `Ty` is still checked for WF. + let span = bound_pred.bounded_ty.span; let predicate = ty::Binder::bind_with_vars( ty::ClauseKind::WellFormed(ty.into()), diff --git a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs index 77e63e38c8c..eb3492f5de6 100644 --- a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs +++ b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs @@ -2495,7 +2495,7 @@ fn deny_non_region_late_bound( format!("late-bound {what} parameter not allowed on {where_}"), ); - let guar = diag.emit_unless(!tcx.features().non_lifetime_binders() || !first); + let guar = diag.emit_unless_delay(!tcx.features().non_lifetime_binders() || !first); first = false; *arg = ResolvedArg::Error(guar); diff --git a/compiler/rustc_hir_analysis/src/errors.rs b/compiler/rustc_hir_analysis/src/errors.rs index fbd21f8b100..26a98722b34 100644 --- a/compiler/rustc_hir_analysis/src/errors.rs +++ b/compiler/rustc_hir_analysis/src/errors.rs @@ -280,13 +280,6 @@ pub(crate) struct CopyImplOnTypeWithDtor { } #[derive(Diagnostic)] -#[diag(hir_analysis_multiple_relaxed_default_bounds, code = E0203)] -pub(crate) struct MultipleRelaxedDefaultBounds { - #[primary_span] - pub spans: Vec<Span>, -} - -#[derive(Diagnostic)] #[diag(hir_analysis_copy_impl_on_non_adt, code = E0206)] pub(crate) struct CopyImplOnNonAdt { #[primary_span] @@ -320,13 +313,6 @@ pub(crate) struct TraitObjectDeclaredWithNoTraits { } #[derive(Diagnostic)] -#[diag(hir_analysis_pointee_sized_trait_object)] -pub(crate) struct PointeeSizedTraitObject { - #[primary_span] - pub span: Span, -} - -#[derive(Diagnostic)] #[diag(hir_analysis_ambiguous_lifetime_bound, code = E0227)] pub(crate) struct AmbiguousLifetimeBound { #[primary_span] 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 9a752aeccdd..d7a827c649d 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs @@ -6,7 +6,7 @@ use rustc_errors::struct_span_code_err; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LocalDefId}; -use rustc_hir::{AmbigArg, LangItem, PolyTraitRef}; +use rustc_hir::{AmbigArg, PolyTraitRef}; use rustc_middle::bug; use rustc_middle::ty::{ self as ty, IsSuggestable, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, @@ -85,17 +85,17 @@ fn search_bounds_for<'tcx>( } } -fn collect_unbounds<'tcx>( +fn collect_relaxed_bounds<'tcx>( hir_bounds: &'tcx [hir::GenericBound<'tcx>], self_ty_where_predicates: Option<(LocalDefId, &'tcx [hir::WherePredicate<'tcx>])>, ) -> SmallVec<[&'tcx PolyTraitRef<'tcx>; 1]> { - let mut unbounds: SmallVec<[_; 1]> = SmallVec::new(); + let mut relaxed_bounds: SmallVec<[_; 1]> = SmallVec::new(); search_bounds_for(hir_bounds, self_ty_where_predicates, |ptr| { if matches!(ptr.modifiers.polarity, hir::BoundPolarity::Maybe(_)) { - unbounds.push(ptr); + relaxed_bounds.push(ptr); } }); - unbounds + relaxed_bounds } fn collect_bounds<'a, 'tcx>( @@ -124,13 +124,13 @@ fn collect_sizedness_bounds<'tcx>( self_ty_where_predicates: Option<(LocalDefId, &'tcx [hir::WherePredicate<'tcx>])>, span: Span, ) -> CollectedSizednessBounds { - let sized_did = tcx.require_lang_item(LangItem::Sized, span); + let sized_did = tcx.require_lang_item(hir::LangItem::Sized, span); let sized = collect_bounds(hir_bounds, self_ty_where_predicates, sized_did); - let meta_sized_did = tcx.require_lang_item(LangItem::MetaSized, span); + let meta_sized_did = tcx.require_lang_item(hir::LangItem::MetaSized, span); let meta_sized = collect_bounds(hir_bounds, self_ty_where_predicates, meta_sized_did); - let pointee_sized_did = tcx.require_lang_item(LangItem::PointeeSized, span); + let pointee_sized_did = tcx.require_lang_item(hir::LangItem::PointeeSized, span); let pointee_sized = collect_bounds(hir_bounds, self_ty_where_predicates, pointee_sized_did); CollectedSizednessBounds { sized, meta_sized, pointee_sized } @@ -151,24 +151,6 @@ fn add_trait_bound<'tcx>( } impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { - /// Skip `PointeeSized` bounds. - /// - /// `PointeeSized` is a "fake bound" insofar as anywhere a `PointeeSized` bound exists, there - /// is actually the absence of any bounds. This avoids limitations around non-global where - /// clauses being preferred over item bounds (where `PointeeSized` bounds would be - /// proven) - which can result in errors when a `PointeeSized` supertrait/bound/predicate is - /// added to some items. - pub(crate) fn should_skip_sizedness_bound<'hir>( - &self, - bound: &'hir hir::GenericBound<'tcx>, - ) -> bool { - bound - .trait_ref() - .and_then(|tr| tr.trait_def_id()) - .map(|did| self.tcx().is_lang_item(did, LangItem::PointeeSized)) - .unwrap_or(false) - } - /// Adds sizedness bounds to a trait, trait alias, parameter, opaque type or associated type. /// /// - On parameters, opaque type and associated types, add default `Sized` bound if no explicit @@ -193,8 +175,8 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { return; } - let meta_sized_did = tcx.require_lang_item(LangItem::MetaSized, span); - let pointee_sized_did = tcx.require_lang_item(LangItem::PointeeSized, span); + let meta_sized_did = tcx.require_lang_item(hir::LangItem::MetaSized, span); + let pointee_sized_did = tcx.require_lang_item(hir::LangItem::PointeeSized, span); // If adding sizedness bounds to a trait, then there are some relevant early exits if let Some(trait_did) = trait_did { @@ -209,9 +191,22 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { return; } } else { - // Report invalid unbounds on sizedness-bounded generic parameters. - let unbounds = collect_unbounds(hir_bounds, self_ty_where_predicates); - self.check_and_report_invalid_unbounds_on_param(unbounds); + // Report invalid relaxed bounds. + // FIXME: Since we only call this validation function here in this function, we only + // fully validate relaxed bounds in contexts where we perform + // "sized elaboration". In most cases that doesn't matter because we *usually* + // reject such relaxed bounds outright during AST lowering. + // However, this can easily get out of sync! Ideally, we would perform this step + // where we are guaranteed to catch *all* bounds like in + // `Self::lower_poly_trait_ref`. List of concrete issues: + // FIXME(more_maybe_bounds): We don't call this for e.g., trait object tys or + // supertrait bounds! + // FIXME(trait_alias, #143122): We don't call it for the RHS. Arguably however, + // AST lowering should reject them outright. + // FIXME(associated_type_bounds): We don't call this for them. However, AST + // lowering should reject them outright (#135229). + let bounds = collect_relaxed_bounds(hir_bounds, self_ty_where_predicates); + self.check_and_report_invalid_relaxed_bounds(bounds); } let collected = collect_sizedness_bounds(tcx, hir_bounds, self_ty_where_predicates, span); @@ -231,7 +226,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { } else { // If there are no explicit sizedness bounds on a parameter then add a default // `Sized` bound. - let sized_did = tcx.require_lang_item(LangItem::Sized, span); + let sized_did = tcx.require_lang_item(hir::LangItem::Sized, span); add_trait_bound(tcx, bounds, self_ty, sized_did, span); } } @@ -463,10 +458,6 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { 'tcx: 'hir, { for hir_bound in hir_bounds { - if self.should_skip_sizedness_bound(hir_bound) { - continue; - } - // In order to avoid cycles, when we're lowering `SelfTraitThatDefines`, // we skip over any traits that don't define the given associated type. if let PredicateFilter::SelfTraitThatDefines(assoc_ident) = predicate_filter { @@ -482,12 +473,8 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { match hir_bound { hir::GenericBound::Trait(poly_trait_ref) => { - let hir::TraitBoundModifiers { constness, polarity } = poly_trait_ref.modifiers; let _ = self.lower_poly_trait_ref( - &poly_trait_ref.trait_ref, - poly_trait_ref.span, - constness, - polarity, + poly_trait_ref, param_ty, bounds, predicate_filter, 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 364ad38556b..76bb59e3f09 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 @@ -2,7 +2,6 @@ use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet}; use rustc_errors::codes::*; use rustc_errors::struct_span_code_err; use rustc_hir as hir; -use rustc_hir::LangItem; use rustc_hir::def::{DefKind, Res}; use rustc_lint_defs::builtin::UNUSED_ASSOCIATED_TYPE_BOUNDS; use rustc_middle::ty::elaborate::ClauseWithSupertraitSpan; @@ -18,9 +17,7 @@ use tracing::{debug, instrument}; use super::HirTyLowerer; use crate::errors::SelfInTypeAlias; -use crate::hir_ty_lowering::{ - GenericArgCountMismatch, GenericArgCountResult, PredicateFilter, RegionInferReason, -}; +use crate::hir_ty_lowering::{GenericArgCountMismatch, PredicateFilter, RegionInferReason}; impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { /// Lower a trait object type from the HIR to our internal notion of a type. @@ -38,24 +35,15 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { let mut user_written_bounds = Vec::new(); let mut potential_assoc_types = Vec::new(); - for trait_bound in hir_bounds.iter() { - if let hir::BoundPolarity::Maybe(_) = trait_bound.modifiers.polarity { - continue; - } - if let GenericArgCountResult { - correct: - Err(GenericArgCountMismatch { invalid_args: cur_potential_assoc_types, .. }), - .. - } = self.lower_poly_trait_ref( - &trait_bound.trait_ref, - trait_bound.span, - trait_bound.modifiers.constness, - hir::BoundPolarity::Positive, + for poly_trait_ref in hir_bounds.iter() { + let result = self.lower_poly_trait_ref( + poly_trait_ref, dummy_self, &mut user_written_bounds, PredicateFilter::SelfOnly, - ) { - potential_assoc_types.extend(cur_potential_assoc_types); + ); + if let Err(GenericArgCountMismatch { invalid_args, .. }) = result.correct { + potential_assoc_types.extend(invalid_args); } } @@ -81,13 +69,6 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { let guar = self.report_trait_object_addition_traits(®ular_traits); return Ty::new_error(tcx, guar); } - // We don't support `PointeeSized` principals - let pointee_sized_did = tcx.require_lang_item(LangItem::PointeeSized, span); - if regular_traits.iter().any(|(pred, _)| pred.def_id() == pointee_sized_did) { - let guar = self.report_pointee_sized_trait_object(span); - return Ty::new_error(tcx, guar); - } - // Don't create a dyn trait if we have errors in the principal. if let Err(guar) = regular_traits.error_reported() { return Ty::new_error(tcx, guar); diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs index 5d85a3f8455..287a5532f01 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs @@ -8,7 +8,7 @@ use rustc_errors::{ }; use rustc_hir::def::{CtorOf, DefKind, Res}; use rustc_hir::def_id::DefId; -use rustc_hir::{self as hir, HirId, LangItem, PolyTraitRef}; +use rustc_hir::{self as hir, HirId, PolyTraitRef}; use rustc_middle::bug; use rustc_middle::ty::fast_reject::{TreatParams, simplify_type}; use rustc_middle::ty::print::{PrintPolyTraitRefExt as _, PrintTraitRefExt as _}; @@ -29,59 +29,54 @@ use tracing::debug; use super::InherentAssocCandidate; use crate::errors::{ self, AssocItemConstraintsNotAllowedHere, ManualImplementation, MissingTypeParams, - ParenthesizedFnTraitExpansion, PointeeSizedTraitObject, TraitObjectDeclaredWithNoTraits, + ParenthesizedFnTraitExpansion, TraitObjectDeclaredWithNoTraits, }; use crate::fluent_generated as fluent; use crate::hir_ty_lowering::{AssocItemQSelf, HirTyLowerer}; impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { - /// Check for multiple relaxed default bounds and relaxed bounds of non-sizedness traits. - pub(crate) fn check_and_report_invalid_unbounds_on_param( + /// Check for duplicate relaxed bounds and relaxed bounds of non-default traits. + pub(crate) fn check_and_report_invalid_relaxed_bounds( &self, - unbounds: SmallVec<[&PolyTraitRef<'_>; 1]>, + relaxed_bounds: SmallVec<[&PolyTraitRef<'_>; 1]>, ) { let tcx = self.tcx(); - let sized_did = tcx.require_lang_item(LangItem::Sized, DUMMY_SP); + let mut grouped_bounds = FxIndexMap::<_, Vec<_>>::default(); - let mut unique_bounds = FxIndexSet::default(); - let mut seen_repeat = false; - for unbound in &unbounds { - if let Res::Def(DefKind::Trait, unbound_def_id) = unbound.trait_ref.path.res { - seen_repeat |= !unique_bounds.insert(unbound_def_id); + for bound in &relaxed_bounds { + if let Res::Def(DefKind::Trait, trait_def_id) = bound.trait_ref.path.res { + grouped_bounds.entry(trait_def_id).or_default().push(bound.span); } } - if unbounds.len() > 1 { - let err = errors::MultipleRelaxedDefaultBounds { - spans: unbounds.iter().map(|ptr| ptr.span).collect(), - }; - - if seen_repeat { - tcx.dcx().emit_err(err); - } else if !tcx.features().more_maybe_bounds() { - tcx.sess.create_feature_err(err, sym::more_maybe_bounds).emit(); - }; + for (trait_def_id, spans) in grouped_bounds { + if spans.len() > 1 { + let name = tcx.item_name(trait_def_id); + self.dcx() + .struct_span_err(spans, format!("duplicate relaxed `{name}` bounds")) + .with_code(E0203) + .emit(); + } } - for unbound in unbounds { - if let Res::Def(DefKind::Trait, did) = unbound.trait_ref.path.res - && ((did == sized_did) || tcx.is_default_trait(did)) + let sized_def_id = tcx.require_lang_item(hir::LangItem::Sized, DUMMY_SP); + + for bound in relaxed_bounds { + if let Res::Def(DefKind::Trait, def_id) = bound.trait_ref.path.res + && (def_id == sized_def_id || tcx.is_default_trait(def_id)) { continue; } - - let unbound_traits = match tcx.sess.opts.unstable_opts.experimental_default_bounds { - true => "`?Sized` and `experimental_default_bounds`", - false => "`?Sized`", - }; self.dcx().span_err( - unbound.span, - format!( - "relaxing a default bound only does something for {}; all other traits are \ - not bound by default", - unbound_traits - ), + bound.span, + if tcx.sess.opts.unstable_opts.experimental_default_bounds + || tcx.features().more_maybe_bounds() + { + "bound modifier `?` can only be applied to default traits like `Sized`" + } else { + "bound modifier `?` can only be applied to `Sized`" + }, ); } } @@ -1410,10 +1405,6 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { self.dcx().emit_err(TraitObjectDeclaredWithNoTraits { span, trait_alias_span }) } - - pub(super) fn report_pointee_sized_trait_object(&self, span: Span) -> ErrorGuaranteed { - self.dcx().emit_err(PointeeSizedTraitObject { span }) - } } /// Emit an error for the given associated item constraint. diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs index 8c7c3750865..fc519c194bb 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs @@ -570,7 +570,7 @@ pub(crate) fn check_generic_arg_count( gen_args, def_id, )) - .emit_unless(all_params_are_binded) + .emit_unless_delay(all_params_are_binded) }); Err(reported) 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 a5bd7c1a34a..d7687998358 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs @@ -747,18 +747,46 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>` /// where `'a` is a bound region at depth 0. Similarly, the `trait_ref` would be `Bar<'a>`. /// The lowered poly-trait-ref will track this binder explicitly, however. - #[instrument(level = "debug", skip(self, span, constness, bounds))] + #[instrument(level = "debug", skip(self, bounds))] pub(crate) fn lower_poly_trait_ref( &self, - trait_ref: &hir::TraitRef<'tcx>, - span: Span, - constness: hir::BoundConstness, - polarity: hir::BoundPolarity, + poly_trait_ref: &hir::PolyTraitRef<'tcx>, self_ty: Ty<'tcx>, bounds: &mut Vec<(ty::Clause<'tcx>, Span)>, predicate_filter: PredicateFilter, ) -> GenericArgCountResult { + let tcx = self.tcx(); + + // We use the *resolved* bound vars later instead of the HIR ones since the former + // also include the bound vars of the overarching predicate if applicable. + let hir::PolyTraitRef { bound_generic_params: _, modifiers, ref trait_ref, span } = + *poly_trait_ref; + let hir::TraitBoundModifiers { constness, polarity } = modifiers; + let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()); + + // Relaxed bounds `?Trait` and `PointeeSized` bounds aren't represented in the `middle::ty` IR + // as they denote the *absence* of a default bound. However, we can't bail out early here since + // we still need to perform several validation steps (see below). Instead, simply "pour" all + // resulting bounds "down the drain", i.e., into a new `Vec` that just gets dropped at the end. + let (polarity, bounds) = match polarity { + rustc_ast::BoundPolarity::Positive + if tcx.is_lang_item(trait_def_id, hir::LangItem::PointeeSized) => + { + // To elaborate on the comment directly above, regarding `PointeeSized` specifically, + // we don't "reify" such bounds to avoid trait system limitations -- namely, + // non-global where-clauses being preferred over item bounds (where `PointeeSized` + // bounds would be proven) -- which can result in errors when a `PointeeSized` + // supertrait / bound / predicate is added to some items. + (ty::PredicatePolarity::Positive, &mut Vec::new()) + } + rustc_ast::BoundPolarity::Positive => (ty::PredicatePolarity::Positive, bounds), + rustc_ast::BoundPolarity::Negative(_) => (ty::PredicatePolarity::Negative, bounds), + rustc_ast::BoundPolarity::Maybe(_) => { + (ty::PredicatePolarity::Positive, &mut Vec::new()) + } + }; + let trait_segment = trait_ref.path.segments.last().unwrap(); let _ = self.prohibit_generic_args( @@ -775,7 +803,6 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { Some(self_ty), ); - let tcx = self.tcx(); let bound_vars = tcx.late_bound_vars(trait_ref.hir_ref_id); debug!(?bound_vars); @@ -786,27 +813,6 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { debug!(?poly_trait_ref); - let polarity = match polarity { - rustc_ast::BoundPolarity::Positive => ty::PredicatePolarity::Positive, - rustc_ast::BoundPolarity::Negative(_) => ty::PredicatePolarity::Negative, - rustc_ast::BoundPolarity::Maybe(_) => { - // Validate associated type at least. We may want to reject these - // outright in the future... - for constraint in trait_segment.args().constraints { - let _ = self.lower_assoc_item_constraint( - trait_ref.hir_ref_id, - poly_trait_ref, - constraint, - &mut Default::default(), - &mut Default::default(), - constraint.span, - predicate_filter, - ); - } - return arg_count; - } - }; - // We deal with const conditions later. match predicate_filter { PredicateFilter::All @@ -909,7 +915,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { // Don't register any associated item constraints for negative bounds, // since we should have emitted an error for them earlier, and they // would not be well-formed! - if polarity != ty::PredicatePolarity::Positive { + if polarity == ty::PredicatePolarity::Negative { self.dcx().span_delayed_bug( constraint.span, "negative trait bounds should not have assoc item constraints", @@ -2489,6 +2495,14 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { ty::List::empty(), PredicateFilter::All, ); + self.add_sizedness_bounds( + &mut bounds, + self_ty, + hir_bounds, + None, + None, + hir_ty.span, + ); self.register_trait_ascription_bounds(bounds, hir_ty.hir_id, hir_ty.span); self_ty } diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index b2a229ad651..6d67535da5f 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -1775,7 +1775,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { ); } - let reported = err.emit_unless(unsized_return); + let reported = err.emit_unless_delay(unsized_return); self.final_ty = Some(Ty::new_error(fcx.tcx, reported)); } diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 067ee0f0eb0..08e8164078c 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -1549,7 +1549,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // If the assignment expression itself is ill-formed, don't // bother emitting another error - err.emit_unless(lhs_ty.references_error() || rhs_ty.references_error()) + err.emit_unless_delay(lhs_ty.references_error() || rhs_ty.references_error()) } pub(super) fn check_expr_let( @@ -3865,7 +3865,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.dcx() .create_err(NoVariantNamed { span: ident.span, ident, ty: container }) .with_span_label(field.span, "variant not found") - .emit_unless(container.references_error()); + .emit_unless_delay(container.references_error()); break; }; let Some(&subfield) = fields.next() else { @@ -3897,7 +3897,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { enum_span: field.span, field_span: subident.span, }) - .emit_unless(container.references_error()); + .emit_unless_delay(container.references_error()); break; }; diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index a438cde018c..fb6897c7d89 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -1055,17 +1055,11 @@ fn run_required_analyses(tcx: TyCtxt<'_>) { }); }, { - sess.time("unused_lib_feature_checking", || { - rustc_passes::stability::check_unused_or_stable_features(tcx) - }); - }, - { // We force these queries to run, // since they might not otherwise get called. // This marks the corresponding crate-level attributes // as used, and ensures that their values are valid. tcx.ensure_ok().limits(()); - tcx.ensure_ok().stability_index(()); } ); }); diff --git a/compiler/rustc_interface/src/tests.rs b/compiler/rustc_interface/src/tests.rs index 360b5629e9d..8771bb44050 100644 --- a/compiler/rustc_interface/src/tests.rs +++ b/compiler/rustc_interface/src/tests.rs @@ -13,10 +13,10 @@ use rustc_session::config::{ CoverageOptions, DebugInfo, DumpMonoStatsFormat, ErrorOutputType, ExternEntry, ExternLocation, Externs, FmtDebug, FunctionReturn, InliningThreshold, Input, InstrumentCoverage, InstrumentXRay, LinkSelfContained, LinkerPluginLto, LocationDetail, LtoCli, MirIncludeSpans, - NextSolverConfig, OomStrategy, Options, OutFileName, OutputType, OutputTypes, PAuthKey, PacRet, - Passes, PatchableFunctionEntry, Polonius, ProcMacroExecutionStrategy, Strip, SwitchWithOptPath, - SymbolManglingVersion, WasiExecModel, build_configuration, build_session_options, - rustc_optgroups, + NextSolverConfig, Offload, OomStrategy, Options, OutFileName, OutputType, OutputTypes, + PAuthKey, PacRet, Passes, PatchableFunctionEntry, Polonius, ProcMacroExecutionStrategy, Strip, + SwitchWithOptPath, SymbolManglingVersion, WasiExecModel, build_configuration, + build_session_options, rustc_optgroups, }; use rustc_session::lint::Level; use rustc_session::search_paths::SearchPath; @@ -833,6 +833,7 @@ fn test_unstable_options_tracking_hash() { tracked!(no_profiler_runtime, true); tracked!(no_trait_vptr, true); tracked!(no_unique_section_names, true); + tracked!(offload, vec![Offload::Enable]); tracked!(on_broken_pipe, OnBrokenPipe::Kill); tracked!(oom, OomStrategy::Panic); tracked!(osx_rpath_install_name, true); diff --git a/compiler/rustc_lint/src/ptr_nulls.rs b/compiler/rustc_lint/src/ptr_nulls.rs index 826bce2c315..b2fa0fba76d 100644 --- a/compiler/rustc_lint/src/ptr_nulls.rs +++ b/compiler/rustc_lint/src/ptr_nulls.rs @@ -160,12 +160,10 @@ impl<'tcx> LateLintPass<'tcx> for PtrNullChecks { let (arg_indices, are_zsts_allowed): (&[_], _) = match diag_name { sym::ptr_read | sym::ptr_read_unaligned - | sym::ptr_read_volatile | sym::ptr_replace | sym::ptr_write | sym::ptr_write_bytes - | sym::ptr_write_unaligned - | sym::ptr_write_volatile => (&[0], true), + | sym::ptr_write_unaligned => (&[0], true), sym::slice_from_raw_parts | sym::slice_from_raw_parts_mut => (&[0], false), sym::ptr_copy | sym::ptr_copy_nonoverlapping diff --git a/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp b/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp index cc33764e485..a2e4d7306cb 100644 --- a/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp +++ b/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp @@ -396,7 +396,7 @@ extern "C" LLVMTargetMachineRef LLVMRustCreateTargetMachine( bool EmitStackSizeSection, bool RelaxELFRelocations, bool UseInitArray, const char *SplitDwarfFile, const char *OutputObjFile, const char *DebugInfoCompression, bool UseEmulatedTls, - const char *ArgsCstrBuff, size_t ArgsCstrBuffLen) { + const char *ArgsCstrBuff, size_t ArgsCstrBuffLen, bool UseWasmEH) { auto OptLevel = fromRust(RustOptLevel); auto RM = fromRust(RustReloc); @@ -462,6 +462,9 @@ extern "C" LLVMTargetMachineRef LLVMRustCreateTargetMachine( Options.ThreadModel = ThreadModel::Single; } + if (UseWasmEH) + Options.ExceptionModel = ExceptionHandling::Wasm; + Options.EmitStackSizeSection = EmitStackSizeSection; if (ArgsCstrBuff != nullptr) { @@ -700,6 +703,10 @@ struct LLVMRustSanitizerOptions { #ifdef ENZYME extern "C" void registerEnzymeAndPassPipeline(llvm::PassBuilder &PB, /* augmentPassBuilder */ bool); + +extern "C" { +extern llvm::cl::opt<std::string> EnzymeFunctionToAnalyze; +} #endif extern "C" LLVMRustResult LLVMRustOptimize( @@ -1069,6 +1076,15 @@ extern "C" LLVMRustResult LLVMRustOptimize( return LLVMRustResult::Failure; } + // Check if PrintTAFn was used and add type analysis pass if needed + if (!EnzymeFunctionToAnalyze.empty()) { + if (auto Err = PB.parsePassPipeline(MPM, "print-type-analysis")) { + std::string ErrMsg = toString(std::move(Err)); + LLVMRustSetLastError(ErrMsg.c_str()); + return LLVMRustResult::Failure; + } + } + if (PrintAfterEnzyme) { // Handle the Rust flag `-Zautodiff=PrintModAfter`. std::string Banner = "Module after EnzymeNewPM"; diff --git a/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp b/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp index 90aa9188c83..82568ed4ae1 100644 --- a/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp +++ b/compiler/rustc_llvm/llvm-wrapper/RustWrapper.cpp @@ -1591,12 +1591,49 @@ extern "C" LLVMValueRef LLVMRustBuildMemSet(LLVMBuilderRef B, LLVMValueRef Dst, MaybeAlign(DstAlign), IsVolatile)); } +extern "C" void LLVMRustPositionBuilderPastAllocas(LLVMBuilderRef B, + LLVMValueRef Fn) { + Function *F = unwrap<Function>(Fn); + unwrap(B)->SetInsertPointPastAllocas(F); +} extern "C" void LLVMRustPositionBuilderAtStart(LLVMBuilderRef B, LLVMBasicBlockRef BB) { auto Point = unwrap(BB)->getFirstInsertionPt(); unwrap(B)->SetInsertPoint(unwrap(BB), Point); } +extern "C" void LLVMRustPositionBefore(LLVMBuilderRef B, LLVMValueRef Instr) { + if (auto I = dyn_cast<Instruction>(unwrap<Value>(Instr))) { + unwrap(B)->SetInsertPoint(I); + } +} + +extern "C" void LLVMRustPositionAfter(LLVMBuilderRef B, LLVMValueRef Instr) { + if (auto I = dyn_cast<Instruction>(unwrap<Value>(Instr))) { + auto J = I->getNextNonDebugInstruction(); + unwrap(B)->SetInsertPoint(J); + } +} + +extern "C" LLVMValueRef +LLVMRustGetFunctionCall(LLVMValueRef Fn, const char *Name, size_t NameLen) { + auto targetName = StringRef(Name, NameLen); + Function *F = unwrap<Function>(Fn); + for (auto &BB : *F) { + for (auto &I : BB) { + if (auto *callInst = llvm::dyn_cast<llvm::CallBase>(&I)) { + const llvm::Function *calledFunc = callInst->getCalledFunction(); + if (calledFunc && calledFunc->getName() == targetName) { + // Found a call to the target function + return wrap(callInst); + } + } + } + } + + return nullptr; +} + extern "C" bool LLVMRustConstIntGetZExtValue(LLVMValueRef CV, uint64_t *value) { auto C = unwrap<llvm::ConstantInt>(CV); if (C->getBitWidth() > 64) diff --git a/compiler/rustc_metadata/src/creader.rs b/compiler/rustc_metadata/src/creader.rs index e65c7a68426..438eff33054 100644 --- a/compiler/rustc_metadata/src/creader.rs +++ b/compiler/rustc_metadata/src/creader.rs @@ -12,7 +12,6 @@ use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::owned_slice::OwnedSlice; use rustc_data_structures::svh::Svh; use rustc_data_structures::sync::{self, FreezeReadGuard, FreezeWriteGuard}; -use rustc_errors::DiagCtxtHandle; use rustc_expand::base::SyntaxExtension; use rustc_fs_util::try_canonicalize; use rustc_hir as hir; @@ -23,8 +22,10 @@ use rustc_middle::bug; use rustc_middle::ty::data_structures::IndexSet; use rustc_middle::ty::{TyCtxt, TyCtxtFeed}; use rustc_proc_macro::bridge::client::ProcMacro; +use rustc_session::Session; use rustc_session::config::{ - CrateType, ExtendedTargetModifierInfo, ExternLocation, OptionsTargetModifiers, TargetModifier, + CrateType, ExtendedTargetModifierInfo, ExternLocation, Externs, OptionsTargetModifiers, + TargetModifier, }; use rustc_session::cstore::{CrateDepKind, CrateSource, ExternCrate, ExternCrateSource}; use rustc_session::lint::{self, BuiltinLintDiag}; @@ -70,6 +71,8 @@ pub struct CStore { /// Unused externs of the crate unused_externs: Vec<Symbol>, + + used_extern_options: FxHashSet<Symbol>, } impl std::fmt::Debug for CStore { @@ -78,28 +81,6 @@ impl std::fmt::Debug for CStore { } } -pub struct CrateLoader<'a, 'tcx: 'a> { - // Immutable configuration. - tcx: TyCtxt<'tcx>, - // Mutable output. - cstore: &'a mut CStore, - used_extern_options: &'a mut FxHashSet<Symbol>, -} - -impl<'a, 'tcx> std::ops::Deref for CrateLoader<'a, 'tcx> { - type Target = TyCtxt<'tcx>; - - fn deref(&self) -> &Self::Target { - &self.tcx - } -} - -impl<'a, 'tcx> CrateLoader<'a, 'tcx> { - fn dcx(&self) -> DiagCtxtHandle<'tcx> { - self.tcx.dcx() - } -} - pub enum LoadedMacro { MacroDef { def: MacroDef, @@ -227,8 +208,8 @@ impl CStore { fn intern_stable_crate_id<'tcx>( &mut self, - root: &CrateRoot, tcx: TyCtxt<'tcx>, + root: &CrateRoot, ) -> Result<TyCtxtFeed<'tcx, CrateNum>, CrateError> { assert_eq!(self.metas.len(), tcx.untracked().stable_crate_ids.read().len()); let num = tcx.create_crate_num(root.stable_crate_id()).map_err(|existing| { @@ -495,21 +476,18 @@ impl CStore { has_global_allocator: false, has_alloc_error_handler: false, unused_externs: Vec::new(), + used_extern_options: Default::default(), } } -} -impl<'a, 'tcx> CrateLoader<'a, 'tcx> { - pub fn new( - tcx: TyCtxt<'tcx>, - cstore: &'a mut CStore, - used_extern_options: &'a mut FxHashSet<Symbol>, - ) -> Self { - CrateLoader { tcx, cstore, used_extern_options } - } - - fn existing_match(&self, name: Symbol, hash: Option<Svh>, kind: PathKind) -> Option<CrateNum> { - for (cnum, data) in self.cstore.iter_crate_data() { + fn existing_match( + &self, + externs: &Externs, + name: Symbol, + hash: Option<Svh>, + kind: PathKind, + ) -> Option<CrateNum> { + for (cnum, data) in self.iter_crate_data() { if data.name() != name { trace!("{} did not match {}", data.name(), name); continue; @@ -533,8 +511,8 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { // We're also sure to compare *paths*, not actual byte slices. The // `source` stores paths which are normalized which may be different // from the strings on the command line. - let source = self.cstore.get_crate_data(cnum).cdata.source(); - if let Some(entry) = self.sess.opts.externs.get(name.as_str()) { + let source = self.get_crate_data(cnum).cdata.source(); + if let Some(entry) = externs.get(name.as_str()) { // Only use `--extern crate_name=path` here, not `--extern crate_name`. if let Some(mut files) = entry.files() { if files.any(|l| { @@ -587,6 +565,7 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { /// command parameter is set to `public-dependency` fn is_private_dep( &self, + externs: &Externs, name: Symbol, private_dep: Option<bool>, origin: CrateOrigin<'_>, @@ -595,7 +574,7 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { return true; } - let extern_private = self.sess.opts.externs.get(name.as_str()).map(|e| e.is_private_dep); + let extern_private = externs.get(name.as_str()).map(|e| e.is_private_dep); match (extern_private, private_dep) { // Explicit non-private via `--extern`, explicit non-private from metadata, or // unspecified with default to public. @@ -605,8 +584,9 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { } } - fn register_crate( + fn register_crate<'tcx>( &mut self, + tcx: TyCtxt<'tcx>, host_lib: Option<Library>, origin: CrateOrigin<'_>, lib: Library, @@ -615,15 +595,15 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { private_dep: Option<bool>, ) -> Result<CrateNum, CrateError> { let _prof_timer = - self.sess.prof.generic_activity_with_arg("metadata_register_crate", name.as_str()); + tcx.sess.prof.generic_activity_with_arg("metadata_register_crate", name.as_str()); let Library { source, metadata } = lib; let crate_root = metadata.get_root(); let host_hash = host_lib.as_ref().map(|lib| lib.metadata.get_root().hash()); - let private_dep = self.is_private_dep(name, private_dep, origin); + let private_dep = self.is_private_dep(&tcx.sess.opts.externs, name, private_dep, origin); // Claim this crate number and cache it - let feed = self.cstore.intern_stable_crate_id(&crate_root, self.tcx)?; + let feed = self.intern_stable_crate_id(tcx, &crate_root)?; let cnum = feed.key(); info!( @@ -643,8 +623,15 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { &crate_paths }; - let cnum_map = - self.resolve_crate_deps(dep_root, &crate_root, &metadata, cnum, dep_kind, private_dep)?; + let cnum_map = self.resolve_crate_deps( + tcx, + dep_root, + &crate_root, + &metadata, + cnum, + dep_kind, + private_dep, + )?; let raw_proc_macros = if crate_root.is_proc_macro_crate() { let temp_root; @@ -656,14 +643,14 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { None => (&source, &crate_root), }; let dlsym_dylib = dlsym_source.dylib.as_ref().expect("no dylib for a proc-macro crate"); - Some(self.dlsym_proc_macros(&dlsym_dylib.0, dlsym_root.stable_crate_id())?) + Some(self.dlsym_proc_macros(tcx.sess, &dlsym_dylib.0, dlsym_root.stable_crate_id())?) } else { None }; let crate_metadata = CrateMetadata::new( - self.sess, - self.cstore, + tcx.sess, + self, metadata, crate_root, raw_proc_macros, @@ -675,13 +662,14 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { host_hash, ); - self.cstore.set_crate_data(cnum, crate_metadata); + self.set_crate_data(cnum, crate_metadata); Ok(cnum) } - fn load_proc_macro<'b>( + fn load_proc_macro<'a, 'b>( &self, + sess: &'a Session, locator: &mut CrateLocator<'b>, crate_rejections: &mut CrateRejections, path_kind: PathKind, @@ -690,13 +678,13 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { where 'a: 'b, { - if self.sess.opts.unstable_opts.dual_proc_macros { + if sess.opts.unstable_opts.dual_proc_macros { // Use a new crate locator and crate rejections so trying to load a proc macro doesn't // affect the error message we emit let mut proc_macro_locator = locator.clone(); // Try to load a proc macro - proc_macro_locator.for_target_proc_macro(self.sess, path_kind); + proc_macro_locator.for_target_proc_macro(sess, path_kind); // Load the proc macro crate for the target let target_result = @@ -713,7 +701,7 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { *crate_rejections = CrateRejections::default(); // Load the proc macro crate for the host - locator.for_proc_macro(self.sess, path_kind); + locator.for_proc_macro(sess, path_kind); locator.hash = host_hash; @@ -734,7 +722,7 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { let mut proc_macro_locator = locator.clone(); // Load the proc macro crate for the host - proc_macro_locator.for_proc_macro(self.sess, path_kind); + proc_macro_locator.for_proc_macro(sess, path_kind); let Some(host_result) = self.load(&mut proc_macro_locator, &mut CrateRejections::default())? @@ -746,32 +734,39 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { } } - fn resolve_crate( + fn resolve_crate<'tcx>( &mut self, + tcx: TyCtxt<'tcx>, name: Symbol, span: Span, dep_kind: CrateDepKind, origin: CrateOrigin<'_>, ) -> Option<CrateNum> { self.used_extern_options.insert(name); - match self.maybe_resolve_crate(name, dep_kind, origin) { + match self.maybe_resolve_crate(tcx, name, dep_kind, origin) { Ok(cnum) => { - self.cstore.set_used_recursively(cnum); + self.set_used_recursively(cnum); Some(cnum) } Err(err) => { debug!("failed to resolve crate {} {:?}", name, dep_kind); let missing_core = self - .maybe_resolve_crate(sym::core, CrateDepKind::Explicit, CrateOrigin::Extern) + .maybe_resolve_crate( + tcx, + sym::core, + CrateDepKind::Explicit, + CrateOrigin::Extern, + ) .is_err(); - err.report(self.sess, span, missing_core); + err.report(tcx.sess, span, missing_core); None } } } - fn maybe_resolve_crate<'b>( + fn maybe_resolve_crate<'b, 'tcx>( &'b mut self, + tcx: TyCtxt<'tcx>, name: Symbol, mut dep_kind: CrateDepKind, origin: CrateOrigin<'b>, @@ -789,17 +784,19 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { let path_kind = if dep.is_some() { PathKind::Dependency } else { PathKind::Crate }; let private_dep = origin.private_dep(); - let result = if let Some(cnum) = self.existing_match(name, hash, path_kind) { + let result = if let Some(cnum) = + self.existing_match(&tcx.sess.opts.externs, name, hash, path_kind) + { (LoadResult::Previous(cnum), None) } else { info!("falling back to a load"); let mut locator = CrateLocator::new( - self.sess, - &*self.cstore.metadata_loader, + tcx.sess, + &*self.metadata_loader, name, // The all loop is because `--crate-type=rlib --crate-type=rlib` is // legal and produces both inside this type. - self.tcx.crate_types().iter().all(|c| *c == CrateType::Rlib), + tcx.crate_types().iter().all(|c| *c == CrateType::Rlib), hash, extra_filename, path_kind, @@ -812,6 +809,7 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { info!("falling back to loading proc_macro"); dep_kind = CrateDepKind::MacrosOnly; match self.load_proc_macro( + tcx.sess, &mut locator, &mut crate_rejections, path_kind, @@ -831,8 +829,9 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { // not specified by `--extern` on command line parameters, it may be // `private-dependency` when `register_crate` is called for the first time. Then it must be updated to // `public-dependency` here. - let private_dep = self.is_private_dep(name, private_dep, origin); - let data = self.cstore.get_crate_data_mut(cnum); + let private_dep = + self.is_private_dep(&tcx.sess.opts.externs, name, private_dep, origin); + let data = self.get_crate_data_mut(cnum); if data.is_proc_macro_crate() { dep_kind = CrateDepKind::MacrosOnly; } @@ -842,7 +841,7 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { } (LoadResult::Loaded(library), host_library) => { info!("register newly loaded library for `{}`", name); - self.register_crate(host_library, origin, library, dep_kind, name, private_dep) + self.register_crate(tcx, host_library, origin, library, dep_kind, name, private_dep) } _ => panic!(), } @@ -863,7 +862,7 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { // duplicates by just using the first crate. let root = library.metadata.get_root(); let mut result = LoadResult::Loaded(library); - for (cnum, data) in self.cstore.iter_crate_data() { + for (cnum, data) in self.iter_crate_data() { if data.name() == root.name() && root.hash() == data.hash() { assert!(locator.hash.is_none()); info!("load success, going to previous cnum: {}", cnum); @@ -877,6 +876,7 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { /// Go through the crate metadata and load any crates that it references. fn resolve_crate_deps( &mut self, + tcx: TyCtxt<'_>, dep_root: &CratePaths, crate_root: &CrateRoot, metadata: &MetadataBlob, @@ -913,6 +913,7 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { _ => dep.kind, }; let cnum = self.maybe_resolve_crate( + tcx, dep.name, dep_kind, CrateOrigin::IndirectDependency { @@ -930,10 +931,11 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { fn dlsym_proc_macros( &self, + sess: &Session, path: &Path, stable_crate_id: StableCrateId, ) -> Result<&'static [ProcMacro], CrateError> { - let sym_name = self.sess.generate_proc_macro_decls_symbol(stable_crate_id); + let sym_name = sess.generate_proc_macro_decls_symbol(stable_crate_id); debug!("trying to dlsym proc_macros {} for symbol `{}`", path.display(), sym_name); unsafe { @@ -955,10 +957,10 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { } } - fn inject_panic_runtime(&mut self, krate: &ast::Crate) { + fn inject_panic_runtime(&mut self, tcx: TyCtxt<'_>, krate: &ast::Crate) { // If we're only compiling an rlib, then there's no need to select a // panic runtime, so we just skip this section entirely. - let only_rlib = self.tcx.crate_types().iter().all(|ct| *ct == CrateType::Rlib); + let only_rlib = tcx.crate_types().iter().all(|ct| *ct == CrateType::Rlib); if only_rlib { info!("panic runtime injection skipped, only generating rlib"); return; @@ -968,7 +970,7 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { // the same time we perform some general validation of the DAG we've got // going such as ensuring everything has a compatible panic strategy. let mut needs_panic_runtime = attr::contains_name(&krate.attrs, sym::needs_panic_runtime); - for (_cnum, data) in self.cstore.iter_crate_data() { + for (_cnum, data) in self.iter_crate_data() { needs_panic_runtime |= data.needs_panic_runtime(); } @@ -987,7 +989,7 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { // Also note that we have yet to perform validation of the crate graph // in terms of everyone has a compatible panic runtime format, that's // performed later as part of the `dependency_format` module. - let desired_strategy = self.sess.panic_strategy(); + let desired_strategy = tcx.sess.panic_strategy(); let name = match desired_strategy { PanicStrategy::Unwind => sym::panic_unwind, PanicStrategy::Abort => sym::panic_abort, @@ -995,64 +997,64 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { info!("panic runtime not found -- loading {}", name); let Some(cnum) = - self.resolve_crate(name, DUMMY_SP, CrateDepKind::Implicit, CrateOrigin::Injected) + self.resolve_crate(tcx, name, DUMMY_SP, CrateDepKind::Implicit, CrateOrigin::Injected) else { return; }; - let data = self.cstore.get_crate_data(cnum); + let data = self.get_crate_data(cnum); // Sanity check the loaded crate to ensure it is indeed a panic runtime // and the panic strategy is indeed what we thought it was. if !data.is_panic_runtime() { - self.dcx().emit_err(errors::CrateNotPanicRuntime { crate_name: name }); + tcx.dcx().emit_err(errors::CrateNotPanicRuntime { crate_name: name }); } if data.required_panic_strategy() != Some(desired_strategy) { - self.dcx() + tcx.dcx() .emit_err(errors::NoPanicStrategy { crate_name: name, strategy: desired_strategy }); } - self.cstore.injected_panic_runtime = Some(cnum); + self.injected_panic_runtime = Some(cnum); } - fn inject_profiler_runtime(&mut self) { + fn inject_profiler_runtime(&mut self, tcx: TyCtxt<'_>) { let needs_profiler_runtime = - self.sess.instrument_coverage() || self.sess.opts.cg.profile_generate.enabled(); - if !needs_profiler_runtime || self.sess.opts.unstable_opts.no_profiler_runtime { + tcx.sess.instrument_coverage() || tcx.sess.opts.cg.profile_generate.enabled(); + if !needs_profiler_runtime || tcx.sess.opts.unstable_opts.no_profiler_runtime { return; } info!("loading profiler"); - let name = Symbol::intern(&self.sess.opts.unstable_opts.profiler_runtime); + let name = Symbol::intern(&tcx.sess.opts.unstable_opts.profiler_runtime); let Some(cnum) = - self.resolve_crate(name, DUMMY_SP, CrateDepKind::Implicit, CrateOrigin::Injected) + self.resolve_crate(tcx, name, DUMMY_SP, CrateDepKind::Implicit, CrateOrigin::Injected) else { return; }; - let data = self.cstore.get_crate_data(cnum); + let data = self.get_crate_data(cnum); // Sanity check the loaded crate to ensure it is indeed a profiler runtime if !data.is_profiler_runtime() { - self.dcx().emit_err(errors::NotProfilerRuntime { crate_name: name }); + tcx.dcx().emit_err(errors::NotProfilerRuntime { crate_name: name }); } } - fn inject_allocator_crate(&mut self, krate: &ast::Crate) { - self.cstore.has_global_allocator = + fn inject_allocator_crate(&mut self, tcx: TyCtxt<'_>, krate: &ast::Crate) { + self.has_global_allocator = match &*fn_spans(krate, Symbol::intern(&global_fn_name(sym::alloc))) { [span1, span2, ..] => { - self.dcx() + tcx.dcx() .emit_err(errors::NoMultipleGlobalAlloc { span2: *span2, span1: *span1 }); true } spans => !spans.is_empty(), }; - self.cstore.has_alloc_error_handler = match &*fn_spans( + self.has_alloc_error_handler = match &*fn_spans( krate, Symbol::intern(alloc_error_handler_name(AllocatorKind::Global)), ) { [span1, span2, ..] => { - self.dcx() + tcx.dcx() .emit_err(errors::NoMultipleAllocErrorHandler { span2: *span2, span1: *span1 }); true } @@ -1063,7 +1065,7 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { // about through the `#![needs_allocator]` attribute and is typically // written down in liballoc. if !attr::contains_name(&krate.attrs, sym::needs_allocator) - && !self.cstore.iter_crate_data().any(|(_, data)| data.needs_allocator()) + && !self.iter_crate_data().any(|(_, data)| data.needs_allocator()) { return; } @@ -1071,7 +1073,7 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { // At this point we've determined that we need an allocator. Let's see // if our compilation session actually needs an allocator based on what // we're emitting. - let all_rlib = self.tcx.crate_types().iter().all(|ct| matches!(*ct, CrateType::Rlib)); + let all_rlib = tcx.crate_types().iter().all(|ct| matches!(*ct, CrateType::Rlib)); if all_rlib { return; } @@ -1086,12 +1088,12 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { #[allow(rustc::symbol_intern_string_literal)] let this_crate = Symbol::intern("this crate"); - let mut global_allocator = self.cstore.has_global_allocator.then_some(this_crate); - for (_, data) in self.cstore.iter_crate_data() { + let mut global_allocator = self.has_global_allocator.then_some(this_crate); + for (_, data) in self.iter_crate_data() { if data.has_global_allocator() { match global_allocator { Some(other_crate) => { - self.dcx().emit_err(errors::ConflictingGlobalAlloc { + tcx.dcx().emit_err(errors::ConflictingGlobalAlloc { crate_name: data.name(), other_crate_name: other_crate, }); @@ -1100,12 +1102,12 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { } } } - let mut alloc_error_handler = self.cstore.has_alloc_error_handler.then_some(this_crate); - for (_, data) in self.cstore.iter_crate_data() { + let mut alloc_error_handler = self.has_alloc_error_handler.then_some(this_crate); + for (_, data) in self.iter_crate_data() { if data.has_alloc_error_handler() { match alloc_error_handler { Some(other_crate) => { - self.dcx().emit_err(errors::ConflictingAllocErrorHandler { + tcx.dcx().emit_err(errors::ConflictingAllocErrorHandler { crate_name: data.name(), other_crate_name: other_crate, }); @@ -1116,35 +1118,36 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { } if global_allocator.is_some() { - self.cstore.allocator_kind = Some(AllocatorKind::Global); + self.allocator_kind = Some(AllocatorKind::Global); } else { // Ok we haven't found a global allocator but we still need an // allocator. At this point our allocator request is typically fulfilled // by the standard library, denoted by the `#![default_lib_allocator]` // attribute. if !attr::contains_name(&krate.attrs, sym::default_lib_allocator) - && !self.cstore.iter_crate_data().any(|(_, data)| data.has_default_lib_allocator()) + && !self.iter_crate_data().any(|(_, data)| data.has_default_lib_allocator()) { - self.dcx().emit_err(errors::GlobalAllocRequired); + tcx.dcx().emit_err(errors::GlobalAllocRequired); } - self.cstore.allocator_kind = Some(AllocatorKind::Default); + self.allocator_kind = Some(AllocatorKind::Default); } if alloc_error_handler.is_some() { - self.cstore.alloc_error_handler_kind = Some(AllocatorKind::Global); + self.alloc_error_handler_kind = Some(AllocatorKind::Global); } else { // The alloc crate provides a default allocation error handler if // one isn't specified. - self.cstore.alloc_error_handler_kind = Some(AllocatorKind::Default); + self.alloc_error_handler_kind = Some(AllocatorKind::Default); } } - fn inject_forced_externs(&mut self) { - for (name, entry) in self.sess.opts.externs.iter() { + fn inject_forced_externs(&mut self, tcx: TyCtxt<'_>) { + for (name, entry) in tcx.sess.opts.externs.iter() { if entry.force { let name_interned = Symbol::intern(name); if !self.used_extern_options.contains(&name_interned) { self.resolve_crate( + tcx, name_interned, DUMMY_SP, CrateDepKind::Explicit, @@ -1156,7 +1159,7 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { } /// Inject the `compiler_builtins` crate if it is not already in the graph. - fn inject_compiler_builtins(&mut self, krate: &ast::Crate) { + fn inject_compiler_builtins(&mut self, tcx: TyCtxt<'_>, krate: &ast::Crate) { // `compiler_builtins` does not get extern builtins, nor do `#![no_core]` crates if attr::contains_name(&krate.attrs, sym::compiler_builtins) || attr::contains_name(&krate.attrs, sym::no_core) @@ -1167,7 +1170,7 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { // If a `#![compiler_builtins]` crate already exists, avoid injecting it twice. This is // the common case since usually it appears as a dependency of `std` or `alloc`. - for (cnum, cmeta) in self.cstore.iter_crate_data() { + for (cnum, cmeta) in self.iter_crate_data() { if cmeta.is_compiler_builtins() { info!("`compiler_builtins` already exists (cnum = {cnum}); skipping injection"); return; @@ -1176,6 +1179,7 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { // `compiler_builtins` is not yet in the graph; inject it. Error on resolution failure. let Some(cnum) = self.resolve_crate( + tcx, sym::compiler_builtins, krate.spans.inner_span.shrink_to_lo(), CrateDepKind::Explicit, @@ -1186,17 +1190,17 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { }; // Sanity check that the loaded crate is `#![compiler_builtins]` - let cmeta = self.cstore.get_crate_data(cnum); + let cmeta = self.get_crate_data(cnum); if !cmeta.is_compiler_builtins() { - self.dcx().emit_err(errors::CrateNotCompilerBuiltins { crate_name: cmeta.name() }); + tcx.dcx().emit_err(errors::CrateNotCompilerBuiltins { crate_name: cmeta.name() }); } } - fn report_unused_deps(&mut self, krate: &ast::Crate) { + fn report_unused_deps_in_crate(&mut self, tcx: TyCtxt<'_>, krate: &ast::Crate) { // Make a point span rather than covering the whole file let span = krate.spans.inner_span.shrink_to_lo(); // Complain about anything left over - for (name, entry) in self.sess.opts.externs.iter() { + for (name, entry) in tcx.sess.opts.externs.iter() { if let ExternLocation::FoundInLibrarySearchDirectories = entry.location { // Don't worry about pathless `--extern foo` sysroot references continue; @@ -1211,25 +1215,25 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { } // Got a real unused --extern - if self.sess.opts.json_unused_externs.is_enabled() { - self.cstore.unused_externs.push(name_interned); + if tcx.sess.opts.json_unused_externs.is_enabled() { + self.unused_externs.push(name_interned); continue; } - self.sess.psess.buffer_lint( + tcx.sess.psess.buffer_lint( lint::builtin::UNUSED_CRATE_DEPENDENCIES, span, ast::CRATE_NODE_ID, BuiltinLintDiag::UnusedCrateDependency { extern_crate: name_interned, - local_crate: self.tcx.crate_name(LOCAL_CRATE), + local_crate: tcx.crate_name(LOCAL_CRATE), }, ); } } - fn report_future_incompatible_deps(&self, krate: &ast::Crate) { - let name = self.tcx.crate_name(LOCAL_CRATE); + fn report_future_incompatible_deps(&self, tcx: TyCtxt<'_>, krate: &ast::Crate) { + let name = tcx.crate_name(LOCAL_CRATE); if name.as_str() == "wasm_bindgen" { let major = env::var("CARGO_PKG_VERSION_MAJOR") @@ -1257,26 +1261,27 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { // Make a point span rather than covering the whole file let span = krate.spans.inner_span.shrink_to_lo(); - self.sess.dcx().emit_err(errors::WasmCAbi { span }); + tcx.sess.dcx().emit_err(errors::WasmCAbi { span }); } } - pub fn postprocess(&mut self, krate: &ast::Crate) { - self.inject_compiler_builtins(krate); - self.inject_forced_externs(); - self.inject_profiler_runtime(); - self.inject_allocator_crate(krate); - self.inject_panic_runtime(krate); + pub fn postprocess(&mut self, tcx: TyCtxt<'_>, krate: &ast::Crate) { + self.inject_compiler_builtins(tcx, krate); + self.inject_forced_externs(tcx); + self.inject_profiler_runtime(tcx); + self.inject_allocator_crate(tcx, krate); + self.inject_panic_runtime(tcx, krate); - self.report_unused_deps(krate); - self.report_future_incompatible_deps(krate); + self.report_unused_deps_in_crate(tcx, krate); + self.report_future_incompatible_deps(tcx, krate); - info!("{:?}", CrateDump(self.cstore)); + info!("{:?}", CrateDump(self)); } /// Process an `extern crate foo` AST node. pub fn process_extern_crate( &mut self, + tcx: TyCtxt<'_>, item: &ast::Item, def_id: LocalDefId, definitions: &Definitions, @@ -1286,7 +1291,7 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { debug!("resolving extern crate stmt. ident: {} orig_name: {:?}", ident, orig_name); let name = match orig_name { Some(orig_name) => { - validate_crate_name(self.sess, orig_name, Some(item.span)); + validate_crate_name(tcx.sess, orig_name, Some(item.span)); orig_name } None => ident.name, @@ -1297,10 +1302,11 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { CrateDepKind::Explicit }; - let cnum = self.resolve_crate(name, item.span, dep_kind, CrateOrigin::Extern)?; + let cnum = + self.resolve_crate(tcx, name, item.span, dep_kind, CrateOrigin::Extern)?; let path_len = definitions.def_path(def_id).data.len(); - self.cstore.update_extern_crate( + self.update_extern_crate( cnum, ExternCrate { src: ExternCrateSource::Extern(def_id.to_def_id()), @@ -1315,10 +1321,16 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { } } - pub fn process_path_extern(&mut self, name: Symbol, span: Span) -> Option<CrateNum> { - let cnum = self.resolve_crate(name, span, CrateDepKind::Explicit, CrateOrigin::Extern)?; + pub fn process_path_extern( + &mut self, + tcx: TyCtxt<'_>, + name: Symbol, + span: Span, + ) -> Option<CrateNum> { + let cnum = + self.resolve_crate(tcx, name, span, CrateDepKind::Explicit, CrateOrigin::Extern)?; - self.cstore.update_extern_crate( + self.update_extern_crate( cnum, ExternCrate { src: ExternCrateSource::Path, @@ -1332,8 +1344,8 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { Some(cnum) } - pub fn maybe_process_path_extern(&mut self, name: Symbol) -> Option<CrateNum> { - self.maybe_resolve_crate(name, CrateDepKind::Explicit, CrateOrigin::Extern).ok() + pub fn maybe_process_path_extern(&mut self, tcx: TyCtxt<'_>, name: Symbol) -> Option<CrateNum> { + self.maybe_resolve_crate(tcx, name, CrateDepKind::Explicit, CrateOrigin::Extern).ok() } } diff --git a/compiler/rustc_middle/src/middle/stability.rs b/compiler/rustc_middle/src/middle/stability.rs index 99faba7b2c0..dc9311188e8 100644 --- a/compiler/rustc_middle/src/middle/stability.rs +++ b/compiler/rustc_middle/src/middle/stability.rs @@ -7,10 +7,9 @@ use rustc_ast::NodeId; use rustc_attr_data_structures::{ self as attrs, ConstStability, DefaultBodyStability, DeprecatedSince, Deprecation, Stability, }; -use rustc_data_structures::unord::UnordMap; use rustc_errors::{Applicability, Diag, EmissionGuarantee}; use rustc_feature::GateIssue; -use rustc_hir::def_id::{DefId, LocalDefId, LocalDefIdMap}; +use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::{self as hir, HirId}; use rustc_macros::{Decodable, Encodable, HashStable, Subdiagnostic}; use rustc_session::Session; @@ -65,48 +64,6 @@ impl DeprecationEntry { } } -/// A stability index, giving the stability level for items and methods. -#[derive(HashStable, Debug)] -pub struct Index { - /// This is mostly a cache, except the stabilities of local items - /// are filled by the annotator. - pub stab_map: LocalDefIdMap<Stability>, - pub const_stab_map: LocalDefIdMap<ConstStability>, - pub default_body_stab_map: LocalDefIdMap<DefaultBodyStability>, - pub depr_map: LocalDefIdMap<DeprecationEntry>, - /// Mapping from feature name to feature name based on the `implied_by` field of `#[unstable]` - /// attributes. If a `#[unstable(feature = "implier", implied_by = "impliee")]` attribute - /// exists, then this map will have a `impliee -> implier` entry. - /// - /// This mapping is necessary unless both the `#[stable]` and `#[unstable]` attributes should - /// specify their implications (both `implies` and `implied_by`). If only one of the two - /// attributes do (as in the current implementation, `implied_by` in `#[unstable]`), then this - /// mapping is necessary for diagnostics. When a "unnecessary feature attribute" error is - /// reported, only the `#[stable]` attribute information is available, so the map is necessary - /// to know that the feature implies another feature. If it were reversed, and the `#[stable]` - /// attribute had an `implies` meta item, then a map would be necessary when avoiding a "use of - /// unstable feature" error for a feature that was implied. - pub implications: UnordMap<Symbol, Symbol>, -} - -impl Index { - pub fn local_stability(&self, def_id: LocalDefId) -> Option<Stability> { - self.stab_map.get(&def_id).copied() - } - - pub fn local_const_stability(&self, def_id: LocalDefId) -> Option<ConstStability> { - self.const_stab_map.get(&def_id).copied() - } - - pub fn local_default_body_stability(&self, def_id: LocalDefId) -> Option<DefaultBodyStability> { - self.default_body_stab_map.get(&def_id).copied() - } - - pub fn local_deprecation_entry(&self, def_id: LocalDefId) -> Option<DeprecationEntry> { - self.depr_map.get(&def_id).cloned() - } -} - pub fn report_unstable( sess: &Session, feature: Symbol, diff --git a/compiler/rustc_middle/src/mir/interpret/allocation.rs b/compiler/rustc_middle/src/mir/interpret/allocation.rs index 133111ff15d..27ead514531 100644 --- a/compiler/rustc_middle/src/mir/interpret/allocation.rs +++ b/compiler/rustc_middle/src/mir/interpret/allocation.rs @@ -702,8 +702,11 @@ impl<Prov: Provenance, Extra, Bytes: AllocBytes> Allocation<Prov, Extra, Bytes> read_provenance: bool, ) -> AllocResult<Scalar<Prov>> { // First and foremost, if anything is uninit, bail. - if self.init_mask.is_range_initialized(range).is_err() { - return Err(AllocError::InvalidUninitBytes(None)); + if let Err(bad) = self.init_mask.is_range_initialized(range) { + return Err(AllocError::InvalidUninitBytes(Some(BadBytesAccess { + access: range, + bad, + }))); } // Get the integer part of the result. We HAVE TO check provenance before returning this! diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index d5c2b6de4ae..ae8c8259be4 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -112,7 +112,7 @@ use crate::middle::exported_symbols::{ExportedSymbol, SymbolExportInfo}; use crate::middle::lib_features::LibFeatures; use crate::middle::privacy::EffectiveVisibilities; use crate::middle::resolve_bound_vars::{ObjectLifetimeDefault, ResolveBoundVars, ResolvedArg}; -use crate::middle::stability::{self, DeprecationEntry}; +use crate::middle::stability::DeprecationEntry; use crate::mir::interpret::{ EvalStaticInitializerRawResult, EvalToAllocationRawResult, EvalToConstValueResult, EvalToValTreeResult, GlobalId, LitToConstInput, @@ -2171,6 +2171,18 @@ rustc_queries! { separate_provide_extern arena_cache } + /// Mapping from feature name to feature name based on the `implied_by` field of `#[unstable]` + /// attributes. If a `#[unstable(feature = "implier", implied_by = "impliee")]` attribute + /// exists, then this map will have a `impliee -> implier` entry. + /// + /// This mapping is necessary unless both the `#[stable]` and `#[unstable]` attributes should + /// specify their implications (both `implies` and `implied_by`). If only one of the two + /// attributes do (as in the current implementation, `implied_by` in `#[unstable]`), then this + /// mapping is necessary for diagnostics. When a "unnecessary feature attribute" error is + /// reported, only the `#[stable]` attribute information is available, so the map is necessary + /// to know that the feature implies another feature. If it were reversed, and the `#[stable]` + /// attribute had an `implies` meta item, then a map would be necessary when avoiding a "use of + /// unstable feature" error for a feature that was implied. query stability_implications(_: CrateNum) -> &'tcx UnordMap<Symbol, Symbol> { arena_cache desc { "calculating the implications between `#[unstable]` features defined in a crate" } @@ -2277,11 +2289,6 @@ rustc_queries! { desc { "fetching potentially unused trait imports" } } - query stability_index(_: ()) -> &'tcx stability::Index { - arena_cache - eval_always - desc { "calculating the stability index for the local crate" } - } /// All available crates in the graph, including those that should not be user-facing /// (such as private crates). query crates(_: ()) -> &'tcx [CrateNum] { diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 81c13e55dd8..7e6bcfee025 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -65,7 +65,7 @@ use crate::infer::canonical::{CanonicalParamEnvCache, CanonicalVarKind, Canonica use crate::lint::lint_level; use crate::metadata::ModChild; use crate::middle::codegen_fn_attrs::{CodegenFnAttrs, TargetFeature}; -use crate::middle::{resolve_bound_vars, stability}; +use crate::middle::resolve_bound_vars; use crate::mir::interpret::{self, Allocation, ConstAllocation}; use crate::mir::{Body, Local, Place, PlaceElem, ProjectionKind, Promoted}; use crate::query::plumbing::QuerySystem; @@ -1807,10 +1807,6 @@ impl<'tcx> TyCtxt<'tcx> { ) } - pub fn stability(self) -> &'tcx stability::Index { - self.stability_index(()) - } - pub fn features(self) -> &'tcx rustc_feature::Features { self.features_query(()) } diff --git a/compiler/rustc_middle/src/ty/inhabitedness/mod.rs b/compiler/rustc_middle/src/ty/inhabitedness/mod.rs index 2a336cc21f4..7eb74b52b44 100644 --- a/compiler/rustc_middle/src/ty/inhabitedness/mod.rs +++ b/compiler/rustc_middle/src/ty/inhabitedness/mod.rs @@ -43,7 +43,6 @@ //! This code should only compile in modules where the uninhabitedness of `Foo` //! is visible. -use rustc_span::sym; use rustc_type_ir::TyKind::*; use tracing::instrument; @@ -85,21 +84,6 @@ impl<'tcx> VariantDef { InhabitedPredicate::all( tcx, self.fields.iter().map(|field| { - // Unstable fields are always considered to be inhabited. In the future, - // this could be extended to be conditional on the field being unstable - // only within the module that's querying the inhabitedness, like: - // `let pred = pred.or(InhabitedPredicate::IsUnstable(field.did));` - // but this is unnecessary for now, since it would only affect nightly-only - // code or code within the standard library itself. - // HACK: We filter out `rustc_private` fields since with the flag - // `-Zforce-unstable-if-unmarked` we consider all unmarked fields to be - // unstable when building the compiler. - if tcx - .lookup_stability(field.did) - .is_some_and(|stab| stab.is_unstable() && stab.feature != sym::rustc_private) - { - return InhabitedPredicate::True; - } let pred = tcx.type_of(field.did).instantiate_identity().inhabited_predicate(tcx); if adt.is_enum() { return pred; diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index 2eb530f328d..9ee64df0ad0 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -1210,30 +1210,6 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } for (assoc_item_def_id, term) in assoc_items { - // Skip printing `<{coroutine@} as Coroutine<_>>::Return` from async blocks, - // unless we can find out what coroutine return type it comes from. - let term = if let Some(ty) = term.skip_binder().as_type() - && let ty::Alias(ty::Projection, proj) = ty.kind() - && let Some(assoc) = tcx.opt_associated_item(proj.def_id) - && assoc - .trait_container(tcx) - .is_some_and(|def_id| tcx.is_lang_item(def_id, LangItem::Coroutine)) - && assoc.opt_name() == Some(rustc_span::sym::Return) - { - if let ty::Coroutine(_, args) = args.type_at(0).kind() { - let return_ty = args.as_coroutine().return_ty(); - if !return_ty.is_ty_var() { - return_ty.into() - } else { - continue; - } - } else { - continue; - } - } else { - term.skip_binder() - }; - if first { p!("<"); first = false; @@ -1243,7 +1219,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { p!(write("{} = ", tcx.associated_item(assoc_item_def_id).name())); - match term.kind() { + match term.skip_binder().kind() { TermKind::Ty(ty) => p!(print(ty)), TermKind::Const(c) => p!(print(c)), }; diff --git a/compiler/rustc_mir_transform/src/elaborate_drops.rs b/compiler/rustc_mir_transform/src/elaborate_drops.rs index b4fa2be1d00..58dff4514a0 100644 --- a/compiler/rustc_mir_transform/src/elaborate_drops.rs +++ b/compiler/rustc_mir_transform/src/elaborate_drops.rs @@ -253,8 +253,8 @@ struct ElaborateDropsCtxt<'a, 'tcx> { } impl fmt::Debug for ElaborateDropsCtxt<'_, '_> { - fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result { - Ok(()) + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("ElaborateDropsCtxt").finish_non_exhaustive() } } diff --git a/compiler/rustc_mir_transform/src/gvn.rs b/compiler/rustc_mir_transform/src/gvn.rs index 07717b7c069..6657f89ceb5 100644 --- a/compiler/rustc_mir_transform/src/gvn.rs +++ b/compiler/rustc_mir_transform/src/gvn.rs @@ -579,7 +579,7 @@ impl<'body, 'tcx> VnState<'body, 'tcx> { CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _) => { let src = self.evaluated[value].as_ref()?; let dest = self.ecx.allocate(ty, MemoryKind::Stack).discard_err()?; - self.ecx.unsize_into(src, ty, &dest.clone().into()).discard_err()?; + self.ecx.unsize_into(src, ty, &dest).discard_err()?; self.ecx .alloc_mark_immutable(dest.ptr().provenance.unwrap().alloc_id()) .discard_err()?; diff --git a/compiler/rustc_mir_transform/src/inline/cycle.rs b/compiler/rustc_mir_transform/src/inline/cycle.rs index 93a81f0dca5..7f9234d1dc8 100644 --- a/compiler/rustc_mir_transform/src/inline/cycle.rs +++ b/compiler/rustc_mir_transform/src/inline/cycle.rs @@ -64,15 +64,15 @@ fn process<'tcx>( typing_env: ty::TypingEnv<'tcx>, caller: ty::Instance<'tcx>, target: LocalDefId, - seen: &mut FxHashSet<ty::Instance<'tcx>>, + seen: &mut FxHashMap<ty::Instance<'tcx>, bool>, involved: &mut FxHashSet<LocalDefId>, recursion_limiter: &mut FxHashMap<DefId, usize>, recursion_limit: Limit, ) -> bool { trace!(%caller); - let mut cycle_found = false; + let mut reaches_root = false; - for &(callee, args) in tcx.mir_inliner_callees(caller.def) { + for &(callee_def_id, args) in tcx.mir_inliner_callees(caller.def) { let Ok(args) = caller.try_instantiate_mir_and_normalize_erasing_regions( tcx, typing_env, @@ -81,14 +81,17 @@ fn process<'tcx>( trace!(?caller, ?typing_env, ?args, "cannot normalize, skipping"); continue; }; - let Ok(Some(callee)) = ty::Instance::try_resolve(tcx, typing_env, callee, args) else { - trace!(?callee, "cannot resolve, skipping"); + let Ok(Some(callee)) = ty::Instance::try_resolve(tcx, typing_env, callee_def_id, args) + else { + trace!(?callee_def_id, "cannot resolve, skipping"); continue; }; // Found a path. if callee.def_id() == target.to_def_id() { - cycle_found = true; + reaches_root = true; + seen.insert(callee, true); + continue; } if tcx.is_constructor(callee.def_id()) { @@ -101,10 +104,17 @@ fn process<'tcx>( continue; } - if seen.insert(callee) { + let callee_reaches_root = if let Some(&c) = seen.get(&callee) { + // Even if we have seen this callee before, and thus don't need + // to recurse into it, we still need to propagate whether it reaches + // the root so that we can mark all the involved callers, in case we + // end up reaching that same recursive callee through some *other* cycle. + c + } else { + seen.insert(callee, false); let recursion = recursion_limiter.entry(callee.def_id()).or_default(); trace!(?callee, recursion = *recursion); - let found_recursion = if recursion_limit.value_within_limit(*recursion) { + let callee_reaches_root = if recursion_limit.value_within_limit(*recursion) { *recursion += 1; ensure_sufficient_stack(|| { process( @@ -122,17 +132,19 @@ fn process<'tcx>( // Pessimistically assume that there could be recursion. true }; - if found_recursion { - if let Some(callee) = callee.def_id().as_local() { - // Calling `optimized_mir` of a non-local definition cannot cycle. - involved.insert(callee); - } - cycle_found = true; + seen.insert(callee, callee_reaches_root); + callee_reaches_root + }; + if callee_reaches_root { + if let Some(callee_def_id) = callee.def_id().as_local() { + // Calling `optimized_mir` of a non-local definition cannot cycle. + involved.insert(callee_def_id); } + reaches_root = true; } } - cycle_found + reaches_root } #[instrument(level = "debug", skip(tcx), ret)] @@ -166,7 +178,7 @@ pub(crate) fn mir_callgraph_cyclic<'tcx>( typing_env, root_instance, root, - &mut FxHashSet::default(), + &mut FxHashMap::default(), &mut involved, &mut FxHashMap::default(), recursion_limit, diff --git a/compiler/rustc_mir_transform/src/shim.rs b/compiler/rustc_mir_transform/src/shim.rs index cdbc74cdfa8..6c65b072bec 100644 --- a/compiler/rustc_mir_transform/src/shim.rs +++ b/compiler/rustc_mir_transform/src/shim.rs @@ -434,8 +434,8 @@ pub(super) struct DropShimElaborator<'a, 'tcx> { } impl fmt::Debug for DropShimElaborator<'_, '_> { - fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { - Ok(()) + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { + f.debug_struct("DropShimElaborator").finish_non_exhaustive() } } diff --git a/compiler/rustc_mir_transform/src/validate.rs b/compiler/rustc_mir_transform/src/validate.rs index cbb9bbfd12f..5860072d541 100644 --- a/compiler/rustc_mir_transform/src/validate.rs +++ b/compiler/rustc_mir_transform/src/validate.rs @@ -119,14 +119,16 @@ impl<'a, 'tcx> CfgChecker<'a, 'tcx> { #[track_caller] fn fail(&self, location: Location, msg: impl AsRef<str>) { // We might see broken MIR when other errors have already occurred. - assert!( - self.tcx.dcx().has_errors().is_some(), - "broken MIR in {:?} ({}) at {:?}:\n{}", - self.body.source.instance, - self.when, - location, - msg.as_ref(), - ); + if self.tcx.dcx().has_errors().is_none() { + span_bug!( + self.body.source_info(location).span, + "broken MIR in {:?} ({}) at {:?}:\n{}", + self.body.source.instance, + self.when, + location, + msg.as_ref(), + ); + } } fn check_edge(&mut self, location: Location, bb: BasicBlock, edge_kind: EdgeKind) { @@ -719,6 +721,15 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { ); } + if adt_def.repr().simd() { + self.fail( + location, + format!( + "Projecting into SIMD type {adt_def:?} is banned by MCP#838" + ), + ); + } + let var = parent_ty.variant_index.unwrap_or(FIRST_VARIANT); let Some(field) = adt_def.variant(var).fields.get(f) else { fail_out_of_bounds(self, location); 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 098dc9dbaf0..650b85d99d2 100644 --- a/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs +++ b/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs @@ -1219,10 +1219,8 @@ where // the type (even if after unification and processing nested goals // it does not hold) will disqualify the built-in auto impl. // - // This differs from the current stable behavior and fixes #84857. - // Due to breakage found via crater, we currently instead lint - // patterns which can be used to exploit this unsoundness on stable, - // see #93367 for more details. + // We've originally had a more permissive check here which resulted + // in unsoundness, see #84857. ty::Bool | ty::Char | ty::Int(_) diff --git a/compiler/rustc_parse/src/lexer/diagnostics.rs b/compiler/rustc_parse/src/lexer/diagnostics.rs index 0b97d4e6993..6de001fc998 100644 --- a/compiler/rustc_parse/src/lexer/diagnostics.rs +++ b/compiler/rustc_parse/src/lexer/diagnostics.rs @@ -34,9 +34,12 @@ pub(super) fn same_indentation_level(sm: &SourceMap, open_sp: Span, close_sp: Sp // When we get a `)` or `]` for `{`, we should emit help message here // it's more friendly compared to report `unmatched error` in later phase -fn report_missing_open_delim(err: &mut Diag<'_>, unmatched_delims: &[UnmatchedDelim]) -> bool { +pub(super) fn report_missing_open_delim( + err: &mut Diag<'_>, + unmatched_delims: &mut Vec<UnmatchedDelim>, +) -> bool { let mut reported_missing_open = false; - for unmatch_brace in unmatched_delims.iter() { + unmatched_delims.retain(|unmatch_brace| { if let Some(delim) = unmatch_brace.found_delim && matches!(delim, Delimiter::Parenthesis | Delimiter::Bracket) { @@ -45,13 +48,20 @@ fn report_missing_open_delim(err: &mut Diag<'_>, unmatched_delims: &[UnmatchedDe Delimiter::Bracket => "[", _ => unreachable!(), }; + + if let Some(unclosed_span) = unmatch_brace.unclosed_span { + err.span_label(unclosed_span, "the nearest open delimiter"); + } err.span_label( unmatch_brace.found_span.shrink_to_lo(), format!("missing open `{missed_open}` for this delimiter"), ); reported_missing_open = true; + false + } else { + true } - } + }); reported_missing_open } @@ -61,10 +71,6 @@ pub(super) fn report_suspicious_mismatch_block( sm: &SourceMap, delim: Delimiter, ) { - if report_missing_open_delim(err, &diag_info.unmatched_delims) { - return; - } - let mut matched_spans: Vec<(Span, bool)> = diag_info .matching_block_spans .iter() diff --git a/compiler/rustc_parse/src/lexer/tokentrees.rs b/compiler/rustc_parse/src/lexer/tokentrees.rs index fbea958dcc5..64748199f28 100644 --- a/compiler/rustc_parse/src/lexer/tokentrees.rs +++ b/compiler/rustc_parse/src/lexer/tokentrees.rs @@ -3,7 +3,9 @@ use rustc_ast::tokenstream::{DelimSpacing, DelimSpan, Spacing, TokenStream, Toke use rustc_ast_pretty::pprust::token_to_string; use rustc_errors::Diag; -use super::diagnostics::{report_suspicious_mismatch_block, same_indentation_level}; +use super::diagnostics::{ + report_missing_open_delim, report_suspicious_mismatch_block, same_indentation_level, +}; use super::{Lexer, UnmatchedDelim}; impl<'psess, 'src> Lexer<'psess, 'src> { @@ -244,7 +246,16 @@ impl<'psess, 'src> Lexer<'psess, 'src> { let msg = format!("unexpected closing delimiter: `{token_str}`"); let mut err = self.dcx().struct_span_err(self.token.span, msg); - report_suspicious_mismatch_block(&mut err, &self.diag_info, self.psess.source_map(), delim); + // if there is no missing open delim, report suspicious mismatch block + if !report_missing_open_delim(&mut err, &mut self.diag_info.unmatched_delims) { + report_suspicious_mismatch_block( + &mut err, + &self.diag_info, + self.psess.source_map(), + delim, + ); + } + err.span_label(self.token.span, "unexpected closing delimiter"); err } diff --git a/compiler/rustc_passes/messages.ftl b/compiler/rustc_passes/messages.ftl index d1b856ca415..51e23edb9bb 100644 --- a/compiler/rustc_passes/messages.ftl +++ b/compiler/rustc_passes/messages.ftl @@ -560,7 +560,8 @@ passes_only_has_effect_on = `#[{$attr_name}]` only has an effect on {$target_name -> [function] functions [module] modules - [implementation_block] implementation blocks + [trait_implementation_block] trait implementation blocks + [inherent_implementation_block] inherent implementation blocks *[unspecified] (unspecified--this is a compiler bug) } diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 2766b14bb8d..3ec6a1124a6 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -11,11 +11,17 @@ use std::slice; use rustc_abi::{Align, ExternAbi, Size}; use rustc_ast::{AttrStyle, LitKind, MetaItemInner, MetaItemKind, ast, join_path_syms}; -use rustc_attr_data_structures::{AttributeKind, InlineAttr, ReprAttr, find_attr}; +use rustc_attr_data_structures::{ + AttributeKind, InlineAttr, PartialConstStability, ReprAttr, Stability, StabilityLevel, + find_attr, +}; use rustc_attr_parsing::{AttributeParser, Late}; use rustc_data_structures::fx::FxHashMap; use rustc_errors::{Applicability, DiagCtxtHandle, IntoDiagArg, MultiSpan, StashKey}; -use rustc_feature::{AttributeDuplicates, AttributeType, BUILTIN_ATTRIBUTE_MAP, BuiltinAttribute}; +use rustc_feature::{ + ACCEPTED_LANG_FEATURES, AttributeDuplicates, AttributeType, BUILTIN_ATTRIBUTE_MAP, + BuiltinAttribute, +}; use rustc_hir::def::DefKind; use rustc_hir::def_id::LocalModDefId; use rustc_hir::intravisit::{self, Visitor}; @@ -36,6 +42,7 @@ use rustc_session::lint; use rustc_session::lint::builtin::{ CONFLICTING_REPR_HINTS, INVALID_DOC_ATTRIBUTES, INVALID_MACRO_EXPORT_ARGUMENTS, MALFORMED_DIAGNOSTIC_ATTRIBUTES, MISPLACED_DIAGNOSTIC_ATTRIBUTES, UNUSED_ATTRIBUTES, + USELESS_DEPRECATED, }; use rustc_session::parse::feature_err; use rustc_span::edition::Edition; @@ -161,12 +168,18 @@ impl<'tcx> CheckAttrVisitor<'tcx> { sym::automatically_derived, *attr_span, target, - Target::Impl, + Target::Impl { of_trait: true }, ), Attribute::Parsed( - AttributeKind::Stability { span, .. } - | AttributeKind::ConstStability { span, .. }, - ) => self.check_stability_promotable(*span, target), + AttributeKind::Stability { + span: attr_span, + stability: Stability { level, feature }, + } + | AttributeKind::ConstStability { + span: attr_span, + stability: PartialConstStability { level, feature, .. }, + }, + ) => self.check_stability(*attr_span, span, level, *feature, target), Attribute::Parsed(AttributeKind::Inline(InlineAttr::Force { .. }, ..)) => {} // handled separately below Attribute::Parsed(AttributeKind::Inline(kind, attr_span)) => { self.check_inline(hir_id, *attr_span, span, kind, target) @@ -494,7 +507,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { attr: &Attribute, item: Option<ItemLike<'_>>, ) { - if !matches!(target, Target::Impl) + if !matches!(target, Target::Impl { .. }) || matches!( item, Some(ItemLike::Item(hir::Item { kind: hir::ItemKind::Impl(_impl),.. })) @@ -598,7 +611,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { Target::Fn | Target::Closure | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) - | Target::Impl + | Target::Impl { .. } | Target::Mod => return, // These are "functions", but they aren't allowed because they don't @@ -987,9 +1000,9 @@ impl<'tcx> CheckAttrVisitor<'tcx> { let span = meta.span(); if let Some(location) = match target { Target::AssocTy => { - let parent_def_id = self.tcx.hir_get_parent_item(hir_id).def_id; - let containing_item = self.tcx.hir_expect_item(parent_def_id); - if Target::from_item(containing_item) == Target::Impl { + if let DefKind::Impl { .. } = + self.tcx.def_kind(self.tcx.local_parent(hir_id.owner.def_id)) + { Some("type alias in implementation block") } else { None @@ -1012,7 +1025,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | Target::Arm | Target::ForeignMod | Target::Closure - | Target::Impl + | Target::Impl { .. } | Target::WherePredicate => Some(target.name()), Target::ExternCrate | Target::Use @@ -1033,7 +1046,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | Target::ForeignFn | Target::ForeignStatic | Target::ForeignTy - | Target::GenericParam(..) + | Target::GenericParam { .. } | Target::MacroDef | Target::PatField | Target::ExprField => None, @@ -1590,7 +1603,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { let article = match target { Target::ExternCrate | Target::Enum - | Target::Impl + | Target::Impl { .. } | Target::Expression | Target::Arm | Target::AssocConst @@ -2274,7 +2287,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { match target { // FIXME(staged_api): There's no reason we can't support more targets here. We're just // being conservative to begin with. - Target::Fn | Target::Impl => {} + Target::Fn | Target::Impl { .. } => {} Target::ExternCrate | Target::Use | Target::Static @@ -2300,7 +2313,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { | Target::ForeignFn | Target::ForeignStatic | Target::ForeignTy - | Target::GenericParam(_) + | Target::GenericParam { .. } | Target::MacroDef | Target::Param | Target::PatField @@ -2320,13 +2333,30 @@ impl<'tcx> CheckAttrVisitor<'tcx> { } } - fn check_stability_promotable(&self, span: Span, target: Target) { + fn check_stability( + &self, + attr_span: Span, + item_span: Span, + level: &StabilityLevel, + feature: Symbol, + target: Target, + ) { match target { Target::Expression => { - self.dcx().emit_err(errors::StabilityPromotable { attr_span: span }); + self.dcx().emit_err(errors::StabilityPromotable { attr_span }); } _ => {} } + + // Stable *language* features shouldn't be used as unstable library features. + // (Not doing this for stable library features is checked by tidy.) + if level.is_unstable() + && ACCEPTED_LANG_FEATURES.iter().find(|f| f.name == feature).is_some() + { + self.tcx + .dcx() + .emit_err(errors::UnstableAttrForAlreadyStableFeature { attr_span, item_span }); + } } fn check_link_ordinal(&self, attr_span: Span, _span: Span, target: Target) { @@ -2354,6 +2384,28 @@ impl<'tcx> CheckAttrVisitor<'tcx> { errors::Deprecated, ); } + Target::Impl { of_trait: true } + | Target::GenericParam { has_default: false, kind: _ } => { + self.tcx.emit_node_span_lint( + USELESS_DEPRECATED, + hir_id, + attr.span(), + errors::DeprecatedAnnotationHasNoEffect { span: attr.span() }, + ); + } + Target::AssocConst | Target::Method(..) | Target::AssocTy + if matches!( + self.tcx.def_kind(self.tcx.local_parent(hir_id.owner.def_id)), + DefKind::Impl { of_trait: true } + ) => + { + self.tcx.emit_node_span_lint( + USELESS_DEPRECATED, + hir_id, + attr.span(), + errors::DeprecatedAnnotationHasNoEffect { span: attr.span() }, + ); + } _ => {} } } diff --git a/compiler/rustc_passes/src/errors.rs b/compiler/rustc_passes/src/errors.rs index 37330c0ed6e..c6ab6b0d601 100644 --- a/compiler/rustc_passes/src/errors.rs +++ b/compiler/rustc_passes/src/errors.rs @@ -1373,9 +1373,9 @@ pub(crate) struct UnstableAttrForAlreadyStableFeature { #[primary_span] #[label] #[help] - pub span: Span, + pub attr_span: Span, #[label(passes_item)] - pub item_sp: Span, + pub item_span: Span, } #[derive(Diagnostic)] diff --git a/compiler/rustc_passes/src/lang_items.rs b/compiler/rustc_passes/src/lang_items.rs index 3afed9784de..6fac01827a4 100644 --- a/compiler/rustc_passes/src/lang_items.rs +++ b/compiler/rustc_passes/src/lang_items.rs @@ -287,7 +287,7 @@ impl<'ast, 'tcx> visit::Visitor<'ast> for LanguageItemCollector<'ast, 'tcx> { ast::ItemKind::Union(..) => Target::Union, ast::ItemKind::Trait(_) => Target::Trait, ast::ItemKind::TraitAlias(..) => Target::TraitAlias, - ast::ItemKind::Impl(_) => Target::Impl, + ast::ItemKind::Impl(imp_) => Target::Impl { of_trait: imp_.of_trait.is_some() }, ast::ItemKind::MacroDef(..) => Target::MacroDef, ast::ItemKind::MacCall(_) | ast::ItemKind::DelegationMac(_) => { unreachable!("macros should have been expanded") diff --git a/compiler/rustc_passes/src/lib_features.rs b/compiler/rustc_passes/src/lib_features.rs index 127e0df1332..35d2a655991 100644 --- a/compiler/rustc_passes/src/lib_features.rs +++ b/compiler/rustc_passes/src/lib_features.rs @@ -44,7 +44,7 @@ impl<'tcx> LibFeatureCollector<'tcx> { StabilityLevel::Stable { since, .. } => FeatureStability::AcceptedSince(match since { StableSince::Version(v) => Symbol::intern(&v.to_string()), StableSince::Current => sym::env_CFG_RELEASE, - StableSince::Err => return None, + StableSince::Err(_) => return None, }), }; diff --git a/compiler/rustc_passes/src/stability.rs b/compiler/rustc_passes/src/stability.rs index e5530d52686..40999d622dc 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -1,37 +1,31 @@ //! A pass that annotates every item and method with its stability level, //! propagating default levels lexically from parent to children ast nodes. -use std::mem::replace; use std::num::NonZero; use rustc_ast_lowering::stability::extern_abi_stability; use rustc_attr_data_structures::{ - self as attrs, AttributeKind, ConstStability, DeprecatedSince, PartialConstStability, - Stability, StabilityLevel, StableSince, UnstableReason, VERSION_PLACEHOLDER, find_attr, + self as attrs, AttributeKind, ConstStability, DefaultBodyStability, DeprecatedSince, Stability, + StabilityLevel, StableSince, UnstableReason, VERSION_PLACEHOLDER, find_attr, }; use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::unord::{ExtendUnord, UnordMap, UnordSet}; -use rustc_feature::{ACCEPTED_LANG_FEATURES, EnabledLangFeature, EnabledLibFeature}; +use rustc_feature::{EnabledLangFeature, EnabledLibFeature}; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{CRATE_DEF_ID, LOCAL_CRATE, LocalDefId, LocalModDefId}; -use rustc_hir::hir_id::CRATE_HIR_ID; use rustc_hir::intravisit::{self, Visitor, VisitorExt}; use rustc_hir::{self as hir, AmbigArg, FieldDef, Item, ItemKind, TraitRef, Ty, TyKind, Variant}; use rustc_middle::hir::nested_filter; use rustc_middle::middle::lib_features::{FeatureStability, LibFeatures}; use rustc_middle::middle::privacy::EffectiveVisibilities; -use rustc_middle::middle::stability::{ - AllowUnstable, Deprecated, DeprecationEntry, EvalResult, Index, -}; -use rustc_middle::query::Providers; +use rustc_middle::middle::stability::{AllowUnstable, Deprecated, DeprecationEntry, EvalResult}; +use rustc_middle::query::{LocalCrate, Providers}; use rustc_middle::ty::TyCtxt; use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_session::lint; -use rustc_session::lint::builtin::{ - DEPRECATED, INEFFECTIVE_UNSTABLE_TRAIT_IMPL, USELESS_DEPRECATED, -}; +use rustc_session::lint::builtin::{DEPRECATED, INEFFECTIVE_UNSTABLE_TRAIT_IMPL}; use rustc_span::{Span, Symbol, sym}; -use tracing::{debug, info}; +use tracing::instrument; use crate::errors; @@ -47,359 +41,263 @@ enum AnnotationKind { Container, } -/// Whether to inherit deprecation flags for nested items. In most cases, we do want to inherit -/// deprecation, because nested items rarely have individual deprecation attributes, and so -/// should be treated as deprecated if their parent is. However, default generic parameters -/// have separate deprecation attributes from their parents, so we do not wish to inherit -/// deprecation in this case. For example, inheriting deprecation for `T` in `Foo<T>` -/// would cause a duplicate warning arising from both `Foo` and `T` being deprecated. -#[derive(Clone)] -enum InheritDeprecation { - Yes, - No, +fn inherit_deprecation(def_kind: DefKind) -> bool { + match def_kind { + DefKind::LifetimeParam | DefKind::TyParam | DefKind::ConstParam => false, + _ => true, + } } -impl InheritDeprecation { - fn yes(&self) -> bool { - matches!(self, InheritDeprecation::Yes) +fn inherit_const_stability(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool { + let def_kind = tcx.def_kind(def_id); + match def_kind { + DefKind::AssocFn | DefKind::AssocTy | DefKind::AssocConst => { + match tcx.def_kind(tcx.local_parent(def_id)) { + DefKind::Impl { of_trait: true } => true, + _ => false, + } + } + _ => false, } } -/// Whether to inherit const stability flags for nested items. In most cases, we do not want to -/// inherit const stability: just because an enclosing `fn` is const-stable does not mean -/// all `extern` imports declared in it should be const-stable! However, trait methods -/// inherit const stability attributes from their parent and do not have their own. -enum InheritConstStability { - Yes, - No, -} +fn annotation_kind(tcx: TyCtxt<'_>, def_id: LocalDefId) -> AnnotationKind { + let def_kind = tcx.def_kind(def_id); + match def_kind { + // Inherent impls and foreign modules serve only as containers for other items, + // they don't have their own stability. They still can be annotated as unstable + // and propagate this unstability to children, but this annotation is completely + // optional. They inherit stability from their parents when unannotated. + DefKind::Impl { of_trait: false } | DefKind::ForeignMod => AnnotationKind::Container, + DefKind::Impl { of_trait: true } => AnnotationKind::DeprecationProhibited, + + // Allow stability attributes on default generic arguments. + DefKind::TyParam | DefKind::ConstParam => { + match &tcx.hir_node_by_def_id(def_id).expect_generic_param().kind { + hir::GenericParamKind::Type { default: Some(_), .. } + | hir::GenericParamKind::Const { default: Some(_), .. } => { + AnnotationKind::Container + } + _ => AnnotationKind::Prohibited, + } + } + + // Impl items in trait impls cannot have stability. + DefKind::AssocTy | DefKind::AssocFn | DefKind::AssocConst => { + match tcx.def_kind(tcx.local_parent(def_id)) { + DefKind::Impl { of_trait: true } => AnnotationKind::Prohibited, + _ => AnnotationKind::Required, + } + } -impl InheritConstStability { - fn yes(&self) -> bool { - matches!(self, InheritConstStability::Yes) + _ => AnnotationKind::Required, } } -enum InheritStability { - Yes, - No, -} +fn lookup_deprecation_entry(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<DeprecationEntry> { + let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(def_id)); + let depr = attrs::find_attr!(attrs, + AttributeKind::Deprecation { deprecation, span: _ } => *deprecation + ); -impl InheritStability { - fn yes(&self) -> bool { - matches!(self, InheritStability::Yes) - } + let Some(depr) = depr else { + if inherit_deprecation(tcx.def_kind(def_id)) { + let parent_id = tcx.opt_local_parent(def_id)?; + let parent_depr = tcx.lookup_deprecation_entry(parent_id)?; + return Some(parent_depr); + } + + return None; + }; + + // `Deprecation` is just two pointers, no need to intern it + Some(DeprecationEntry::local(depr, def_id)) } -/// A private tree-walker for producing an `Index`. -struct Annotator<'a, 'tcx> { - tcx: TyCtxt<'tcx>, - index: &'a mut Index, - parent_stab: Option<Stability>, - parent_const_stab: Option<ConstStability>, - parent_depr: Option<DeprecationEntry>, - in_trait_impl: bool, +fn inherit_stability(def_kind: DefKind) -> bool { + match def_kind { + DefKind::Field | DefKind::Variant | DefKind::Ctor(..) => true, + _ => false, + } } -impl<'a, 'tcx> Annotator<'a, 'tcx> { - /// Determine the stability for a node based on its attributes and inherited stability. The - /// stability is recorded in the index and used as the parent. If the node is a function, - /// `fn_sig` is its signature. - fn annotate<F>( - &mut self, - def_id: LocalDefId, - item_sp: Span, - fn_sig: Option<&'tcx hir::FnSig<'tcx>>, - kind: AnnotationKind, - inherit_deprecation: InheritDeprecation, - inherit_const_stability: InheritConstStability, - inherit_from_parent: InheritStability, - visit_children: F, - ) where - F: FnOnce(&mut Self), - { - let attrs = self.tcx.hir_attrs(self.tcx.local_def_id_to_hir_id(def_id)); - debug!("annotate(id = {:?}, attrs = {:?})", def_id, attrs); - - let depr = attrs::find_attr!(attrs, AttributeKind::Deprecation{deprecation, span} => (*deprecation, *span)); - let const_stability_indirect = find_attr!(attrs, AttributeKind::ConstStabilityIndirect); - - let mut is_deprecated = false; - if let Some((depr, span)) = &depr { - is_deprecated = true; - - if matches!(kind, AnnotationKind::Prohibited | AnnotationKind::DeprecationProhibited) { - let hir_id = self.tcx.local_def_id_to_hir_id(def_id); - self.tcx.emit_node_span_lint( - USELESS_DEPRECATED, - hir_id, - *span, - errors::DeprecatedAnnotationHasNoEffect { span: *span }, - ); - } +/// If the `-Z force-unstable-if-unmarked` flag is passed then we provide +/// a parent stability annotation which indicates that this is private +/// with the `rustc_private` feature. This is intended for use when +/// compiling library and `rustc_*` crates themselves so we can leverage crates.io +/// while maintaining the invariant that all sysroot crates are unstable +/// by default and are unable to be used. +const FORCE_UNSTABLE: Stability = Stability { + level: attrs::StabilityLevel::Unstable { + reason: UnstableReason::Default, + issue: NonZero::new(27812), + is_soft: false, + implied_by: None, + old_name: None, + }, + feature: sym::rustc_private, +}; - // `Deprecation` is just two pointers, no need to intern it - let depr_entry = DeprecationEntry::local(*depr, def_id); - self.index.depr_map.insert(def_id, depr_entry); - } else if let Some(parent_depr) = self.parent_depr { - if inherit_deprecation.yes() { - is_deprecated = true; - info!("tagging child {:?} as deprecated from parent", def_id); - self.index.depr_map.insert(def_id, parent_depr); - } +#[instrument(level = "debug", skip(tcx))] +fn lookup_stability(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<Stability> { + // Propagate unstability. This can happen even for non-staged-api crates in case + // -Zforce-unstable-if-unmarked is set. + if !tcx.features().staged_api() { + if !tcx.sess.opts.unstable_opts.force_unstable_if_unmarked { + return None; } - if !self.tcx.features().staged_api() { - // Propagate unstability. This can happen even for non-staged-api crates in case - // -Zforce-unstable-if-unmarked is set. - if let Some(stab) = self.parent_stab { - if inherit_deprecation.yes() && stab.is_unstable() { - self.index.stab_map.insert(def_id, stab); - if fn_sig.is_some_and(|s| s.header.is_const()) { - self.index.const_stab_map.insert( - def_id, - ConstStability::unmarked(const_stability_indirect, stab), - ); - } - } - } + let Some(parent) = tcx.opt_local_parent(def_id) else { return Some(FORCE_UNSTABLE) }; - self.recurse_with_stability_attrs( - depr.map(|(d, _)| DeprecationEntry::local(d, def_id)), - None, - None, - visit_children, - ); - return; + if inherit_deprecation(tcx.def_kind(def_id)) { + let parent = tcx.lookup_stability(parent)?; + if parent.is_unstable() { + return Some(parent); + } } - // # Regular and body stability - let stab = attrs::find_attr!(attrs, AttributeKind::Stability { stability, span } => (*stability, *span)); - let body_stab = - attrs::find_attr!(attrs, AttributeKind::BodyStability { stability, .. } => *stability); + return None; + } - if let Some((depr, span)) = &depr - && depr.is_since_rustc_version() - && stab.is_none() - { - self.tcx.dcx().emit_err(errors::DeprecatedAttribute { span: *span }); - } + // # Regular stability + let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(def_id)); + let stab = + attrs::find_attr!(attrs, AttributeKind::Stability { stability, span: _ } => *stability); - if let Some(body_stab) = body_stab { - // FIXME: check that this item can have body stability + if let Some(stab) = stab { + return Some(stab); + } - self.index.default_body_stab_map.insert(def_id, body_stab); - debug!(?self.index.default_body_stab_map); + if inherit_deprecation(tcx.def_kind(def_id)) { + let Some(parent) = tcx.opt_local_parent(def_id) else { + return tcx + .sess + .opts + .unstable_opts + .force_unstable_if_unmarked + .then_some(FORCE_UNSTABLE); + }; + let parent = tcx.lookup_stability(parent)?; + if parent.is_unstable() || inherit_stability(tcx.def_kind(def_id)) { + return Some(parent); } + } - let stab = stab.map(|(stab, span)| { - // Error if prohibited, or can't inherit anything from a container. - if kind == AnnotationKind::Prohibited - || (kind == AnnotationKind::Container && stab.level.is_stable() && is_deprecated) - { - self.tcx.dcx().emit_err(errors::UselessStability { span, item_sp }); - } + None +} - debug!("annotate: found {:?}", stab); +#[instrument(level = "debug", skip(tcx))] +fn lookup_default_body_stability( + tcx: TyCtxt<'_>, + def_id: LocalDefId, +) -> Option<DefaultBodyStability> { + if !tcx.features().staged_api() { + return None; + } - // Check if deprecated_since < stable_since. If it is, - // this is *almost surely* an accident. - if let ( - &Some(DeprecatedSince::RustcVersion(dep_since)), - &attrs::StabilityLevel::Stable { since: stab_since, .. }, - ) = (&depr.as_ref().map(|(d, _)| d.since), &stab.level) - { - match stab_since { - StableSince::Current => { - self.tcx - .dcx() - .emit_err(errors::CannotStabilizeDeprecated { span, item_sp }); - } - StableSince::Version(stab_since) => { - if dep_since < stab_since { - self.tcx - .dcx() - .emit_err(errors::CannotStabilizeDeprecated { span, item_sp }); - } - } - StableSince::Err => { - // An error already reported. Assume the unparseable stabilization - // version is older than the deprecation version. - } - } - } + let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(def_id)); + // FIXME: check that this item can have body stability + attrs::find_attr!(attrs, AttributeKind::BodyStability { stability, .. } => *stability) +} - // Stable *language* features shouldn't be used as unstable library features. - // (Not doing this for stable library features is checked by tidy.) - if let Stability { level: StabilityLevel::Unstable { .. }, feature } = stab { - if ACCEPTED_LANG_FEATURES.iter().find(|f| f.name == feature).is_some() { - self.tcx - .dcx() - .emit_err(errors::UnstableAttrForAlreadyStableFeature { span, item_sp }); - } - } - if let Stability { - level: StabilityLevel::Unstable { implied_by: Some(implied_by), .. }, - feature, - } = stab +#[instrument(level = "debug", skip(tcx))] +fn lookup_const_stability(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<ConstStability> { + if !tcx.features().staged_api() { + // Propagate unstability. This can happen even for non-staged-api crates in case + // -Zforce-unstable-if-unmarked is set. + if inherit_deprecation(tcx.def_kind(def_id)) { + let parent = tcx.opt_local_parent(def_id)?; + let parent_stab = tcx.lookup_stability(parent)?; + if parent_stab.is_unstable() + && let Some(fn_sig) = tcx.hir_node_by_def_id(def_id).fn_sig() + && fn_sig.header.is_const() { - self.index.implications.insert(implied_by, feature); - } - - self.index.stab_map.insert(def_id, stab); - stab - }); - - if stab.is_none() { - debug!("annotate: stab not found, parent = {:?}", self.parent_stab); - if let Some(stab) = self.parent_stab { - if inherit_deprecation.yes() && stab.is_unstable() || inherit_from_parent.yes() { - self.index.stab_map.insert(def_id, stab); - } + let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(def_id)); + let const_stability_indirect = + find_attr!(attrs, AttributeKind::ConstStabilityIndirect); + return Some(ConstStability::unmarked(const_stability_indirect, parent_stab)); } } - let final_stab = self.index.stab_map.get(&def_id); + return None; + } - // # Const stability + let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(def_id)); + let const_stability_indirect = find_attr!(attrs, AttributeKind::ConstStabilityIndirect); + let const_stab = attrs::find_attr!(attrs, AttributeKind::ConstStability { stability, span: _ } => *stability); + + // After checking the immediate attributes, get rid of the span and compute implied + // const stability: inherit feature gate from regular stability. + let mut const_stab = const_stab + .map(|const_stab| ConstStability::from_partial(const_stab, const_stability_indirect)); + + // If this is a const fn but not annotated with stability markers, see if we can inherit + // regular stability. + if let Some(fn_sig) = tcx.hir_node_by_def_id(def_id).fn_sig() + && fn_sig.header.is_const() + && const_stab.is_none() + // We only ever inherit unstable features. + && let Some(inherit_regular_stab) = tcx.lookup_stability(def_id) + && inherit_regular_stab.is_unstable() + { + const_stab = Some(ConstStability { + // We subject these implicitly-const functions to recursive const stability. + const_stable_indirect: true, + promotable: false, + level: inherit_regular_stab.level, + feature: inherit_regular_stab.feature, + }); + } - let const_stab = attrs::find_attr!(attrs, AttributeKind::ConstStability { stability, span } => (*stability, *span)); + if let Some(const_stab) = const_stab { + return Some(const_stab); + } - // If the current node is a function with const stability attributes (directly given or - // implied), check if the function/method is const or the parent impl block is const. - if let Some(fn_sig) = fn_sig - && !fn_sig.header.is_const() - && const_stab.is_some() - { - self.tcx.dcx().emit_err(errors::MissingConstErr { fn_sig_span: fn_sig.span }); + // `impl const Trait for Type` items forward their const stability to their immediate children. + // FIXME(const_trait_impl): how is this supposed to interact with `#[rustc_const_stable_indirect]`? + // Currently, once that is set, we do not inherit anything from the parent any more. + if inherit_const_stability(tcx, def_id) { + let parent = tcx.opt_local_parent(def_id)?; + let parent = tcx.lookup_const_stability(parent)?; + if parent.is_const_unstable() { + return Some(parent); } + } - // If this is marked const *stable*, it must also be regular-stable. - if let Some((const_stab, const_span)) = const_stab - && let Some(fn_sig) = fn_sig - && const_stab.is_const_stable() - && !stab.is_some_and(|s| s.is_stable()) - { - self.tcx - .dcx() - .emit_err(errors::ConstStableNotStable { fn_sig_span: fn_sig.span, const_span }); - } + None +} - // Stable *language* features shouldn't be used as unstable library features. - // (Not doing this for stable library features is checked by tidy.) - if let Some(( - PartialConstStability { level: StabilityLevel::Unstable { .. }, feature, .. }, - const_span, - )) = const_stab - { - if ACCEPTED_LANG_FEATURES.iter().find(|f| f.name == feature).is_some() { - self.tcx.dcx().emit_err(errors::UnstableAttrForAlreadyStableFeature { - span: const_span, - item_sp, - }); - } - } +/// A private tree-walker for producing an `Index`. +struct Annotator<'tcx> { + tcx: TyCtxt<'tcx>, + implications: UnordMap<Symbol, Symbol>, +} - if let Some((stab, span)) = &const_stab - && stab.is_const_stable() - && const_stability_indirect - { - self.tcx.dcx().emit_err(errors::RustcConstStableIndirectPairing { span: *span }); +impl<'tcx> Annotator<'tcx> { + /// Determine the stability for a node based on its attributes and inherited stability. The + /// stability is recorded in the index and used as the parent. If the node is a function, + /// `fn_sig` is its signature. + #[instrument(level = "trace", skip(self))] + fn annotate(&mut self, def_id: LocalDefId) { + if !self.tcx.features().staged_api() { + return; } - // After checking the immediate attributes, get rid of the span and compute implied - // const stability: inherit feature gate from regular stability. - let mut const_stab = const_stab - .map(|(stab, _span)| ConstStability::from_partial(stab, const_stability_indirect)); - - // If this is a const fn but not annotated with stability markers, see if we can inherit regular stability. - if fn_sig.is_some_and(|s| s.header.is_const()) && const_stab.is_none() && - // We only ever inherit unstable features. - let Some(inherit_regular_stab) = - final_stab.filter(|s| s.is_unstable()) + if let Some(stability) = self.tcx.lookup_stability(def_id) + && let StabilityLevel::Unstable { implied_by: Some(implied_by), .. } = stability.level { - const_stab = Some(ConstStability { - // We subject these implicitly-const functions to recursive const stability. - const_stable_indirect: true, - promotable: false, - level: inherit_regular_stab.level, - feature: inherit_regular_stab.feature, - }); + self.implications.insert(implied_by, stability.feature); } - // Now that everything is computed, insert it into the table. - const_stab.inspect(|const_stab| { - self.index.const_stab_map.insert(def_id, *const_stab); - }); - - if let Some(ConstStability { - level: StabilityLevel::Unstable { implied_by: Some(implied_by), .. }, - feature, - .. - }) = const_stab + if let Some(stability) = self.tcx.lookup_const_stability(def_id) + && let StabilityLevel::Unstable { implied_by: Some(implied_by), .. } = stability.level { - self.index.implications.insert(implied_by, feature); - } - - // `impl const Trait for Type` items forward their const stability to their - // immediate children. - // FIXME(const_trait_impl): how is this supposed to interact with `#[rustc_const_stable_indirect]`? - // Currently, once that is set, we do not inherit anything from the parent any more. - if const_stab.is_none() { - debug!("annotate: const_stab not found, parent = {:?}", self.parent_const_stab); - if let Some(parent) = self.parent_const_stab { - if parent.is_const_unstable() { - self.index.const_stab_map.insert(def_id, parent); - } - } - } - - self.recurse_with_stability_attrs( - depr.map(|(d, _)| DeprecationEntry::local(d, def_id)), - stab, - inherit_const_stability.yes().then_some(const_stab).flatten(), - visit_children, - ); - } - - fn recurse_with_stability_attrs( - &mut self, - depr: Option<DeprecationEntry>, - stab: Option<Stability>, - const_stab: Option<ConstStability>, - f: impl FnOnce(&mut Self), - ) { - // These will be `Some` if this item changes the corresponding stability attribute. - let mut replaced_parent_depr = None; - let mut replaced_parent_stab = None; - let mut replaced_parent_const_stab = None; - - if let Some(depr) = depr { - replaced_parent_depr = Some(replace(&mut self.parent_depr, Some(depr))); - } - if let Some(stab) = stab { - replaced_parent_stab = Some(replace(&mut self.parent_stab, Some(stab))); - } - if let Some(const_stab) = const_stab { - replaced_parent_const_stab = - Some(replace(&mut self.parent_const_stab, Some(const_stab))); - } - - f(self); - - if let Some(orig_parent_depr) = replaced_parent_depr { - self.parent_depr = orig_parent_depr; - } - if let Some(orig_parent_stab) = replaced_parent_stab { - self.parent_stab = orig_parent_stab; - } - if let Some(orig_parent_const_stab) = replaced_parent_const_stab { - self.parent_const_stab = orig_parent_const_stab; + self.implications.insert(implied_by, stability.feature); } } } -impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { +impl<'tcx> Visitor<'tcx> for Annotator<'tcx> { /// Because stability levels are scoped lexically, we want to walk /// nested items in the context of the outer item, so enable /// deep-walking. @@ -410,184 +308,51 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> { } fn visit_item(&mut self, i: &'tcx Item<'tcx>) { - let orig_in_trait_impl = self.in_trait_impl; - let mut kind = AnnotationKind::Required; - let mut const_stab_inherit = InheritConstStability::No; - let mut fn_sig = None; - match i.kind { - // Inherent impls and foreign modules serve only as containers for other items, - // they don't have their own stability. They still can be annotated as unstable - // and propagate this instability to children, but this annotation is completely - // optional. They inherit stability from their parents when unannotated. - hir::ItemKind::Impl(hir::Impl { of_trait: None, .. }) - | hir::ItemKind::ForeignMod { .. } => { - self.in_trait_impl = false; - kind = AnnotationKind::Container; - } - hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => { - self.in_trait_impl = true; - kind = AnnotationKind::DeprecationProhibited; - const_stab_inherit = InheritConstStability::Yes; - } hir::ItemKind::Struct(_, _, ref sd) => { if let Some(ctor_def_id) = sd.ctor_def_id() { - self.annotate( - ctor_def_id, - i.span, - None, - AnnotationKind::Required, - InheritDeprecation::Yes, - InheritConstStability::No, - InheritStability::Yes, - |_| {}, - ) + self.annotate(ctor_def_id); } } - hir::ItemKind::Fn { sig: ref item_fn_sig, .. } => { - fn_sig = Some(item_fn_sig); - } _ => {} } - self.annotate( - i.owner_id.def_id, - i.span, - fn_sig, - kind, - InheritDeprecation::Yes, - const_stab_inherit, - InheritStability::No, - |v| intravisit::walk_item(v, i), - ); - self.in_trait_impl = orig_in_trait_impl; + self.annotate(i.owner_id.def_id); + intravisit::walk_item(self, i) } fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) { - let fn_sig = match ti.kind { - hir::TraitItemKind::Fn(ref fn_sig, _) => Some(fn_sig), - _ => None, - }; - - self.annotate( - ti.owner_id.def_id, - ti.span, - fn_sig, - AnnotationKind::Required, - InheritDeprecation::Yes, - InheritConstStability::No, - InheritStability::No, - |v| { - intravisit::walk_trait_item(v, ti); - }, - ); + self.annotate(ti.owner_id.def_id); + intravisit::walk_trait_item(self, ti); } fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) { - let kind = - if self.in_trait_impl { AnnotationKind::Prohibited } else { AnnotationKind::Required }; - - let fn_sig = match ii.kind { - hir::ImplItemKind::Fn(ref fn_sig, _) => Some(fn_sig), - _ => None, - }; - - self.annotate( - ii.owner_id.def_id, - ii.span, - fn_sig, - kind, - InheritDeprecation::Yes, - InheritConstStability::No, - InheritStability::No, - |v| { - intravisit::walk_impl_item(v, ii); - }, - ); + self.annotate(ii.owner_id.def_id); + intravisit::walk_impl_item(self, ii); } fn visit_variant(&mut self, var: &'tcx Variant<'tcx>) { - self.annotate( - var.def_id, - var.span, - None, - AnnotationKind::Required, - InheritDeprecation::Yes, - InheritConstStability::No, - InheritStability::Yes, - |v| { - if let Some(ctor_def_id) = var.data.ctor_def_id() { - v.annotate( - ctor_def_id, - var.span, - None, - AnnotationKind::Required, - InheritDeprecation::Yes, - InheritConstStability::No, - InheritStability::Yes, - |_| {}, - ); - } + self.annotate(var.def_id); + if let Some(ctor_def_id) = var.data.ctor_def_id() { + self.annotate(ctor_def_id); + } - intravisit::walk_variant(v, var) - }, - ) + intravisit::walk_variant(self, var) } fn visit_field_def(&mut self, s: &'tcx FieldDef<'tcx>) { - self.annotate( - s.def_id, - s.span, - None, - AnnotationKind::Required, - InheritDeprecation::Yes, - InheritConstStability::No, - InheritStability::Yes, - |v| { - intravisit::walk_field_def(v, s); - }, - ); + self.annotate(s.def_id); + intravisit::walk_field_def(self, s); } fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) { - let fn_sig = match &i.kind { - rustc_hir::ForeignItemKind::Fn(fn_sig, ..) => Some(fn_sig), - _ => None, - }; - self.annotate( - i.owner_id.def_id, - i.span, - fn_sig, - AnnotationKind::Required, - InheritDeprecation::Yes, - InheritConstStability::No, - InheritStability::No, - |v| { - intravisit::walk_foreign_item(v, i); - }, - ); + self.annotate(i.owner_id.def_id); + intravisit::walk_foreign_item(self, i); } fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>) { - let kind = match &p.kind { - // Allow stability attributes on default generic arguments. - hir::GenericParamKind::Type { default: Some(_), .. } - | hir::GenericParamKind::Const { default: Some(_), .. } => AnnotationKind::Container, - _ => AnnotationKind::Prohibited, - }; - - self.annotate( - p.def_id, - p.span, - None, - kind, - InheritDeprecation::No, - InheritConstStability::No, - InheritStability::No, - |v| { - intravisit::walk_generic_param(v, p); - }, - ); + self.annotate(p.def_id); + intravisit::walk_generic_param(self, p); } } @@ -597,18 +362,119 @@ struct MissingStabilityAnnotations<'tcx> { } impl<'tcx> MissingStabilityAnnotations<'tcx> { - fn check_missing_stability(&self, def_id: LocalDefId, span: Span) { - let stab = self.tcx.stability().local_stability(def_id); + /// Verify that deprecation and stability attributes make sense with one another. + #[instrument(level = "trace", skip(self))] + fn check_compatible_stability(&self, def_id: LocalDefId) { + if !self.tcx.features().staged_api() { + return; + } + + let depr = self.tcx.lookup_deprecation_entry(def_id); + let stab = self.tcx.lookup_stability(def_id); + let const_stab = self.tcx.lookup_const_stability(def_id); + + macro_rules! find_attr_span { + ($name:ident) => {{ + let attrs = self.tcx.hir_attrs(self.tcx.local_def_id_to_hir_id(def_id)); + attrs::find_attr!(attrs, AttributeKind::$name { span, .. } => *span) + }} + } + + if stab.is_none() + && depr.map_or(false, |d| d.attr.is_since_rustc_version()) + && let Some(span) = find_attr_span!(Deprecation) + { + self.tcx.dcx().emit_err(errors::DeprecatedAttribute { span }); + } + + if let Some(stab) = stab { + // Error if prohibited, or can't inherit anything from a container. + let kind = annotation_kind(self.tcx, def_id); + if kind == AnnotationKind::Prohibited + || (kind == AnnotationKind::Container && stab.level.is_stable() && depr.is_some()) + { + if let Some(span) = find_attr_span!(Stability) { + let item_sp = self.tcx.def_span(def_id); + self.tcx.dcx().emit_err(errors::UselessStability { span, item_sp }); + } + } + + // Check if deprecated_since < stable_since. If it is, + // this is *almost surely* an accident. + if let Some(depr) = depr + && let DeprecatedSince::RustcVersion(dep_since) = depr.attr.since + && let attrs::StabilityLevel::Stable { since: stab_since, .. } = stab.level + && let Some(span) = find_attr_span!(Stability) + { + let item_sp = self.tcx.def_span(def_id); + match stab_since { + StableSince::Current => { + self.tcx + .dcx() + .emit_err(errors::CannotStabilizeDeprecated { span, item_sp }); + } + StableSince::Version(stab_since) => { + if dep_since < stab_since { + self.tcx + .dcx() + .emit_err(errors::CannotStabilizeDeprecated { span, item_sp }); + } + } + StableSince::Err(_) => { + // An error already reported. Assume the unparseable stabilization + // version is older than the deprecation version. + } + } + } + } + + // If the current node is a function with const stability attributes (directly given or + // implied), check if the function/method is const or the parent impl block is const. + let fn_sig = self.tcx.hir_node_by_def_id(def_id).fn_sig(); + if let Some(fn_sig) = fn_sig + && !fn_sig.header.is_const() + && const_stab.is_some() + && find_attr_span!(ConstStability).is_some() + { + self.tcx.dcx().emit_err(errors::MissingConstErr { fn_sig_span: fn_sig.span }); + } + + // If this is marked const *stable*, it must also be regular-stable. + if let Some(const_stab) = const_stab + && let Some(fn_sig) = fn_sig + && const_stab.is_const_stable() + && !stab.is_some_and(|s| s.is_stable()) + && let Some(const_span) = find_attr_span!(ConstStability) + { + self.tcx + .dcx() + .emit_err(errors::ConstStableNotStable { fn_sig_span: fn_sig.span, const_span }); + } + + if let Some(stab) = &const_stab + && stab.is_const_stable() + && stab.const_stable_indirect + && let Some(span) = find_attr_span!(ConstStability) + { + self.tcx.dcx().emit_err(errors::RustcConstStableIndirectPairing { span }); + } + } + + #[instrument(level = "debug", skip(self))] + fn check_missing_stability(&self, def_id: LocalDefId) { + let stab = self.tcx.lookup_stability(def_id); + self.tcx.ensure_ok().lookup_const_stability(def_id); if !self.tcx.sess.is_test_crate() && stab.is_none() && self.effective_visibilities.is_reachable(def_id) { let descr = self.tcx.def_descr(def_id.to_def_id()); + let span = self.tcx.def_span(def_id); self.tcx.dcx().emit_err(errors::MissingStabilityAttr { span, descr }); } } - fn check_missing_const_stability(&self, def_id: LocalDefId, span: Span) { + fn check_missing_const_stability(&self, def_id: LocalDefId) { let is_const = self.tcx.is_const_fn(def_id.to_def_id()) || (self.tcx.def_kind(def_id.to_def_id()) == DefKind::Trait && self.tcx.is_const_trait(def_id.to_def_id())); @@ -618,6 +484,7 @@ impl<'tcx> MissingStabilityAnnotations<'tcx> { && self.effective_visibilities.is_reachable(def_id) && self.tcx.lookup_const_stability(def_id).is_none() { + let span = self.tcx.def_span(def_id); let descr = self.tcx.def_descr(def_id.to_def_id()); self.tcx.dcx().emit_err(errors::MissingConstStabAttr { span, descr }); } @@ -632,6 +499,8 @@ impl<'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'tcx> { } fn visit_item(&mut self, i: &'tcx Item<'tcx>) { + self.check_compatible_stability(i.owner_id.def_id); + // Inherent impls and foreign modules serve only as containers for other items, // they don't have their own stability. They still can be annotated as unstable // and propagate this instability to children, but this annotation is completely @@ -641,119 +510,97 @@ impl<'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'tcx> { hir::ItemKind::Impl(hir::Impl { of_trait: None, .. }) | hir::ItemKind::ForeignMod { .. } ) { - self.check_missing_stability(i.owner_id.def_id, i.span); + self.check_missing_stability(i.owner_id.def_id); } // Ensure stable `const fn` have a const stability attribute. - self.check_missing_const_stability(i.owner_id.def_id, i.span); + self.check_missing_const_stability(i.owner_id.def_id); intravisit::walk_item(self, i) } fn visit_trait_item(&mut self, ti: &'tcx hir::TraitItem<'tcx>) { - self.check_missing_stability(ti.owner_id.def_id, ti.span); + self.check_compatible_stability(ti.owner_id.def_id); + self.check_missing_stability(ti.owner_id.def_id); intravisit::walk_trait_item(self, ti); } fn visit_impl_item(&mut self, ii: &'tcx hir::ImplItem<'tcx>) { + self.check_compatible_stability(ii.owner_id.def_id); let impl_def_id = self.tcx.hir_get_parent_item(ii.hir_id()); if self.tcx.impl_trait_ref(impl_def_id).is_none() { - self.check_missing_stability(ii.owner_id.def_id, ii.span); - self.check_missing_const_stability(ii.owner_id.def_id, ii.span); + self.check_missing_stability(ii.owner_id.def_id); + self.check_missing_const_stability(ii.owner_id.def_id); } intravisit::walk_impl_item(self, ii); } fn visit_variant(&mut self, var: &'tcx Variant<'tcx>) { - self.check_missing_stability(var.def_id, var.span); + self.check_compatible_stability(var.def_id); + self.check_missing_stability(var.def_id); if let Some(ctor_def_id) = var.data.ctor_def_id() { - self.check_missing_stability(ctor_def_id, var.span); + self.check_missing_stability(ctor_def_id); } intravisit::walk_variant(self, var); } fn visit_field_def(&mut self, s: &'tcx FieldDef<'tcx>) { - self.check_missing_stability(s.def_id, s.span); + self.check_compatible_stability(s.def_id); + self.check_missing_stability(s.def_id); intravisit::walk_field_def(self, s); } fn visit_foreign_item(&mut self, i: &'tcx hir::ForeignItem<'tcx>) { - self.check_missing_stability(i.owner_id.def_id, i.span); + self.check_compatible_stability(i.owner_id.def_id); + self.check_missing_stability(i.owner_id.def_id); intravisit::walk_foreign_item(self, i); } - // Note that we don't need to `check_missing_stability` for default generic parameters, - // as we assume that any default generic parameters without attributes are automatically - // stable (assuming they have not inherited instability from their parent). -} -fn stability_index(tcx: TyCtxt<'_>, (): ()) -> Index { - let mut index = Index { - stab_map: Default::default(), - const_stab_map: Default::default(), - default_body_stab_map: Default::default(), - depr_map: Default::default(), - implications: Default::default(), - }; - - { - let mut annotator = Annotator { - tcx, - index: &mut index, - parent_stab: None, - parent_const_stab: None, - parent_depr: None, - in_trait_impl: false, - }; - - // If the `-Z force-unstable-if-unmarked` flag is passed then we provide - // a parent stability annotation which indicates that this is private - // with the `rustc_private` feature. This is intended for use when - // compiling `librustc_*` crates themselves so we can leverage crates.io - // while maintaining the invariant that all sysroot crates are unstable - // by default and are unable to be used. - if tcx.sess.opts.unstable_opts.force_unstable_if_unmarked { - let stability = Stability { - level: attrs::StabilityLevel::Unstable { - reason: UnstableReason::Default, - issue: NonZero::new(27812), - is_soft: false, - implied_by: None, - old_name: None, - }, - feature: sym::rustc_private, - }; - annotator.parent_stab = Some(stability); - } - - annotator.annotate( - CRATE_DEF_ID, - tcx.hir_span(CRATE_HIR_ID), - None, - AnnotationKind::Required, - InheritDeprecation::Yes, - InheritConstStability::No, - InheritStability::No, - |v| tcx.hir_walk_toplevel_module(v), - ); + fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>) { + self.check_compatible_stability(p.def_id); + // Note that we don't need to `check_missing_stability` for default generic parameters, + // as we assume that any default generic parameters without attributes are automatically + // stable (assuming they have not inherited instability from their parent). + intravisit::walk_generic_param(self, p); } - index +} + +fn stability_implications(tcx: TyCtxt<'_>, LocalCrate: LocalCrate) -> UnordMap<Symbol, Symbol> { + let mut annotator = Annotator { tcx, implications: Default::default() }; + annotator.annotate(CRATE_DEF_ID); + tcx.hir_walk_toplevel_module(&mut annotator); + annotator.implications } /// Cross-references the feature names of unstable APIs with enabled /// features and possibly prints errors. fn check_mod_unstable_api_usage(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) { tcx.hir_visit_item_likes_in_module(module_def_id, &mut Checker { tcx }); + + let is_staged_api = + tcx.sess.opts.unstable_opts.force_unstable_if_unmarked || tcx.features().staged_api(); + if is_staged_api { + let effective_visibilities = &tcx.effective_visibilities(()); + let mut missing = MissingStabilityAnnotations { tcx, effective_visibilities }; + if module_def_id.is_top_level_module() { + missing.check_missing_stability(CRATE_DEF_ID); + } + tcx.hir_visit_item_likes_in_module(module_def_id, &mut missing); + } + + if module_def_id.is_top_level_module() { + check_unused_or_stable_features(tcx) + } } pub(crate) fn provide(providers: &mut Providers) { *providers = Providers { check_mod_unstable_api_usage, - stability_index, - stability_implications: |tcx, _| tcx.stability().implications.clone(), - lookup_stability: |tcx, id| tcx.stability().local_stability(id), - lookup_const_stability: |tcx, id| tcx.stability().local_const_stability(id), - lookup_default_body_stability: |tcx, id| tcx.stability().local_default_body_stability(id), - lookup_deprecation_entry: |tcx, id| tcx.stability().local_deprecation_entry(id), + stability_implications, + lookup_stability, + lookup_const_stability, + lookup_default_body_stability, + lookup_deprecation_entry, ..*providers }; } @@ -1058,7 +905,7 @@ fn is_unstable_reexport(tcx: TyCtxt<'_>, id: hir::HirId) -> bool { }; let def_id = owner.def_id; - let Some(stab) = tcx.stability().local_stability(def_id) else { + let Some(stab) = tcx.lookup_stability(def_id) else { return false; }; @@ -1127,16 +974,9 @@ impl<'tcx> Visitor<'tcx> for CheckTraitImplStable<'tcx> { /// Given the list of enabled features that were not language features (i.e., that /// were expected to be library features), and the list of features used from /// libraries, identify activated features that don't exist and error about them. +// This is `pub` for rustdoc. rustc should call it through `check_mod_unstable_api_usage`. pub fn check_unused_or_stable_features(tcx: TyCtxt<'_>) { - let is_staged_api = - tcx.sess.opts.unstable_opts.force_unstable_if_unmarked || tcx.features().staged_api(); - if is_staged_api { - let effective_visibilities = &tcx.effective_visibilities(()); - let mut missing = MissingStabilityAnnotations { tcx, effective_visibilities }; - missing.check_missing_stability(CRATE_DEF_ID, tcx.hir_span(CRATE_HIR_ID)); - tcx.hir_walk_toplevel_module(&mut missing); - tcx.hir_visit_all_item_likes_in_crate(&mut missing); - } + let _prof_timer = tcx.sess.timer("unused_lib_feature_checking"); let enabled_lang_features = tcx.features().enabled_lang_features(); let mut lang_features = UnordSet::default(); diff --git a/compiler/rustc_pattern_analysis/src/rustc.rs b/compiler/rustc_pattern_analysis/src/rustc.rs index ee72b676b38..0c1b0d622f2 100644 --- a/compiler/rustc_pattern_analysis/src/rustc.rs +++ b/compiler/rustc_pattern_analysis/src/rustc.rs @@ -16,7 +16,7 @@ use rustc_middle::ty::{ }; use rustc_middle::{bug, span_bug}; use rustc_session::lint; -use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, sym}; +use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span}; use crate::constructor::Constructor::*; use crate::constructor::{ @@ -238,10 +238,7 @@ impl<'p, 'tcx: 'p> RustcPatCtxt<'p, 'tcx> { let is_visible = adt.is_enum() || field.vis.is_accessible_from(cx.module, cx.tcx); let is_uninhabited = cx.is_uninhabited(*ty); - let is_unstable = cx.tcx.lookup_stability(field.did).is_some_and(|stab| { - stab.is_unstable() && stab.feature != sym::rustc_private - }); - let skip = is_uninhabited && (!is_visible || is_unstable); + let skip = is_uninhabited && !is_visible; (ty, PrivateUninhabitedField(skip)) }); cx.dropless_arena.alloc_from_iter(tys) diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index 80c13e44d7d..9dd80bc9964 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -1624,6 +1624,10 @@ impl<'tcx> PrivateItemsInPublicInterfacesChecker<'_, 'tcx> { self.check(def_id, item_visibility, effective_vis).generics().predicates(); for assoc_item in tcx.associated_items(id.owner_id).in_definition_order() { + if assoc_item.is_impl_trait_in_trait() { + continue; + } + self.check_assoc_item(assoc_item, item_visibility, effective_vis); if assoc_item.is_type() { @@ -1736,6 +1740,10 @@ impl<'tcx> PrivateItemsInPublicInterfacesChecker<'_, 'tcx> { check.ty().trait_ref(); for assoc_item in tcx.associated_items(id.owner_id).in_definition_order() { + if assoc_item.is_impl_trait_in_trait() { + continue; + } + let impl_item_vis = if !of_trait { min(tcx.local_visibility(assoc_item.def_id.expect_local()), impl_vis, tcx) } else { diff --git a/compiler/rustc_resolve/src/build_reduced_graph.rs b/compiler/rustc_resolve/src/build_reduced_graph.rs index 675ea9d1e98..737577baa7a 100644 --- a/compiler/rustc_resolve/src/build_reduced_graph.rs +++ b/compiler/rustc_resolve/src/build_reduced_graph.rs @@ -49,7 +49,8 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { ns: Namespace, binding: NameBinding<'ra>, ) { - if let Err(old_binding) = self.try_define(parent, ident, ns, binding, false) { + let key = self.new_disambiguated_key(ident, ns); + if let Err(old_binding) = self.try_define(parent, key, binding, false) { self.report_conflict(parent, ident, ns, old_binding, binding); } } @@ -441,18 +442,16 @@ impl<'a, 'ra, 'tcx> BuildReducedGraphVisitor<'a, 'ra, 'tcx> { self.r.indeterminate_imports.push(import); match import.kind { + // Don't add unresolved underscore imports to modules + ImportKind::Single { target: Ident { name: kw::Underscore, .. }, .. } => {} ImportKind::Single { target, type_ns_only, .. } => { - // Don't add underscore imports to `single_imports` - // because they cannot define any usable names. - if target.name != kw::Underscore { - self.r.per_ns(|this, ns| { - if !type_ns_only || ns == TypeNS { - let key = BindingKey::new(target, ns); - let mut resolution = this.resolution(current_module, key).borrow_mut(); - resolution.single_imports.insert(import); - } - }); - } + self.r.per_ns(|this, ns| { + if !type_ns_only || ns == TypeNS { + let key = BindingKey::new(target, ns); + let mut resolution = this.resolution(current_module, key).borrow_mut(); + resolution.single_imports.insert(import); + } + }); } // We don't add prelude imports to the globs since they only affect lexical scopes, // which are not relevant to import resolution. @@ -898,9 +897,12 @@ impl<'a, 'ra, 'tcx> BuildReducedGraphVisitor<'a, 'ra, 'tcx> { Some(self.r.graph_root) } else { let tcx = self.r.tcx; - let crate_id = self.r.crate_loader(|c| { - c.process_extern_crate(item, local_def_id, &tcx.definitions_untracked()) - }); + let crate_id = self.r.cstore_mut().process_extern_crate( + self.r.tcx, + item, + local_def_id, + &tcx.definitions_untracked(), + ); crate_id.map(|crate_id| { self.r.extern_crate_map.insert(local_def_id, crate_id); self.r.expect_module(crate_id.as_def_id()) @@ -1406,12 +1408,9 @@ impl<'a, 'ra, 'tcx> Visitor<'a> for BuildReducedGraphVisitor<'a, 'ra, 'tcx> { let parent = self.parent_scope.module; let expansion = self.parent_scope.expansion; self.r.define(parent, ident, ns, self.res(def_id), vis, item.span, expansion); - } else if !matches!(&item.kind, AssocItemKind::Delegation(deleg) if deleg.from_glob) - && ident.name != kw::Underscore - { - // Don't add underscore names, they cannot be looked up anyway. + } else if !matches!(&item.kind, AssocItemKind::Delegation(deleg) if deleg.from_glob) { let impl_def_id = self.r.tcx.local_parent(local_def_id); - let key = BindingKey::new(ident, ns); + let key = BindingKey::new(ident.normalize_to_macros_2_0(), ns); self.r.impl_binding_keys.entry(impl_def_id).or_default().insert(key); } diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs index f6f45adabe9..d72fbc189e7 100644 --- a/compiler/rustc_resolve/src/diagnostics.rs +++ b/compiler/rustc_resolve/src/diagnostics.rs @@ -1425,7 +1425,8 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { // otherwise cause duplicate suggestions. continue; } - let Some(crate_id) = self.crate_loader(|c| c.maybe_process_path_extern(ident.name)) + let Some(crate_id) = + self.cstore_mut().maybe_process_path_extern(self.tcx, ident.name) else { continue; }; diff --git a/compiler/rustc_resolve/src/imports.rs b/compiler/rustc_resolve/src/imports.rs index b4c15ed1ca7..0a4c25b0eb0 100644 --- a/compiler/rustc_resolve/src/imports.rs +++ b/compiler/rustc_resolve/src/imports.rs @@ -25,7 +25,7 @@ use rustc_span::{Ident, Span, Symbol, kw, sym}; use smallvec::SmallVec; use tracing::debug; -use crate::Namespace::{self, *}; +use crate::Namespace::*; use crate::diagnostics::{DiagMode, Suggestion, import_candidates}; use crate::errors::{ CannotBeReexportedCratePublic, CannotBeReexportedCratePublicNS, CannotBeReexportedPrivate, @@ -338,20 +338,13 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { pub(crate) fn try_define( &mut self, module: Module<'ra>, - ident: Ident, - ns: Namespace, + key: BindingKey, binding: NameBinding<'ra>, warn_ambiguity: bool, ) -> Result<(), NameBinding<'ra>> { let res = binding.res(); - self.check_reserved_macro_name(ident, res); + self.check_reserved_macro_name(key.ident, res); self.set_binding_parent_module(binding, module); - // Even if underscore names cannot be looked up, we still need to add them to modules, - // because they can be fetched by glob imports from those modules, and bring traits - // into scope both directly and through glob imports. - let key = BindingKey::new_disambiguated(ident, ns, || { - (module.0.0.lazy_resolutions.borrow().len() + 1).try_into().unwrap() - }); self.update_resolution(module, key, warn_ambiguity, |this, resolution| { if let Some(old_binding) = resolution.best_binding() { if res == Res::Err && old_binding.res() != Res::Err { @@ -390,7 +383,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { (old_glob @ true, false) | (old_glob @ false, true) => { let (glob_binding, non_glob_binding) = if old_glob { (old_binding, binding) } else { (binding, old_binding) }; - if ns == MacroNS + if key.ns == MacroNS && non_glob_binding.expansion != LocalExpnId::ROOT && glob_binding.res() != non_glob_binding.res() { @@ -496,10 +489,10 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { }; if self.is_accessible_from(binding.vis, scope) { let imported_binding = self.import(binding, *import); + let key = BindingKey { ident, ..key }; let _ = self.try_define( import.parent_scope.module, - ident, - key.ns, + key, imported_binding, warn_ambiguity, ); @@ -521,15 +514,11 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { let dummy_binding = self.dummy_binding; let dummy_binding = self.import(dummy_binding, import); self.per_ns(|this, ns| { - let module = import.parent_scope.module; - let _ = this.try_define(module, target, ns, dummy_binding, false); - // Don't remove underscores from `single_imports`, they were never added. - if target.name != kw::Underscore { - let key = BindingKey::new(target, ns); - this.update_resolution(module, key, false, |_, resolution| { - resolution.single_imports.swap_remove(&import); - }) - } + let key = BindingKey::new(target, ns); + let _ = this.try_define(import.parent_scope.module, key, dummy_binding, false); + this.update_resolution(import.parent_scope.module, key, false, |_, resolution| { + resolution.single_imports.swap_remove(&import); + }) }); self.record_use(target, dummy_binding, Used::Other); } else if import.imported_module.get().is_none() { @@ -906,7 +895,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { PendingBinding::Ready(Some(imported_binding)) } Err(Determinacy::Determined) => { - // Don't remove underscores from `single_imports`, they were never added. + // Don't update the resolution for underscores, because it was never added. if target.name != kw::Underscore { let key = BindingKey::new(target, ns); this.update_resolution(parent, key, false, |_, resolution| { @@ -1521,8 +1510,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { .is_some_and(|binding| binding.warn_ambiguity_recursive()); let _ = self.try_define( import.parent_scope.module, - key.ident, - key.ns, + key, imported_binding, warn_ambiguity, ); diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs index 93cec8daa5a..a3a770502de 100644 --- a/compiler/rustc_resolve/src/late.rs +++ b/compiler/rustc_resolve/src/late.rs @@ -2913,7 +2913,7 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> { self.r .dcx() .create_err(errors::UnderscoreLifetimeIsReserved { span: param.ident.span }) - .emit_unless(is_raw_underscore_lifetime); + .emit_unless_delay(is_raw_underscore_lifetime); // Record lifetime res, so lowering knows there is something fishy. self.record_lifetime_param(param.id, LifetimeRes::Error); continue; diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs index ee462d90764..69095942f52 100644 --- a/compiler/rustc_resolve/src/late/diagnostics.rs +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -2485,7 +2485,8 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { let extern_prelude = self.r.extern_prelude.clone(); names.extend(extern_prelude.iter().flat_map(|(ident, _)| { self.r - .crate_loader(|c| c.maybe_process_path_extern(ident.name)) + .cstore_mut() + .maybe_process_path_extern(self.r.tcx, ident.name) .and_then(|crate_id| { let crate_mod = Res::Def(DefKind::Mod, crate_id.as_def_id()); diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index f38fee8dea5..0d41a822e8a 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -45,7 +45,7 @@ use rustc_attr_data_structures::StrippedCfgItem; 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::sync::{FreezeReadGuard, FreezeWriteGuard}; use rustc_data_structures::unord::{UnordMap, UnordSet}; use rustc_errors::{Applicability, Diag, ErrCode, ErrorGuaranteed}; use rustc_expand::base::{DeriveResolution, SyntaxExtension, SyntaxExtensionKind}; @@ -58,7 +58,7 @@ use rustc_hir::def_id::{CRATE_DEF_ID, CrateNum, DefId, LOCAL_CRATE, LocalDefId, use rustc_hir::definitions::DisambiguatorState; use rustc_hir::{PrimTy, TraitCandidate}; use rustc_index::bit_set::DenseBitSet; -use rustc_metadata::creader::{CStore, CrateLoader}; +use rustc_metadata::creader::CStore; use rustc_middle::metadata::ModChild; use rustc_middle::middle::privacy::EffectiveVisibilities; use rustc_middle::query::Providers; @@ -532,26 +532,15 @@ struct BindingKey { /// identifier. ident: Ident, ns: Namespace, - /// When we add an underscore binding (with ident `_`) to some module, this field has - /// a non-zero value that uniquely identifies this binding in that module. - /// For non-underscore bindings this field is zero. - /// When a key is constructed for name lookup (as opposed to name definition), this field is - /// also zero, even for underscore names, so for underscores the lookup will never succeed. + /// 0 if ident is not `_`, otherwise a value that's unique to the specific + /// `_` in the expanded AST that introduced this binding. disambiguator: u32, } impl BindingKey { fn new(ident: Ident, ns: Namespace) -> Self { - BindingKey { ident: ident.normalize_to_macros_2_0(), ns, disambiguator: 0 } - } - - fn new_disambiguated( - ident: Ident, - ns: Namespace, - disambiguator: impl FnOnce() -> u32, - ) -> BindingKey { - let disambiguator = if ident.name == kw::Underscore { disambiguator() } else { 0 }; - BindingKey { ident: ident.normalize_to_macros_2_0(), ns, disambiguator } + let ident = ident.normalize_to_macros_2_0(); + BindingKey { ident, ns, disambiguator: 0 } } } @@ -1098,6 +1087,8 @@ pub struct Resolver<'ra, 'tcx> { extern_module_map: RefCell<FxIndexMap<DefId, Module<'ra>>>, binding_parent_modules: FxHashMap<NameBinding<'ra>, Module<'ra>>, + underscore_disambiguator: u32, + /// Maps glob imports to the names of items actually imported. glob_map: FxIndexMap<LocalDefId, FxIndexSet<Symbol>>, glob_error: Option<ErrorGuaranteed>, @@ -1119,7 +1110,6 @@ pub struct Resolver<'ra, 'tcx> { builtin_types_bindings: FxHashMap<Symbol, NameBinding<'ra>>, builtin_attrs_bindings: FxHashMap<Symbol, NameBinding<'ra>>, registered_tool_bindings: FxHashMap<Ident, NameBinding<'ra>>, - used_extern_options: FxHashSet<Symbol>, macro_names: FxHashSet<Ident>, builtin_macros: FxHashMap<Symbol, SyntaxExtensionKind>, registered_tools: &'tcx RegisteredTools, @@ -1510,6 +1500,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { extern_crate_map: Default::default(), module_children: Default::default(), trait_map: NodeMap::default(), + underscore_disambiguator: 0, empty_module, local_module_map, extern_module_map: Default::default(), @@ -1554,7 +1545,6 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { (*ident, binding) }) .collect(), - used_extern_options: Default::default(), macro_names: FxHashSet::default(), builtin_macros: Default::default(), registered_tools, @@ -1741,18 +1731,14 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { StableHashingContext::new(self.tcx.sess, self.tcx.untracked()) } - fn crate_loader<T>(&mut self, f: impl FnOnce(&mut CrateLoader<'_, '_>) -> T) -> T { - f(&mut CrateLoader::new( - self.tcx, - &mut CStore::from_tcx_mut(self.tcx), - &mut self.used_extern_options, - )) - } - fn cstore(&self) -> FreezeReadGuard<'_, CStore> { CStore::from_tcx(self.tcx) } + fn cstore_mut(&self) -> FreezeWriteGuard<'_, CStore> { + CStore::from_tcx_mut(self.tcx) + } + fn dummy_ext(&self, macro_kind: MacroKind) -> Arc<SyntaxExtension> { match macro_kind { MacroKind::Bang => Arc::clone(&self.dummy_ext_bang), @@ -1798,7 +1784,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { self.tcx.sess.time("resolve_report_errors", || self.report_errors(krate)); self.tcx .sess - .time("resolve_postprocess", || self.crate_loader(|c| c.postprocess(krate))); + .time("resolve_postprocess", || self.cstore_mut().postprocess(self.tcx, krate)); }); // Make sure we don't mutate the cstore from here on. @@ -1895,6 +1881,17 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { import_ids } + fn new_disambiguated_key(&mut self, ident: Ident, ns: Namespace) -> BindingKey { + let ident = ident.normalize_to_macros_2_0(); + let disambiguator = if ident.name == kw::Underscore { + self.underscore_disambiguator += 1; + self.underscore_disambiguator + } else { + 0 + }; + BindingKey { ident, ns, disambiguator } + } + fn resolutions(&mut self, module: Module<'ra>) -> &'ra Resolutions<'ra> { if module.populate_on_access.get() { module.populate_on_access.set(false); @@ -2153,7 +2150,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { Some(if let Some(binding) = entry.binding { if finalize { if !entry.is_import() { - self.crate_loader(|c| c.process_path_extern(ident.name, ident.span)); + self.cstore_mut().process_path_extern(self.tcx, ident.name, ident.span); } else if entry.introduced_by_item { self.record_use(ident, binding, Used::Other); } @@ -2162,13 +2159,13 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { } else { let crate_id = if finalize { let Some(crate_id) = - self.crate_loader(|c| c.process_path_extern(ident.name, ident.span)) + self.cstore_mut().process_path_extern(self.tcx, ident.name, ident.span) else { return Some(self.dummy_binding); }; crate_id } else { - self.crate_loader(|c| c.maybe_process_path_extern(ident.name))? + self.cstore_mut().maybe_process_path_extern(self.tcx, ident.name)? }; let res = Res::Def(DefKind::Mod, crate_id.as_def_id()); self.arenas.new_pub_res_binding(res, DUMMY_SP, LocalExpnId::ROOT) diff --git a/compiler/rustc_resolve/src/macros.rs b/compiler/rustc_resolve/src/macros.rs index 0e8904a7dea..77ef7f56c09 100644 --- a/compiler/rustc_resolve/src/macros.rs +++ b/compiler/rustc_resolve/src/macros.rs @@ -530,7 +530,7 @@ impl<'ra, 'tcx> ResolverExpand for Resolver<'ra, 'tcx> { target_trait.for_each_child(self, |this, ident, ns, _binding| { // FIXME: Adjust hygiene for idents from globs, like for glob imports. if let Some(overriding_keys) = this.impl_binding_keys.get(&impl_def_id) - && overriding_keys.contains(&BindingKey::new(ident, ns)) + && overriding_keys.contains(&BindingKey::new(ident.normalize_to_macros_2_0(), ns)) { // The name is overridden, do not produce it from the glob delegation. } else { diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index d6215e1de04..7bea8685724 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -226,6 +226,13 @@ pub enum CoverageLevel { Mcdc, } +// The different settings that the `-Z offload` flag can have. +#[derive(Clone, Copy, PartialEq, Hash, Debug)] +pub enum Offload { + /// Enable the llvm offload pipeline + Enable, +} + /// The different settings that the `-Z autodiff` flag can have. #[derive(Clone, PartialEq, Hash, Debug)] pub enum AutoDiff { @@ -2706,6 +2713,15 @@ pub fn build_session_options(early_dcx: &mut EarlyDiagCtxt, matches: &getopts::M ) } + if !nightly_options::is_unstable_enabled(matches) + && unstable_opts.offload.contains(&Offload::Enable) + { + early_dcx.early_fatal( + "`-Zoffload=Enable` also requires `-Zunstable-options` \ + and a nightly compiler", + ) + } + let target_triple = parse_target_triple(early_dcx, matches); // Ensure `-Z unstable-options` is required when using the unstable `-C link-self-contained` and @@ -3178,7 +3194,7 @@ pub(crate) mod dep_tracking { AutoDiff, BranchProtection, CFGuard, CFProtection, CollapseMacroDebuginfo, CoverageOptions, CrateType, DebugInfo, DebugInfoCompression, ErrorOutputType, FmtDebug, FunctionReturn, InliningThreshold, InstrumentCoverage, InstrumentXRay, LinkerPluginLto, LocationDetail, - LtoCli, MirStripDebugInfo, NextSolverConfig, OomStrategy, OptLevel, OutFileName, + LtoCli, MirStripDebugInfo, NextSolverConfig, Offload, OomStrategy, OptLevel, OutFileName, OutputType, OutputTypes, PatchableFunctionEntry, Polonius, RemapPathScopeComponents, ResolveDocLinks, SourceFileHashAlgorithm, SplitDwarfKind, SwitchWithOptPath, SymbolManglingVersion, WasiExecModel, @@ -3225,6 +3241,7 @@ pub(crate) mod dep_tracking { impl_dep_tracking_hash_via_hash!( (), AutoDiff, + Offload, bool, usize, NonZero<usize>, diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index 2bdde2f887a..b33e3815ea4 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -726,6 +726,7 @@ mod desc { pub(crate) const parse_list_with_polarity: &str = "a comma-separated list of strings, with elements beginning with + or -"; pub(crate) const parse_autodiff: &str = "a comma separated list of settings: `Enable`, `PrintSteps`, `PrintTA`, `PrintTAFn`, `PrintAA`, `PrintPerf`, `PrintModBefore`, `PrintModAfter`, `PrintModFinal`, `PrintPasses`, `NoPostopt`, `LooseTypes`, `Inline`"; + pub(crate) const parse_offload: &str = "a comma separated list of settings: `Enable`"; pub(crate) const parse_comma_list: &str = "a comma-separated list of strings"; pub(crate) const parse_opt_comma_list: &str = parse_comma_list; pub(crate) const parse_number: &str = "a number"; @@ -1357,6 +1358,27 @@ pub mod parse { } } + pub(crate) fn parse_offload(slot: &mut Vec<Offload>, v: Option<&str>) -> bool { + let Some(v) = v else { + *slot = vec![]; + return true; + }; + let mut v: Vec<&str> = v.split(",").collect(); + v.sort_unstable(); + for &val in v.iter() { + let variant = match val { + "Enable" => Offload::Enable, + _ => { + // FIXME(ZuseZ4): print an error saying which value is not recognized + return false; + } + }; + slot.push(variant); + } + + true + } + pub(crate) fn parse_autodiff(slot: &mut Vec<AutoDiff>, v: Option<&str>) -> bool { let Some(v) = v else { *slot = vec![]; @@ -2401,6 +2423,11 @@ options! { "do not use unique names for text and data sections when -Z function-sections is used"), normalize_docs: bool = (false, parse_bool, [TRACKED], "normalize associated items in rustdoc when generating documentation"), + offload: Vec<crate::config::Offload> = (Vec::new(), parse_offload, [TRACKED], + "a list of offload flags to enable + Mandatory setting: + `=Enable` + Currently the only option available"), on_broken_pipe: OnBrokenPipe = (OnBrokenPipe::Default, parse_on_broken_pipe, [TRACKED], "behavior of std::io::ErrorKind::BrokenPipe (SIGPIPE)"), oom: OomStrategy = (OomStrategy::Abort, parse_oom_strategy, [TRACKED], diff --git a/compiler/rustc_target/src/spec/targets/amdgcn_amd_amdhsa.rs b/compiler/rustc_target/src/spec/targets/amdgcn_amd_amdhsa.rs index f20782cabb8..0d6c6194e26 100644 --- a/compiler/rustc_target/src/spec/targets/amdgcn_amd_amdhsa.rs +++ b/compiler/rustc_target/src/spec/targets/amdgcn_amd_amdhsa.rs @@ -3,7 +3,7 @@ use crate::spec::{Cc, LinkerFlavor, Lld, PanicStrategy, Target, TargetMetadata, pub(crate) fn target() -> Target { Target { arch: "amdgpu".into(), - data_layout: "e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32-p7:160:256:256:32-p8:128:128-p9:192:256:256:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-G1-ni:7:8:9".into(), + data_layout: "e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32-p7:160:256:256:32-p8:128:128:128:48-p9:192:256:256:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-G1-ni:7:8:9".into(), llvm_target: "amdgcn-amd-amdhsa".into(), metadata: TargetMetadata { description: Some("AMD GPU".into()), diff --git a/compiler/rustc_trait_selection/src/solve/delegate.rs b/compiler/rustc_trait_selection/src/solve/delegate.rs index 17429e15cce..7426504e139 100644 --- a/compiler/rustc_trait_selection/src/solve/delegate.rs +++ b/compiler/rustc_trait_selection/src/solve/delegate.rs @@ -12,11 +12,11 @@ use rustc_infer::traits::solve::Goal; use rustc_middle::traits::query::NoSolution; use rustc_middle::traits::solve::Certainty; use rustc_middle::ty::{ - self, SizedTraitKind, Ty, TyCtxt, TypeFlags, TypeFoldable, TypeVisitableExt as _, TypingMode, + self, Ty, TyCtxt, TypeFlags, TypeFoldable, TypeVisitableExt as _, TypingMode, }; use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span}; -use crate::traits::{EvaluateConstErr, ObligationCause, specialization_graph}; +use crate::traits::{EvaluateConstErr, ObligationCause, sizedness_fast_path, specialization_graph}; #[repr(transparent)] pub struct SolverDelegate<'tcx>(InferCtxt<'tcx>); @@ -76,19 +76,11 @@ impl<'tcx> rustc_next_trait_solver::delegate::SolverDelegate for SolverDelegate< if trait_pred.polarity() == ty::PredicatePolarity::Positive { match self.0.tcx.as_lang_item(trait_pred.def_id()) { - Some(LangItem::Sized) - if self - .resolve_vars_if_possible(trait_pred.self_ty().skip_binder()) - .has_trivial_sizedness(self.0.tcx, SizedTraitKind::Sized) => - { - return Some(Certainty::Yes); - } - Some(LangItem::MetaSized) - if self - .resolve_vars_if_possible(trait_pred.self_ty().skip_binder()) - .has_trivial_sizedness(self.0.tcx, SizedTraitKind::MetaSized) => - { - return Some(Certainty::Yes); + Some(LangItem::Sized) | Some(LangItem::MetaSized) => { + let predicate = self.resolve_vars_if_possible(goal.predicate); + if sizedness_fast_path(self.tcx, predicate, goal.param_env) { + return Some(Certainty::Yes); + } } Some(LangItem::Copy | LangItem::Clone) => { let self_ty = diff --git a/compiler/rustc_trait_selection/src/traits/fulfill.rs b/compiler/rustc_trait_selection/src/traits/fulfill.rs index e35f89358e9..6b884b36080 100644 --- a/compiler/rustc_trait_selection/src/traits/fulfill.rs +++ b/compiler/rustc_trait_selection/src/traits/fulfill.rs @@ -363,7 +363,7 @@ impl<'a, 'tcx> ObligationProcessor for FulfillProcessor<'a, 'tcx> { let infcx = self.selcx.infcx; - if sizedness_fast_path(infcx.tcx, obligation.predicate) { + if sizedness_fast_path(infcx.tcx, obligation.predicate, obligation.param_env) { return ProcessResult::Changed(thin_vec![]); } diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/prove_predicate.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/prove_predicate.rs index 22eeb285b37..f24214145ba 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/prove_predicate.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/prove_predicate.rs @@ -15,7 +15,7 @@ impl<'tcx> super::QueryTypeOp<'tcx> for ProvePredicate<'tcx> { tcx: TyCtxt<'tcx>, key: &ParamEnvAnd<'tcx, Self>, ) -> Option<Self::QueryResponse> { - if sizedness_fast_path(tcx, key.value.predicate) { + if sizedness_fast_path(tcx, key.value.predicate, key.param_env) { return Some(()); } diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index 2b563c5b8d5..f90316f520b 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -597,7 +597,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { None => self.check_recursion_limit(&obligation, &obligation)?, } - if sizedness_fast_path(self.tcx(), obligation.predicate) { + if sizedness_fast_path(self.tcx(), obligation.predicate, obligation.param_env) { return Ok(EvaluatedToOk); } diff --git a/compiler/rustc_trait_selection/src/traits/util.rs b/compiler/rustc_trait_selection/src/traits/util.rs index 0c14b124e25..c3d60ec45c4 100644 --- a/compiler/rustc_trait_selection/src/traits/util.rs +++ b/compiler/rustc_trait_selection/src/traits/util.rs @@ -365,7 +365,11 @@ impl<'tcx> TypeFolder<TyCtxt<'tcx>> for PlaceholderReplacer<'_, 'tcx> { } } -pub fn sizedness_fast_path<'tcx>(tcx: TyCtxt<'tcx>, predicate: ty::Predicate<'tcx>) -> bool { +pub fn sizedness_fast_path<'tcx>( + tcx: TyCtxt<'tcx>, + predicate: ty::Predicate<'tcx>, + param_env: ty::ParamEnv<'tcx>, +) -> bool { // Proving `Sized`/`MetaSized`, very often on "obviously sized" types like // `&T`, accounts for about 60% percentage of the predicates we have to prove. No need to // canonicalize and all that for such cases. @@ -390,6 +394,20 @@ pub fn sizedness_fast_path<'tcx>(tcx: TyCtxt<'tcx>, predicate: ty::Predicate<'tc debug!("fast path -- trivial sizedness"); return true; } + + if matches!(trait_pred.self_ty().kind(), ty::Param(_) | ty::Placeholder(_)) { + for clause in param_env.caller_bounds() { + if let ty::ClauseKind::Trait(clause_pred) = clause.kind().skip_binder() + && clause_pred.polarity == ty::PredicatePolarity::Positive + && clause_pred.self_ty() == trait_pred.self_ty() + && (clause_pred.def_id() == trait_pred.def_id() + || (sizedness == SizedTraitKind::MetaSized + && tcx.is_lang_item(clause_pred.def_id(), LangItem::Sized))) + { + return true; + } + } + } } false diff --git a/compiler/rustc_traits/src/evaluate_obligation.rs b/compiler/rustc_traits/src/evaluate_obligation.rs index 7771db855d7..819b8e3231c 100644 --- a/compiler/rustc_traits/src/evaluate_obligation.rs +++ b/compiler/rustc_traits/src/evaluate_obligation.rs @@ -24,7 +24,7 @@ fn evaluate_obligation<'tcx>( debug!("evaluate_obligation: goal={:#?}", goal); let ParamEnvAnd { param_env, value: predicate } = goal; - if sizedness_fast_path(tcx, predicate) { + if sizedness_fast_path(tcx, predicate, param_env) { return Ok(EvaluationResult::EvaluatedToOk); } diff --git a/library/compiler-builtins/.github/workflows/rustc-pull.yml b/library/compiler-builtins/.github/workflows/rustc-pull.yml new file mode 100644 index 00000000000..ba698492e42 --- /dev/null +++ b/library/compiler-builtins/.github/workflows/rustc-pull.yml @@ -0,0 +1,23 @@ +# Perform a subtree sync (pull) using the josh-sync tool once every few days (or on demand). +name: rustc-pull + +on: + workflow_dispatch: + schedule: + # Run at 04:00 UTC every Monday and Thursday + - cron: '0 4 * * 1,4' + +jobs: + pull: + if: github.repository == 'rust-lang/compiler-builtins' + uses: rust-lang/josh-sync/.github/workflows/rustc-pull.yml@main + with: + # https://rust-lang.zulipchat.com/#narrow/channel/219381-t-libs/topic/compiler-builtins.20subtree.20sync.20automation/with/528482375 + zulip-stream-id: 219381 + zulip-topic: 'compiler-builtins subtree sync automation' + zulip-bot-email: "compiler-builtins-ci-bot@rust-lang.zulipchat.com" + pr-base-branch: master + branch-name: rustc-pull + secrets: + zulip-api-token: ${{ secrets.ZULIP_API_TOKEN }} + token: ${{ secrets.GITHUB_TOKEN }} diff --git a/library/compiler-builtins/CONTRIBUTING.md b/library/compiler-builtins/CONTRIBUTING.md index 9f67cfc3157..9ae4f893c60 100644 --- a/library/compiler-builtins/CONTRIBUTING.md +++ b/library/compiler-builtins/CONTRIBUTING.md @@ -165,3 +165,12 @@ cargo bench --no-default-features \ [`iai-callgrind-runner`]: https://crates.io/crates/iai-callgrind-runner [Valgrind]: https://valgrind.org/ + +## Subtree synchronization + +`compiler-builtins` is included as a [Josh subtree] in the main compiler +repository (`rust-lang/rust`). You can find a guide on how to create synchronization +(pull and push) PRs at the [`rustc-dev-guide` page]. + +[Josh subtree]: https://rustc-dev-guide.rust-lang.org/external-repos.html#josh-subtrees +[`rustc-dev-guide` page]: https://rustc-dev-guide.rust-lang.org/external-repos.html#synchronizing-a-josh-subtree diff --git a/library/compiler-builtins/Cargo.toml b/library/compiler-builtins/Cargo.toml index 41350c6cb99..956d738f3b1 100644 --- a/library/compiler-builtins/Cargo.toml +++ b/library/compiler-builtins/Cargo.toml @@ -3,7 +3,6 @@ resolver = "2" members = [ "builtins-shim", "builtins-test", - "crates/josh-sync", "crates/libm-macros", "crates/musl-math-sys", "crates/panic-handler", diff --git a/library/compiler-builtins/builtins-test/Cargo.toml b/library/compiler-builtins/builtins-test/Cargo.toml index 093d4633f87..00a9d8579d1 100644 --- a/library/compiler-builtins/builtins-test/Cargo.toml +++ b/library/compiler-builtins/builtins-test/Cargo.toml @@ -12,9 +12,9 @@ license = "MIT AND Apache-2.0 WITH LLVM-exception AND (MIT OR Apache-2.0)" # `xoshiro128**` is used for its quality, size, and speed at generating `u32` shift amounts. rand_xoshiro = "0.7" # To compare float builtins against -rustc_apfloat = "0.2.2" +rustc_apfloat = "0.2.3" # Really a dev dependency, but dev dependencies can't be optional -iai-callgrind = { version = "0.14.1", optional = true } +iai-callgrind = { version = "0.15.2", optional = true } [dependencies.compiler_builtins] path = "../builtins-shim" diff --git a/library/compiler-builtins/ci/bench-icount.sh b/library/compiler-builtins/ci/bench-icount.sh index d2baebb52d8..12228b9da97 100755 --- a/library/compiler-builtins/ci/bench-icount.sh +++ b/library/compiler-builtins/ci/bench-icount.sh @@ -28,7 +28,7 @@ function run_icount_benchmarks() { iai_args=( "--home" "$(pwd)/$iai_home" - "--regression=ir=5.0" + "--callgrind-limits=ir=5.0" "--save-summary" ) diff --git a/library/compiler-builtins/compiler-builtins/src/mem/impls.rs b/library/compiler-builtins/compiler-builtins/src/mem/impls.rs index 14a4787485d..da16dee25ce 100644 --- a/library/compiler-builtins/compiler-builtins/src/mem/impls.rs +++ b/library/compiler-builtins/compiler-builtins/src/mem/impls.rs @@ -15,6 +15,7 @@ // this use. Of course this is not a guarantee that such use will work, it just means that this // crate doing wrapping pointer arithmetic with a method that must not wrap won't be the problem if // something does go wrong at runtime. +use core::ffi::c_int; use core::intrinsics::likely; const WORD_SIZE: usize = core::mem::size_of::<usize>(); @@ -384,13 +385,13 @@ pub unsafe fn set_bytes(mut s: *mut u8, c: u8, mut n: usize) { } #[inline(always)] -pub unsafe fn compare_bytes(s1: *const u8, s2: *const u8, n: usize) -> i32 { +pub unsafe fn compare_bytes(s1: *const u8, s2: *const u8, n: usize) -> c_int { let mut i = 0; while i < n { let a = *s1.wrapping_add(i); let b = *s2.wrapping_add(i); if a != b { - return a as i32 - b as i32; + return c_int::from(a) - c_int::from(b); } i += 1; } diff --git a/library/compiler-builtins/compiler-builtins/src/mem/mod.rs b/library/compiler-builtins/compiler-builtins/src/mem/mod.rs index 6828f3804e0..a227f60a294 100644 --- a/library/compiler-builtins/compiler-builtins/src/mem/mod.rs +++ b/library/compiler-builtins/compiler-builtins/src/mem/mod.rs @@ -3,13 +3,6 @@ // FIXME(e2024): this eventually needs to be removed. #![allow(unsafe_op_in_unsafe_fn)] -#[allow(warnings)] -#[cfg(target_pointer_width = "16")] -type c_int = i16; -#[allow(warnings)] -#[cfg(not(target_pointer_width = "16"))] -type c_int = i32; - // memcpy/memmove/memset have optimized implementations on some architectures #[cfg_attr( all(not(feature = "no-asm"), target_arch = "x86_64"), @@ -38,18 +31,18 @@ intrinsics! { } #[mem_builtin] - pub unsafe extern "C" fn memset(s: *mut u8, c: crate::mem::c_int, n: usize) -> *mut u8 { + pub unsafe extern "C" fn memset(s: *mut u8, c: core::ffi::c_int, n: usize) -> *mut u8 { impls::set_bytes(s, c as u8, n); s } #[mem_builtin] - pub unsafe extern "C" fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32 { + pub unsafe extern "C" fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> core::ffi::c_int { impls::compare_bytes(s1, s2, n) } #[mem_builtin] - pub unsafe extern "C" fn bcmp(s1: *const u8, s2: *const u8, n: usize) -> i32 { + pub unsafe extern "C" fn bcmp(s1: *const u8, s2: *const u8, n: usize) -> core::ffi::c_int { memcmp(s1, s2, n) } diff --git a/library/compiler-builtins/crates/josh-sync/Cargo.toml b/library/compiler-builtins/crates/josh-sync/Cargo.toml deleted file mode 100644 index 8e2e891db54..00000000000 --- a/library/compiler-builtins/crates/josh-sync/Cargo.toml +++ /dev/null @@ -1,8 +0,0 @@ -[package] -name = "josh-sync" -edition = "2024" -publish = false - -[dependencies] -directories = "6.0.0" -regex-lite = "0.1.6" diff --git a/library/compiler-builtins/crates/josh-sync/src/main.rs b/library/compiler-builtins/crates/josh-sync/src/main.rs deleted file mode 100644 index 7f0b1190033..00000000000 --- a/library/compiler-builtins/crates/josh-sync/src/main.rs +++ /dev/null @@ -1,45 +0,0 @@ -use std::io::{Read, Write}; -use std::process::exit; -use std::{env, io}; - -use crate::sync::{GitSync, Josh}; - -mod sync; - -const USAGE: &str = r#"Utility for synchroniing compiler-builtins with rust-lang/rust - -Usage: - - josh-sync rustc-pull - - Pull from rust-lang/rust to compiler-builtins. Creates a commit - updating the version file, followed by a merge commit. - - josh-sync rustc-push GITHUB_USERNAME [BRANCH] - - Create a branch off of rust-lang/rust updating compiler-builtins. -"#; - -fn main() { - let sync = GitSync::from_current_dir(); - - // Collect args, then recollect as str refs so we can match on them - let args: Vec<_> = env::args().collect(); - let args: Vec<&str> = args.iter().map(String::as_str).collect(); - - match args.as_slice()[1..] { - ["rustc-pull"] => sync.rustc_pull(None), - ["rustc-push", github_user, branch] => sync.rustc_push(github_user, Some(branch)), - ["rustc-push", github_user] => sync.rustc_push(github_user, None), - ["start-josh"] => { - let _josh = Josh::start(); - println!("press enter to stop"); - io::stdout().flush().unwrap(); - let _ = io::stdin().read(&mut [0u8]).unwrap(); - } - _ => { - println!("{USAGE}"); - exit(1); - } - } -} diff --git a/library/compiler-builtins/crates/josh-sync/src/sync.rs b/library/compiler-builtins/crates/josh-sync/src/sync.rs deleted file mode 100644 index 2d89d2d1cea..00000000000 --- a/library/compiler-builtins/crates/josh-sync/src/sync.rs +++ /dev/null @@ -1,401 +0,0 @@ -use std::borrow::Cow; -use std::net::{SocketAddr, TcpStream}; -use std::process::{Command, Stdio, exit}; -use std::time::Duration; -use std::{env, fs, process, thread}; - -use regex_lite::Regex; - -const JOSH_PORT: u16 = 42042; -const DEFAULT_PR_BRANCH: &str = "update-builtins"; - -pub struct GitSync { - upstream_repo: String, - upstream_ref: String, - upstream_url: String, - josh_filter: String, - josh_url_base: String, -} - -/// This code was adapted from the miri repository, via the rustc-dev-guide -/// (<https://github.com/rust-lang/rustc-dev-guide/tree/c51adbd12d/josh-sync>) -impl GitSync { - pub fn from_current_dir() -> Self { - let upstream_repo = - env::var("UPSTREAM_ORG").unwrap_or_else(|_| "rust-lang".to_owned()) + "/rust"; - - Self { - upstream_url: format!("https://github.com/{upstream_repo}"), - upstream_repo, - upstream_ref: env::var("UPSTREAM_REF").unwrap_or_else(|_| "HEAD".to_owned()), - josh_filter: ":/library/compiler-builtins".to_owned(), - josh_url_base: format!("http://localhost:{JOSH_PORT}"), - } - } - - /// Pull from rust-lang/rust to compiler-builtins. - pub fn rustc_pull(&self, commit: Option<String>) { - let Self { - upstream_ref, - upstream_url, - upstream_repo, - .. - } = self; - - let new_upstream_base = commit.unwrap_or_else(|| { - let out = check_output(["git", "ls-remote", upstream_url, upstream_ref]); - out.split_whitespace() - .next() - .unwrap_or_else(|| panic!("could not split output: '{out}'")) - .to_owned() - }); - - ensure_clean(); - - // Make sure josh is running. - let _josh = Josh::start(); - let josh_url_filtered = self.josh_url( - &self.upstream_repo, - Some(&new_upstream_base), - Some(&self.josh_filter), - ); - - let previous_upstream_base = fs::read_to_string("rust-version") - .expect("failed to read `rust-version`") - .trim() - .to_string(); - assert_ne!(previous_upstream_base, new_upstream_base, "nothing to pull"); - - let orig_head = check_output(["git", "rev-parse", "HEAD"]); - println!("original upstream base: {previous_upstream_base}"); - println!("new upstream base: {new_upstream_base}"); - println!("original HEAD: {orig_head}"); - - // Fetch the latest upstream HEAD so we can get a summary. Use the Josh URL for caching. - run([ - "git", - "fetch", - &self.josh_url(&self.upstream_repo, Some(&new_upstream_base), Some(":/")), - &new_upstream_base, - "--depth=1", - ]); - let new_summary = check_output(["git", "log", "-1", "--format=%h %s", &new_upstream_base]); - let new_summary = replace_references(&new_summary, &self.upstream_repo); - - // Update rust-version file. As a separate commit, since making it part of - // the merge has confused the heck out of josh in the past. - // We pass `--no-verify` to avoid running git hooks. - // We do this before the merge so that if there are merge conflicts, we have - // the right rust-version file while resolving them. - fs::write("rust-version", format!("{new_upstream_base}\n")) - .expect("failed to write rust-version"); - - let prep_message = format!( - "Update the upstream Rust version\n\n\ - To prepare for merging from {upstream_repo}, set the version file to:\n\n \ - {new_summary}\n\ - ", - ); - run([ - "git", - "commit", - "rust-version", - "--no-verify", - "-m", - &prep_message, - ]); - - // Fetch given rustc commit. - run(["git", "fetch", &josh_url_filtered]); - let incoming_ref = check_output(["git", "rev-parse", "FETCH_HEAD"]); - println!("incoming ref: {incoming_ref}"); - - let merge_message = format!( - "Merge ref '{upstream_head_short}{filter}' from {upstream_url}\n\n\ - Pull recent changes from {upstream_repo} via Josh.\n\n\ - Upstream ref: {new_upstream_base}\n\ - Filtered ref: {incoming_ref}\n\ - ", - upstream_head_short = &new_upstream_base[..12], - filter = self.josh_filter - ); - - // This should not add any new root commits. So count those before and after merging. - let num_roots = || -> u32 { - let out = check_output(["git", "rev-list", "HEAD", "--max-parents=0", "--count"]); - out.trim() - .parse::<u32>() - .unwrap_or_else(|e| panic!("failed to parse `{out}`: {e}")) - }; - let num_roots_before = num_roots(); - - let pre_merge_sha = check_output(["git", "rev-parse", "HEAD"]); - println!("pre-merge HEAD: {pre_merge_sha}"); - - // Merge the fetched commit. - run([ - "git", - "merge", - "FETCH_HEAD", - "--no-verify", - "--no-ff", - "-m", - &merge_message, - ]); - - let current_sha = check_output(["git", "rev-parse", "HEAD"]); - if current_sha == pre_merge_sha { - run(["git", "reset", "--hard", &orig_head]); - eprintln!( - "No merge was performed, no changes to pull were found. \ - Rolled back the preparation commit." - ); - exit(1); - } - - // Check that the number of roots did not increase. - assert_eq!( - num_roots(), - num_roots_before, - "Josh created a new root commit. This is probably not the history you want." - ); - } - - /// Construct an update to rust-lang/rust from compiler-builtins. - pub fn rustc_push(&self, github_user: &str, branch: Option<&str>) { - let Self { - josh_filter, - upstream_url, - .. - } = self; - - let branch = branch.unwrap_or(DEFAULT_PR_BRANCH); - let josh_url = self.josh_url(&format!("{github_user}/rust"), None, Some(josh_filter)); - let user_upstream_url = format!("git@github.com:{github_user}/rust.git"); - - let Ok(rustc_git) = env::var("RUSTC_GIT") else { - panic!("the RUSTC_GIT environment variable must be set to a rust-lang/rust checkout") - }; - - ensure_clean(); - let base = fs::read_to_string("rust-version") - .expect("failed to read `rust-version`") - .trim() - .to_string(); - - // Make sure josh is running. - let _josh = Josh::start(); - - // Prepare the branch. Pushing works much better if we use as base exactly - // the commit that we pulled from last time, so we use the `rust-version` - // file to find out which commit that would be. - println!("Preparing {github_user}/rust (base: {base})..."); - - if Command::new("git") - .args(["-C", &rustc_git, "fetch", &user_upstream_url, branch]) - .output() // capture output - .expect("could not run fetch") - .status - .success() - { - panic!( - "The branch '{branch}' seems to already exist in '{user_upstream_url}'. \ - Please delete it and try again." - ); - } - - run(["git", "-C", &rustc_git, "fetch", upstream_url, &base]); - - run_cfg("git", |c| { - c.args([ - "-C", - &rustc_git, - "push", - &user_upstream_url, - &format!("{base}:refs/heads/{branch}"), - ]) - .stdout(Stdio::null()) - .stderr(Stdio::null()) // silence the "create GitHub PR" message - }); - println!("pushed PR branch"); - - // Do the actual push. - println!("Pushing changes..."); - run(["git", "push", &josh_url, &format!("HEAD:{branch}")]); - println!(); - - // Do a round-trip check to make sure the push worked as expected. - run(["git", "fetch", &josh_url, branch]); - - let head = check_output(["git", "rev-parse", "HEAD"]); - let fetch_head = check_output(["git", "rev-parse", "FETCH_HEAD"]); - assert_eq!( - head, fetch_head, - "Josh created a non-roundtrip push! Do NOT merge this into rustc!\n\ - Expected {head}, got {fetch_head}." - ); - println!( - "Confirmed that the push round-trips back to compiler-builtins properly. Please \ - create a rustc PR:" - ); - // Open PR with `subtree update` title to silence the `no-merges` triagebot check - println!( - " {upstream_url}/compare/{github_user}:{branch}?quick_pull=1\ - &title=Update%20the%20%60compiler-builtins%60%20subtree\ - &body=Update%20the%20Josh%20subtree%20to%20https%3A%2F%2Fgithub.com%2Frust-lang%2F\ - compiler-builtins%2Fcommit%2F{head_short}.%0A%0Ar%3F%20%40ghost", - head_short = &head[..12], - ); - } - - /// Construct a url to the local Josh server with (optionally) - fn josh_url(&self, repo: &str, rev: Option<&str>, filter: Option<&str>) -> String { - format!( - "{base}/{repo}.git{at}{rev}{filter}{filt_git}", - base = self.josh_url_base, - at = if rev.is_some() { "@" } else { "" }, - rev = rev.unwrap_or_default(), - filter = filter.unwrap_or_default(), - filt_git = if filter.is_some() { ".git" } else { "" } - ) - } -} - -/// Fail if there are files that need to be checked in. -fn ensure_clean() { - let read = check_output(["git", "status", "--untracked-files=no", "--porcelain"]); - assert!( - read.is_empty(), - "working directory must be clean before performing rustc pull" - ); -} - -/* Helpers for running commands with logged invocations */ - -/// Run a command from an array, passing its output through. -fn run<'a, Args: AsRef<[&'a str]>>(l: Args) { - let l = l.as_ref(); - run_cfg(l[0], |c| c.args(&l[1..])); -} - -/// Run a command from an array, collecting its output. -fn check_output<'a, Args: AsRef<[&'a str]>>(l: Args) -> String { - let l = l.as_ref(); - check_output_cfg(l[0], |c| c.args(&l[1..])) -} - -/// [`run`] with configuration. -fn run_cfg(prog: &str, f: impl FnOnce(&mut Command) -> &mut Command) { - // self.read(l.as_ref()); - check_output_cfg(prog, |c| f(c.stdout(Stdio::inherit()))); -} - -/// [`read`] with configuration. All shell helpers print the command and pass stderr. -fn check_output_cfg(prog: &str, f: impl FnOnce(&mut Command) -> &mut Command) -> String { - let mut cmd = Command::new(prog); - cmd.stderr(Stdio::inherit()); - f(&mut cmd); - eprintln!("+ {cmd:?}"); - let out = cmd.output().expect("command failed"); - assert!(out.status.success()); - String::from_utf8(out.stdout.trim_ascii().to_vec()).expect("non-UTF8 output") -} - -/// Replace `#1234`-style issue/PR references with `repo#1234` to ensure links work across -/// repositories. -fn replace_references<'a>(s: &'a str, repo: &str) -> Cow<'a, str> { - let re = Regex::new(r"\B(?P<id>#\d+)\b").unwrap(); - re.replace(s, &format!("{repo}$id")) -} - -/// Create a wrapper that stops Josh on drop. -pub struct Josh(process::Child); - -impl Josh { - pub fn start() -> Self { - // Determine cache directory. - let user_dirs = - directories::ProjectDirs::from("org", "rust-lang", "rustc-compiler-builtins-josh") - .unwrap(); - let local_dir = user_dirs.cache_dir().to_owned(); - - // Start josh, silencing its output. - #[expect(clippy::zombie_processes, reason = "clippy can't handle the loop")] - let josh = process::Command::new("josh-proxy") - .arg("--local") - .arg(local_dir) - .args([ - "--remote=https://github.com", - &format!("--port={JOSH_PORT}"), - "--no-background", - ]) - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .spawn() - .expect("failed to start josh-proxy, make sure it is installed"); - - // Wait until the port is open. We try every 10ms until 1s passed. - for _ in 0..100 { - // This will generally fail immediately when the port is still closed. - let addr = SocketAddr::from(([127, 0, 0, 1], JOSH_PORT)); - let josh_ready = TcpStream::connect_timeout(&addr, Duration::from_millis(1)); - - if josh_ready.is_ok() { - println!("josh up and running"); - return Josh(josh); - } - - // Not ready yet. - thread::sleep(Duration::from_millis(10)); - } - panic!("Even after waiting for 1s, josh-proxy is still not available.") - } -} - -impl Drop for Josh { - fn drop(&mut self) { - if cfg!(unix) { - // Try to gracefully shut it down. - Command::new("kill") - .args(["-s", "INT", &self.0.id().to_string()]) - .output() - .expect("failed to SIGINT josh-proxy"); - // Sadly there is no "wait with timeout"... so we just give it some time to finish. - thread::sleep(Duration::from_millis(100)); - // Now hopefully it is gone. - if self - .0 - .try_wait() - .expect("failed to wait for josh-proxy") - .is_some() - { - return; - } - } - // If that didn't work (or we're not on Unix), kill it hard. - eprintln!( - "I have to kill josh-proxy the hard way, let's hope this does not \ - break anything." - ); - self.0.kill().expect("failed to SIGKILL josh-proxy"); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_replace() { - assert_eq!(replace_references("#1234", "r-l/rust"), "r-l/rust#1234"); - assert_eq!(replace_references("#1234x", "r-l/rust"), "#1234x"); - assert_eq!( - replace_references("merge #1234", "r-l/rust"), - "merge r-l/rust#1234" - ); - assert_eq!( - replace_references("foo/bar#1234", "r-l/rust"), - "foo/bar#1234" - ); - } -} diff --git a/library/compiler-builtins/crates/libm-macros/Cargo.toml b/library/compiler-builtins/crates/libm-macros/Cargo.toml index 6bbf47784ff..100a8d0ec30 100644 --- a/library/compiler-builtins/crates/libm-macros/Cargo.toml +++ b/library/compiler-builtins/crates/libm-macros/Cargo.toml @@ -12,7 +12,7 @@ proc-macro = true heck = "0.5.0" proc-macro2 = "1.0.95" quote = "1.0.40" -syn = { version = "2.0.101", features = ["full", "extra-traits", "visit-mut"] } +syn = { version = "2.0.104", features = ["full", "extra-traits", "visit-mut"] } [lints.rust] # Values used during testing diff --git a/library/compiler-builtins/crates/musl-math-sys/Cargo.toml b/library/compiler-builtins/crates/musl-math-sys/Cargo.toml index 3b88117343b..39f6fa9065b 100644 --- a/library/compiler-builtins/crates/musl-math-sys/Cargo.toml +++ b/library/compiler-builtins/crates/musl-math-sys/Cargo.toml @@ -11,4 +11,4 @@ license = "MIT OR Apache-2.0" libm = { path = "../../libm" } [build-dependencies] -cc = "1.2.25" +cc = "1.2.29" diff --git a/library/compiler-builtins/josh-sync.toml b/library/compiler-builtins/josh-sync.toml new file mode 100644 index 00000000000..599a12af8e5 --- /dev/null +++ b/library/compiler-builtins/josh-sync.toml @@ -0,0 +1,3 @@ +org = "rust-lang" +repo = "compiler-builtins" +path = "library/compiler-builtins" diff --git a/library/compiler-builtins/libm-test/Cargo.toml b/library/compiler-builtins/libm-test/Cargo.toml index 05fcc3234e0..0af6b0c1da5 100644 --- a/library/compiler-builtins/libm-test/Cargo.toml +++ b/library/compiler-builtins/libm-test/Cargo.toml @@ -31,8 +31,8 @@ short-benchmarks = [] anyhow = "1.0.98" # This is not directly used but is required so we can enable `gmp-mpfr-sys/force-cross`. gmp-mpfr-sys = { version = "1.6.5", optional = true, default-features = false } -iai-callgrind = { version = "0.14.1", optional = true } -indicatif = { version = "0.17.11", default-features = false } +iai-callgrind = { version = "0.15.2", optional = true } +indicatif = { version = "0.18.0", default-features = false } libm = { path = "../libm", features = ["unstable-public-internals"] } libm-macros = { path = "../crates/libm-macros" } musl-math-sys = { path = "../crates/musl-math-sys", optional = true } diff --git a/library/compiler-builtins/libm/src/math/support/float_traits.rs b/library/compiler-builtins/libm/src/math/support/float_traits.rs index c3e7eeec245..fb790e69615 100644 --- a/library/compiler-builtins/libm/src/math/support/float_traits.rs +++ b/library/compiler-builtins/libm/src/math/support/float_traits.rs @@ -363,6 +363,7 @@ pub const fn f32_from_bits(bits: u32) -> f32 { } /// `f32::to_bits` +#[allow(dead_code)] // workaround for false positive RUST-144060 #[allow(unnecessary_transmutes)] // lint appears in newer versions of Rust pub const fn f32_to_bits(x: f32) -> u32 { // SAFETY: POD cast with no preconditions @@ -377,6 +378,7 @@ pub const fn f64_from_bits(bits: u64) -> f64 { } /// `f64::to_bits` +#[allow(dead_code)] // workaround for false positive RUST-144060 #[allow(unnecessary_transmutes)] // lint appears in newer versions of Rust pub const fn f64_to_bits(x: f64) -> u64 { // SAFETY: POD cast with no preconditions diff --git a/library/compiler-builtins/rust-version b/library/compiler-builtins/rust-version index 73183983599..a4db05a8796 100644 --- a/library/compiler-builtins/rust-version +++ b/library/compiler-builtins/rust-version @@ -1 +1 @@ -d087f112b7d1323446c7b39a8b616aee7fa56b3d +82310651b93a594a3fd69015e1562186a080d94c diff --git a/library/compiler-builtins/triagebot.toml b/library/compiler-builtins/triagebot.toml index ecc05da0195..8a2356c2b1c 100644 --- a/library/compiler-builtins/triagebot.toml +++ b/library/compiler-builtins/triagebot.toml @@ -4,7 +4,7 @@ # Warns when a PR contains merge commits # Documentation at: https://forge.rust-lang.org/triagebot/no-merge.html [no-merges] -exclude_titles = ["Update from"] +exclude_titles = ["Rustc pull update"] # Canonicalize issue numbers to avoid closing the wrong issue # when commits are included in subtrees, as well as warning links in commits. @@ -19,3 +19,6 @@ check-commits = false # Enable issue transfers within the org # Documentation at: https://forge.rust-lang.org/triagebot/transfer.html [transfer] + +# Automatically close and reopen PRs made by bots to run CI on them +[bot-pull-requests] diff --git a/library/core/src/any.rs b/library/core/src/any.rs index 39cdf6efda0..38393379a78 100644 --- a/library/core/src/any.rs +++ b/library/core/src/any.rs @@ -783,7 +783,7 @@ impl TypeId { // This is a provenance-stripping memcpy. for (i, chunk) in self.data.iter().copied().enumerate() { - let chunk = chunk.expose_provenance().to_ne_bytes(); + let chunk = chunk.addr().to_ne_bytes(); let start = i * chunk.len(); bytes[start..(start + chunk.len())].copy_from_slice(&chunk); } diff --git a/library/core/src/array/mod.rs b/library/core/src/array/mod.rs index 62203e132b7..1c23218552a 100644 --- a/library/core/src/array/mod.rs +++ b/library/core/src/array/mod.rs @@ -198,7 +198,8 @@ impl Error for TryFromSliceError { } #[stable(feature = "try_from_slice_error", since = "1.36.0")] -impl From<Infallible> for TryFromSliceError { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl const From<Infallible> for TryFromSliceError { fn from(x: Infallible) -> TryFromSliceError { match x {} } diff --git a/library/core/src/ascii/ascii_char.rs b/library/core/src/ascii/ascii_char.rs index 0b72b4780f1..054ddf84470 100644 --- a/library/core/src/ascii/ascii_char.rs +++ b/library/core/src/ascii/ascii_char.rs @@ -546,7 +546,8 @@ macro_rules! into_int_impl { ($($ty:ty)*) => { $( #[unstable(feature = "ascii_char", issue = "110998")] - impl From<AsciiChar> for $ty { + #[rustc_const_unstable(feature = "const_try", issue = "74935")] + impl const From<AsciiChar> for $ty { #[inline] fn from(chr: AsciiChar) -> $ty { chr as u8 as $ty diff --git a/library/core/src/async_iter/async_iter.rs b/library/core/src/async_iter/async_iter.rs index 069c50c2531..c21c08320be 100644 --- a/library/core/src/async_iter/async_iter.rs +++ b/library/core/src/async_iter/async_iter.rs @@ -28,15 +28,15 @@ pub trait AsyncIterator { /// async iterator state: /// /// - `Poll::Pending` means that this async iterator's next value is not ready - /// yet. Implementations will ensure that the current task will be notified - /// when the next value may be ready. + /// yet. Implementations will ensure that the current task will be notified + /// when the next value may be ready. /// /// - `Poll::Ready(Some(val))` means that the async iterator has successfully - /// produced a value, `val`, and may produce further values on subsequent - /// `poll_next` calls. + /// produced a value, `val`, and may produce further values on subsequent + /// `poll_next` calls. /// /// - `Poll::Ready(None)` means that the async iterator has terminated, and - /// `poll_next` should not be invoked again. + /// `poll_next` should not be invoked again. /// /// # Panics /// diff --git a/library/core/src/char/convert.rs b/library/core/src/char/convert.rs index 78cd89fefae..23061cb663b 100644 --- a/library/core/src/char/convert.rs +++ b/library/core/src/char/convert.rs @@ -36,7 +36,8 @@ pub(super) const unsafe fn from_u32_unchecked(i: u32) -> char { } #[stable(feature = "char_convert", since = "1.13.0")] -impl From<char> for u32 { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl const From<char> for u32 { /// Converts a [`char`] into a [`u32`]. /// /// # Examples @@ -53,7 +54,8 @@ impl From<char> for u32 { } #[stable(feature = "more_char_conversions", since = "1.51.0")] -impl From<char> for u64 { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl const From<char> for u64 { /// Converts a [`char`] into a [`u64`]. /// /// # Examples @@ -72,7 +74,8 @@ impl From<char> for u64 { } #[stable(feature = "more_char_conversions", since = "1.51.0")] -impl From<char> for u128 { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl const From<char> for u128 { /// Converts a [`char`] into a [`u128`]. /// /// # Examples @@ -157,7 +160,8 @@ impl TryFrom<char> for u16 { /// for a superset of Windows-1252 that fills the remaining blanks with corresponding /// C0 and C1 control codes. #[stable(feature = "char_convert", since = "1.13.0")] -impl From<u8> for char { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl const From<u8> for char { /// Converts a [`u8`] into a [`char`]. /// /// # Examples @@ -247,7 +251,8 @@ const fn char_try_from_u32(i: u32) -> Result<char, CharTryFromError> { } #[stable(feature = "try_from", since = "1.34.0")] -impl TryFrom<u32> for char { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl const TryFrom<u32> for char { type Error = CharTryFromError; #[inline] diff --git a/library/core/src/cmp.rs b/library/core/src/cmp.rs index 6419ae99113..1b9af10a6fd 100644 --- a/library/core/src/cmp.rs +++ b/library/core/src/cmp.rs @@ -1482,13 +1482,14 @@ pub trait PartialOrd<Rhs: PointeeSized = Self>: PartialEq<Rhs> + PointeeSized { } } -fn default_chaining_impl<T: PointeeSized, U: PointeeSized>( +fn default_chaining_impl<T, U>( lhs: &T, rhs: &U, p: impl FnOnce(Ordering) -> bool, ) -> ControlFlow<bool> where - T: PartialOrd<U>, + T: PartialOrd<U> + PointeeSized, + U: PointeeSized, { // It's important that this only call `partial_cmp` once, not call `eq` then // one of the relational operators. We don't want to `bcmp`-then-`memcp` a diff --git a/library/core/src/convert/mod.rs b/library/core/src/convert/mod.rs index 38381dbdf23..220a24caf09 100644 --- a/library/core/src/convert/mod.rs +++ b/library/core/src/convert/mod.rs @@ -216,6 +216,8 @@ pub const fn identity<T>(x: T) -> T { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[rustc_diagnostic_item = "AsRef"] +#[const_trait] +#[rustc_const_unstable(feature = "const_try", issue = "74935")] pub trait AsRef<T: PointeeSized>: PointeeSized { /// Converts this type into a shared reference of the (usually inferred) input type. #[stable(feature = "rust1", since = "1.0.0")] @@ -367,6 +369,8 @@ pub trait AsRef<T: PointeeSized>: PointeeSized { /// `&mut Vec<u8>`, for example, is the better choice (callers need to pass the correct type then). #[stable(feature = "rust1", since = "1.0.0")] #[rustc_diagnostic_item = "AsMut"] +#[const_trait] +#[rustc_const_unstable(feature = "const_try", issue = "74935")] pub trait AsMut<T: PointeeSized>: PointeeSized { /// Converts this type into a mutable reference of the (usually inferred) input type. #[stable(feature = "rust1", since = "1.0.0")] @@ -710,9 +714,10 @@ pub trait TryFrom<T>: Sized { // As lifts over & #[stable(feature = "rust1", since = "1.0.0")] -impl<T: PointeeSized, U: PointeeSized> AsRef<U> for &T +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl<T: PointeeSized, U: PointeeSized> const AsRef<U> for &T where - T: AsRef<U>, + T: ~const AsRef<U>, { #[inline] fn as_ref(&self) -> &U { @@ -722,9 +727,10 @@ where // As lifts over &mut #[stable(feature = "rust1", since = "1.0.0")] -impl<T: PointeeSized, U: PointeeSized> AsRef<U> for &mut T +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl<T: PointeeSized, U: PointeeSized> const AsRef<U> for &mut T where - T: AsRef<U>, + T: ~const AsRef<U>, { #[inline] fn as_ref(&self) -> &U { @@ -742,9 +748,10 @@ where // AsMut lifts over &mut #[stable(feature = "rust1", since = "1.0.0")] -impl<T: PointeeSized, U: PointeeSized> AsMut<U> for &mut T +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl<T: PointeeSized, U: PointeeSized> const AsMut<U> for &mut T where - T: AsMut<U>, + T: ~const AsMut<U>, { #[inline] fn as_mut(&mut self) -> &mut U { @@ -840,7 +847,8 @@ where //////////////////////////////////////////////////////////////////////////////// #[stable(feature = "rust1", since = "1.0.0")] -impl<T> AsRef<[T]> for [T] { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl<T> const AsRef<[T]> for [T] { #[inline(always)] fn as_ref(&self) -> &[T] { self @@ -848,7 +856,8 @@ impl<T> AsRef<[T]> for [T] { } #[stable(feature = "rust1", since = "1.0.0")] -impl<T> AsMut<[T]> for [T] { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl<T> const AsMut<[T]> for [T] { #[inline(always)] fn as_mut(&mut self) -> &mut [T] { self @@ -856,7 +865,8 @@ impl<T> AsMut<[T]> for [T] { } #[stable(feature = "rust1", since = "1.0.0")] -impl AsRef<str> for str { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl const AsRef<str> for str { #[inline(always)] fn as_ref(&self) -> &str { self @@ -864,7 +874,8 @@ impl AsRef<str> for str { } #[stable(feature = "as_mut_str_for_str", since = "1.51.0")] -impl AsMut<str> for str { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl const AsMut<str> for str { #[inline(always)] fn as_mut(&mut self) -> &mut str { self @@ -925,7 +936,8 @@ impl AsMut<str> for str { pub enum Infallible {} #[stable(feature = "convert_infallible", since = "1.34.0")] -impl Clone for Infallible { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl const Clone for Infallible { fn clone(&self) -> Infallible { match *self {} } @@ -953,7 +965,8 @@ impl Error for Infallible { } #[stable(feature = "convert_infallible", since = "1.34.0")] -impl PartialEq for Infallible { +#[rustc_const_unstable(feature = "const_cmp", issue = "143800")] +impl const PartialEq for Infallible { fn eq(&self, _: &Infallible) -> bool { match *self {} } @@ -977,7 +990,8 @@ impl Ord for Infallible { } #[stable(feature = "convert_infallible", since = "1.34.0")] -impl From<!> for Infallible { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl const From<!> for Infallible { #[inline] fn from(x: !) -> Self { x diff --git a/library/core/src/convert/num.rs b/library/core/src/convert/num.rs index 50616732b77..affb4eb64d3 100644 --- a/library/core/src/convert/num.rs +++ b/library/core/src/convert/num.rs @@ -69,7 +69,8 @@ macro_rules! impl_from { }; ($Small:ty => $Large:ty, #[$attr:meta], $doc:expr $(,)?) => { #[$attr] - impl From<$Small> for $Large { + #[rustc_const_unstable(feature = "const_try", issue = "74935")] + impl const From<$Small> for $Large { // Rustdocs on the impl block show a "[+] show undocumented items" toggle. // Rustdocs on functions do not. #[doc = $doc] @@ -200,7 +201,8 @@ macro_rules! impl_float_from_bool { )? ) => { #[stable(feature = "float_from_bool", since = "1.68.0")] - impl From<bool> for $float { + #[rustc_const_unstable(feature = "const_try", issue = "74935")] + impl const From<bool> for $float { #[doc = concat!("Converts a [`bool`] to [`", stringify!($float),"`] losslessly.")] /// The resulting value is positive `0.0` for `false` and `1.0` for `true` values. /// @@ -250,7 +252,8 @@ impl_float_from_bool!( macro_rules! impl_try_from_unbounded { ($source:ty => $($target:ty),+) => {$( #[stable(feature = "try_from", since = "1.34.0")] - impl TryFrom<$source> for $target { + #[rustc_const_unstable(feature = "const_try", issue = "74935")] + impl const TryFrom<$source> for $target { type Error = TryFromIntError; /// Tries to create the target number type from a source @@ -268,7 +271,8 @@ macro_rules! impl_try_from_unbounded { macro_rules! impl_try_from_lower_bounded { ($source:ty => $($target:ty),+) => {$( #[stable(feature = "try_from", since = "1.34.0")] - impl TryFrom<$source> for $target { + #[rustc_const_unstable(feature = "const_try", issue = "74935")] + impl const TryFrom<$source> for $target { type Error = TryFromIntError; /// Tries to create the target number type from a source @@ -290,7 +294,8 @@ macro_rules! impl_try_from_lower_bounded { macro_rules! impl_try_from_upper_bounded { ($source:ty => $($target:ty),+) => {$( #[stable(feature = "try_from", since = "1.34.0")] - impl TryFrom<$source> for $target { + #[rustc_const_unstable(feature = "const_try", issue = "74935")] + impl const TryFrom<$source> for $target { type Error = TryFromIntError; /// Tries to create the target number type from a source @@ -312,7 +317,8 @@ macro_rules! impl_try_from_upper_bounded { macro_rules! impl_try_from_both_bounded { ($source:ty => $($target:ty),+) => {$( #[stable(feature = "try_from", since = "1.34.0")] - impl TryFrom<$source> for $target { + #[rustc_const_unstable(feature = "const_try", issue = "74935")] + impl const TryFrom<$source> for $target { type Error = TryFromIntError; /// Tries to create the target number type from a source @@ -450,7 +456,8 @@ use crate::num::NonZero; macro_rules! impl_nonzero_int_from_nonzero_int { ($Small:ty => $Large:ty) => { #[stable(feature = "nz_int_conv", since = "1.41.0")] - impl From<NonZero<$Small>> for NonZero<$Large> { + #[rustc_const_unstable(feature = "const_try", issue = "74935")] + impl const From<NonZero<$Small>> for NonZero<$Large> { // Rustdocs on the impl block show a "[+] show undocumented items" toggle. // Rustdocs on functions do not. #[doc = concat!("Converts <code>[NonZero]\\<[", stringify!($Small), "]></code> ")] @@ -540,7 +547,8 @@ impl_nonzero_int_try_from_int!(isize); macro_rules! impl_nonzero_int_try_from_nonzero_int { ($source:ty => $($target:ty),+) => {$( #[stable(feature = "nzint_try_from_nzint_conv", since = "1.49.0")] - impl TryFrom<NonZero<$source>> for NonZero<$target> { + #[rustc_const_unstable(feature = "const_try", issue = "74935")] + impl const TryFrom<NonZero<$source>> for NonZero<$target> { type Error = TryFromIntError; // Rustdocs on the impl block show a "[+] show undocumented items" toggle. diff --git a/library/core/src/fmt/mod.rs b/library/core/src/fmt/mod.rs index 228a331e1da..8ac29e5b076 100644 --- a/library/core/src/fmt/mod.rs +++ b/library/core/src/fmt/mod.rs @@ -854,7 +854,6 @@ impl Display for Arguments<'_> { /// }"; /// assert_eq!(format!("The origin is: {origin:#?}"), expected); /// ``` - #[stable(feature = "rust1", since = "1.0.0")] #[rustc_on_unimplemented( on( diff --git a/library/core/src/intrinsics/mod.rs b/library/core/src/intrinsics/mod.rs index f90e6851d1f..106cc725fee 100644 --- a/library/core/src/intrinsics/mod.rs +++ b/library/core/src/intrinsics/mod.rs @@ -1379,6 +1379,7 @@ pub unsafe fn fmuladdf128(a: f128, b: f128, c: f128) -> f128; /// /// The stabilized version of this intrinsic is /// [`f16::floor`](../../std/primitive.f16.html#method.floor) +#[rustc_intrinsic_const_stable_indirect] #[rustc_intrinsic] #[rustc_nounwind] pub const unsafe fn floorf16(x: f16) -> f16; @@ -1386,6 +1387,7 @@ pub const unsafe fn floorf16(x: f16) -> f16; /// /// The stabilized version of this intrinsic is /// [`f32::floor`](../../std/primitive.f32.html#method.floor) +#[rustc_intrinsic_const_stable_indirect] #[rustc_intrinsic] #[rustc_nounwind] pub const unsafe fn floorf32(x: f32) -> f32; @@ -1393,6 +1395,7 @@ pub const unsafe fn floorf32(x: f32) -> f32; /// /// The stabilized version of this intrinsic is /// [`f64::floor`](../../std/primitive.f64.html#method.floor) +#[rustc_intrinsic_const_stable_indirect] #[rustc_intrinsic] #[rustc_nounwind] pub const unsafe fn floorf64(x: f64) -> f64; @@ -1400,6 +1403,7 @@ pub const unsafe fn floorf64(x: f64) -> f64; /// /// The stabilized version of this intrinsic is /// [`f128::floor`](../../std/primitive.f128.html#method.floor) +#[rustc_intrinsic_const_stable_indirect] #[rustc_intrinsic] #[rustc_nounwind] pub const unsafe fn floorf128(x: f128) -> f128; @@ -1408,6 +1412,7 @@ pub const unsafe fn floorf128(x: f128) -> f128; /// /// The stabilized version of this intrinsic is /// [`f16::ceil`](../../std/primitive.f16.html#method.ceil) +#[rustc_intrinsic_const_stable_indirect] #[rustc_intrinsic] #[rustc_nounwind] pub const unsafe fn ceilf16(x: f16) -> f16; @@ -1415,6 +1420,7 @@ pub const unsafe fn ceilf16(x: f16) -> f16; /// /// The stabilized version of this intrinsic is /// [`f32::ceil`](../../std/primitive.f32.html#method.ceil) +#[rustc_intrinsic_const_stable_indirect] #[rustc_intrinsic] #[rustc_nounwind] pub const unsafe fn ceilf32(x: f32) -> f32; @@ -1422,6 +1428,7 @@ pub const unsafe fn ceilf32(x: f32) -> f32; /// /// The stabilized version of this intrinsic is /// [`f64::ceil`](../../std/primitive.f64.html#method.ceil) +#[rustc_intrinsic_const_stable_indirect] #[rustc_intrinsic] #[rustc_nounwind] pub const unsafe fn ceilf64(x: f64) -> f64; @@ -1429,6 +1436,7 @@ pub const unsafe fn ceilf64(x: f64) -> f64; /// /// The stabilized version of this intrinsic is /// [`f128::ceil`](../../std/primitive.f128.html#method.ceil) +#[rustc_intrinsic_const_stable_indirect] #[rustc_intrinsic] #[rustc_nounwind] pub const unsafe fn ceilf128(x: f128) -> f128; @@ -1437,6 +1445,7 @@ pub const unsafe fn ceilf128(x: f128) -> f128; /// /// The stabilized version of this intrinsic is /// [`f16::trunc`](../../std/primitive.f16.html#method.trunc) +#[rustc_intrinsic_const_stable_indirect] #[rustc_intrinsic] #[rustc_nounwind] pub const unsafe fn truncf16(x: f16) -> f16; @@ -1444,6 +1453,7 @@ pub const unsafe fn truncf16(x: f16) -> f16; /// /// The stabilized version of this intrinsic is /// [`f32::trunc`](../../std/primitive.f32.html#method.trunc) +#[rustc_intrinsic_const_stable_indirect] #[rustc_intrinsic] #[rustc_nounwind] pub const unsafe fn truncf32(x: f32) -> f32; @@ -1451,6 +1461,7 @@ pub const unsafe fn truncf32(x: f32) -> f32; /// /// The stabilized version of this intrinsic is /// [`f64::trunc`](../../std/primitive.f64.html#method.trunc) +#[rustc_intrinsic_const_stable_indirect] #[rustc_intrinsic] #[rustc_nounwind] pub const unsafe fn truncf64(x: f64) -> f64; @@ -1458,6 +1469,7 @@ pub const unsafe fn truncf64(x: f64) -> f64; /// /// The stabilized version of this intrinsic is /// [`f128::trunc`](../../std/primitive.f128.html#method.trunc) +#[rustc_intrinsic_const_stable_indirect] #[rustc_intrinsic] #[rustc_nounwind] pub const unsafe fn truncf128(x: f128) -> f128; @@ -1467,6 +1479,7 @@ pub const unsafe fn truncf128(x: f128) -> f128; /// /// The stabilized version of this intrinsic is /// [`f16::round_ties_even`](../../std/primitive.f16.html#method.round_ties_even) +#[rustc_intrinsic_const_stable_indirect] #[rustc_intrinsic] #[rustc_nounwind] pub const fn round_ties_even_f16(x: f16) -> f16; @@ -1476,6 +1489,7 @@ pub const fn round_ties_even_f16(x: f16) -> f16; /// /// The stabilized version of this intrinsic is /// [`f32::round_ties_even`](../../std/primitive.f32.html#method.round_ties_even) +#[rustc_intrinsic_const_stable_indirect] #[rustc_intrinsic] #[rustc_nounwind] pub const fn round_ties_even_f32(x: f32) -> f32; @@ -1485,6 +1499,7 @@ pub const fn round_ties_even_f32(x: f32) -> f32; /// /// The stabilized version of this intrinsic is /// [`f64::round_ties_even`](../../std/primitive.f64.html#method.round_ties_even) +#[rustc_intrinsic_const_stable_indirect] #[rustc_intrinsic] #[rustc_nounwind] pub const fn round_ties_even_f64(x: f64) -> f64; @@ -1494,6 +1509,7 @@ pub const fn round_ties_even_f64(x: f64) -> f64; /// /// The stabilized version of this intrinsic is /// [`f128::round_ties_even`](../../std/primitive.f128.html#method.round_ties_even) +#[rustc_intrinsic_const_stable_indirect] #[rustc_intrinsic] #[rustc_nounwind] pub const fn round_ties_even_f128(x: f128) -> f128; @@ -1502,6 +1518,7 @@ pub const fn round_ties_even_f128(x: f128) -> f128; /// /// The stabilized version of this intrinsic is /// [`f16::round`](../../std/primitive.f16.html#method.round) +#[rustc_intrinsic_const_stable_indirect] #[rustc_intrinsic] #[rustc_nounwind] pub const unsafe fn roundf16(x: f16) -> f16; @@ -1509,6 +1526,7 @@ pub const unsafe fn roundf16(x: f16) -> f16; /// /// The stabilized version of this intrinsic is /// [`f32::round`](../../std/primitive.f32.html#method.round) +#[rustc_intrinsic_const_stable_indirect] #[rustc_intrinsic] #[rustc_nounwind] pub const unsafe fn roundf32(x: f32) -> f32; @@ -1516,6 +1534,7 @@ pub const unsafe fn roundf32(x: f32) -> f32; /// /// The stabilized version of this intrinsic is /// [`f64::round`](../../std/primitive.f64.html#method.round) +#[rustc_intrinsic_const_stable_indirect] #[rustc_intrinsic] #[rustc_nounwind] pub const unsafe fn roundf64(x: f64) -> f64; @@ -1523,6 +1542,7 @@ pub const unsafe fn roundf64(x: f64) -> f64; /// /// The stabilized version of this intrinsic is /// [`f128::round`](../../std/primitive.f128.html#method.round) +#[rustc_intrinsic_const_stable_indirect] #[rustc_intrinsic] #[rustc_nounwind] pub const unsafe fn roundf128(x: f128) -> f128; diff --git a/library/core/src/iter/adapters/zip.rs b/library/core/src/iter/adapters/zip.rs index 8090c98e7ed..c5e199c3082 100644 --- a/library/core/src/iter/adapters/zip.rs +++ b/library/core/src/iter/adapters/zip.rs @@ -18,7 +18,6 @@ pub struct Zip<A, B> { // index, len and a_len are only used by the specialized version of zip index: usize, len: usize, - a_len: usize, } impl<A: Iterator, B: Iterator> Zip<A, B> { pub(in crate::iter) fn new(a: A, b: B) -> Zip<A, B> { @@ -158,7 +157,6 @@ macro_rules! zip_impl_general_defaults { b, index: 0, // unused len: 0, // unused - a_len: 0, // unused } } @@ -299,9 +297,8 @@ where B: TrustedRandomAccess + Iterator, { fn new(a: A, b: B) -> Self { - let a_len = a.size(); - let len = cmp::min(a_len, b.size()); - Zip { a, b, index: 0, len, a_len } + let len = cmp::min(a.size(), b.size()); + Zip { a, b, index: 0, len } } #[inline] @@ -315,17 +312,6 @@ where unsafe { Some((self.a.__iterator_get_unchecked(i), self.b.__iterator_get_unchecked(i))) } - } else if A::MAY_HAVE_SIDE_EFFECT && self.index < self.a_len { - let i = self.index; - // as above, increment before executing code that may panic - self.index += 1; - self.len += 1; - // match the base implementation's potential side effects - // SAFETY: we just checked that `i` < `self.a.len()` - unsafe { - self.a.__iterator_get_unchecked(i); - } - None } else { None } @@ -371,36 +357,42 @@ where A: DoubleEndedIterator + ExactSizeIterator, B: DoubleEndedIterator + ExactSizeIterator, { - if A::MAY_HAVE_SIDE_EFFECT || B::MAY_HAVE_SIDE_EFFECT { - let sz_a = self.a.size(); - let sz_b = self.b.size(); - // Adjust a, b to equal length, make sure that only the first call - // of `next_back` does this, otherwise we will break the restriction - // on calls to `self.next_back()` after calling `get_unchecked()`. - if sz_a != sz_b { + // No effects when the iterator is exhausted, to reduce the number of + // cases the unsafe code has to handle. + // See #137255 for a case where where too many epicycles lead to unsoundness. + if self.index < self.len { + let old_len = self.len; + + // since get_unchecked and the side-effecting code can execute user code + // which can panic we decrement the counter beforehand + // so that the same index won't be accessed twice, as required by TrustedRandomAccess. + // Additionally this will ensure that the side-effects code won't run a second time. + self.len -= 1; + + // Adjust a, b to equal length if we're iterating backwards. + if A::MAY_HAVE_SIDE_EFFECT || B::MAY_HAVE_SIDE_EFFECT { + // note if some forward-iteration already happened then these aren't the real + // remaining lengths of the inner iterators, so we have to relate them to + // Zip's internal length-tracking. let sz_a = self.a.size(); - if A::MAY_HAVE_SIDE_EFFECT && sz_a > self.len { - for _ in 0..sz_a - self.len { - // since next_back() may panic we increment the counters beforehand - // to keep Zip's state in sync with the underlying iterator source - self.a_len -= 1; - self.a.next_back(); - } - debug_assert_eq!(self.a_len, self.len); - } let sz_b = self.b.size(); - if B::MAY_HAVE_SIDE_EFFECT && sz_b > self.len { - for _ in 0..sz_b - self.len { - self.b.next_back(); + // This condition can and must only be true on the first `next_back` call, + // otherwise we will break the restriction on calls to `self.next_back()` + // after calling `get_unchecked()`. + if sz_a != sz_b && (old_len == sz_a || old_len == sz_b) { + if A::MAY_HAVE_SIDE_EFFECT && sz_a > old_len { + for _ in 0..sz_a - old_len { + self.a.next_back(); + } } + if B::MAY_HAVE_SIDE_EFFECT && sz_b > old_len { + for _ in 0..sz_b - old_len { + self.b.next_back(); + } + } + debug_assert_eq!(self.a.size(), self.b.size()); } } - } - if self.index < self.len { - // since get_unchecked executes code which can panic we increment the counters beforehand - // so that the same index won't be accessed twice, as required by TrustedRandomAccess - self.len -= 1; - self.a_len -= 1; let i = self.len; // SAFETY: `i` is smaller than the previous value of `self.len`, // which is also smaller than or equal to `self.a.len()` and `self.b.len()` diff --git a/library/core/src/iter/traits/collect.rs b/library/core/src/iter/traits/collect.rs index 3bc9cff8072..ab276500679 100644 --- a/library/core/src/iter/traits/collect.rs +++ b/library/core/src/iter/traits/collect.rs @@ -436,7 +436,6 @@ pub trait Extend<A> { /// **For implementors:** For a collection to unsafely rely on this method's safety precondition (that is, /// invoke UB if they are violated), it must implement `extend_reserve` correctly. In other words, /// callers may assume that if they `extend_reserve`ed enough space they can call this method. - // This method is for internal usage only. It is only on the trait because of specialization's limitations. #[unstable(feature = "extend_one_unchecked", issue = "none")] #[doc(hidden)] diff --git a/library/core/src/iter/traits/iterator.rs b/library/core/src/iter/traits/iterator.rs index f296792b1dc..10f9d464f7d 100644 --- a/library/core/src/iter/traits/iterator.rs +++ b/library/core/src/iter/traits/iterator.rs @@ -3414,10 +3414,10 @@ pub trait Iterator { /// ``` #[stable(feature = "iter_copied", since = "1.36.0")] #[rustc_diagnostic_item = "iter_copied"] - fn copied<'a, T: 'a>(self) -> Copied<Self> + fn copied<'a, T>(self) -> Copied<Self> where + T: Copy + 'a, Self: Sized + Iterator<Item = &'a T>, - T: Copy, { Copied::new(self) } @@ -3462,10 +3462,10 @@ pub trait Iterator { /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[rustc_diagnostic_item = "iter_cloned"] - fn cloned<'a, T: 'a>(self) -> Cloned<Self> + fn cloned<'a, T>(self) -> Cloned<Self> where + T: Clone + 'a, Self: Sized + Iterator<Item = &'a T>, - T: Clone, { Cloned::new(self) } diff --git a/library/core/src/lib.rs b/library/core/src/lib.rs index 729de5ffc8f..3c33f4b1368 100644 --- a/library/core/src/lib.rs +++ b/library/core/src/lib.rs @@ -39,9 +39,9 @@ //! return. You should mark your implementation using `#[panic_handler]`. //! //! * `rust_eh_personality` - is used by the failure mechanisms of the -//! compiler. This is often mapped to GCC's personality function, but crates -//! which do not trigger a panic can be assured that this function is never -//! called. The `lang` attribute is called `eh_personality`. +//! compiler. This is often mapped to GCC's personality function, but crates +//! which do not trigger a panic can be assured that this function is never +//! called. The `lang` attribute is called `eh_personality`. #![stable(feature = "core", since = "1.6.0")] #![doc( diff --git a/library/core/src/mem/maybe_uninit.rs b/library/core/src/mem/maybe_uninit.rs index fc35e54bb0d..34d8370da7e 100644 --- a/library/core/src/mem/maybe_uninit.rs +++ b/library/core/src/mem/maybe_uninit.rs @@ -1005,28 +1005,6 @@ impl<T> MaybeUninit<T> { } } - /// Deprecated version of [`slice::assume_init_ref`]. - #[unstable(feature = "maybe_uninit_slice", issue = "63569")] - #[deprecated( - note = "replaced by inherent assume_init_ref method; will eventually be removed", - since = "1.83.0" - )] - pub const unsafe fn slice_assume_init_ref(slice: &[Self]) -> &[T] { - // SAFETY: Same for both methods. - unsafe { slice.assume_init_ref() } - } - - /// Deprecated version of [`slice::assume_init_mut`]. - #[unstable(feature = "maybe_uninit_slice", issue = "63569")] - #[deprecated( - note = "replaced by inherent assume_init_mut method; will eventually be removed", - since = "1.83.0" - )] - pub const unsafe fn slice_assume_init_mut(slice: &mut [Self]) -> &mut [T] { - // SAFETY: Same for both methods. - unsafe { slice.assume_init_mut() } - } - /// Gets a pointer to the first element of the array. #[unstable(feature = "maybe_uninit_slice", issue = "63569")] #[inline(always)] @@ -1040,94 +1018,6 @@ impl<T> MaybeUninit<T> { pub const fn slice_as_mut_ptr(this: &mut [MaybeUninit<T>]) -> *mut T { this.as_mut_ptr() as *mut T } - - /// Deprecated version of [`slice::write_copy_of_slice`]. - #[unstable(feature = "maybe_uninit_write_slice", issue = "79995")] - #[deprecated( - note = "replaced by inherent write_copy_of_slice method; will eventually be removed", - since = "1.83.0" - )] - pub fn copy_from_slice<'a>(this: &'a mut [MaybeUninit<T>], src: &[T]) -> &'a mut [T] - where - T: Copy, - { - this.write_copy_of_slice(src) - } - - /// Deprecated version of [`slice::write_clone_of_slice`]. - #[unstable(feature = "maybe_uninit_write_slice", issue = "79995")] - #[deprecated( - note = "replaced by inherent write_clone_of_slice method; will eventually be removed", - since = "1.83.0" - )] - pub fn clone_from_slice<'a>(this: &'a mut [MaybeUninit<T>], src: &[T]) -> &'a mut [T] - where - T: Clone, - { - this.write_clone_of_slice(src) - } - - /// Deprecated version of [`slice::write_filled`]. - #[unstable(feature = "maybe_uninit_fill", issue = "117428")] - #[deprecated( - note = "replaced by inherent write_filled method; will eventually be removed", - since = "1.83.0" - )] - pub fn fill<'a>(this: &'a mut [MaybeUninit<T>], value: T) -> &'a mut [T] - where - T: Clone, - { - this.write_filled(value) - } - - /// Deprecated version of [`slice::write_with`]. - #[unstable(feature = "maybe_uninit_fill", issue = "117428")] - #[deprecated( - note = "replaced by inherent write_with method; will eventually be removed", - since = "1.83.0" - )] - pub fn fill_with<'a, F>(this: &'a mut [MaybeUninit<T>], mut f: F) -> &'a mut [T] - where - F: FnMut() -> T, - { - this.write_with(|_| f()) - } - - /// Deprecated version of [`slice::write_iter`]. - #[unstable(feature = "maybe_uninit_fill", issue = "117428")] - #[deprecated( - note = "replaced by inherent write_iter method; will eventually be removed", - since = "1.83.0" - )] - pub fn fill_from<'a, I>( - this: &'a mut [MaybeUninit<T>], - it: I, - ) -> (&'a mut [T], &'a mut [MaybeUninit<T>]) - where - I: IntoIterator<Item = T>, - { - this.write_iter(it) - } - - /// Deprecated version of [`slice::as_bytes`]. - #[unstable(feature = "maybe_uninit_as_bytes", issue = "93092")] - #[deprecated( - note = "replaced by inherent as_bytes method; will eventually be removed", - since = "1.83.0" - )] - pub fn slice_as_bytes(this: &[MaybeUninit<T>]) -> &[MaybeUninit<u8>] { - this.as_bytes() - } - - /// Deprecated version of [`slice::as_bytes_mut`]. - #[unstable(feature = "maybe_uninit_as_bytes", issue = "93092")] - #[deprecated( - note = "replaced by inherent as_bytes_mut method; will eventually be removed", - since = "1.83.0" - )] - pub fn slice_as_bytes_mut(this: &mut [MaybeUninit<T>]) -> &mut [MaybeUninit<u8>] { - this.as_bytes_mut() - } } impl<T> [MaybeUninit<T>] { @@ -1304,7 +1194,7 @@ impl<T> [MaybeUninit<T>] { /// Fills a slice with elements returned by calling a closure for each index. /// /// This method uses a closure to create new values. If you'd rather `Clone` a given value, use - /// [`MaybeUninit::fill`]. If you want to use the `Default` trait to generate values, you can + /// [slice::write_filled]. If you want to use the `Default` trait to generate values, you can /// pass [`|_| Default::default()`][Default::default] as the argument. /// /// # Panics @@ -1463,7 +1353,7 @@ impl<T> [MaybeUninit<T>] { /// use std::mem::MaybeUninit; /// /// let mut uninit = [MaybeUninit::<u16>::uninit(), MaybeUninit::<u16>::uninit()]; - /// let uninit_bytes = MaybeUninit::slice_as_bytes_mut(&mut uninit); + /// let uninit_bytes = uninit.as_bytes_mut(); /// uninit_bytes.write_copy_of_slice(&[0x12, 0x34, 0x56, 0x78]); /// let vals = unsafe { uninit.assume_init_ref() }; /// if cfg!(target_endian = "little") { diff --git a/library/core/src/mem/mod.rs b/library/core/src/mem/mod.rs index 1bd12d818cf..2198d098c4b 100644 --- a/library/core/src/mem/mod.rs +++ b/library/core/src/mem/mod.rs @@ -36,7 +36,7 @@ pub use crate::intrinsics::transmute; /// * If you want to leak memory, see [`Box::leak`]. /// * If you want to obtain a raw pointer to the memory, see [`Box::into_raw`]. /// * If you want to dispose of a value properly, running its destructor, see -/// [`mem::drop`]. +/// [`mem::drop`]. /// /// # Safety /// diff --git a/library/core/src/net/ip_addr.rs b/library/core/src/net/ip_addr.rs index aaa68e8d7d1..6adeb2aa3fd 100644 --- a/library/core/src/net/ip_addr.rs +++ b/library/core/src/net/ip_addr.rs @@ -787,7 +787,6 @@ impl Ipv4Addr { /// [IANA IPv4 Special-Purpose Address Registry]: https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml /// [unspecified address]: Ipv4Addr::UNSPECIFIED /// [broadcast address]: Ipv4Addr::BROADCAST - /// /// # Examples /// @@ -1089,7 +1088,8 @@ impl fmt::Debug for IpAddr { } #[stable(feature = "ip_from_ip", since = "1.16.0")] -impl From<Ipv4Addr> for IpAddr { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl const From<Ipv4Addr> for IpAddr { /// Copies this address to a new `IpAddr::V4`. /// /// # Examples @@ -1111,7 +1111,8 @@ impl From<Ipv4Addr> for IpAddr { } #[stable(feature = "ip_from_ip", since = "1.16.0")] -impl From<Ipv6Addr> for IpAddr { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl const From<Ipv6Addr> for IpAddr { /// Copies this address to a new `IpAddr::V6`. /// /// # Examples @@ -1221,7 +1222,8 @@ impl Ord for Ipv4Addr { } #[stable(feature = "ip_u32", since = "1.1.0")] -impl From<Ipv4Addr> for u32 { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl const From<Ipv4Addr> for u32 { /// Uses [`Ipv4Addr::to_bits`] to convert an IPv4 address to a host byte order `u32`. #[inline] fn from(ip: Ipv4Addr) -> u32 { @@ -1230,7 +1232,8 @@ impl From<Ipv4Addr> for u32 { } #[stable(feature = "ip_u32", since = "1.1.0")] -impl From<u32> for Ipv4Addr { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl const From<u32> for Ipv4Addr { /// Uses [`Ipv4Addr::from_bits`] to convert a host byte order `u32` into an IPv4 address. #[inline] fn from(ip: u32) -> Ipv4Addr { @@ -1239,7 +1242,8 @@ impl From<u32> for Ipv4Addr { } #[stable(feature = "from_slice_v4", since = "1.9.0")] -impl From<[u8; 4]> for Ipv4Addr { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl const From<[u8; 4]> for Ipv4Addr { /// Creates an `Ipv4Addr` from a four element byte array. /// /// # Examples @@ -1257,7 +1261,8 @@ impl From<[u8; 4]> for Ipv4Addr { } #[stable(feature = "ip_from_slice", since = "1.17.0")] -impl From<[u8; 4]> for IpAddr { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl const From<[u8; 4]> for IpAddr { /// Creates an `IpAddr::V4` from a four element byte array. /// /// # Examples @@ -2211,7 +2216,8 @@ impl Ord for Ipv6Addr { } #[stable(feature = "i128", since = "1.26.0")] -impl From<Ipv6Addr> for u128 { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl const From<Ipv6Addr> for u128 { /// Uses [`Ipv6Addr::to_bits`] to convert an IPv6 address to a host byte order `u128`. #[inline] fn from(ip: Ipv6Addr) -> u128 { @@ -2219,7 +2225,8 @@ impl From<Ipv6Addr> for u128 { } } #[stable(feature = "i128", since = "1.26.0")] -impl From<u128> for Ipv6Addr { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl const From<u128> for Ipv6Addr { /// Uses [`Ipv6Addr::from_bits`] to convert a host byte order `u128` to an IPv6 address. #[inline] fn from(ip: u128) -> Ipv6Addr { @@ -2228,7 +2235,8 @@ impl From<u128> for Ipv6Addr { } #[stable(feature = "ipv6_from_octets", since = "1.9.0")] -impl From<[u8; 16]> for Ipv6Addr { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl const From<[u8; 16]> for Ipv6Addr { /// Creates an `Ipv6Addr` from a sixteen element byte array. /// /// # Examples @@ -2255,7 +2263,8 @@ impl From<[u8; 16]> for Ipv6Addr { } #[stable(feature = "ipv6_from_segments", since = "1.16.0")] -impl From<[u16; 8]> for Ipv6Addr { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl const From<[u16; 8]> for Ipv6Addr { /// Creates an `Ipv6Addr` from an eight element 16-bit array. /// /// # Examples @@ -2283,7 +2292,8 @@ impl From<[u16; 8]> for Ipv6Addr { } #[stable(feature = "ip_from_slice", since = "1.17.0")] -impl From<[u8; 16]> for IpAddr { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl const From<[u8; 16]> for IpAddr { /// Creates an `IpAddr::V6` from a sixteen element byte array. /// /// # Examples @@ -2310,7 +2320,8 @@ impl From<[u8; 16]> for IpAddr { } #[stable(feature = "ip_from_slice", since = "1.17.0")] -impl From<[u16; 8]> for IpAddr { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl const From<[u16; 8]> for IpAddr { /// Creates an `IpAddr::V6` from an eight element 16-bit array. /// /// # Examples diff --git a/library/core/src/net/socket_addr.rs b/library/core/src/net/socket_addr.rs index 936f9f64930..69924199f99 100644 --- a/library/core/src/net/socket_addr.rs +++ b/library/core/src/net/socket_addr.rs @@ -592,7 +592,8 @@ impl SocketAddrV6 { } #[stable(feature = "ip_from_ip", since = "1.16.0")] -impl From<SocketAddrV4> for SocketAddr { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl const From<SocketAddrV4> for SocketAddr { /// Converts a [`SocketAddrV4`] into a [`SocketAddr::V4`]. #[inline] fn from(sock4: SocketAddrV4) -> SocketAddr { @@ -601,7 +602,8 @@ impl From<SocketAddrV4> for SocketAddr { } #[stable(feature = "ip_from_ip", since = "1.16.0")] -impl From<SocketAddrV6> for SocketAddr { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl const From<SocketAddrV6> for SocketAddr { /// Converts a [`SocketAddrV6`] into a [`SocketAddr::V6`]. #[inline] fn from(sock6: SocketAddrV6) -> SocketAddr { @@ -610,7 +612,8 @@ impl From<SocketAddrV6> for SocketAddr { } #[stable(feature = "addr_from_into_ip", since = "1.17.0")] -impl<I: Into<IpAddr>> From<(I, u16)> for SocketAddr { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl<I: ~const Into<IpAddr>> const From<(I, u16)> for SocketAddr { /// Converts a tuple struct (Into<[`IpAddr`]>, `u16`) into a [`SocketAddr`]. /// /// This conversion creates a [`SocketAddr::V4`] for an [`IpAddr::V4`] diff --git a/library/core/src/num/error.rs b/library/core/src/num/error.rs index f9c4cdd0ebe..cfedd465cab 100644 --- a/library/core/src/num/error.rs +++ b/library/core/src/num/error.rs @@ -26,14 +26,16 @@ impl Error for TryFromIntError { } #[stable(feature = "try_from", since = "1.34.0")] -impl From<Infallible> for TryFromIntError { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl const From<Infallible> for TryFromIntError { fn from(x: Infallible) -> TryFromIntError { match x {} } } #[unstable(feature = "never_type", issue = "35121")] -impl From<!> for TryFromIntError { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl const From<!> for TryFromIntError { #[inline] fn from(never: !) -> TryFromIntError { // Match rather than coerce to make sure that code like diff --git a/library/core/src/num/f128.rs b/library/core/src/num/f128.rs index 4c09c930c79..69e6c100e76 100644 --- a/library/core/src/num/f128.rs +++ b/library/core/src/num/f128.rs @@ -1448,7 +1448,6 @@ impl f128 { #[rustc_allow_incoherent_impl] #[unstable(feature = "f128", issue = "116909")] #[rustc_const_unstable(feature = "f128", issue = "116909")] - // #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] #[must_use = "method returns a new number and does not mutate the original value"] pub const fn floor(self) -> f128 { // SAFETY: intrinsic with no preconditions @@ -1478,7 +1477,6 @@ impl f128 { #[rustc_allow_incoherent_impl] #[unstable(feature = "f128", issue = "116909")] #[rustc_const_unstable(feature = "f128", issue = "116909")] - // #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] #[must_use = "method returns a new number and does not mutate the original value"] pub const fn ceil(self) -> f128 { // SAFETY: intrinsic with no preconditions @@ -1514,7 +1512,6 @@ impl f128 { #[rustc_allow_incoherent_impl] #[unstable(feature = "f128", issue = "116909")] #[rustc_const_unstable(feature = "f128", issue = "116909")] - // #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] #[must_use = "method returns a new number and does not mutate the original value"] pub const fn round(self) -> f128 { // SAFETY: intrinsic with no preconditions @@ -1548,7 +1545,6 @@ impl f128 { #[rustc_allow_incoherent_impl] #[unstable(feature = "f128", issue = "116909")] #[rustc_const_unstable(feature = "f128", issue = "116909")] - // #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] #[must_use = "method returns a new number and does not mutate the original value"] pub const fn round_ties_even(self) -> f128 { intrinsics::round_ties_even_f128(self) @@ -1580,7 +1576,6 @@ impl f128 { #[rustc_allow_incoherent_impl] #[unstable(feature = "f128", issue = "116909")] #[rustc_const_unstable(feature = "f128", issue = "116909")] - // #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] #[must_use = "method returns a new number and does not mutate the original value"] pub const fn trunc(self) -> f128 { // SAFETY: intrinsic with no preconditions @@ -1611,7 +1606,6 @@ impl f128 { #[rustc_allow_incoherent_impl] #[unstable(feature = "f128", issue = "116909")] #[rustc_const_unstable(feature = "f128", issue = "116909")] - // #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] #[must_use = "method returns a new number and does not mutate the original value"] pub const fn fract(self) -> f128 { self - self.trunc() diff --git a/library/core/src/num/f16.rs b/library/core/src/num/f16.rs index 1d98a485c4f..b66cef03d20 100644 --- a/library/core/src/num/f16.rs +++ b/library/core/src/num/f16.rs @@ -1424,7 +1424,6 @@ impl f16 { #[rustc_allow_incoherent_impl] #[unstable(feature = "f16", issue = "116909")] #[rustc_const_unstable(feature = "f16", issue = "116909")] - // #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] #[must_use = "method returns a new number and does not mutate the original value"] pub const fn floor(self) -> f16 { // SAFETY: intrinsic with no preconditions @@ -1454,7 +1453,6 @@ impl f16 { #[rustc_allow_incoherent_impl] #[unstable(feature = "f16", issue = "116909")] #[rustc_const_unstable(feature = "f16", issue = "116909")] - // #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] #[must_use = "method returns a new number and does not mutate the original value"] pub const fn ceil(self) -> f16 { // SAFETY: intrinsic with no preconditions @@ -1490,7 +1488,6 @@ impl f16 { #[rustc_allow_incoherent_impl] #[unstable(feature = "f16", issue = "116909")] #[rustc_const_unstable(feature = "f16", issue = "116909")] - // #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] #[must_use = "method returns a new number and does not mutate the original value"] pub const fn round(self) -> f16 { // SAFETY: intrinsic with no preconditions @@ -1524,7 +1521,6 @@ impl f16 { #[rustc_allow_incoherent_impl] #[unstable(feature = "f16", issue = "116909")] #[rustc_const_unstable(feature = "f16", issue = "116909")] - // #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] #[must_use = "method returns a new number and does not mutate the original value"] pub const fn round_ties_even(self) -> f16 { intrinsics::round_ties_even_f16(self) @@ -1556,7 +1552,6 @@ impl f16 { #[rustc_allow_incoherent_impl] #[unstable(feature = "f16", issue = "116909")] #[rustc_const_unstable(feature = "f16", issue = "116909")] - // #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] #[must_use = "method returns a new number and does not mutate the original value"] pub const fn trunc(self) -> f16 { // SAFETY: intrinsic with no preconditions @@ -1587,7 +1582,6 @@ impl f16 { #[rustc_allow_incoherent_impl] #[unstable(feature = "f16", issue = "116909")] #[rustc_const_unstable(feature = "f16", issue = "116909")] - // #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] #[must_use = "method returns a new number and does not mutate the original value"] pub const fn fract(self) -> f16 { self - self.trunc() diff --git a/library/core/src/num/f32.rs b/library/core/src/num/f32.rs index b460c7d0205..f8344da79ad 100644 --- a/library/core/src/num/f32.rs +++ b/library/core/src/num/f32.rs @@ -1591,7 +1591,6 @@ pub mod math { /// [`f32::floor`]: ../../../std/primitive.f32.html#method.floor #[inline] #[unstable(feature = "core_float_math", issue = "137578")] - #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] #[must_use = "method returns a new number and does not mutate the original value"] pub const fn floor(x: f32) -> f32 { // SAFETY: intrinsic with no preconditions @@ -1622,7 +1621,6 @@ pub mod math { #[doc(alias = "ceiling")] #[must_use = "method returns a new number and does not mutate the original value"] #[unstable(feature = "core_float_math", issue = "137578")] - #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] pub const fn ceil(x: f32) -> f32 { // SAFETY: intrinsic with no preconditions unsafe { intrinsics::ceilf32(x) } @@ -1657,7 +1655,6 @@ pub mod math { #[inline] #[unstable(feature = "core_float_math", issue = "137578")] #[must_use = "method returns a new number and does not mutate the original value"] - #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] pub const fn round(x: f32) -> f32 { // SAFETY: intrinsic with no preconditions unsafe { intrinsics::roundf32(x) } @@ -1691,7 +1688,6 @@ pub mod math { #[inline] #[unstable(feature = "core_float_math", issue = "137578")] #[must_use = "method returns a new number and does not mutate the original value"] - #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] pub const fn round_ties_even(x: f32) -> f32 { intrinsics::round_ties_even_f32(x) } @@ -1722,7 +1718,6 @@ pub mod math { #[doc(alias = "truncate")] #[must_use = "method returns a new number and does not mutate the original value"] #[unstable(feature = "core_float_math", issue = "137578")] - #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] pub const fn trunc(x: f32) -> f32 { // SAFETY: intrinsic with no preconditions unsafe { intrinsics::truncf32(x) } @@ -1752,7 +1747,6 @@ pub mod math { /// [`f32::fract`]: ../../../std/primitive.f32.html#method.fract #[inline] #[unstable(feature = "core_float_math", issue = "137578")] - #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] #[must_use = "method returns a new number and does not mutate the original value"] pub const fn fract(x: f32) -> f32 { x - trunc(x) diff --git a/library/core/src/num/f64.rs b/library/core/src/num/f64.rs index 3cd079b84eb..93da63c896e 100644 --- a/library/core/src/num/f64.rs +++ b/library/core/src/num/f64.rs @@ -1589,7 +1589,6 @@ pub mod math { /// [`f64::floor`]: ../../../std/primitive.f64.html#method.floor #[inline] #[unstable(feature = "core_float_math", issue = "137578")] - #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] #[must_use = "method returns a new number and does not mutate the original value"] pub const fn floor(x: f64) -> f64 { // SAFETY: intrinsic with no preconditions @@ -1619,7 +1618,6 @@ pub mod math { #[inline] #[doc(alias = "ceiling")] #[unstable(feature = "core_float_math", issue = "137578")] - #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] #[must_use = "method returns a new number and does not mutate the original value"] pub const fn ceil(x: f64) -> f64 { // SAFETY: intrinsic with no preconditions @@ -1654,7 +1652,6 @@ pub mod math { /// [`f64::round`]: ../../../std/primitive.f64.html#method.round #[inline] #[unstable(feature = "core_float_math", issue = "137578")] - #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] #[must_use = "method returns a new number and does not mutate the original value"] pub const fn round(x: f64) -> f64 { // SAFETY: intrinsic with no preconditions @@ -1688,7 +1685,6 @@ pub mod math { /// [`f64::round_ties_even`]: ../../../std/primitive.f64.html#method.round_ties_even #[inline] #[unstable(feature = "core_float_math", issue = "137578")] - #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] #[must_use = "method returns a new number and does not mutate the original value"] pub const fn round_ties_even(x: f64) -> f64 { intrinsics::round_ties_even_f64(x) @@ -1719,7 +1715,6 @@ pub mod math { #[inline] #[doc(alias = "truncate")] #[unstable(feature = "core_float_math", issue = "137578")] - #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] #[must_use = "method returns a new number and does not mutate the original value"] pub const fn trunc(x: f64) -> f64 { // SAFETY: intrinsic with no preconditions @@ -1750,7 +1745,6 @@ pub mod math { /// [`f64::fract`]: ../../../std/primitive.f64.html#method.fract #[inline] #[unstable(feature = "core_float_math", issue = "137578")] - #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] #[must_use = "method returns a new number and does not mutate the original value"] pub const fn fract(x: f64) -> f64 { x - trunc(x) diff --git a/library/core/src/num/int_log10.rs b/library/core/src/num/int_log10.rs index 28a3f5d880a..649a736b6e7 100644 --- a/library/core/src/num/int_log10.rs +++ b/library/core/src/num/int_log10.rs @@ -1,5 +1,5 @@ -/// These functions compute the integer logarithm of their type, assuming -/// that someone has already checked that the value is strictly positive. +//! These functions compute the integer logarithm of their type, assuming +//! that someone has already checked that the value is strictly positive. // 0 < val <= u8::MAX #[inline] diff --git a/library/core/src/num/mod.rs b/library/core/src/num/mod.rs index faa41ddf13c..acfe38b7a37 100644 --- a/library/core/src/num/mod.rs +++ b/library/core/src/num/mod.rs @@ -1378,7 +1378,8 @@ const fn from_ascii_radix_panic(radix: u32) -> ! { macro_rules! from_str_int_impl { ($signedness:ident $($int_ty:ty)+) => {$( #[stable(feature = "rust1", since = "1.0.0")] - impl FromStr for $int_ty { + #[rustc_const_unstable(feature = "const_try", issue = "74935")] + impl const FromStr for $int_ty { type Err = ParseIntError; /// Parses an integer from a string slice with decimal digits. diff --git a/library/core/src/num/nonzero.rs b/library/core/src/num/nonzero.rs index b8900c4113a..f793602de50 100644 --- a/library/core/src/num/nonzero.rs +++ b/library/core/src/num/nonzero.rs @@ -297,7 +297,8 @@ where } #[stable(feature = "from_nonzero", since = "1.31.0")] -impl<T> From<NonZero<T>> for T +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl<T> const From<NonZero<T>> for T where T: ZeroablePrimitive, { diff --git a/library/core/src/num/uint_macros.rs b/library/core/src/num/uint_macros.rs index ab6823249c3..584cd60fbe5 100644 --- a/library/core/src/num/uint_macros.rs +++ b/library/core/src/num/uint_macros.rs @@ -556,7 +556,7 @@ macro_rules! uint_impl { pub const fn strict_add(self, rhs: Self) -> Self { let (a, b) = self.overflowing_add(rhs); if b { overflow_panic::add() } else { a } - } + } /// Unchecked integer addition. Computes `self + rhs`, assuming overflow /// cannot occur. @@ -653,7 +653,7 @@ macro_rules! uint_impl { pub const fn strict_add_signed(self, rhs: $SignedT) -> Self { let (a, b) = self.overflowing_add_signed(rhs); if b { overflow_panic::add() } else { a } - } + } /// Checked integer subtraction. Computes `self - rhs`, returning /// `None` if overflow occurred. @@ -713,7 +713,7 @@ macro_rules! uint_impl { pub const fn strict_sub(self, rhs: Self) -> Self { let (a, b) = self.overflowing_sub(rhs); if b { overflow_panic::sub() } else { a } - } + } /// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow /// cannot occur. @@ -805,6 +805,43 @@ macro_rules! uint_impl { } } + /// Strict subtraction with a signed integer. Computes `self - rhs`, + /// panicking if overflow occurred. + /// + /// # Panics + /// + /// ## Overflow behavior + /// + /// This function will always panic on overflow, regardless of whether overflow checks are enabled. + /// + /// # Examples + /// + /// ``` + /// #![feature(strict_overflow_ops)] + #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".strict_sub_signed(2), 1);")] + /// ``` + /// + /// The following panic because of overflow: + /// + /// ```should_panic + /// #![feature(strict_overflow_ops)] + #[doc = concat!("let _ = 1", stringify!($SelfT), ".strict_sub_signed(2);")] + /// ``` + /// + /// ```should_panic + /// #![feature(strict_overflow_ops)] + #[doc = concat!("let _ = (", stringify!($SelfT), "::MAX).strict_sub_signed(-1);")] + /// ``` + #[unstable(feature = "strict_overflow_ops", issue = "118260")] + #[must_use = "this returns the result of the operation, \ + without modifying the original"] + #[inline] + #[track_caller] + pub const fn strict_sub_signed(self, rhs: $SignedT) -> Self { + let (a, b) = self.overflowing_sub_signed(rhs); + if b { overflow_panic::sub() } else { a } + } + #[doc = concat!( "Checked integer subtraction. Computes `self - rhs` and checks if the result fits into an [`", stringify!($SignedT), "`], returning `None` if overflow occurred." @@ -913,7 +950,7 @@ macro_rules! uint_impl { pub const fn strict_mul(self, rhs: Self) -> Self { let (a, b) = self.overflowing_mul(rhs); if b { overflow_panic::mul() } else { a } - } + } /// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow /// cannot occur. diff --git a/library/core/src/ops/try_trait.rs b/library/core/src/ops/try_trait.rs index aebbddb4f1c..a889c824be5 100644 --- a/library/core/src/ops/try_trait.rs +++ b/library/core/src/ops/try_trait.rs @@ -128,7 +128,9 @@ use crate::ops::ControlFlow; )] #[doc(alias = "?")] #[lang = "Try"] -pub trait Try: FromResidual { +#[const_trait] +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +pub trait Try: ~const FromResidual { /// The type of the value produced by `?` when *not* short-circuiting. #[unstable(feature = "try_trait_v2", issue = "84277", old_name = "try_trait")] type Output; @@ -304,6 +306,8 @@ pub trait Try: FromResidual { )] #[rustc_diagnostic_item = "FromResidual"] #[unstable(feature = "try_trait_v2", issue = "84277", old_name = "try_trait")] +#[const_trait] +#[rustc_const_unstable(feature = "const_try", issue = "74935")] pub trait FromResidual<R = <Self as Try>::Residual> { /// Constructs the type from a compatible `Residual` type. /// @@ -357,6 +361,8 @@ where /// and in the other direction, /// `<Result<Infallible, E> as Residual<T>>::TryType = Result<T, E>`. #[unstable(feature = "try_trait_v2_residual", issue = "91285")] +#[const_trait] +#[rustc_const_unstable(feature = "const_try", issue = "74935")] pub trait Residual<O> { /// The "return" type of this meta-function. #[unstable(feature = "try_trait_v2_residual", issue = "91285")] diff --git a/library/core/src/option.rs b/library/core/src/option.rs index 8036c59e893..ed070fbd227 100644 --- a/library/core/src/option.rs +++ b/library/core/src/option.rs @@ -842,7 +842,7 @@ impl<T> Option<T> { // just needs to be aligned, which it is because `&self` is aligned and // the offset used is a multiple of alignment. // - // In the new version, the intrinsic always returns a pointer to an + // Here we assume that `offset_of!` always returns an offset to an // in-bounds and correctly aligned position for a `T` (even if in the // `None` case it's just padding). unsafe { @@ -2144,9 +2144,12 @@ const fn expect_failed(msg: &str) -> ! { ///////////////////////////////////////////////////////////////////////////// #[stable(feature = "rust1", since = "1.0.0")] -impl<T> Clone for Option<T> +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl<T> const Clone for Option<T> where - T: Clone, + // FIXME(const_hack): the T: ~const Destruct should be inferred from the Self: ~const Destruct in clone_from. + // See https://github.com/rust-lang/rust/issues/144207 + T: ~const Clone + ~const Destruct, { #[inline] fn clone(&self) -> Self { @@ -2230,7 +2233,8 @@ impl<'a, T> IntoIterator for &'a mut Option<T> { } #[stable(since = "1.12.0", feature = "option_from")] -impl<T> From<T> for Option<T> { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl<T> const From<T> for Option<T> { /// Moves `val` into a new [`Some`]. /// /// # Examples @@ -2246,7 +2250,8 @@ impl<T> From<T> for Option<T> { } #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")] -impl<'a, T> From<&'a Option<T>> for Option<&'a T> { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl<'a, T> const From<&'a Option<T>> for Option<&'a T> { /// Converts from `&Option<T>` to `Option<&T>`. /// /// # Examples @@ -2273,7 +2278,8 @@ impl<'a, T> From<&'a Option<T>> for Option<&'a T> { } #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")] -impl<'a, T> From<&'a mut Option<T>> for Option<&'a mut T> { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl<'a, T> const From<&'a mut Option<T>> for Option<&'a mut T> { /// Converts from `&mut Option<T>` to `Option<&mut T>` /// /// # Examples @@ -2593,7 +2599,8 @@ impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> { } #[unstable(feature = "try_trait_v2", issue = "84277", old_name = "try_trait")] -impl<T> ops::Try for Option<T> { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl<T> const ops::Try for Option<T> { type Output = T; type Residual = Option<convert::Infallible>; @@ -2612,9 +2619,10 @@ impl<T> ops::Try for Option<T> { } #[unstable(feature = "try_trait_v2", issue = "84277", old_name = "try_trait")] +#[rustc_const_unstable(feature = "const_try", issue = "74935")] // Note: manually specifying the residual type instead of using the default to work around // https://github.com/rust-lang/rust/issues/99940 -impl<T> ops::FromResidual<Option<convert::Infallible>> for Option<T> { +impl<T> const ops::FromResidual<Option<convert::Infallible>> for Option<T> { #[inline] fn from_residual(residual: Option<convert::Infallible>) -> Self { match residual { @@ -2625,7 +2633,8 @@ impl<T> ops::FromResidual<Option<convert::Infallible>> for Option<T> { #[diagnostic::do_not_recommend] #[unstable(feature = "try_trait_v2_yeet", issue = "96374")] -impl<T> ops::FromResidual<ops::Yeet<()>> for Option<T> { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl<T> const ops::FromResidual<ops::Yeet<()>> for Option<T> { #[inline] fn from_residual(ops::Yeet(()): ops::Yeet<()>) -> Self { None @@ -2633,7 +2642,8 @@ impl<T> ops::FromResidual<ops::Yeet<()>> for Option<T> { } #[unstable(feature = "try_trait_v2_residual", issue = "91285")] -impl<T> ops::Residual<T> for Option<convert::Infallible> { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl<T> const ops::Residual<T> for Option<convert::Infallible> { type TryType = Option<T>; } diff --git a/library/core/src/primitive_docs.rs b/library/core/src/primitive_docs.rs index 5bd80149a1d..9a1ba7d1728 100644 --- a/library/core/src/primitive_docs.rs +++ b/library/core/src/primitive_docs.rs @@ -1363,7 +1363,6 @@ mod prim_f16 {} /// x = a + b + c + d; // As written /// x = (a + c) + (b + d); // Reordered to shorten critical path and enable vectorization /// ``` - #[stable(feature = "rust1", since = "1.0.0")] mod prim_f32 {} diff --git a/library/core/src/ptr/alignment.rs b/library/core/src/ptr/alignment.rs index 6d473a4bd56..bd5b4e21baa 100644 --- a/library/core/src/ptr/alignment.rs +++ b/library/core/src/ptr/alignment.rs @@ -189,7 +189,8 @@ impl TryFrom<usize> for Alignment { } #[unstable(feature = "ptr_alignment_type", issue = "102070")] -impl From<Alignment> for NonZero<usize> { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl const From<Alignment> for NonZero<usize> { #[inline] fn from(align: Alignment) -> NonZero<usize> { align.as_nonzero() @@ -197,7 +198,8 @@ impl From<Alignment> for NonZero<usize> { } #[unstable(feature = "ptr_alignment_type", issue = "102070")] -impl From<Alignment> for usize { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl const From<Alignment> for usize { #[inline] fn from(align: Alignment) -> usize { align.as_usize() diff --git a/library/core/src/ptr/docs/as_uninit_slice.md b/library/core/src/ptr/docs/as_uninit_slice.md index c80c0405883..1113f4748c2 100644 --- a/library/core/src/ptr/docs/as_uninit_slice.md +++ b/library/core/src/ptr/docs/as_uninit_slice.md @@ -10,24 +10,24 @@ When calling this method, you have to ensure that *either* the pointer is null * all of the following is true: * The pointer must be [valid] for reads for `ptr.len() * size_of::<T>()` many bytes, -and it must be properly aligned. This means in particular: + and it must be properly aligned. This means in particular: * The entire memory range of this slice must be contained within a single [allocation]! -Slices can never span across multiple allocations. + Slices can never span across multiple allocations. * The pointer must be aligned even for zero-length slices. One -reason for this is that enum layout optimizations may rely on references -(including slices of any length) being aligned and non-null to distinguish -them from other data. You can obtain a pointer that is usable as `data` -for zero-length slices using [`NonNull::dangling()`]. + reason for this is that enum layout optimizations may rely on references + (including slices of any length) being aligned and non-null to distinguish + them from other data. You can obtain a pointer that is usable as `data` + for zero-length slices using [`NonNull::dangling()`]. * The total size `ptr.len() * size_of::<T>()` of the slice must be no larger than `isize::MAX`. -See the safety documentation of [`pointer::offset`]. + See the safety documentation of [`pointer::offset`]. * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is -arbitrarily chosen and does not necessarily reflect the actual lifetime of the data. -In particular, while this reference exists, the memory the pointer points to must -not get mutated (except inside `UnsafeCell`). + arbitrarily chosen and does not necessarily reflect the actual lifetime of the data. + In particular, while this reference exists, the memory the pointer points to must + not get mutated (except inside `UnsafeCell`). This applies even if the result of this method is unused! diff --git a/library/core/src/ptr/mod.rs b/library/core/src/ptr/mod.rs index fe8c6f83034..dbe3999b4a4 100644 --- a/library/core/src/ptr/mod.rs +++ b/library/core/src/ptr/mod.rs @@ -28,7 +28,8 @@ //! undefined behavior to perform two concurrent accesses to the same location from different //! threads unless both accesses only read from memory. Notice that this explicitly //! includes [`read_volatile`] and [`write_volatile`]: Volatile accesses cannot -//! be used for inter-thread synchronization. +//! be used for inter-thread synchronization, regardless of whether they are acting on +//! Rust memory or not. //! * The result of casting a reference to a pointer is valid for as long as the //! underlying allocation is live and no reference (just raw pointers) is used to //! access the same memory. That is, reference and pointer accesses cannot be @@ -114,6 +115,10 @@ //! fully contiguous (i.e., has no "holes"), there is no guarantee that this //! will not change in the future. //! +//! Allocations must behave like "normal" memory: in particular, reads must not have +//! side-effects, and writes must become visible to other threads using the usual synchronization +//! primitives. +//! //! For any allocation with `base` address, `size`, and a set of //! `addresses`, the following are guaranteed: //! - For all addresses `a` in `addresses`, `a` is in the range `base .. (base + @@ -2021,54 +2026,61 @@ pub const unsafe fn write_unaligned<T>(dst: *mut T, src: T) { } } -/// Performs a volatile read of the value from `src` without moving it. This -/// leaves the memory in `src` unchanged. -/// -/// Volatile operations are intended to act on I/O memory, and are guaranteed -/// to not be elided or reordered by the compiler across other volatile -/// operations. -/// -/// # Notes -/// -/// Rust does not currently have a rigorously and formally defined memory model, -/// so the precise semantics of what "volatile" means here is subject to change -/// over time. That being said, the semantics will almost always end up pretty -/// similar to [C11's definition of volatile][c11]. -/// -/// The compiler shouldn't change the relative order or number of volatile -/// memory operations. However, volatile memory operations on zero-sized types -/// (e.g., if a zero-sized type is passed to `read_volatile`) are noops -/// and may be ignored. -/// -/// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf +/// Performs a volatile read of the value from `src` without moving it. +/// +/// Volatile operations are intended to act on I/O memory. As such, they are considered externally +/// observable events (just like syscalls, but less opaque), and are guaranteed to not be elided or +/// reordered by the compiler across other externally observable events. With this in mind, there +/// are two cases of usage that need to be distinguished: +/// +/// - When a volatile operation is used for memory inside an [allocation], it behaves exactly like +/// [`read`], except for the additional guarantee that it won't be elided or reordered (see +/// above). This implies that the operation will actually access memory and not e.g. be lowered to +/// reusing data from a previous read. Other than that, all the usual rules for memory accesses +/// apply (including provenance). In particular, just like in C, whether an operation is volatile +/// has no bearing whatsoever on questions involving concurrent accesses from multiple threads. +/// Volatile accesses behave exactly like non-atomic accesses in that regard. +/// +/// - Volatile operations, however, may also be used to access memory that is _outside_ of any Rust +/// allocation. In this use-case, the pointer does *not* have to be [valid] for reads. This is +/// typically used for CPU and peripheral registers that must be accessed via an I/O memory +/// mapping, most commonly at fixed addresses reserved by the hardware. These often have special +/// semantics associated to their manipulation, and cannot be used as general purpose memory. +/// Here, any address value is possible, including 0 and [`usize::MAX`], so long as the semantics +/// of such a read are well-defined by the target hardware. The provenance of the pointer is +/// irrelevant, and it can be created with [`without_provenance`]. The access must not trap. It +/// can cause side-effects, but those must not affect Rust-allocated memory in any way. This +/// access is still not considered [atomic], and as such it cannot be used for inter-thread +/// synchronization. +/// +/// Note that volatile memory operations where T is a zero-sized type are noops and may be ignored. +/// +/// [allocation]: crate::ptr#allocated-object +/// [atomic]: crate::sync::atomic#memory-model-for-atomic-accesses /// /// # Safety /// +/// Like [`read`], `read_volatile` creates a bitwise copy of `T`, regardless of whether `T` is +/// [`Copy`]. If `T` is not [`Copy`], using both the returned value and the value at `*src` can +/// [violate memory safety][read-ownership]. However, storing non-[`Copy`] types in volatile memory +/// is almost certainly incorrect. +/// /// Behavior is undefined if any of the following conditions are violated: /// -/// * `src` must be [valid] for reads. +/// * `src` must be either [valid] for reads, or it must point to memory outside of all Rust +/// allocations and reading from that memory must: +/// - not trap, and +/// - not cause any memory inside a Rust allocation to be modified. /// /// * `src` must be properly aligned. /// -/// * `src` must point to a properly initialized value of type `T`. -/// -/// Like [`read`], `read_volatile` creates a bitwise copy of `T`, regardless of -/// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the returned -/// value and the value at `*src` can [violate memory safety][read-ownership]. -/// However, storing non-[`Copy`] types in volatile memory is almost certainly -/// incorrect. +/// * Reading from `src` must produce a properly initialized value of type `T`. /// /// Note that even if `T` has size `0`, the pointer must be properly aligned. /// /// [valid]: self#safety /// [read-ownership]: read#ownership-of-the-returned-value /// -/// Just like in C, whether an operation is volatile has no bearing whatsoever -/// on questions involving concurrent access from multiple threads. Volatile -/// accesses behave exactly like non-atomic accesses in that regard. In particular, -/// a race between a `read_volatile` and any write operation to the same location -/// is undefined behavior. -/// /// # Examples /// /// Basic usage: @@ -2090,50 +2102,63 @@ pub unsafe fn read_volatile<T>(src: *const T) -> T { unsafe { ub_checks::assert_unsafe_precondition!( check_language_ub, - "ptr::read_volatile requires that the pointer argument is aligned and non-null", + "ptr::read_volatile requires that the pointer argument is aligned", ( addr: *const () = src as *const (), align: usize = align_of::<T>(), - is_zst: bool = T::IS_ZST, - ) => ub_checks::maybe_is_aligned_and_not_null(addr, align, is_zst) + ) => ub_checks::maybe_is_aligned(addr, align) ); intrinsics::volatile_load(src) } } -/// Performs a volatile write of a memory location with the given value without -/// reading or dropping the old value. -/// -/// Volatile operations are intended to act on I/O memory, and are guaranteed -/// to not be elided or reordered by the compiler across other volatile -/// operations. -/// -/// `write_volatile` does not drop the contents of `dst`. This is safe, but it -/// could leak allocations or resources, so care should be taken not to overwrite -/// an object that should be dropped. -/// -/// Additionally, it does not drop `src`. Semantically, `src` is moved into the -/// location pointed to by `dst`. -/// -/// # Notes -/// -/// Rust does not currently have a rigorously and formally defined memory model, -/// so the precise semantics of what "volatile" means here is subject to change -/// over time. That being said, the semantics will almost always end up pretty -/// similar to [C11's definition of volatile][c11]. -/// -/// The compiler shouldn't change the relative order or number of volatile -/// memory operations. However, volatile memory operations on zero-sized types -/// (e.g., if a zero-sized type is passed to `write_volatile`) are noops -/// and may be ignored. -/// -/// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf +/// Performs a volatile write of a memory location with the given value without reading or dropping +/// the old value. +/// +/// Volatile operations are intended to act on I/O memory. As such, they are considered externally +/// observable events (just like syscalls), and are guaranteed to not be elided or reordered by the +/// compiler across other externally observable events. With this in mind, there are two cases of +/// usage that need to be distinguished: +/// +/// - When a volatile operation is used for memory inside an [allocation], it behaves exactly like +/// [`write`][write()], except for the additional guarantee that it won't be elided or reordered +/// (see above). This implies that the operation will actually access memory and not e.g. be +/// lowered to a register access. Other than that, all the usual rules for memory accesses apply +/// (including provenance). In particular, just like in C, whether an operation is volatile has no +/// bearing whatsoever on questions involving concurrent access from multiple threads. Volatile +/// accesses behave exactly like non-atomic accesses in that regard. +/// +/// - Volatile operations, however, may also be used to access memory that is _outside_ of any Rust +/// allocation. In this use-case, the pointer does *not* have to be [valid] for writes. This is +/// typically used for CPU and peripheral registers that must be accessed via an I/O memory +/// mapping, most commonly at fixed addresses reserved by the hardware. These often have special +/// semantics associated to their manipulation, and cannot be used as general purpose memory. +/// Here, any address value is possible, including 0 and [`usize::MAX`], so long as the semantics +/// of such a write are well-defined by the target hardware. The provenance of the pointer is +/// irrelevant, and it can be created with [`without_provenance`]. The access must not trap. It +/// can cause side-effects, but those must not affect Rust-allocated memory in any way. This +/// access is still not considered [atomic], and as such it cannot be used for inter-thread +/// synchronization. +/// +/// Note that volatile memory operations on zero-sized types (e.g., if a zero-sized type is passed +/// to `write_volatile`) are noops and may be ignored. +/// +/// `write_volatile` does not drop the contents of `dst`. This is safe, but it could leak +/// allocations or resources, so care should be taken not to overwrite an object that should be +/// dropped when operating on Rust memory. Additionally, it does not drop `src`. Semantically, `src` +/// is moved into the location pointed to by `dst`. +/// +/// [allocation]: crate::ptr#allocated-object +/// [atomic]: crate::sync::atomic#memory-model-for-atomic-accesses /// /// # Safety /// /// Behavior is undefined if any of the following conditions are violated: /// -/// * `dst` must be [valid] for writes. +/// * `dst` must be either [valid] for writes, or it must point to memory outside of all Rust +/// allocations and writing to that memory must: +/// - not trap, and +/// - not cause any memory inside a Rust allocation to be modified. /// /// * `dst` must be properly aligned. /// @@ -2141,12 +2166,6 @@ pub unsafe fn read_volatile<T>(src: *const T) -> T { /// /// [valid]: self#safety /// -/// Just like in C, whether an operation is volatile has no bearing whatsoever -/// on questions involving concurrent access from multiple threads. Volatile -/// accesses behave exactly like non-atomic accesses in that regard. In particular, -/// a race between a `write_volatile` and any other operation (reading or writing) -/// on the same location is undefined behavior. -/// /// # Examples /// /// Basic usage: @@ -2170,12 +2189,11 @@ pub unsafe fn write_volatile<T>(dst: *mut T, src: T) { unsafe { ub_checks::assert_unsafe_precondition!( check_language_ub, - "ptr::write_volatile requires that the pointer argument is aligned and non-null", + "ptr::write_volatile requires that the pointer argument is aligned", ( addr: *mut () = dst as *mut (), align: usize = align_of::<T>(), - is_zst: bool = T::IS_ZST, - ) => ub_checks::maybe_is_aligned_and_not_null(addr, align, is_zst) + ) => ub_checks::maybe_is_aligned(addr, align) ); intrinsics::volatile_store(dst, src); } diff --git a/library/core/src/result.rs b/library/core/src/result.rs index 7f3f2964985..f65257ff59b 100644 --- a/library/core/src/result.rs +++ b/library/core/src/result.rs @@ -1288,9 +1288,11 @@ impl<T, E> Result<T, E> { /// ``` #[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")] #[inline] - pub fn into_ok(self) -> T + #[rustc_allow_const_fn_unstable(const_precise_live_drops)] + #[rustc_const_unstable(feature = "const_try", issue = "74935")] + pub const fn into_ok(self) -> T where - E: Into<!>, + E: ~const Into<!>, { match self { Ok(x) => x, @@ -1323,9 +1325,11 @@ impl<T, E> Result<T, E> { /// ``` #[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")] #[inline] - pub fn into_err(self) -> E + #[rustc_allow_const_fn_unstable(const_precise_live_drops)] + #[rustc_const_unstable(feature = "const_try", issue = "74935")] + pub const fn into_err(self) -> E where - T: Into<!>, + T: ~const Into<!>, { match self { Ok(x) => x.into(), @@ -2052,7 +2056,8 @@ impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> { } #[unstable(feature = "try_trait_v2", issue = "84277", old_name = "try_trait")] -impl<T, E> ops::Try for Result<T, E> { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl<T, E> const ops::Try for Result<T, E> { type Output = T; type Residual = Result<convert::Infallible, E>; @@ -2071,7 +2076,10 @@ impl<T, E> ops::Try for Result<T, E> { } #[unstable(feature = "try_trait_v2", issue = "84277", old_name = "try_trait")] -impl<T, E, F: From<E>> ops::FromResidual<Result<convert::Infallible, E>> for Result<T, F> { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl<T, E, F: ~const From<E>> const ops::FromResidual<Result<convert::Infallible, E>> + for Result<T, F> +{ #[inline] #[track_caller] fn from_residual(residual: Result<convert::Infallible, E>) -> Self { @@ -2082,7 +2090,8 @@ impl<T, E, F: From<E>> ops::FromResidual<Result<convert::Infallible, E>> for Res } #[diagnostic::do_not_recommend] #[unstable(feature = "try_trait_v2_yeet", issue = "96374")] -impl<T, E, F: From<E>> ops::FromResidual<ops::Yeet<E>> for Result<T, F> { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl<T, E, F: ~const From<E>> const ops::FromResidual<ops::Yeet<E>> for Result<T, F> { #[inline] fn from_residual(ops::Yeet(e): ops::Yeet<E>) -> Self { Err(From::from(e)) @@ -2090,6 +2099,7 @@ impl<T, E, F: From<E>> ops::FromResidual<ops::Yeet<E>> for Result<T, F> { } #[unstable(feature = "try_trait_v2_residual", issue = "91285")] -impl<T, E> ops::Residual<T> for Result<convert::Infallible, E> { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl<T, E> const ops::Residual<T> for Result<convert::Infallible, E> { type TryType = Result<T, E>; } diff --git a/library/core/src/slice/mod.rs b/library/core/src/slice/mod.rs index 32419024db9..6fe5affc48b 100644 --- a/library/core/src/slice/mod.rs +++ b/library/core/src/slice/mod.rs @@ -971,7 +971,7 @@ impl<T> [T] { /// assert!(v == [3, 2, 1]); /// ``` #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_slice_reverse", issue = "135120")] + #[rustc_const_stable(feature = "const_slice_reverse", since = "CURRENT_RUSTC_VERSION")] #[inline] pub const fn reverse(&mut self) { let half_len = self.len() / 2; @@ -1004,6 +1004,7 @@ impl<T> [T] { // this check tells LLVM that the indexing below is // in-bounds. Then after inlining -- once the actual // lengths of the slices are known -- it's removed. + // FIXME(const_trait_impl) replace with let (a, b) = (&mut a[..n], &mut b[..n]); let (a, _) = a.split_at_mut(n); let (b, _) = b.split_at_mut(n); diff --git a/library/core/src/str/mod.rs b/library/core/src/str/mod.rs index 18a516c0f60..029abf17539 100644 --- a/library/core/src/str/mod.rs +++ b/library/core/src/str/mod.rs @@ -2651,7 +2651,6 @@ impl str { /// you're trying to parse into. /// /// `parse` can parse into any type that implements the [`FromStr`] trait. - /// /// # Errors /// diff --git a/library/core/src/str/traits.rs b/library/core/src/str/traits.rs index d0f2b9226bf..1597d1c1fa8 100644 --- a/library/core/src/str/traits.rs +++ b/library/core/src/str/traits.rs @@ -825,6 +825,8 @@ unsafe impl const SliceIndex<str> for ops::RangeToInclusive<usize> { /// assert!(Point::from_str("(1 2)").is_err()); /// ``` #[stable(feature = "rust1", since = "1.0.0")] +#[const_trait] +#[rustc_const_unstable(feature = "const_try", issue = "74935")] pub trait FromStr: Sized { /// The associated error which can be returned from parsing. #[stable(feature = "rust1", since = "1.0.0")] diff --git a/library/core/src/sync/atomic.rs b/library/core/src/sync/atomic.rs index 04c8d1473b0..546f3d91a80 100644 --- a/library/core/src/sync/atomic.rs +++ b/library/core/src/sync/atomic.rs @@ -2518,7 +2518,8 @@ impl<T> AtomicPtr<T> { #[cfg(target_has_atomic_load_store = "8")] #[stable(feature = "atomic_bool_from", since = "1.24.0")] -impl From<bool> for AtomicBool { +#[rustc_const_unstable(feature = "const_try", issue = "74935")] +impl const From<bool> for AtomicBool { /// Converts a `bool` into an `AtomicBool`. /// /// # Examples @@ -2615,7 +2616,8 @@ macro_rules! atomic_int { } #[$stable_from] - impl From<$int_type> for $atomic_type { + #[rustc_const_unstable(feature = "const_try", issue = "74935")] + impl const From<$int_type> for $atomic_type { #[doc = concat!("Converts an `", stringify!($int_type), "` into an `", stringify!($atomic_type), "`.")] #[inline] fn from(v: $int_type) -> Self { Self::new(v) } diff --git a/library/core/src/ub_checks.rs b/library/core/src/ub_checks.rs index a7caaeb95cd..b809294cfce 100644 --- a/library/core/src/ub_checks.rs +++ b/library/core/src/ub_checks.rs @@ -121,12 +121,24 @@ pub(crate) const fn maybe_is_aligned_and_not_null( is_zst: bool, ) -> bool { // This is just for safety checks so we can const_eval_select. + maybe_is_aligned(ptr, align) && (is_zst || !ptr.is_null()) +} + +/// Checks whether `ptr` is properly aligned with respect to the given alignment. +/// +/// In `const` this is approximate and can fail spuriously. It is primarily intended +/// for `assert_unsafe_precondition!` with `check_language_ub`, in which case the +/// check is anyway not executed in `const`. +#[inline] +#[rustc_allow_const_fn_unstable(const_eval_select)] +pub(crate) const fn maybe_is_aligned(ptr: *const (), align: usize) -> bool { + // This is just for safety checks so we can const_eval_select. const_eval_select!( - @capture { ptr: *const (), align: usize, is_zst: bool } -> bool: + @capture { ptr: *const (), align: usize } -> bool: if const { - is_zst || !ptr.is_null() + true } else { - ptr.is_aligned_to(align) && (is_zst || !ptr.is_null()) + ptr.is_aligned_to(align) } ) } diff --git a/library/coretests/tests/iter/adapters/cloned.rs b/library/coretests/tests/iter/adapters/cloned.rs index 78babb7feab..0a3dd1ce46e 100644 --- a/library/coretests/tests/iter/adapters/cloned.rs +++ b/library/coretests/tests/iter/adapters/cloned.rs @@ -31,7 +31,8 @@ fn test_cloned_side_effects() { .zip(&[1]); for _ in iter {} } - assert_eq!(count, 2); + // Zip documentation provides some leeway about side-effects + assert!([1, 2].iter().any(|v| *v == count)); } #[test] diff --git a/library/coretests/tests/iter/adapters/zip.rs b/library/coretests/tests/iter/adapters/zip.rs index 70392dca0fa..063e226a61c 100644 --- a/library/coretests/tests/iter/adapters/zip.rs +++ b/library/coretests/tests/iter/adapters/zip.rs @@ -107,9 +107,19 @@ fn test_zip_next_back_side_effects_exhausted() { iter.next(); iter.next(); iter.next(); - iter.next(); + assert_eq!(iter.next(), None); assert_eq!(iter.next_back(), None); - assert_eq!(a, vec![1, 2, 3, 4, 6, 5]); + + assert!(a.starts_with(&[1, 2, 3])); + let a_len = a.len(); + // Tail-side-effects of forward-iteration are "at most one" per next(). + // And for reverse iteration we don't guarantee much either. + // But we can put some bounds on the possible behaviors. + assert!(a_len <= 6); + assert!(a_len >= 3); + a.sort(); + assert_eq!(a, &[1, 2, 3, 4, 5, 6][..a.len()]); + assert_eq!(b, vec![200, 300, 400]); } @@ -120,7 +130,8 @@ fn test_zip_cloned_sideffectful() { for _ in xs.iter().cloned().zip(ys.iter().cloned()) {} - assert_eq!(&xs, &[1, 1, 1, 0][..]); + // Zip documentation permits either case. + assert!([&[1, 1, 1, 0], &[1, 1, 0, 0]].iter().any(|v| &xs == *v)); assert_eq!(&ys, &[1, 1][..]); let xs = [CountClone::new(), CountClone::new()]; @@ -139,7 +150,8 @@ fn test_zip_map_sideffectful() { for _ in xs.iter_mut().map(|x| *x += 1).zip(ys.iter_mut().map(|y| *y += 1)) {} - assert_eq!(&xs, &[1, 1, 1, 1, 1, 0]); + // Zip documentation permits either case. + assert!([&[1, 1, 1, 1, 1, 0], &[1, 1, 1, 1, 0, 0]].iter().any(|v| &xs == *v)); assert_eq!(&ys, &[1, 1, 1, 1]); let mut xs = [0; 4]; @@ -168,7 +180,8 @@ fn test_zip_map_rev_sideffectful() { { let mut it = xs.iter_mut().map(|x| *x += 1).zip(ys.iter_mut().map(|y| *y += 1)); - (&mut it).take(5).count(); + // the current impl only trims the tails if the iterator isn't exhausted + (&mut it).take(3).count(); it.next_back(); } assert_eq!(&xs, &[1, 1, 1, 1, 1, 1]); @@ -211,9 +224,18 @@ fn test_zip_nth_back_side_effects_exhausted() { iter.next(); iter.next(); iter.next(); - iter.next(); + assert_eq!(iter.next(), None); assert_eq!(iter.nth_back(0), None); - assert_eq!(a, vec![1, 2, 3, 4, 6, 5]); + assert!(a.starts_with(&[1, 2, 3])); + let a_len = a.len(); + // Tail-side-effects of forward-iteration are "at most one" per next(). + // And for reverse iteration we don't guarantee much either. + // But we can put some bounds on the possible behaviors. + assert!(a_len <= 6); + assert!(a_len >= 3); + a.sort(); + assert_eq!(a, &[1, 2, 3, 4, 5, 6][..a.len()]); + assert_eq!(b, vec![200, 300, 400]); } @@ -238,32 +260,6 @@ fn test_zip_trusted_random_access_composition() { } #[test] -#[cfg(panic = "unwind")] -fn test_zip_trusted_random_access_next_back_drop() { - use std::panic::{AssertUnwindSafe, catch_unwind}; - - let mut counter = 0; - - let it = [42].iter().map(|e| { - let c = counter; - counter += 1; - if c == 0 { - panic!("bomb"); - } - - e - }); - let it2 = [(); 0].iter(); - let mut zip = it.zip(it2); - catch_unwind(AssertUnwindSafe(|| { - zip.next_back(); - })) - .unwrap_err(); - assert!(zip.next().is_none()); - assert_eq!(counter, 1); -} - -#[test] fn test_double_ended_zip() { let xs = [1, 2, 3, 4, 5, 6]; let ys = [1, 2, 3, 7]; @@ -276,6 +272,63 @@ fn test_double_ended_zip() { } #[test] +#[cfg(panic = "unwind")] +/// Regression test for #137255 +/// A previous implementation of Zip TrustedRandomAccess specializations tried to do a lot of work +/// to preserve side-effects of equalizing the iterator lengths during backwards iteration. +/// This lead to several cases of unsoundness, twice due to being left in an inconsistent state +/// after panics. +/// The new implementation does not try as hard, but we still need panic-safety. +fn test_nested_zip_panic_safety() { + use std::panic::{AssertUnwindSafe, catch_unwind, resume_unwind}; + use std::sync::atomic::{AtomicUsize, Ordering}; + + let mut panic = true; + // keeps track of how often element get visited, must be at most once each + let witness = [8, 9, 10, 11, 12].map(|i| (i, AtomicUsize::new(0))); + let a = witness.as_slice().iter().map(|e| { + e.1.fetch_add(1, Ordering::Relaxed); + if panic { + panic = false; + resume_unwind(Box::new(())) + } + e.0 + }); + // shorter than `a`, so `a` will get trimmed + let b = [1, 2, 3, 4].as_slice().iter().copied(); + // shorter still, so `ab` will get trimmed.` + let c = [5, 6, 7].as_slice().iter().copied(); + + // This will panic during backwards trimming. + let ab = zip(a, b); + // This being Zip + TrustedRandomAccess means it will only call `next_back`` + // during trimming and otherwise do calls `__iterator_get_unchecked` on `ab`. + let mut abc = zip(ab, c); + + assert_eq!(abc.len(), 3); + // This will first trigger backwards trimming before it would normally obtain the + // actual element if it weren't for the panic. + // This used to corrupt the internal state of `abc`, which then lead to + // TrustedRandomAccess safety contract violations in calls to `ab`, + // which ultimately lead to UB. + catch_unwind(AssertUnwindSafe(|| abc.next_back())).ok(); + // check for sane outward behavior after the panic, which indicates a sane internal state. + // Technically these outcomes are not required because a panic frees us from correctness obligations. + assert_eq!(abc.len(), 2); + assert_eq!(abc.next(), Some(((8, 1), 5))); + assert_eq!(abc.next_back(), Some(((9, 2), 6))); + for (i, (_, w)) in witness.iter().enumerate() { + let v = w.load(Ordering::Relaxed); + // required by TRA contract + assert!(v <= 1, "expected idx {i} to be visited at most once, actual: {v}"); + } + // Trimming panicked and should only run once, so this one won't be visited. + // Implementation detail, but not trying to run it again is what keeps + // things simple. + assert_eq!(witness[3].1.load(Ordering::Relaxed), 0); +} + +#[test] fn test_issue_82282() { fn overflowed_zip(arr: &[i32]) -> impl Iterator<Item = (i32, &())> { static UNIT_EMPTY_ARR: [(); 0] = []; diff --git a/library/coretests/tests/lib.rs b/library/coretests/tests/lib.rs index e2249bd7f6a..4cfac9ecc2a 100644 --- a/library/coretests/tests/lib.rs +++ b/library/coretests/tests/lib.rs @@ -19,7 +19,6 @@ #![feature(const_deref)] #![feature(const_destruct)] #![feature(const_eval_select)] -#![feature(const_float_round_methods)] #![feature(const_ops)] #![feature(const_ref_cell)] #![feature(const_trait_impl)] diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index 311b2cb9323..323742a75b0 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -329,7 +329,6 @@ #![feature(bstr_internals)] #![feature(char_internals)] #![feature(clone_to_uninit)] -#![feature(const_float_round_methods)] #![feature(core_intrinsics)] #![feature(core_io_borrowed_buf)] #![feature(duration_constants)] diff --git a/library/std/src/num/f32.rs b/library/std/src/num/f32.rs index e79ec2ae966..2bff73add33 100644 --- a/library/std/src/num/f32.rs +++ b/library/std/src/num/f32.rs @@ -44,7 +44,7 @@ impl f32 { #[rustc_allow_incoherent_impl] #[must_use = "method returns a new number and does not mutate the original value"] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] + #[rustc_const_stable(feature = "const_float_round_methods", since = "CURRENT_RUSTC_VERSION")] #[inline] pub const fn floor(self) -> f32 { core::f32::math::floor(self) @@ -67,7 +67,7 @@ impl f32 { #[rustc_allow_incoherent_impl] #[must_use = "method returns a new number and does not mutate the original value"] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] + #[rustc_const_stable(feature = "const_float_round_methods", since = "CURRENT_RUSTC_VERSION")] #[inline] pub const fn ceil(self) -> f32 { core::f32::math::ceil(self) @@ -96,7 +96,7 @@ impl f32 { #[rustc_allow_incoherent_impl] #[must_use = "method returns a new number and does not mutate the original value"] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] + #[rustc_const_stable(feature = "const_float_round_methods", since = "CURRENT_RUSTC_VERSION")] #[inline] pub const fn round(self) -> f32 { core::f32::math::round(self) @@ -123,7 +123,7 @@ impl f32 { #[rustc_allow_incoherent_impl] #[must_use = "method returns a new number and does not mutate the original value"] #[stable(feature = "round_ties_even", since = "1.77.0")] - #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] + #[rustc_const_stable(feature = "const_float_round_methods", since = "CURRENT_RUSTC_VERSION")] #[inline] pub const fn round_ties_even(self) -> f32 { core::f32::math::round_ties_even(self) @@ -149,7 +149,7 @@ impl f32 { #[rustc_allow_incoherent_impl] #[must_use = "method returns a new number and does not mutate the original value"] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] + #[rustc_const_stable(feature = "const_float_round_methods", since = "CURRENT_RUSTC_VERSION")] #[inline] pub const fn trunc(self) -> f32 { core::f32::math::trunc(self) @@ -173,7 +173,7 @@ impl f32 { #[rustc_allow_incoherent_impl] #[must_use = "method returns a new number and does not mutate the original value"] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] + #[rustc_const_stable(feature = "const_float_round_methods", since = "CURRENT_RUSTC_VERSION")] #[inline] pub const fn fract(self) -> f32 { core::f32::math::fract(self) diff --git a/library/std/src/num/f64.rs b/library/std/src/num/f64.rs index 853417825f9..b71e319f407 100644 --- a/library/std/src/num/f64.rs +++ b/library/std/src/num/f64.rs @@ -44,7 +44,7 @@ impl f64 { #[rustc_allow_incoherent_impl] #[must_use = "method returns a new number and does not mutate the original value"] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] + #[rustc_const_stable(feature = "const_float_round_methods", since = "CURRENT_RUSTC_VERSION")] #[inline] pub const fn floor(self) -> f64 { core::f64::math::floor(self) @@ -67,7 +67,7 @@ impl f64 { #[rustc_allow_incoherent_impl] #[must_use = "method returns a new number and does not mutate the original value"] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] + #[rustc_const_stable(feature = "const_float_round_methods", since = "CURRENT_RUSTC_VERSION")] #[inline] pub const fn ceil(self) -> f64 { core::f64::math::ceil(self) @@ -96,7 +96,7 @@ impl f64 { #[rustc_allow_incoherent_impl] #[must_use = "method returns a new number and does not mutate the original value"] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] + #[rustc_const_stable(feature = "const_float_round_methods", since = "CURRENT_RUSTC_VERSION")] #[inline] pub const fn round(self) -> f64 { core::f64::math::round(self) @@ -123,7 +123,7 @@ impl f64 { #[rustc_allow_incoherent_impl] #[must_use = "method returns a new number and does not mutate the original value"] #[stable(feature = "round_ties_even", since = "1.77.0")] - #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] + #[rustc_const_stable(feature = "const_float_round_methods", since = "CURRENT_RUSTC_VERSION")] #[inline] pub const fn round_ties_even(self) -> f64 { core::f64::math::round_ties_even(self) @@ -149,7 +149,7 @@ impl f64 { #[rustc_allow_incoherent_impl] #[must_use = "method returns a new number and does not mutate the original value"] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] + #[rustc_const_stable(feature = "const_float_round_methods", since = "CURRENT_RUSTC_VERSION")] #[inline] pub const fn trunc(self) -> f64 { core::f64::math::trunc(self) @@ -173,7 +173,7 @@ impl f64 { #[rustc_allow_incoherent_impl] #[must_use = "method returns a new number and does not mutate the original value"] #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_float_round_methods", issue = "141555")] + #[rustc_const_stable(feature = "const_float_round_methods", since = "CURRENT_RUSTC_VERSION")] #[inline] pub const fn fract(self) -> f64 { core::f64::math::fract(self) diff --git a/src/bootstrap/README.md b/src/bootstrap/README.md index 6ce4c6d62fa..2965174b45b 100644 --- a/src/bootstrap/README.md +++ b/src/bootstrap/README.md @@ -105,7 +105,7 @@ build/ debuginfo/ ... - # Bootstrap host tools (which are always compiled with the stage0 compiler) + # Host tools (which are always compiled with the stage0 compiler) # are stored here. bootstrap-tools/ diff --git a/src/bootstrap/bootstrap.py b/src/bootstrap/bootstrap.py index d8c6be78247..40e08361a0f 100644 --- a/src/bootstrap/bootstrap.py +++ b/src/bootstrap/bootstrap.py @@ -8,6 +8,7 @@ import re import shutil import subprocess import sys +import sysconfig import tarfile import tempfile @@ -333,7 +334,11 @@ def default_build_triple(verbose): if ostype == "Android": kernel = "linux-android" else: - kernel = "unknown-linux-gnu" + python_soabi = sysconfig.get_config_var("SOABI") + if python_soabi is not None and "musl" in python_soabi: + kernel = "unknown-linux-musl" + else: + kernel = "unknown-linux-gnu" elif kernel == "SunOS": kernel = "pc-solaris" # On Solaris, uname -m will return a machine classification instead diff --git a/src/bootstrap/src/core/build_steps/check.rs b/src/bootstrap/src/core/build_steps/check.rs index 3278b55305c..cfe090b22dc 100644 --- a/src/bootstrap/src/core/build_steps/check.rs +++ b/src/bootstrap/src/core/build_steps/check.rs @@ -4,7 +4,10 @@ use crate::core::build_steps::compile::{ add_to_sysroot, run_cargo, rustc_cargo, rustc_cargo_env, std_cargo, std_crates_for_run_make, }; use crate::core::build_steps::tool; -use crate::core::build_steps::tool::{COMPILETEST_ALLOW_FEATURES, SourceType, prepare_tool_cargo}; +use crate::core::build_steps::tool::{ + COMPILETEST_ALLOW_FEATURES, SourceType, ToolTargetBuildMode, get_tool_target_compiler, + prepare_tool_cargo, +}; use crate::core::builder::{ self, Alias, Builder, Kind, RunConfig, ShouldRun, Step, StepMetadata, crate_description, }; @@ -252,8 +255,10 @@ fn prepare_compiler_for_check( mode: Mode, ) -> Compiler { let host = builder.host_target; + match mode { Mode::ToolBootstrap => builder.compiler(0, host), + Mode::ToolTarget => get_tool_target_compiler(builder, ToolTargetBuildMode::Build(target)), Mode::ToolStd => { if builder.config.compile_time_deps { // When --compile-time-deps is passed, we can't use any rustc @@ -350,7 +355,7 @@ impl Step for CodegenBackend { cargo .arg("--manifest-path") .arg(builder.src.join(format!("compiler/rustc_codegen_{backend}/Cargo.toml"))); - rustc_cargo_env(builder, &mut cargo, target, build_compiler.stage); + rustc_cargo_env(builder, &mut cargo, target); let _guard = builder.msg_check(format!("rustc_codegen_{backend}"), target, None); @@ -365,132 +370,18 @@ impl Step for CodegenBackend { } } -/// Checks Rust analyzer that links to .rmetas from a checked rustc. -#[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub struct RustAnalyzer { - pub build_compiler: Compiler, - pub target: TargetSelection, -} - -impl Step for RustAnalyzer { - type Output = (); - const ONLY_HOSTS: bool = true; - const DEFAULT: bool = true; - - fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { - let builder = run.builder; - run.path("src/tools/rust-analyzer").default_condition( - builder - .config - .tools - .as_ref() - .is_none_or(|tools| tools.iter().any(|tool| tool == "rust-analyzer")), - ) - } - - fn make_run(run: RunConfig<'_>) { - let build_compiler = prepare_compiler_for_check(run.builder, run.target, Mode::ToolRustc); - run.builder.ensure(RustAnalyzer { build_compiler, target: run.target }); - } - - fn run(self, builder: &Builder<'_>) { - let build_compiler = self.build_compiler; - let target = self.target; - - let mut cargo = prepare_tool_cargo( - builder, - build_compiler, - Mode::ToolRustc, - target, - builder.kind, - "src/tools/rust-analyzer", - SourceType::InTree, - &["in-rust-tree".to_owned()], - ); - - cargo.allow_features(crate::core::build_steps::tool::RustAnalyzer::ALLOW_FEATURES); - - cargo.arg("--bins"); - cargo.arg("--tests"); - cargo.arg("--benches"); - - // Cargo's output path in a given stage, compiled by a particular - // compiler for the specified target. - let stamp = BuildStamp::new(&builder.cargo_out(build_compiler, Mode::ToolRustc, target)) - .with_prefix("rust-analyzer-check"); - - let _guard = builder.msg_check("rust-analyzer artifacts", target, None); - run_cargo(builder, cargo, builder.config.free_args.clone(), &stamp, vec![], true, false); - } - - fn metadata(&self) -> Option<StepMetadata> { - Some(StepMetadata::check("rust-analyzer", self.target).built_by(self.build_compiler)) - } -} - -/// Compiletest is implicitly "checked" when it gets built in order to run tests, -/// so this is mainly for people working on compiletest to run locally. -#[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub struct Compiletest { - pub target: TargetSelection, -} - -impl Step for Compiletest { - type Output = (); - const ONLY_HOSTS: bool = true; - const DEFAULT: bool = false; - - fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { - run.path("src/tools/compiletest") - } - - fn make_run(run: RunConfig<'_>) { - run.builder.ensure(Compiletest { target: run.target }); - } - - fn run(self, builder: &Builder<'_>) { - let mode = if builder.config.compiletest_use_stage0_libtest { - Mode::ToolBootstrap - } else { - Mode::ToolStd - }; - let build_compiler = prepare_compiler_for_check(builder, self.target, mode); - - let mut cargo = prepare_tool_cargo( - builder, - build_compiler, - mode, - self.target, - builder.kind, - "src/tools/compiletest", - SourceType::InTree, - &[], - ); - - cargo.allow_features(COMPILETEST_ALLOW_FEATURES); - - cargo.arg("--all-targets"); - - let stamp = BuildStamp::new(&builder.cargo_out(build_compiler, mode, self.target)) - .with_prefix("compiletest-check"); - - let _guard = builder.msg_check("compiletest artifacts", self.target, None); - run_cargo(builder, cargo, builder.config.free_args.clone(), &stamp, vec![], true, false); - } - - fn metadata(&self) -> Option<StepMetadata> { - Some(StepMetadata::check("compiletest", self.target)) - } -} - macro_rules! tool_check_step { ( $name:ident { // The part of this path after the final '/' is also used as a display name. path: $path:literal $(, alt_path: $alt_path:literal )* - , mode: $mode:path + // Closure that returns `Mode` based on the passed `&Builder<'_>` + , mode: $mode:expr + // Subset of nightly features that are allowed to be used when checking $(, allow_features: $allow_features:expr )? + // Features that should be enabled when checking + $(, enable_features: [$($enable_features:expr),*] )? $(, default: $default:literal )? $( , )? } @@ -513,10 +404,13 @@ macro_rules! tool_check_step { fn make_run(run: RunConfig<'_>) { let target = run.target; - let build_compiler = prepare_compiler_for_check(run.builder, target, $mode); + let builder = run.builder; + let mode = $mode(builder); + + let build_compiler = prepare_compiler_for_check(run.builder, target, mode); // It doesn't make sense to cross-check bootstrap tools - if $mode == Mode::ToolBootstrap && target != run.builder.host_target { + if mode == Mode::ToolBootstrap && target != run.builder.host_target { println!("WARNING: not checking bootstrap tool {} for target {target} as it is a bootstrap (host-only) tool", stringify!($path)); return; }; @@ -531,7 +425,9 @@ macro_rules! tool_check_step { $( _value = $allow_features; )? _value }; - run_tool_check_step(builder, build_compiler, target, $path, $mode, allow_features); + let extra_features: &[&str] = &[$($($enable_features),*)?]; + let mode = $mode(builder); + run_tool_check_step(builder, build_compiler, target, $path, mode, allow_features, extra_features); } fn metadata(&self) -> Option<StepMetadata> { @@ -549,9 +445,11 @@ fn run_tool_check_step( path: &str, mode: Mode, allow_features: &str, + extra_features: &[&str], ) { let display_name = path.rsplit('/').next().unwrap(); + let extra_features = extra_features.iter().map(|f| f.to_string()).collect::<Vec<String>>(); let mut cargo = prepare_tool_cargo( builder, build_compiler, @@ -564,12 +462,19 @@ fn run_tool_check_step( // steps should probably be marked non-default so that the default // checks aren't affected by toolstate being broken. SourceType::InTree, - &[], + &extra_features, ); cargo.allow_features(allow_features); - // FIXME: check bootstrap doesn't currently work with --all-targets - cargo.arg("--all-targets"); + // FIXME: check bootstrap doesn't currently work when multiple targets are checked + // FIXME: rust-analyzer does not work with --all-targets + if display_name == "rust-analyzer" { + cargo.arg("--bins"); + cargo.arg("--tests"); + cargo.arg("--benches"); + } else { + cargo.arg("--all-targets"); + } let stamp = BuildStamp::new(&builder.cargo_out(build_compiler, mode, target)) .with_prefix(&format!("{display_name}-check")); @@ -588,43 +493,66 @@ fn run_tool_check_step( tool_check_step!(Rustdoc { path: "src/tools/rustdoc", alt_path: "src/librustdoc", - mode: Mode::ToolRustc + mode: |_builder| Mode::ToolRustc }); // Clippy, miri and Rustfmt are hybrids. They are external tools, but use a git subtree instead // of a submodule. Since the SourceType only drives the deny-warnings // behavior, treat it as in-tree so that any new warnings in clippy will be // rejected. -tool_check_step!(Clippy { path: "src/tools/clippy", mode: Mode::ToolRustc }); -tool_check_step!(Miri { path: "src/tools/miri", mode: Mode::ToolRustc }); -tool_check_step!(CargoMiri { path: "src/tools/miri/cargo-miri", mode: Mode::ToolRustc }); -tool_check_step!(Rustfmt { path: "src/tools/rustfmt", mode: Mode::ToolRustc }); +tool_check_step!(Clippy { path: "src/tools/clippy", mode: |_builder| Mode::ToolRustc }); +tool_check_step!(Miri { path: "src/tools/miri", mode: |_builder| Mode::ToolRustc }); +tool_check_step!(CargoMiri { path: "src/tools/miri/cargo-miri", mode: |_builder| Mode::ToolRustc }); +tool_check_step!(Rustfmt { path: "src/tools/rustfmt", mode: |_builder| Mode::ToolRustc }); +tool_check_step!(RustAnalyzer { + path: "src/tools/rust-analyzer", + mode: |_builder| Mode::ToolRustc, + allow_features: tool::RustAnalyzer::ALLOW_FEATURES, + enable_features: ["in-rust-tree"], +}); tool_check_step!(MiroptTestTools { path: "src/tools/miropt-test-tools", - mode: Mode::ToolBootstrap + mode: |_builder| Mode::ToolBootstrap }); // We want to test the local std tool_check_step!(TestFloatParse { path: "src/tools/test-float-parse", - mode: Mode::ToolStd, + mode: |_builder| Mode::ToolStd, allow_features: tool::TestFloatParse::ALLOW_FEATURES }); tool_check_step!(FeaturesStatusDump { path: "src/tools/features-status-dump", - mode: Mode::ToolBootstrap + mode: |_builder| Mode::ToolBootstrap }); -tool_check_step!(Bootstrap { path: "src/bootstrap", mode: Mode::ToolBootstrap, default: false }); +tool_check_step!(Bootstrap { + path: "src/bootstrap", + mode: |_builder| Mode::ToolBootstrap, + default: false +}); // `run-make-support` will be built as part of suitable run-make compiletest test steps, but support // check to make it easier to work on. tool_check_step!(RunMakeSupport { path: "src/tools/run-make-support", - mode: Mode::ToolBootstrap, + mode: |_builder| Mode::ToolBootstrap, default: false }); tool_check_step!(CoverageDump { path: "src/tools/coverage-dump", - mode: Mode::ToolBootstrap, + mode: |_builder| Mode::ToolBootstrap, default: false }); + +// Compiletest is implicitly "checked" when it gets built in order to run tests, +// so this is mainly for people working on compiletest to run locally. +tool_check_step!(Compiletest { + path: "src/tools/compiletest", + mode: |builder: &Builder<'_>| if builder.config.compiletest_use_stage0_libtest { + Mode::ToolBootstrap + } else { + Mode::ToolStd + }, + allow_features: COMPILETEST_ALLOW_FEATURES, + default: false, +}); diff --git a/src/bootstrap/src/core/build_steps/compile.rs b/src/bootstrap/src/core/build_steps/compile.rs index 09bb2e35bda..c7e7b0160b1 100644 --- a/src/bootstrap/src/core/build_steps/compile.rs +++ b/src/bootstrap/src/core/build_steps/compile.rs @@ -19,7 +19,7 @@ use serde_derive::Deserialize; use tracing::{instrument, span}; use crate::core::build_steps::gcc::{Gcc, add_cg_gcc_cargo_flags}; -use crate::core::build_steps::tool::SourceType; +use crate::core::build_steps::tool::{SourceType, copy_lld_artifacts}; use crate::core::build_steps::{dist, llvm}; use crate::core::builder; use crate::core::builder::{ @@ -1316,15 +1316,10 @@ pub fn rustc_cargo( cargo.env("RUSTC_WRAPPER", ccache); } - rustc_cargo_env(builder, cargo, target, build_compiler.stage); + rustc_cargo_env(builder, cargo, target); } -pub fn rustc_cargo_env( - builder: &Builder<'_>, - cargo: &mut Cargo, - target: TargetSelection, - build_stage: u32, -) { +pub fn rustc_cargo_env(builder: &Builder<'_>, cargo: &mut Cargo, target: TargetSelection) { // Set some configuration variables picked up by build scripts and // the compiler alike cargo @@ -1379,18 +1374,24 @@ pub fn rustc_cargo_env( cargo.rustflag("--cfg=llvm_enzyme"); } - // Note that this is disabled if LLVM itself is disabled or we're in a check - // build. If we are in a check build we still go ahead here presuming we've - // detected that LLVM is already built and good to go which helps prevent - // busting caches (e.g. like #71152). + // These conditionals represent a tension between three forces: + // - For non-check builds, we need to define some LLVM-related environment + // variables, requiring LLVM to have been built. + // - For check builds, we want to avoid building LLVM if possible. + // - Check builds and non-check builds should have the same environment if + // possible, to avoid unnecessary rebuilds due to cache-busting. + // + // Therefore we try to avoid building LLVM for check builds, but only if + // building LLVM would be expensive. If "building" LLVM is cheap + // (i.e. it's already built or is downloadable), we prefer to maintain a + // consistent environment between check and non-check builds. if builder.config.llvm_enabled(target) { - let building_is_expensive = + let building_llvm_is_expensive = crate::core::build_steps::llvm::prebuilt_llvm_config(builder, target, false) .should_build(); - // `top_stage == stage` might be false for `check --stage 1`, if we are building the stage 1 compiler - let can_skip_build = builder.kind == Kind::Check && builder.top_stage == build_stage; - let should_skip_build = building_is_expensive && can_skip_build; - if !should_skip_build { + + let skip_llvm = (builder.kind == Kind::Check) && building_llvm_is_expensive; + if !skip_llvm { rustc_llvm_env(builder, cargo, target) } } @@ -1407,6 +1408,9 @@ pub fn rustc_cargo_env( /// Pass down configuration from the LLVM build into the build of /// rustc_llvm and rustc_codegen_llvm. +/// +/// Note that this has the side-effect of _building LLVM_, which is sometimes +/// unwanted (e.g. for check builds). fn rustc_llvm_env(builder: &Builder<'_>, cargo: &mut Cargo, target: TargetSelection) { if builder.config.is_rust_llvm(target) { cargo.env("LLVM_RUSTLLVM", "1"); @@ -1665,7 +1669,7 @@ impl Step for CodegenBackend { cargo .arg("--manifest-path") .arg(builder.src.join(format!("compiler/rustc_codegen_{backend}/Cargo.toml"))); - rustc_cargo_env(builder, &mut cargo, target, compiler.stage); + rustc_cargo_env(builder, &mut cargo, target); // Ideally, we'd have a separate step for the individual codegen backends, // like we have in tests (test::CodegenGCC) but that would require a lot of restructuring. @@ -2050,19 +2054,20 @@ impl Step for Assemble { } } - let maybe_install_llvm_bitcode_linker = |compiler| { + let maybe_install_llvm_bitcode_linker = || { if builder.config.llvm_bitcode_linker_enabled { trace!("llvm-bitcode-linker enabled, installing"); - let llvm_bitcode_linker = - builder.ensure(crate::core::build_steps::tool::LlvmBitcodeLinker { - build_compiler: compiler, - target: target_compiler.host, - }); + let llvm_bitcode_linker = builder.ensure( + crate::core::build_steps::tool::LlvmBitcodeLinker::from_target_compiler( + builder, + target_compiler, + ), + ); // Copy the llvm-bitcode-linker to the self-contained binary directory let bindir_self_contained = builder - .sysroot(compiler) - .join(format!("lib/rustlib/{}/bin/self-contained", compiler.host)); + .sysroot(target_compiler) + .join(format!("lib/rustlib/{}/bin/self-contained", target_compiler.host)); let tool_exe = exe("llvm-bitcode-linker", target_compiler.host); t!(fs::create_dir_all(&bindir_self_contained)); @@ -2089,9 +2094,9 @@ impl Step for Assemble { builder.info(&format!("Creating a sysroot for stage{stage} compiler (use `rustup toolchain link 'name' build/host/stage{stage}`)", stage = target_compiler.stage)); } - let mut precompiled_compiler = target_compiler; - precompiled_compiler.forced_compiler(true); - maybe_install_llvm_bitcode_linker(precompiled_compiler); + // FIXME: this is incomplete, we do not copy a bunch of other stuff to the downloaded + // sysroot... + maybe_install_llvm_bitcode_linker(); return target_compiler; } @@ -2256,10 +2261,12 @@ impl Step for Assemble { copy_codegen_backends_to_sysroot(builder, build_compiler, target_compiler); if builder.config.lld_enabled { - builder.ensure(crate::core::build_steps::tool::LldWrapper { - build_compiler, - target_compiler, - }); + let lld_wrapper = + builder.ensure(crate::core::build_steps::tool::LldWrapper::for_use_by_compiler( + builder, + target_compiler, + )); + copy_lld_artifacts(builder, lld_wrapper, target_compiler); } if builder.config.llvm_enabled(target_compiler.host) && builder.config.llvm_tools_enabled { @@ -2284,15 +2291,14 @@ impl Step for Assemble { } // In addition to `rust-lld` also install `wasm-component-ld` when - // LLD is enabled. This is a relatively small binary that primarily - // delegates to the `rust-lld` binary for linking and then runs - // logic to create the final binary. This is used by the - // `wasm32-wasip2` target of Rust. + // is enabled. This is used by the `wasm32-wasip2` target of Rust. if builder.tool_enabled("wasm-component-ld") { - let wasm_component = builder.ensure(crate::core::build_steps::tool::WasmComponentLd { - compiler: build_compiler, - target: target_compiler.host, - }); + let wasm_component = builder.ensure( + crate::core::build_steps::tool::WasmComponentLd::for_use_by_compiler( + builder, + target_compiler, + ), + ); builder.copy_link( &wasm_component.tool_path, &libdir_bin.join(wasm_component.tool_path.file_name().unwrap()), @@ -2300,7 +2306,7 @@ impl Step for Assemble { ); } - maybe_install_llvm_bitcode_linker(target_compiler); + maybe_install_llvm_bitcode_linker(); // Ensure that `libLLVM.so` ends up in the newly build compiler directory, // so that it can be found when the newly built `rustc` is run. diff --git a/src/bootstrap/src/core/build_steps/dist.rs b/src/bootstrap/src/core/build_steps/dist.rs index 8b2d65ace50..39e4fb2ac01 100644 --- a/src/bootstrap/src/core/build_steps/dist.rs +++ b/src/bootstrap/src/core/build_steps/dist.rs @@ -1575,7 +1575,10 @@ impl Step for Extended { compiler: builder.compiler(stage, target), backend: "cranelift".to_string(), }); - add_component!("llvm-bitcode-linker" => LlvmBitcodeLinker {compiler, target}); + add_component!("llvm-bitcode-linker" => LlvmBitcodeLinker { + build_compiler: compiler, + target + }); let etc = builder.src.join("src/etc/installer"); @@ -2341,9 +2344,13 @@ impl Step for LlvmTools { } } +/// Distributes the `llvm-bitcode-linker` tool so that it can be used by a compiler whose host +/// is `target`. #[derive(Debug, PartialOrd, Ord, Clone, Hash, PartialEq, Eq)] pub struct LlvmBitcodeLinker { - pub compiler: Compiler, + /// The linker will be compiled by this compiler. + pub build_compiler: Compiler, + /// The linker will by usable by rustc on this host. pub target: TargetSelection, } @@ -2359,9 +2366,8 @@ impl Step for LlvmBitcodeLinker { fn make_run(run: RunConfig<'_>) { run.builder.ensure(LlvmBitcodeLinker { - compiler: run.builder.compiler_for( - run.builder.top_stage, - run.builder.config.host_target, + build_compiler: tool::LlvmBitcodeLinker::get_build_compiler_for_target( + run.builder, run.target, ), target: run.target, @@ -2369,13 +2375,10 @@ impl Step for LlvmBitcodeLinker { } fn run(self, builder: &Builder<'_>) -> Option<GeneratedTarball> { - let compiler = self.compiler; let target = self.target; - builder.ensure(compile::Rustc::new(compiler, target)); - - let llbc_linker = - builder.ensure(tool::LlvmBitcodeLinker { build_compiler: compiler, target }); + let llbc_linker = builder + .ensure(tool::LlvmBitcodeLinker::from_build_compiler(self.build_compiler, target)); let self_contained_bin_dir = format!("lib/rustlib/{}/bin/self-contained", target.triple); diff --git a/src/bootstrap/src/core/build_steps/install.rs b/src/bootstrap/src/core/build_steps/install.rs index 4434d6658eb..4156b49a8b3 100644 --- a/src/bootstrap/src/core/build_steps/install.rs +++ b/src/bootstrap/src/core/build_steps/install.rs @@ -287,7 +287,7 @@ install!((self, builder, _config), } }; LlvmBitcodeLinker, alias = "llvm-bitcode-linker", Self::should_build(_config), only_hosts: true, { - if let Some(tarball) = builder.ensure(dist::LlvmBitcodeLinker { compiler: self.compiler, target: self.target }) { + if let Some(tarball) = builder.ensure(dist::LlvmBitcodeLinker { build_compiler: self.compiler, target: self.target }) { install_sh(builder, "llvm-bitcode-linker", self.compiler.stage, Some(self.target), &tarball); } else { builder.info( diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs index 9e7ea5c115f..7652ea1a488 100644 --- a/src/bootstrap/src/core/build_steps/test.rs +++ b/src/bootstrap/src/core/build_steps/test.rs @@ -1757,6 +1757,10 @@ NOTE: if you're sure you want to do this, please open an issue as to why. In the cmd.arg("--host").arg(&*compiler.host.triple); cmd.arg("--llvm-filecheck").arg(builder.llvm_filecheck(builder.config.host_target)); + if let Some(codegen_backend) = builder.config.default_codegen_backend(compiler.host) { + cmd.arg("--codegen-backend").arg(&codegen_backend); + } + if builder.build.config.llvm_enzyme { cmd.arg("--has-enzyme"); } @@ -1810,7 +1814,24 @@ NOTE: if you're sure you want to do this, please open an issue as to why. In the } let mut flags = if is_rustdoc { Vec::new() } else { vec!["-Crpath".to_string()] }; - flags.push(format!("-Cdebuginfo={}", builder.config.rust_debuginfo_level_tests)); + flags.push(format!( + "-Cdebuginfo={}", + if suite == "codegen" { + // codegen tests typically check LLVM IR and are sensitive to additional debuginfo. + // So do not apply `rust.debuginfo-level-tests` for codegen tests. + if builder.config.rust_debuginfo_level_tests + != crate::core::config::DebuginfoLevel::None + { + println!( + "NOTE: ignoring `rust.debuginfo-level-tests={}` for codegen tests", + builder.config.rust_debuginfo_level_tests + ); + } + crate::core::config::DebuginfoLevel::None + } else { + builder.config.rust_debuginfo_level_tests + } + )); flags.extend(builder.config.cmd.compiletest_rustc_args().iter().map(|s| s.to_string())); if suite != "mir-opt" { @@ -2945,7 +2966,8 @@ impl Step for RemoteCopyLibs { builder.info(&format!("REMOTE copy libs to emulator ({target})")); - let remote_test_server = builder.ensure(tool::RemoteTestServer { compiler, target }); + let remote_test_server = + builder.ensure(tool::RemoteTestServer { build_compiler: compiler, target }); // Spawn the emulator and wait for it to come online let tool = builder.tool_exe(Tool::RemoteTestClient); @@ -3386,7 +3408,7 @@ impl Step for CodegenCranelift { cargo .arg("--manifest-path") .arg(builder.src.join("compiler/rustc_codegen_cranelift/build_system/Cargo.toml")); - compile::rustc_cargo_env(builder, &mut cargo, target, compiler.stage); + compile::rustc_cargo_env(builder, &mut cargo, target); // Avoid incremental cache issues when changing rustc cargo.env("CARGO_BUILD_INCREMENTAL", "false"); @@ -3518,7 +3540,7 @@ impl Step for CodegenGCC { cargo .arg("--manifest-path") .arg(builder.src.join("compiler/rustc_codegen_gcc/build_system/Cargo.toml")); - compile::rustc_cargo_env(builder, &mut cargo, target, compiler.stage); + compile::rustc_cargo_env(builder, &mut cargo, target); add_cg_gcc_cargo_flags(&mut cargo, &gcc); // Avoid incremental cache issues when changing rustc diff --git a/src/bootstrap/src/core/build_steps/tool.rs b/src/bootstrap/src/core/build_steps/tool.rs index 1c994b0ccfc..f5fa33b98f3 100644 --- a/src/bootstrap/src/core/build_steps/tool.rs +++ b/src/bootstrap/src/core/build_steps/tool.rs @@ -42,7 +42,8 @@ pub enum ToolArtifactKind { #[derive(Debug, Clone, Hash, PartialEq, Eq)] struct ToolBuild { - compiler: Compiler, + /// Compiler that will build this tool. + build_compiler: Compiler, target: TargetSelection, tool: &'static str, path: &'static str, @@ -112,34 +113,34 @@ impl Step for ToolBuild { let mut tool = self.tool; let path = self.path; - let target_compiler = self.compiler; - self.compiler = if self.mode == Mode::ToolRustc { - get_tool_rustc_compiler(builder, self.compiler) + let target_compiler = self.build_compiler; + self.build_compiler = if self.mode == Mode::ToolRustc { + get_tool_rustc_compiler(builder, self.build_compiler) } else { - self.compiler + self.build_compiler }; match self.mode { Mode::ToolRustc => { // If compiler was forced, its artifacts should have been prepared earlier. - if !self.compiler.is_forced_compiler() { - builder.std(self.compiler, self.compiler.host); - builder.ensure(compile::Rustc::new(self.compiler, target)); + if !self.build_compiler.is_forced_compiler() { + builder.std(self.build_compiler, self.build_compiler.host); + builder.ensure(compile::Rustc::new(self.build_compiler, target)); } } Mode::ToolStd => { // If compiler was forced, its artifacts should have been prepared earlier. - if !self.compiler.is_forced_compiler() { - builder.std(self.compiler, target) + if !self.build_compiler.is_forced_compiler() { + builder.std(self.build_compiler, target); } } - Mode::ToolBootstrap => {} // uses downloaded stage0 compiler libs + Mode::ToolBootstrap | Mode::ToolTarget => {} // uses downloaded stage0 compiler libs _ => panic!("unexpected Mode for tool build"), } let mut cargo = prepare_tool_cargo( builder, - self.compiler, + self.build_compiler, self.mode, target, Kind::Build, @@ -161,7 +162,7 @@ impl Step for ToolBuild { // Rustc tools (miri, clippy, cargo, rustfmt, rust-analyzer) // could use the additional optimizations. - if self.mode == Mode::ToolRustc && is_lto_stage(&self.compiler) { + if self.mode == Mode::ToolRustc && is_lto_stage(&self.build_compiler) { let lto = match builder.config.rust_lto { RustcLto::Off => Some("off"), RustcLto::Thin => Some("thin"), @@ -183,8 +184,9 @@ impl Step for ToolBuild { Kind::Build, self.mode, self.tool, - self.compiler.stage, - &self.compiler.host, + // A stage N tool is built with the stage N-1 compiler. + self.build_compiler.stage + 1, + &self.build_compiler.host, &self.target, ); @@ -207,14 +209,14 @@ impl Step for ToolBuild { } let tool_path = match self.artifact_kind { ToolArtifactKind::Binary => { - copy_link_tool_bin(builder, self.compiler, self.target, self.mode, tool) + copy_link_tool_bin(builder, self.build_compiler, self.target, self.mode, tool) } ToolArtifactKind::Library => builder - .cargo_out(self.compiler, self.mode, self.target) + .cargo_out(self.build_compiler, self.mode, self.target) .join(format!("lib{tool}.rlib")), }; - ToolBuildResult { tool_path, build_compiler: self.compiler, target_compiler } + ToolBuildResult { tool_path, build_compiler: self.build_compiler, target_compiler } } } } @@ -365,6 +367,47 @@ pub(crate) fn get_tool_rustc_compiler( builder.compiler(target_compiler.stage.saturating_sub(1), builder.config.host_target) } +/// Determines how to build a `ToolTarget`, i.e. which compiler should be used to compile it. +/// The compiler stage is automatically bumped if we need to cross-compile a stage 1 tool. +pub enum ToolTargetBuildMode { + /// Build the tool using rustc that corresponds to the selected CLI stage. + Build(TargetSelection), + /// Build the tool so that it can be attached to the sysroot of the passed compiler. + /// Since we always dist stage 2+, the compiler that builds the tool in this case has to be + /// stage 1+. + Dist(Compiler), +} + +/// Returns compiler that is able to compile a `ToolTarget` tool with the given `mode`. +pub(crate) fn get_tool_target_compiler( + builder: &Builder<'_>, + mode: ToolTargetBuildMode, +) -> Compiler { + let (target, build_compiler_stage) = match mode { + ToolTargetBuildMode::Build(target) => { + assert!(builder.top_stage > 0); + // If we want to build a stage N tool, we need to compile it with stage N-1 rustc + (target, builder.top_stage - 1) + } + ToolTargetBuildMode::Dist(target_compiler) => { + assert!(target_compiler.stage > 0); + // If we want to dist a stage N rustc, we want to attach stage N tool to it. + // And to build that tool, we need to compile it with stage N-1 rustc + (target_compiler.host, target_compiler.stage - 1) + } + }; + + let compiler = if builder.host_target == target { + builder.compiler(build_compiler_stage, builder.host_target) + } else { + // If we are cross-compiling a stage 1 tool, we cannot do that with a stage 0 compiler, + // so we auto-bump the tool's stage to 2, which means we need a stage 1 compiler. + builder.compiler(build_compiler_stage.max(1), builder.host_target) + }; + builder.std(compiler, target); + compiler +} + /// Links a built tool binary with the given `name` from the build directory to the /// tools directory. fn copy_link_tool_bin( @@ -451,7 +494,7 @@ macro_rules! bootstrap_tool { let compiletest_wants_stage0 = $tool_name == "compiletest" && builder.config.compiletest_use_stage0_libtest; builder.ensure(ToolBuild { - compiler: self.compiler, + build_compiler: self.compiler, target: self.target, tool: $tool_name, mode: if is_unstable && !compiletest_wants_stage0 { @@ -521,7 +564,6 @@ bootstrap_tool!( // rustdoc-gui-test has a crate dependency on compiletest, so it needs the same unstable features. RustdocGUITest, "src/tools/rustdoc-gui-test", "rustdoc-gui-test", is_unstable_tool = true, allow_features = COMPILETEST_ALLOW_FEATURES; CoverageDump, "src/tools/coverage-dump", "coverage-dump"; - WasmComponentLd, "src/tools/wasm-component-ld", "wasm-component-ld", is_unstable_tool = true, allow_features = "min_specialization"; UnicodeTableGenerator, "src/tools/unicode-table-generator", "unicode-table-generator"; FeaturesStatusDump, "src/tools/features-status-dump", "features-status-dump"; OptimizedDist, "src/tools/opt-dist", "opt-dist", submodules = &["src/tools/rustc-perf"]; @@ -560,7 +602,7 @@ impl Step for RustcPerf { builder.require_submodule("src/tools/rustc-perf", None); let tool = ToolBuild { - compiler: self.compiler, + build_compiler: self.compiler, target: self.target, tool: "collector", mode: Mode::ToolBootstrap, @@ -576,7 +618,7 @@ impl Step for RustcPerf { let res = builder.ensure(tool.clone()); // We also need to symlink the `rustc-fake` binary to the corresponding directory, // because `collector` expects it in the same directory. - copy_link_tool_bin(builder, tool.compiler, tool.target, tool.mode, "rustc-fake"); + copy_link_tool_bin(builder, tool.build_compiler, tool.target, tool.mode, "rustc-fake"); res } @@ -620,7 +662,7 @@ impl Step for ErrorIndex { fn run(self, builder: &Builder<'_>) -> ToolBuildResult { builder.ensure(ToolBuild { - compiler: self.compiler, + build_compiler: self.compiler, target: self.compiler.host, tool: "error_index_generator", mode: Mode::ToolRustc, @@ -636,7 +678,7 @@ impl Step for ErrorIndex { #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct RemoteTestServer { - pub compiler: Compiler, + pub build_compiler: Compiler, pub target: TargetSelection, } @@ -649,17 +691,20 @@ impl Step for RemoteTestServer { fn make_run(run: RunConfig<'_>) { run.builder.ensure(RemoteTestServer { - compiler: run.builder.compiler(run.builder.top_stage, run.builder.config.host_target), + build_compiler: get_tool_target_compiler( + run.builder, + ToolTargetBuildMode::Build(run.target), + ), target: run.target, }); } fn run(self, builder: &Builder<'_>) -> ToolBuildResult { builder.ensure(ToolBuild { - compiler: self.compiler, + build_compiler: self.build_compiler, target: self.target, tool: "remote-test-server", - mode: Mode::ToolStd, + mode: Mode::ToolTarget, path: "src/tools/remote-test-server", source_type: SourceType::InTree, extra_features: Vec::new(), @@ -668,6 +713,10 @@ impl Step for RemoteTestServer { artifact_kind: ToolArtifactKind::Binary, }) } + + fn metadata(&self) -> Option<StepMetadata> { + Some(StepMetadata::build("remote-test-server", self.target).built_by(self.build_compiler)) + } } #[derive(Debug, Clone, Hash, PartialEq, Eq, Ord, PartialOrd)] @@ -757,7 +806,7 @@ impl Step for Rustdoc { let ToolBuildResult { tool_path, build_compiler, target_compiler } = builder.ensure(ToolBuild { - compiler: target_compiler, + build_compiler: target_compiler, target, // Cargo adds a number of paths to the dylib search path on windows, which results in // the wrong rustdoc being executed. To avoid the conflicting rustdocs, we name the "tool" @@ -825,7 +874,7 @@ impl Step for Cargo { builder.build.require_submodule("src/tools/cargo", None); builder.ensure(ToolBuild { - compiler: self.compiler, + build_compiler: self.compiler, target: self.target, tool: "cargo", mode: Mode::ToolRustc, @@ -839,17 +888,50 @@ impl Step for Cargo { } } +/// Represents a built LldWrapper, the `lld-wrapper` tool itself, and a directory +/// containing a build of LLD. +#[derive(Clone)] +pub struct BuiltLldWrapper { + tool: ToolBuildResult, + lld_dir: PathBuf, +} + #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct LldWrapper { pub build_compiler: Compiler, - pub target_compiler: Compiler, + pub target: TargetSelection, +} + +impl LldWrapper { + /// Returns `LldWrapper` that should be **used** by the passed compiler. + pub fn for_use_by_compiler(builder: &Builder<'_>, target_compiler: Compiler) -> Self { + Self { + build_compiler: get_tool_target_compiler( + builder, + ToolTargetBuildMode::Dist(target_compiler), + ), + target: target_compiler.host, + } + } } impl Step for LldWrapper { - type Output = ToolBuildResult; + type Output = BuiltLldWrapper; + + const ONLY_HOSTS: bool = true; fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { - run.never() + run.path("src/tools/lld-wrapper") + } + + fn make_run(run: RunConfig<'_>) { + run.builder.ensure(LldWrapper { + build_compiler: get_tool_target_compiler( + run.builder, + ToolTargetBuildMode::Build(run.target), + ), + target: run.target, + }); } #[cfg_attr( @@ -858,25 +940,16 @@ impl Step for LldWrapper { level = "debug", name = "LldWrapper::run", skip_all, - fields(build_compiler = ?self.build_compiler, target_compiler = ?self.target_compiler), + fields(build_compiler = ?self.build_compiler), ), )] - fn run(self, builder: &Builder<'_>) -> ToolBuildResult { - if builder.config.dry_run() { - return ToolBuildResult { - tool_path: Default::default(), - build_compiler: self.build_compiler, - target_compiler: self.target_compiler, - }; - } - - let target = self.target_compiler.host; - - let tool_result = builder.ensure(ToolBuild { - compiler: self.build_compiler, - target, + fn run(self, builder: &Builder<'_>) -> Self::Output { + let lld_dir = builder.ensure(llvm::Lld { target: self.target }); + let tool = builder.ensure(ToolBuild { + build_compiler: self.build_compiler, + target: self.target, tool: "lld-wrapper", - mode: Mode::ToolStd, + mode: Mode::ToolTarget, path: "src/tools/lld-wrapper", source_type: SourceType::InTree, extra_features: Vec::new(), @@ -884,38 +957,110 @@ impl Step for LldWrapper { cargo_args: Vec::new(), artifact_kind: ToolArtifactKind::Binary, }); + BuiltLldWrapper { tool, lld_dir } + } - let libdir_bin = builder.sysroot_target_bindir(self.target_compiler, target); - t!(fs::create_dir_all(&libdir_bin)); + fn metadata(&self) -> Option<StepMetadata> { + Some(StepMetadata::build("LldWrapper", self.target).built_by(self.build_compiler)) + } +} - let lld_install = builder.ensure(llvm::Lld { target }); - let src_exe = exe("lld", target); - let dst_exe = exe("rust-lld", target); +pub(crate) fn copy_lld_artifacts( + builder: &Builder<'_>, + lld_wrapper: BuiltLldWrapper, + target_compiler: Compiler, +) { + let target = target_compiler.host; + let libdir_bin = builder.sysroot_target_bindir(target_compiler, target); + t!(fs::create_dir_all(&libdir_bin)); + + let src_exe = exe("lld", target); + let dst_exe = exe("rust-lld", target); + + builder.copy_link( + &lld_wrapper.lld_dir.join("bin").join(src_exe), + &libdir_bin.join(dst_exe), + FileType::Executable, + ); + let self_contained_lld_dir = libdir_bin.join("gcc-ld"); + t!(fs::create_dir_all(&self_contained_lld_dir)); + + for name in crate::LLD_FILE_NAMES { builder.copy_link( - &lld_install.join("bin").join(src_exe), - &libdir_bin.join(dst_exe), + &lld_wrapper.tool.tool_path, + &self_contained_lld_dir.join(exe(name, target)), FileType::Executable, ); - let self_contained_lld_dir = libdir_bin.join("gcc-ld"); - t!(fs::create_dir_all(&self_contained_lld_dir)); - - for name in crate::LLD_FILE_NAMES { - builder.copy_link( - &tool_result.tool_path, - &self_contained_lld_dir.join(exe(name, target)), - FileType::Executable, - ); + } +} + +/// Builds the `wasm-component-ld` linker wrapper, which is shipped with rustc to be executed on the +/// host platform where rustc runs. +#[derive(Debug, Clone, Hash, PartialEq, Eq)] +pub struct WasmComponentLd { + build_compiler: Compiler, + target: TargetSelection, +} + +impl WasmComponentLd { + /// Returns `WasmComponentLd` that should be **used** by the passed compiler. + pub fn for_use_by_compiler(builder: &Builder<'_>, target_compiler: Compiler) -> Self { + Self { + build_compiler: get_tool_target_compiler( + builder, + ToolTargetBuildMode::Dist(target_compiler), + ), + target: target_compiler.host, } + } +} + +impl Step for WasmComponentLd { + type Output = ToolBuildResult; + + const ONLY_HOSTS: bool = true; + + fn should_run(run: ShouldRun<'_>) -> ShouldRun<'_> { + run.path("src/tools/wasm-component-ld") + } + + fn make_run(run: RunConfig<'_>) { + run.builder.ensure(WasmComponentLd { + build_compiler: get_tool_target_compiler( + run.builder, + ToolTargetBuildMode::Build(run.target), + ), + target: run.target, + }); + } - tool_result + #[cfg_attr( + feature = "tracing", + instrument( + level = "debug", + name = "WasmComponentLd::run", + skip_all, + fields(build_compiler = ?self.build_compiler), + ), + )] + fn run(self, builder: &Builder<'_>) -> ToolBuildResult { + builder.ensure(ToolBuild { + build_compiler: self.build_compiler, + target: self.target, + tool: "wasm-component-ld", + mode: Mode::ToolTarget, + path: "src/tools/wasm-component-ld", + source_type: SourceType::InTree, + extra_features: vec![], + allow_features: "", + cargo_args: vec![], + artifact_kind: ToolArtifactKind::Binary, + }) } fn metadata(&self) -> Option<StepMetadata> { - Some( - StepMetadata::build("LldWrapper", self.target_compiler.host) - .built_by(self.build_compiler), - ) + Some(StepMetadata::build("WasmComponentLd", self.target).built_by(self.build_compiler)) } } @@ -948,7 +1093,7 @@ impl Step for RustAnalyzer { fn run(self, builder: &Builder<'_>) -> ToolBuildResult { builder.ensure(ToolBuild { - compiler: self.compiler, + build_compiler: self.compiler, target: self.target, tool: "rust-analyzer", mode: Mode::ToolRustc, @@ -993,7 +1138,7 @@ impl Step for RustAnalyzerProcMacroSrv { fn run(self, builder: &Builder<'_>) -> Option<ToolBuildResult> { let tool_result = builder.ensure(ToolBuild { - compiler: self.compiler, + build_compiler: self.compiler, target: self.target, tool: "rust-analyzer-proc-macro-srv", mode: Mode::ToolRustc, @@ -1021,8 +1166,35 @@ impl Step for RustAnalyzerProcMacroSrv { #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct LlvmBitcodeLinker { - pub build_compiler: Compiler, - pub target: TargetSelection, + build_compiler: Compiler, + target: TargetSelection, +} + +impl LlvmBitcodeLinker { + /// Returns `LlvmBitcodeLinker` that will be **compiled** by the passed compiler, for the given + /// `target`. + pub fn from_build_compiler(build_compiler: Compiler, target: TargetSelection) -> Self { + Self { build_compiler, target } + } + + /// Returns `LlvmBitcodeLinker` that should be **used** by the passed compiler. + pub fn from_target_compiler(builder: &Builder<'_>, target_compiler: Compiler) -> Self { + Self { + build_compiler: get_tool_target_compiler( + builder, + ToolTargetBuildMode::Dist(target_compiler), + ), + target: target_compiler.host, + } + } + + /// Return a compiler that is able to build this tool for the given `target`. + pub fn get_build_compiler_for_target( + builder: &Builder<'_>, + target: TargetSelection, + ) -> Compiler { + get_tool_target_compiler(builder, ToolTargetBuildMode::Build(target)) + } } impl Step for LlvmBitcodeLinker { @@ -1038,9 +1210,7 @@ impl Step for LlvmBitcodeLinker { fn make_run(run: RunConfig<'_>) { run.builder.ensure(LlvmBitcodeLinker { - build_compiler: run - .builder - .compiler(run.builder.top_stage, run.builder.config.host_target), + build_compiler: Self::get_build_compiler_for_target(run.builder, run.target), target: run.target, }); } @@ -1051,10 +1221,10 @@ impl Step for LlvmBitcodeLinker { )] fn run(self, builder: &Builder<'_>) -> ToolBuildResult { builder.ensure(ToolBuild { - compiler: self.build_compiler, + build_compiler: self.build_compiler, target: self.target, tool: "llvm-bitcode-linker", - mode: Mode::ToolRustc, + mode: Mode::ToolTarget, path: "src/tools/llvm-bitcode-linker", source_type: SourceType::InTree, extra_features: vec![], @@ -1239,7 +1409,7 @@ fn run_tool_build_step( let ToolBuildResult { tool_path, build_compiler, target_compiler } = builder.ensure(ToolBuild { - compiler, + build_compiler: compiler, target, tool: tool_name, mode: Mode::ToolRustc, @@ -1338,7 +1508,7 @@ impl Step for TestFloatParse { let compiler = builder.compiler(builder.top_stage, bootstrap_host); builder.ensure(ToolBuild { - compiler, + build_compiler: compiler, target: bootstrap_host, tool: "test-float-parse", mode: Mode::ToolStd, diff --git a/src/bootstrap/src/core/builder/cargo.rs b/src/bootstrap/src/core/builder/cargo.rs index a3b471ca56e..badd5f24dba 100644 --- a/src/bootstrap/src/core/builder/cargo.rs +++ b/src/bootstrap/src/core/builder/cargo.rs @@ -537,7 +537,7 @@ impl Builder<'_> { } } - let stage = if compiler.stage == 0 && self.local_rebuild { + let build_compiler_stage = if compiler.stage == 0 && self.local_rebuild { // Assume the local-rebuild rustc already has stage1 features. 1 } else { @@ -545,15 +545,17 @@ impl Builder<'_> { }; // We synthetically interpret a stage0 compiler used to build tools as a - // "raw" compiler in that it's the exact snapshot we download. Normally - // the stage0 build means it uses libraries build by the stage0 - // compiler, but for tools we just use the precompiled libraries that - // we've downloaded - let use_snapshot = mode == Mode::ToolBootstrap; - assert!(!use_snapshot || stage == 0 || self.local_rebuild); - - let maybe_sysroot = self.sysroot(compiler); - let sysroot = if use_snapshot { self.rustc_snapshot_sysroot() } else { &maybe_sysroot }; + // "raw" compiler in that it's the exact snapshot we download. For things like + // ToolRustc, we would have to use the artificial stage0-sysroot compiler instead. + let use_snapshot = + mode == Mode::ToolBootstrap || (mode == Mode::ToolTarget && build_compiler_stage == 0); + assert!(!use_snapshot || build_compiler_stage == 0 || self.local_rebuild); + + let sysroot = if use_snapshot { + self.rustc_snapshot_sysroot().to_path_buf() + } else { + self.sysroot(compiler) + }; let libdir = self.rustc_libdir(compiler); let sysroot_str = sysroot.as_os_str().to_str().expect("sysroot should be UTF-8"); @@ -562,7 +564,7 @@ impl Builder<'_> { } let mut rustflags = Rustflags::new(target); - if stage != 0 { + if build_compiler_stage != 0 { if let Ok(s) = env::var("CARGOFLAGS_NOT_BOOTSTRAP") { cargo.args(s.split_whitespace()); } @@ -604,7 +606,7 @@ impl Builder<'_> { // sysroot. Passing this cfg enables raw-dylib support instead, which makes the native // library unnecessary. This can be removed when windows-rs enables raw-dylib // unconditionally. - if let Mode::Rustc | Mode::ToolRustc | Mode::ToolBootstrap = mode { + if let Mode::Rustc | Mode::ToolRustc | Mode::ToolBootstrap | Mode::ToolTarget = mode { rustflags.arg("--cfg=windows_raw_dylib"); } @@ -657,7 +659,7 @@ impl Builder<'_> { // FIXME(rust-lang/cargo#5754) we shouldn't be using special command arguments // to the host invocation here, but rather Cargo should know what flags to pass rustc // itself. - if stage == 0 { + if build_compiler_stage == 0 { hostflags.arg("--cfg=bootstrap"); } @@ -666,7 +668,7 @@ impl Builder<'_> { // #71458. let mut rustdocflags = rustflags.clone(); rustdocflags.propagate_cargo_env("RUSTDOCFLAGS"); - if stage == 0 { + if build_compiler_stage == 0 { rustdocflags.env("RUSTDOCFLAGS_BOOTSTRAP"); } else { rustdocflags.env("RUSTDOCFLAGS_NOT_BOOTSTRAP"); @@ -677,7 +679,7 @@ impl Builder<'_> { } match mode { - Mode::Std | Mode::ToolBootstrap | Mode::ToolStd => {} + Mode::Std | Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolTarget => {} Mode::Rustc | Mode::Codegen | Mode::ToolRustc => { // Build proc macros both for the host and the target unless proc-macros are not // supported by the target. @@ -719,7 +721,7 @@ impl Builder<'_> { // feature on the rustc side. cargo.arg("-Zbinary-dep-depinfo"); let allow_features = match mode { - Mode::ToolBootstrap | Mode::ToolStd => { + Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolTarget => { // Restrict the allowed features so we don't depend on nightly // accidentally. // @@ -833,7 +835,7 @@ impl Builder<'_> { cargo .env("RUSTBUILD_NATIVE_DIR", self.native_dir(target)) .env("RUSTC_REAL", self.rustc(compiler)) - .env("RUSTC_STAGE", stage.to_string()) + .env("RUSTC_STAGE", build_compiler_stage.to_string()) .env("RUSTC_SYSROOT", sysroot) .env("RUSTC_LIBDIR", libdir) .env("RUSTDOC", self.bootstrap_out.join("rustdoc")) @@ -878,7 +880,7 @@ impl Builder<'_> { let debuginfo_level = match mode { Mode::Rustc | Mode::Codegen => self.config.rust_debuginfo_level_rustc, Mode::Std => self.config.rust_debuginfo_level_std, - Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolRustc => { + Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolRustc | Mode::ToolTarget => { self.config.rust_debuginfo_level_tools } }; @@ -890,11 +892,10 @@ impl Builder<'_> { profile_var("DEBUG_ASSERTIONS"), match mode { Mode::Std => self.config.std_debug_assertions, - Mode::Rustc => self.config.rustc_debug_assertions, - Mode::Codegen => self.config.rustc_debug_assertions, - Mode::ToolBootstrap => self.config.tools_debug_assertions, - Mode::ToolStd => self.config.tools_debug_assertions, - Mode::ToolRustc => self.config.tools_debug_assertions, + Mode::Rustc | Mode::Codegen => self.config.rustc_debug_assertions, + Mode::ToolBootstrap | Mode::ToolStd | Mode::ToolRustc | Mode::ToolTarget => { + self.config.tools_debug_assertions + } } .to_string(), ); @@ -965,7 +966,11 @@ impl Builder<'_> { cargo.env("CFG_VIRTUAL_RUSTC_DEV_SOURCE_BASE_DIR", map_to); } } - Mode::Std | Mode::ToolBootstrap | Mode::ToolRustc | Mode::ToolStd => { + Mode::Std + | Mode::ToolBootstrap + | Mode::ToolRustc + | Mode::ToolStd + | Mode::ToolTarget => { if let Some(ref map_to) = self.build.debuginfo_map_to(GitRepo::Rustc, RemapScheme::NonCompiler) { @@ -1280,7 +1285,7 @@ impl Builder<'_> { }; if let Some(limit) = limit - && (stage == 0 + && (build_compiler_stage == 0 || self.config.default_codegen_backend(target).unwrap_or_default() == "llvm") { rustflags.arg(&format!("-Cllvm-args=-import-instr-limit={limit}")); diff --git a/src/bootstrap/src/core/builder/mod.rs b/src/bootstrap/src/core/builder/mod.rs index 1b75d00b30e..d73e2bce25b 100644 --- a/src/bootstrap/src/core/builder/mod.rs +++ b/src/bootstrap/src/core/builder/mod.rs @@ -963,6 +963,7 @@ impl<'a> Builder<'a> { tool::RemoteTestServer, tool::RemoteTestClient, tool::RustInstaller, + tool::FeaturesStatusDump, tool::Cargo, tool::RustAnalyzer, tool::RustAnalyzerProcMacroSrv, @@ -984,6 +985,8 @@ impl<'a> Builder<'a> { tool::CoverageDump, tool::LlvmBitcodeLinker, tool::RustcPerf, + tool::WasmComponentLd, + tool::LldWrapper ), Kind::Clippy => describe!( clippy::Std, diff --git a/src/bootstrap/src/core/builder/tests.rs b/src/bootstrap/src/core/builder/tests.rs index 51a90649692..c025a8b15d0 100644 --- a/src/bootstrap/src/core/builder/tests.rs +++ b/src/bootstrap/src/core/builder/tests.rs @@ -712,7 +712,11 @@ mod snapshot { [build] llvm <host> [build] rustc 0 <host> -> rustc 1 <host> "); + } + #[test] + fn build_rustc_no_explicit_stage() { + let ctx = TestCtx::new(); insta::assert_snapshot!( ctx.config("build") .path("rustc") @@ -769,11 +773,11 @@ mod snapshot { [build] llvm <host> [build] rustc 0 <host> -> rustc 1 <host> [build] rustc 0 <host> -> LldWrapper 1 <host> - [build] rustc 1 <host> -> LlvmBitcodeLinker 2 <host> + [build] rustc 0 <host> -> LlvmBitcodeLinker 1 <host> [build] rustc 1 <host> -> std 1 <host> [build] rustc 1 <host> -> rustc 2 <host> [build] rustc 1 <host> -> LldWrapper 2 <host> - [build] rustc 2 <host> -> LlvmBitcodeLinker 3 <host> + [build] rustc 1 <host> -> LlvmBitcodeLinker 2 <host> [build] rustc 2 <host> -> std 2 <host> [build] rustdoc 1 <host> " @@ -793,17 +797,17 @@ mod snapshot { [build] llvm <host> [build] rustc 0 <host> -> rustc 1 <host> [build] rustc 0 <host> -> LldWrapper 1 <host> - [build] rustc 1 <host> -> LlvmBitcodeLinker 2 <host> + [build] rustc 0 <host> -> LlvmBitcodeLinker 1 <host> [build] rustc 1 <host> -> std 1 <host> [build] rustc 1 <host> -> rustc 2 <host> [build] rustc 1 <host> -> LldWrapper 2 <host> - [build] rustc 2 <host> -> LlvmBitcodeLinker 3 <host> + [build] rustc 1 <host> -> LlvmBitcodeLinker 2 <host> [build] rustc 1 <host> -> std 1 <target1> [build] rustc 2 <host> -> std 2 <target1> [build] llvm <target1> [build] rustc 1 <host> -> rustc 2 <target1> [build] rustc 1 <host> -> LldWrapper 2 <target1> - [build] rustc 2 <target1> -> LlvmBitcodeLinker 3 <target1> + [build] rustc 1 <host> -> LlvmBitcodeLinker 2 <target1> [build] rustdoc 1 <target1> " ); @@ -1062,18 +1066,28 @@ mod snapshot { fn dist_extended() { let ctx = TestCtx::new(); insta::assert_snapshot!( - ctx - .config("dist") - .args(&["--set", "build.extended=true"]) - .render_steps(), @r" + ctx.config("dist") + .args(&[ + "--set", + "build.extended=true", + "--set", + "rust.llvm-bitcode-linker=true", + "--set", + "rust.lld=true", + ]) + .render_steps(), @r" [build] rustc 0 <host> -> UnstableBookGen 1 <host> [build] rustc 0 <host> -> Rustbook 1 <host> [build] llvm <host> [build] rustc 0 <host> -> rustc 1 <host> + [build] rustc 0 <host> -> LldWrapper 1 <host> [build] rustc 0 <host> -> WasmComponentLd 1 <host> + [build] rustc 0 <host> -> LlvmBitcodeLinker 1 <host> [build] rustc 1 <host> -> std 1 <host> [build] rustc 1 <host> -> rustc 2 <host> + [build] rustc 1 <host> -> LldWrapper 2 <host> [build] rustc 1 <host> -> WasmComponentLd 2 <host> + [build] rustc 1 <host> -> LlvmBitcodeLinker 2 <host> [build] rustdoc 1 <host> [doc] std 2 <host> crates=[alloc,compiler_builtins,core,panic_abort,panic_unwind,proc_macro,std,sysroot,test,unwind] [build] rustc 2 <host> -> std 2 <host> @@ -1092,7 +1106,6 @@ mod snapshot { [build] rustc 0 <host> -> cargo-clippy 1 <host> [build] rustc 0 <host> -> miri 1 <host> [build] rustc 0 <host> -> cargo-miri 1 <host> - [build] rustc 1 <host> -> LlvmBitcodeLinker 2 <host> "); } @@ -1294,17 +1307,19 @@ mod snapshot { ctx.config("check") .path("compiler") .render_steps(), @r" - [build] llvm <host> [check] rustc 0 <host> -> rustc 1 <host> [check] rustc 0 <host> -> cranelift 1 <host> [check] rustc 0 <host> -> gcc 1 <host> "); + } + #[test] + fn check_rustc_no_explicit_stage() { + let ctx = TestCtx::new(); insta::assert_snapshot!( ctx.config("check") .path("rustc") .render_steps(), @r" - [build] llvm <host> [check] rustc 0 <host> -> rustc 1 <host> "); } @@ -1324,7 +1339,6 @@ mod snapshot { .path("compiler") .stage(1) .render_steps(), @r" - [build] llvm <host> [check] rustc 0 <host> -> rustc 1 <host> [check] rustc 0 <host> -> cranelift 1 <host> [check] rustc 0 <host> -> gcc 1 <host> @@ -1368,7 +1382,7 @@ mod snapshot { [check] rustc 1 <host> -> Miri 2 <target1> [check] rustc 1 <host> -> CargoMiri 2 <target1> [check] rustc 1 <host> -> Rustfmt 2 <target1> - [check] rustc 1 <host> -> rust-analyzer 2 <target1> + [check] rustc 1 <host> -> RustAnalyzer 2 <target1> [check] rustc 1 <host> -> TestFloatParse 2 <target1> [check] rustc 1 <host> -> std 1 <target1> "); @@ -1456,7 +1470,6 @@ mod snapshot { .paths(&["library", "compiler"]) .args(&args) .render_steps(), @r" - [build] llvm <host> [check] rustc 0 <host> -> rustc 1 <host> [check] rustc 0 <host> -> cranelift 1 <host> [check] rustc 0 <host> -> gcc 1 <host> @@ -1470,7 +1483,6 @@ mod snapshot { ctx.config("check") .path("miri") .render_steps(), @r" - [build] llvm <host> [check] rustc 0 <host> -> rustc 1 <host> [check] rustc 0 <host> -> Miri 1 <host> "); @@ -1491,7 +1503,6 @@ mod snapshot { .path("miri") .stage(1) .render_steps(), @r" - [build] llvm <host> [check] rustc 0 <host> -> rustc 1 <host> [check] rustc 0 <host> -> Miri 1 <host> "); @@ -1519,7 +1530,7 @@ mod snapshot { insta::assert_snapshot!( ctx.config("check") .path("compiletest") - .render_steps(), @"[check] compiletest <host>"); + .render_steps(), @"[check] rustc 0 <host> -> Compiletest 1 <host>"); } #[test] @@ -1533,7 +1544,7 @@ mod snapshot { [build] llvm <host> [build] rustc 0 <host> -> rustc 1 <host> [build] rustc 1 <host> -> std 1 <host> - [check] compiletest <host> + [check] rustc 1 <host> -> Compiletest 2 <host> "); } @@ -1544,7 +1555,6 @@ mod snapshot { ctx.config("check") .path("rustc_codegen_cranelift") .render_steps(), @r" - [build] llvm <host> [check] rustc 0 <host> -> rustc 1 <host> [check] rustc 0 <host> -> cranelift 1 <host> [check] rustc 0 <host> -> gcc 1 <host> @@ -1558,9 +1568,8 @@ mod snapshot { ctx.config("check") .path("rust-analyzer") .render_steps(), @r" - [build] llvm <host> [check] rustc 0 <host> -> rustc 1 <host> - [check] rustc 0 <host> -> rust-analyzer 1 <host> + [check] rustc 0 <host> -> RustAnalyzer 1 <host> "); } diff --git a/src/bootstrap/src/lib.rs b/src/bootstrap/src/lib.rs index 44be51815c7..63aab4d116a 100644 --- a/src/bootstrap/src/lib.rs +++ b/src/bootstrap/src/lib.rs @@ -253,12 +253,24 @@ pub enum Mode { /// These tools are intended to be only executed on the host system that /// invokes bootstrap, and they thus cannot be cross-compiled. /// - /// They are always built using the stage0 compiler, and typically they + /// They are always built using the stage0 compiler, and they /// can be compiled with stable Rust. /// /// These tools also essentially do not participate in staging. ToolBootstrap, + /// Build a cross-compilable helper tool. These tools do not depend on unstable features or + /// compiler internals, but they might be cross-compilable (so we cannot build them using the + /// stage0 compiler, unlike `ToolBootstrap`). + /// + /// Some of these tools are also shipped in our `dist` archives. + /// While we could compile them using the stage0 compiler when not cross-compiling, we instead + /// use the in-tree compiler (and std) to build them, so that we can ship e.g. std security + /// fixes and avoid depending fully on stage0 for the artifacts that we ship. + /// + /// This mode is used e.g. for linkers and linker tools invoked by rustc on its host target. + ToolTarget, + /// Build a tool which uses the locally built std, placing output in the /// "stageN-tools" directory. Its usage is quite rare, mainly used by /// compiletest which needs libtest. @@ -273,11 +285,21 @@ pub enum Mode { impl Mode { pub fn is_tool(&self) -> bool { - matches!(self, Mode::ToolBootstrap | Mode::ToolRustc | Mode::ToolStd) + match self { + Mode::ToolBootstrap | Mode::ToolRustc | Mode::ToolStd | Mode::ToolTarget => true, + Mode::Std | Mode::Codegen | Mode::Rustc => false, + } } pub fn must_support_dlopen(&self) -> bool { - matches!(self, Mode::Std | Mode::Codegen) + match self { + Mode::Std | Mode::Codegen => true, + Mode::ToolBootstrap + | Mode::ToolRustc + | Mode::ToolStd + | Mode::ToolTarget + | Mode::Rustc => false, + } } } @@ -802,17 +824,39 @@ impl Build { /// stage when running with a particular host compiler. /// /// The mode indicates what the root directory is for. - fn stage_out(&self, compiler: Compiler, mode: Mode) -> PathBuf { - let suffix = match mode { - Mode::Std => "-std", - Mode::Rustc => "-rustc", - Mode::Codegen => "-codegen", - Mode::ToolBootstrap => { - return self.out.join(compiler.host).join("bootstrap-tools"); + fn stage_out(&self, build_compiler: Compiler, mode: Mode) -> PathBuf { + use std::fmt::Write; + + fn bootstrap_tool() -> (Option<u32>, &'static str) { + (None, "bootstrap-tools") + } + fn staged_tool(build_compiler: Compiler) -> (Option<u32>, &'static str) { + (Some(build_compiler.stage), "tools") + } + + let (stage, suffix) = match mode { + Mode::Std => (Some(build_compiler.stage), "std"), + Mode::Rustc => (Some(build_compiler.stage), "rustc"), + Mode::Codegen => (Some(build_compiler.stage), "codegen"), + Mode::ToolBootstrap => bootstrap_tool(), + Mode::ToolStd | Mode::ToolRustc => (Some(build_compiler.stage), "tools"), + Mode::ToolTarget => { + // If we're not cross-compiling (the common case), share the target directory with + // bootstrap tools to reuse the build cache. + if build_compiler.stage == 0 { + bootstrap_tool() + } else { + staged_tool(build_compiler) + } } - Mode::ToolStd | Mode::ToolRustc => "-tools", }; - self.out.join(compiler.host).join(format!("stage{}{}", compiler.stage, suffix)) + let path = self.out.join(build_compiler.host); + let mut dir_name = String::new(); + if let Some(stage) = stage { + write!(dir_name, "stage{stage}-").unwrap(); + } + dir_name.push_str(suffix); + path.join(dir_name) } /// Returns the root output directory for all Cargo output in a given stage, diff --git a/src/ci/github-actions/jobs.yml b/src/ci/github-actions/jobs.yml index f0c52fe3d1c..0a6ebe44b3d 100644 --- a/src/ci/github-actions/jobs.yml +++ b/src/ci/github-actions/jobs.yml @@ -172,9 +172,9 @@ try: optional: # This job is used just to test optional jobs. # It will be replaced by tier 2 and tier 3 jobs in the future. - - name: optional-mingw-check-1 + - name: optional-pr-check-1 env: - IMAGE: mingw-check-1 + IMAGE: pr-check-1 <<: *job-linux-4c # Main CI jobs that have to be green to merge a commit into master diff --git a/src/ci/scripts/install-mingw.sh b/src/ci/scripts/install-mingw.sh index ad852071f29..ed87628659b 100755 --- a/src/ci/scripts/install-mingw.sh +++ b/src/ci/scripts/install-mingw.sh @@ -43,4 +43,9 @@ if isWindows && isKnownToBeMingwBuild; then curl -o mingw.7z "${MIRRORS_BASE}/${mingw_archive}" 7z x -y mingw.7z > /dev/null ciCommandAddPath "$(cygpath -m "$(pwd)/${mingw_dir}/bin")" + + # Initialize mingw for the user. + # This should be done by github but isn't for some reason. + # (see https://github.com/actions/runner-images/issues/12600) + /c/msys64/usr/bin/bash -lc ' ' fi diff --git a/src/doc/rustc-dev-guide/src/tests/directives.md b/src/doc/rustc-dev-guide/src/tests/directives.md index 63aa08c389c..5c3ae359ba0 100644 --- a/src/doc/rustc-dev-guide/src/tests/directives.md +++ b/src/doc/rustc-dev-guide/src/tests/directives.md @@ -75,8 +75,10 @@ expectations](ui.md#controlling-passfail-expectations). | `check-fail` | Building (no codegen) should fail | `ui`, `crashes` | N/A | | `build-pass` | Building should pass | `ui`, `crashes`, `codegen`, `incremental` | N/A | | `build-fail` | Building should fail | `ui`, `crashes` | N/A | -| `run-pass` | Running the test binary should pass | `ui`, `crashes`, `incremental` | N/A | -| `run-fail` | Running the test binary should fail | `ui`, `crashes` | N/A | +| `run-pass` | Program must exit with code `0` | `ui`, `crashes`, `incremental` | N/A | +| `run-fail` | Program must exit with code `1..=127` | `ui`, `crashes` | N/A | +| `run-crash` | Program must crash | `ui` | N/A | +| `run-fail-or-crash` | Program must `run-fail` or `run-crash` | `ui` | N/A | | `ignore-pass` | Ignore `--pass` flag | `ui`, `crashes`, `codegen`, `incremental` | N/A | | `dont-check-failure-status` | Don't check exact failure status (i.e. `1`) | `ui`, `incremental` | N/A | | `failure-status` | Check | `ui`, `crashes` | Any `u16` | @@ -203,6 +205,8 @@ settings: on `wasm32-unknown-unknown` target because the target does not support the `proc-macro` crate type. - `needs-target-std` — ignores if target platform does not have std support. +- `ignore-backends` — ignores the listed backends, separated by whitespace characters. +- `needs-backends` — only runs the test if current codegen backend is listed. The following directives will check LLVM support: diff --git a/src/doc/rustc-dev-guide/src/tests/ui.md b/src/doc/rustc-dev-guide/src/tests/ui.md index 4fce5838b6e..9bfc60e08a6 100644 --- a/src/doc/rustc-dev-guide/src/tests/ui.md +++ b/src/doc/rustc-dev-guide/src/tests/ui.md @@ -448,7 +448,7 @@ even run the resulting program. Just add one of the following - `//@ build-pass` — compilation and linking should succeed but do not run the resulting binary. - `//@ run-pass` — compilation should succeed and running the resulting - binary should also succeed. + binary should make it exit with code 0 which indicates success. - Fail directives: - `//@ check-fail` — compilation should fail (the codegen phase is skipped). This is the default for UI tests. @@ -457,10 +457,20 @@ even run the resulting program. Just add one of the following - First time is to ensure that the compile succeeds without the codegen phase - Second time is to ensure that the full compile fails - `//@ run-fail` — compilation should succeed, but running the resulting - binary should fail. - -For `run-pass` and `run-fail` tests, by default the output of the program itself -is not checked. + binary should make it exit with a code in the range `1..=127` which + indicates regular failure. On targets without unwind support, crashes + are also accepted. + - `//@ run-crash` — compilation should succeed, but running the resulting + binary should fail with a crash. Crashing is defined as "not exiting with + a code in the range `0..=127`". Example on Linux: Termination by `SIGABRT` + or `SIGSEGV`. Example on Windows: Exiting with the code for + `STATUS_ILLEGAL_INSTRUCTION` (`0xC000001D`). + - `//@ run-fail-or-crash` — compilation should succeed, but running the + resulting binary should either `run-fail` or `run-crash`. Useful if a test + crashes on some targets but just fails on others. + +For `run-pass`. `run-fail`, `run-crash` and `run-fail-or-crash` tests, by +default the output of the program itself is not checked. If you want to check the output of running the program, include the `check-run-results` directive. This will check for a `.run.stderr` and diff --git a/src/doc/rustc/src/exploit-mitigations.md b/src/doc/rustc/src/exploit-mitigations.md index f8bafe03214..c80d7d8743c 100644 --- a/src/doc/rustc/src/exploit-mitigations.md +++ b/src/doc/rustc/src/exploit-mitigations.md @@ -54,17 +54,17 @@ Summary of exploit mitigations supported by the Rust compiler when building programs for the Linux operating system on the AMD64 architecture and equivalent. -| Exploit mitigation | Supported and enabled by default | Since | -| - | - | - | -| Position-independent executable | Yes | 0.12.0 (2014-10-09) | -| Integer overflow checks | Yes (enabled when debug assertions are enabled, and disabled when debug assertions are disabled) | 1.1.0 (2015-06-25) | -| Non-executable memory regions | Yes | 1.8.0 (2016-04-14) | -| Stack clashing protection | Yes | 1.20.0 (2017-08-31) | -| Read-only relocations and immediate binding | Yes | 1.21.0 (2017-10-12) | -| Heap corruption protection | Yes | 1.32.0 (2019-01-17) (via operating system default or specified allocator) | -| Stack smashing protection | Yes | Nightly | -| Forward-edge control flow protection | Yes | Nightly | -| Backward-edge control flow protection (e.g., shadow and safe stack) | Yes | Nightly | +| Exploit mitigation | Supported | Enabled by default | Since | +| - | - | - | - | +| Position-independent executable | Yes | Yes | 0.12.0 (2014-10-09) | +| Integer overflow checks | Yes | (enabled when debug assertions are enabled, and disabled when debug assertions are disabled) | 1.1.0 (2015-06-25) | +| Non-executable memory regions | Yes | Yes | 1.8.0 (2016-04-14) | +| Stack clashing protection | Yes | Yes | 1.20.0 (2017-08-31) | +| Read-only relocations and immediate binding | Yes | Yes | 1.21.0 (2017-10-12) | +| Heap corruption protection | Yes | Yes | 1.32.0 (2019-01-17) (via operating system default or specified allocator) | +| Stack smashing protection | Yes | No, `-Z stack-protector` | Nightly | +| Forward-edge control flow protection | Yes | No, `-Z sanitizer=cfi` | Nightly | +| Backward-edge control flow protection (e.g., shadow and safe stack) | Yes | No, `-Z sanitizer=shadow-call-stack,safestack` | Nightly | [^all-targets]: See <https://github.com/rust-lang/rust/tree/master/compiler/rustc_target/src/spec> for a list of targets and their default options. diff --git a/src/doc/rustc/src/platform-support/xtensa.md b/src/doc/rustc/src/platform-support/xtensa.md index 994b3adb92e..8592ce7eda9 100644 --- a/src/doc/rustc/src/platform-support/xtensa.md +++ b/src/doc/rustc/src/platform-support/xtensa.md @@ -24,4 +24,4 @@ Xtensa targets that support `std` are documented in the [ESP-IDF platform suppor ## Building the targets -The targets can be built by installing the [Xtensa enabled Rust channel](https://github.com/esp-rs/rust/). See instructions in the [RISC-V and Xtensa Targets section of The Rust on ESP Book](https://docs.esp-rs.org/book/installation/riscv-and-xtensa.html). +The targets can be built by installing the [Xtensa enabled Rust channel](https://github.com/esp-rs/rust/). See instructions in the [RISC-V and Xtensa Targets section of The Rust on ESP Book](https://docs.espressif.com/projects/rust/book/installation/index.html). diff --git a/src/doc/unstable-book/src/compiler-flags/offload.md b/src/doc/unstable-book/src/compiler-flags/offload.md new file mode 100644 index 00000000000..4266e8c11a2 --- /dev/null +++ b/src/doc/unstable-book/src/compiler-flags/offload.md @@ -0,0 +1,8 @@ +# `offload` + +The tracking issue for this feature is: [#131513](https://github.com/rust-lang/rust/issues/131513). + +------------------------ + +This feature will later allow you to run functions on GPUs. It is work in progress. +Set the `-Zoffload=Enable` compiler flag to experiment with it. diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index 09647492d93..5ac5da24299 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -1677,7 +1677,7 @@ impl Type { } } - pub(crate) fn generics<'a>(&'a self) -> Option<impl Iterator<Item = &'a Type>> { + pub(crate) fn generics(&self) -> Option<impl Iterator<Item = &Type>> { match self { Type::Path { path, .. } => path.generics(), _ => None, @@ -2227,7 +2227,7 @@ impl Path { self.segments.last().map(|seg| &seg.args) } - pub(crate) fn generics<'a>(&'a self) -> Option<impl Iterator<Item = &'a Type>> { + pub(crate) fn generics(&self) -> Option<impl Iterator<Item = &Type>> { self.segments.last().and_then(|seg| { if let GenericArgs::AngleBracketed { ref args, .. } = seg.args { Some(args.iter().filter_map(|arg| match arg { diff --git a/src/librustdoc/clean/utils.rs b/src/librustdoc/clean/utils.rs index fd1b17b6476..813fdee57e1 100644 --- a/src/librustdoc/clean/utils.rs +++ b/src/librustdoc/clean/utils.rs @@ -343,13 +343,11 @@ pub(crate) fn name_from_pat(p: &hir::Pat<'_>) -> Symbol { pub(crate) fn print_const(cx: &DocContext<'_>, n: ty::Const<'_>) -> String { match n.kind() { ty::ConstKind::Unevaluated(ty::UnevaluatedConst { def, args: _ }) => { - let s = if let Some(def) = def.as_local() { + if let Some(def) = def.as_local() { rendered_const(cx.tcx, cx.tcx.hir_body_owned_by(def), def) } else { inline::print_inlined_const(cx.tcx, def) - }; - - s + } } // array lengths are obviously usize ty::ConstKind::Value(cv) if *cv.ty.kind() == ty::Uint(ty::UintTy::Usize) => { diff --git a/src/librustdoc/doctest.rs b/src/librustdoc/doctest.rs index 9b4d2533954..38ba6b4503d 100644 --- a/src/librustdoc/doctest.rs +++ b/src/librustdoc/doctest.rs @@ -632,7 +632,7 @@ fn run_test( // the user to exploit nightly-only features on stable runner_compiler.env("RUSTC_BOOTSTRAP", "1"); runner_compiler.args(compiler_args); - runner_compiler.args(&["--crate-type=bin", "-o"]).arg(&output_file); + runner_compiler.args(["--crate-type=bin", "-o"]).arg(&output_file); let mut extern_path = std::ffi::OsString::from(format!( "--extern=doctest_bundle_{edition}=", edition = doctest.edition @@ -657,7 +657,7 @@ fn run_test( extern_path.push(&output_bundle_file); runner_compiler.arg(extern_path); runner_compiler.arg(&runner_input_file); - if std::fs::write(&runner_input_file, &merged_test_code).is_err() { + if std::fs::write(&runner_input_file, merged_test_code).is_err() { // If we cannot write this file for any reason, we leave. All combined tests will be // tested as standalone tests. return Err(TestFailure::CompileError); diff --git a/src/librustdoc/doctest/rust.rs b/src/librustdoc/doctest/rust.rs index 96975105ac5..f5ec828187a 100644 --- a/src/librustdoc/doctest/rust.rs +++ b/src/librustdoc/doctest/rust.rs @@ -140,7 +140,7 @@ impl HirCollector<'_> { .iter() .filter(|a| a.has_name(sym::attr)) .flat_map(|a| a.meta_item_list().unwrap_or_default()) - .map(|i| pprust::meta_list_item_to_string(i)) + .map(pprust::meta_list_item_to_string) { // Add the additional attributes to the global_crate_attrs vector self.collector.global_crate_attrs.push(attr); diff --git a/src/librustdoc/formats/renderer.rs b/src/librustdoc/formats/renderer.rs index 79ff1fa38c3..aa4be4db997 100644 --- a/src/librustdoc/formats/renderer.rs +++ b/src/librustdoc/formats/renderer.rs @@ -81,7 +81,7 @@ fn run_format_inner<'tcx, T: FormatRenderer<'tcx>>( let _timer = prof.generic_activity_with_arg("render_mod_item", item.name.unwrap().to_string()); - cx.mod_item_in(&item)?; + cx.mod_item_in(item)?; let (clean::StrippedItem(box clean::ModuleItem(ref module)) | clean::ModuleItem(ref module)) = item.inner.kind else { @@ -99,7 +99,7 @@ fn run_format_inner<'tcx, T: FormatRenderer<'tcx>>( } else if let Some(item_name) = item.name && !item.is_extern_crate() { - prof.generic_activity_with_arg("render_item", item_name.as_str()).run(|| cx.item(&item))?; + prof.generic_activity_with_arg("render_item", item_name.as_str()).run(|| cx.item(item))?; } Ok(()) } diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index b16485107a0..be8a2d511e9 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -114,9 +114,9 @@ impl clean::Generics { let real_params = fmt::from_fn(|f| real_params.clone().map(|g| g.print(cx)).joined(", ", f)); if f.alternate() { - write!(f, "<{:#}>", real_params) + write!(f, "<{real_params:#}>") } else { - write!(f, "<{}>", real_params) + write!(f, "<{real_params}>") } }) } @@ -594,7 +594,7 @@ pub(crate) fn href_with_root_path( } } }; - let url_parts = make_href(root_path, shortty, url_parts, &fqp, is_remote); + let url_parts = make_href(root_path, shortty, url_parts, fqp, is_remote); Ok((url_parts, shortty, fqp.clone())) } @@ -1115,7 +1115,7 @@ impl clean::Impl { { let last = ty.last(); if f.alternate() { - write!(f, "{}<", last)?; + write!(f, "{last}<")?; self.print_type(inner_type, f, use_absolute, cx)?; write!(f, ">")?; } else { @@ -1219,7 +1219,7 @@ pub(crate) fn print_params(params: &[clean::Parameter], cx: &Context<'_>) -> imp .map(|param| { fmt::from_fn(|f| { if let Some(name) = param.name { - write!(f, "{}: ", name)?; + write!(f, "{name}: ")?; } param.type_.print(cx).fmt(f) }) @@ -1341,7 +1341,7 @@ impl clean::FnDecl { write!(f, "const ")?; } if let Some(name) = param.name { - write!(f, "{}: ", name)?; + write!(f, "{name}: ")?; } param.type_.print(cx).fmt(f)?; } diff --git a/src/librustdoc/html/highlight.rs b/src/librustdoc/html/highlight.rs index b2feee36c93..272180fb990 100644 --- a/src/librustdoc/html/highlight.rs +++ b/src/librustdoc/html/highlight.rs @@ -547,7 +547,7 @@ impl<'a> Iterator for TokenIter<'a> { fn get_real_ident_class(text: &str, allow_path_keywords: bool) -> Option<Class> { let ignore: &[&str] = if allow_path_keywords { &["self", "Self", "super", "crate"] } else { &["self", "Self"] }; - if ignore.iter().any(|k| *k == text) { + if ignore.contains(&text) { return None; } Some(match text { @@ -1159,7 +1159,7 @@ fn string_without_closing_tag<T: Display>( return Some("</a>"); } if !open_tag { - write!(out, "{}", text_s).unwrap(); + out.write_str(&text_s).unwrap(); return None; } let klass_s = klass.as_html(); diff --git a/src/librustdoc/html/layout.rs b/src/librustdoc/html/layout.rs index 50320cb231d..1f92c521d46 100644 --- a/src/librustdoc/html/layout.rs +++ b/src/librustdoc/html/layout.rs @@ -132,6 +132,5 @@ pub(crate) fn redirect(url: &str) -> String { <script>location.replace("{url}" + location.search + location.hash);</script> </body> </html>"##, - url = url, ) } diff --git a/src/librustdoc/html/markdown.rs b/src/librustdoc/html/markdown.rs index e41435de29c..4addf2c3c96 100644 --- a/src/librustdoc/html/markdown.rs +++ b/src/librustdoc/html/markdown.rs @@ -251,7 +251,7 @@ impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'_, 'a, I> { if !parse_result.rust { let added_classes = parse_result.added_classes; let lang_string = if let Some(lang) = parse_result.unknown.first() { - format!("language-{}", lang) + format!("language-{lang}") } else { String::new() }; @@ -999,7 +999,7 @@ impl<'a, 'tcx> TagIterator<'a, 'tcx> { if let Some((_, c)) = self.inner.next() { if c != '=' { - self.emit_error(format!("expected `=`, found `{}`", c)); + self.emit_error(format!("expected `=`, found `{c}`")); return None; } } else { diff --git a/src/librustdoc/html/render/context.rs b/src/librustdoc/html/render/context.rs index 7b814701a73..5ceb1fc988d 100644 --- a/src/librustdoc/html/render/context.rs +++ b/src/librustdoc/html/render/context.rs @@ -193,14 +193,12 @@ impl<'tcx> Context<'tcx> { if it.is_stripped() && let Some(def_id) = it.def_id() && def_id.is_local() + && (self.info.is_inside_inlined_module + || self.shared.cache.inlined_items.contains(&def_id)) { - if self.info.is_inside_inlined_module - || self.shared.cache.inlined_items.contains(&def_id) - { - // For now we're forced to generate a redirect page for stripped items until - // `record_extern_fqn` correctly points to external items. - render_redirect_pages = true; - } + // For now we're forced to generate a redirect page for stripped items until + // `record_extern_fqn` correctly points to external items. + render_redirect_pages = true; } let mut title = String::new(); if !is_module { @@ -254,40 +252,36 @@ impl<'tcx> Context<'tcx> { &self.shared.style_files, ) } else { - if let Some(&(ref names, ty)) = self.cache().paths.get(&it.item_id.expect_def_id()) { - if self.current.len() + 1 != names.len() - || self.current.iter().zip(names.iter()).any(|(a, b)| a != b) - { - // We checked that the redirection isn't pointing to the current file, - // preventing an infinite redirection loop in the generated - // documentation. - - let path = fmt::from_fn(|f| { - for name in &names[..names.len() - 1] { - write!(f, "{name}/")?; - } - write!(f, "{}", print_item_path(ty, names.last().unwrap().as_str())) - }); - match self.shared.redirections { - Some(ref redirections) => { - let mut current_path = String::new(); - for name in &self.current { - current_path.push_str(name.as_str()); - current_path.push('/'); - } - let _ = write!( - current_path, - "{}", - print_item_path(ty, names.last().unwrap().as_str()) - ); - redirections.borrow_mut().insert(current_path, path.to_string()); - } - None => { - return layout::redirect(&format!( - "{root}{path}", - root = self.root_path() - )); + if let Some(&(ref names, ty)) = self.cache().paths.get(&it.item_id.expect_def_id()) + && (self.current.len() + 1 != names.len() + || self.current.iter().zip(names.iter()).any(|(a, b)| a != b)) + { + // We checked that the redirection isn't pointing to the current file, + // preventing an infinite redirection loop in the generated + // documentation. + + let path = fmt::from_fn(|f| { + for name in &names[..names.len() - 1] { + write!(f, "{name}/")?; + } + write!(f, "{}", print_item_path(ty, names.last().unwrap().as_str())) + }); + match self.shared.redirections { + Some(ref redirections) => { + let mut current_path = String::new(); + for name in &self.current { + current_path.push_str(name.as_str()); + current_path.push('/'); } + let _ = write!( + current_path, + "{}", + print_item_path(ty, names.last().unwrap().as_str()) + ); + redirections.borrow_mut().insert(current_path, path.to_string()); + } + None => { + return layout::redirect(&format!("{root}{path}", root = self.root_path())); } } } @@ -762,11 +756,7 @@ impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> { // Flush pending errors. self.shared.fs.close(); let nb_errors = self.shared.errors.iter().map(|err| self.tcx().dcx().err(err)).count(); - if nb_errors > 0 { - Err(Error::new(io::Error::new(io::ErrorKind::Other, "I/O error"), "")) - } else { - Ok(()) - } + if nb_errors > 0 { Err(Error::new(io::Error::other("I/O error"), "")) } else { Ok(()) } } fn mod_item_in(&mut self, item: &clean::Item) -> Result<(), Error> { @@ -842,7 +832,7 @@ impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> { self.info.render_redirect_pages = item.is_stripped(); } - let buf = self.render_item(&item, false); + let buf = self.render_item(item, false); // buf will be empty if the item is stripped and there is no redirect for it if !buf.is_empty() { let name = item.name.as_ref().unwrap(); @@ -853,7 +843,7 @@ impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> { self.shared.fs.write(joint_dst, buf)?; if !self.info.render_redirect_pages { - self.shared.all.borrow_mut().append(full_path(self, &item), &item_type); + self.shared.all.borrow_mut().append(full_path(self, item), &item_type); } // If the item is a macro, redirect from the old macro URL (with !) // to the new one (without). diff --git a/src/librustdoc/html/render/mod.rs b/src/librustdoc/html/render/mod.rs index d8c37137bbc..872dbbcd19e 100644 --- a/src/librustdoc/html/render/mod.rs +++ b/src/librustdoc/html/render/mod.rs @@ -1110,7 +1110,7 @@ fn since_to_string(since: &StableSince) -> Option<String> { match since { StableSince::Version(since) => Some(since.to_string()), StableSince::Current => Some(RustcVersion::CURRENT.to_string()), - StableSince::Err => None, + StableSince::Err(_) => None, } } @@ -1483,10 +1483,10 @@ fn render_deref_methods( } } render_assoc_items_inner(&mut w, cx, container_item, did, what, derefs); - } else if let Some(prim) = target.primitive_type() { - if let Some(&did) = cache.primitive_locations.get(&prim) { - render_assoc_items_inner(&mut w, cx, container_item, did, what, derefs); - } + } else if let Some(prim) = target.primitive_type() + && let Some(&did) = cache.primitive_locations.get(&prim) + { + render_assoc_items_inner(&mut w, cx, container_item, did, what, derefs); } } @@ -2058,21 +2058,20 @@ fn render_impl( // default items which weren't overridden in the implementation block. // We don't emit documentation for default items if they appear in the // Implementations on Foreign Types or Implementors sections. - if rendering_params.show_default_items { - if let Some(t) = trait_ - && !impl_.is_negative_trait_impl() - { - render_default_items( - &mut default_impl_items, - &mut impl_items, - cx, - t, - impl_, - &i.impl_item, - render_mode, - rendering_params, - )?; - } + if rendering_params.show_default_items + && let Some(t) = trait_ + && !impl_.is_negative_trait_impl() + { + render_default_items( + &mut default_impl_items, + &mut impl_items, + cx, + t, + impl_, + &i.impl_item, + render_mode, + rendering_params, + )?; } if render_mode == RenderMode::Normal { let toggled = !(impl_items.is_empty() && default_impl_items.is_empty()); @@ -2570,7 +2569,7 @@ fn collect_paths_for_type(first_ty: &clean::Type, cache: &Cache) -> Vec<String> match ty { clean::Type::Path { path } => process_path(path.def_id()), clean::Type::Tuple(tys) => { - work.extend(tys.into_iter()); + work.extend(tys.iter()); } clean::Type::Slice(ty) => { work.push_back(ty); diff --git a/src/librustdoc/html/render/ordered_json.rs b/src/librustdoc/html/render/ordered_json.rs index d1dddfebc83..be51dad1c2b 100644 --- a/src/librustdoc/html/render/ordered_json.rs +++ b/src/librustdoc/html/render/ordered_json.rs @@ -25,7 +25,7 @@ impl OrderedJson { .into_iter() .sorted_unstable_by(|a, b| a.borrow().cmp(b.borrow())) .format_with(",", |item, f| f(item.borrow())); - Self(format!("[{}]", items)) + Self(format!("[{items}]")) } pub(crate) fn array_unsorted<T: Borrow<Self>, I: IntoIterator<Item = T>>(items: I) -> Self { diff --git a/src/librustdoc/html/render/print_item.rs b/src/librustdoc/html/render/print_item.rs index 5fbda4797cc..02ee34aaac6 100644 --- a/src/librustdoc/html/render/print_item.rs +++ b/src/librustdoc/html/render/print_item.rs @@ -1451,7 +1451,7 @@ item_template!( impl<'a, 'cx: 'a> ItemUnion<'a, 'cx> { fn render_union(&self) -> impl Display { - render_union(self.it, Some(&self.generics), &self.fields, self.cx) + render_union(self.it, Some(self.generics), self.fields, self.cx) } fn document_field(&self, field: &'a clean::Item) -> impl Display { @@ -1982,16 +1982,14 @@ fn item_constant( w.write_str(";")?; } - if !is_literal { - if let Some(value) = &value { - let value_lowercase = value.to_lowercase(); - let expr_lowercase = expr.to_lowercase(); + if !is_literal && let Some(value) = &value { + let value_lowercase = value.to_lowercase(); + let expr_lowercase = expr.to_lowercase(); - if value_lowercase != expr_lowercase - && value_lowercase.trim_end_matches("i32") != expr_lowercase - { - write!(w, " // {value}", value = Escape(value))?; - } + if value_lowercase != expr_lowercase + && value_lowercase.trim_end_matches("i32") != expr_lowercase + { + write!(w, " // {value}", value = Escape(value))?; } } Ok::<(), fmt::Error>(()) @@ -2071,41 +2069,39 @@ fn item_fields( _ => None, }) .peekable(); - if let None | Some(CtorKind::Fn) = ctor_kind { - if fields.peek().is_some() { - let title = format!( - "{}{}", - if ctor_kind.is_none() { "Fields" } else { "Tuple Fields" }, - document_non_exhaustive_header(it), - ); + if let None | Some(CtorKind::Fn) = ctor_kind + && fields.peek().is_some() + { + let title = format!( + "{}{}", + if ctor_kind.is_none() { "Fields" } else { "Tuple Fields" }, + document_non_exhaustive_header(it), + ); + write!( + w, + "{}", + write_section_heading( + &title, + "fields", + Some("fields"), + document_non_exhaustive(it) + ) + )?; + for (index, (field, ty)) in fields.enumerate() { + let field_name = + field.name.map_or_else(|| index.to_string(), |sym| sym.as_str().to_string()); + let id = cx.derive_id(format!("{typ}.{field_name}", typ = ItemType::StructField)); write!( w, - "{}", - write_section_heading( - &title, - "fields", - Some("fields"), - document_non_exhaustive(it) - ) + "<span id=\"{id}\" class=\"{item_type} section-header\">\ + <a href=\"#{id}\" class=\"anchor field\">§</a>\ + <code>{field_name}: {ty}</code>\ + </span>\ + {doc}", + item_type = ItemType::StructField, + ty = ty.print(cx), + doc = document(cx, field, Some(it), HeadingOffset::H3), )?; - for (index, (field, ty)) in fields.enumerate() { - let field_name = field - .name - .map_or_else(|| index.to_string(), |sym| sym.as_str().to_string()); - let id = - cx.derive_id(format!("{typ}.{field_name}", typ = ItemType::StructField)); - write!( - w, - "<span id=\"{id}\" class=\"{item_type} section-header\">\ - <a href=\"#{id}\" class=\"anchor field\">§</a>\ - <code>{field_name}: {ty}</code>\ - </span>\ - {doc}", - item_type = ItemType::StructField, - ty = ty.print(cx), - doc = document(cx, field, Some(it), HeadingOffset::H3), - )?; - } } } Ok(()) diff --git a/src/librustdoc/html/render/search_index.rs b/src/librustdoc/html/render/search_index.rs index 80a59fa218c..3c9be29ccc3 100644 --- a/src/librustdoc/html/render/search_index.rs +++ b/src/librustdoc/html/render/search_index.rs @@ -116,7 +116,7 @@ pub(crate) fn build_index( // Set up alias indexes. for (i, item) in cache.search_index.iter().enumerate() { for alias in &item.aliases[..] { - aliases.entry(alias.as_str().to_lowercase()).or_default().push(i); + aliases.entry(alias.to_string()).or_default().push(i); } } diff --git a/src/librustdoc/html/render/sidebar.rs b/src/librustdoc/html/render/sidebar.rs index 91540e06e33..b9f5ada417c 100644 --- a/src/librustdoc/html/render/sidebar.rs +++ b/src/librustdoc/html/render/sidebar.rs @@ -541,7 +541,7 @@ fn sidebar_deref_methods<'a>( .iter() .filter(|i| { i.inner_impl().trait_.is_none() - && real_target.is_doc_subtype_of(&i.inner_impl().for_, &c) + && real_target.is_doc_subtype_of(&i.inner_impl().for_, c) }) .flat_map(|i| get_methods(i.inner_impl(), true, used_links, deref_mut, cx.tcx())) .collect::<Vec<_>>(); diff --git a/src/librustdoc/html/render/sorted_template.rs b/src/librustdoc/html/render/sorted_template.rs index a7b954ab70b..659c5e6093b 100644 --- a/src/librustdoc/html/render/sorted_template.rs +++ b/src/librustdoc/html/render/sorted_template.rs @@ -63,7 +63,8 @@ impl<F: FileFormat> fmt::Display for SortedTemplate<F> { for (p, fragment) in self.fragments.iter().with_position() { let mut f = DeltaWriter { inner: &mut f, delta: 0 }; let sep = if matches!(p, Position::First | Position::Only) { "" } else { F::SEPARATOR }; - write!(f, "{}{}", sep, fragment)?; + f.write_str(sep)?; + f.write_str(fragment)?; fragment_lengths.push(f.delta); } let offset = Offset { start: self.before.len(), fragment_lengths }; diff --git a/src/librustdoc/html/static/js/rustdoc.d.ts b/src/librustdoc/html/static/js/rustdoc.d.ts index ca2512e5ab6..a9589764547 100644 --- a/src/librustdoc/html/static/js/rustdoc.d.ts +++ b/src/librustdoc/html/static/js/rustdoc.d.ts @@ -219,6 +219,8 @@ declare namespace rustdoc { crate: string, descShard: SearchDescShard, id: number, + // This is the name of the item. For doc aliases, if you want the name of the aliased + // item, take a look at `Row.original.name`. name: string, normalizedName: string, word: string, @@ -227,6 +229,11 @@ declare namespace rustdoc { path: string, ty: number, type: FunctionSearchType | null, + descIndex: number, + bitIndex: number, + implDisambiguator: String | null, + is_alias?: boolean, + original?: Row, } /** diff --git a/src/librustdoc/html/static/js/search.js b/src/librustdoc/html/static/js/search.js index 15cad31f555..2caf214ff73 100644 --- a/src/librustdoc/html/static/js/search.js +++ b/src/librustdoc/html/static/js/search.js @@ -830,7 +830,7 @@ function createQueryElement(query, parserState, name, generics, isInGenerics) { */ function makePrimitiveElement(name, extra) { return Object.assign({ - name: name, + name, id: null, fullPath: [name], pathWithoutLast: [], @@ -1483,6 +1483,7 @@ class DocSearch { */ this.assocTypeIdNameMap = new Map(); this.ALIASES = new Map(); + this.FOUND_ALIASES = new Set(); this.rootPath = rootPath; this.searchState = searchState; @@ -2030,6 +2031,8 @@ class DocSearch { // normalized names, type signature objects and fingerprints, and aliases. id = 0; + /** @type {Array<[string, { [key: string]: Array<number> }, number]>} */ + const allAliases = []; for (const [crate, crateCorpus] of rawSearchIndex) { // a string representing the lengths of each description shard // a string representing the list of function types @@ -2178,10 +2181,10 @@ class DocSearch { paths[i] = { ty, name, path, exactPath, unboxFlag }; } - // convert `item*` into an object form, and construct word indices. + // Convert `item*` into an object form, and construct word indices. // - // before any analysis is performed lets gather the search terms to - // search against apart from the rest of the data. This is a quick + // Before any analysis is performed, let's gather the search terms to + // search against apart from the rest of the data. This is a quick // operation that is cached for the life of the page state so that // all other search operations have access to this cached data for // faster analysis operations @@ -2269,29 +2272,58 @@ class DocSearch { } if (aliases) { - const currentCrateAliases = new Map(); - this.ALIASES.set(crate, currentCrateAliases); - for (const alias_name in aliases) { - if (!Object.prototype.hasOwnProperty.call(aliases, alias_name)) { - continue; - } - - /** @type{number[]} */ - let currentNameAliases; - if (currentCrateAliases.has(alias_name)) { - currentNameAliases = currentCrateAliases.get(alias_name); - } else { - currentNameAliases = []; - currentCrateAliases.set(alias_name, currentNameAliases); - } - for (const local_alias of aliases[alias_name]) { - currentNameAliases.push(local_alias + currentIndex); - } - } + // We need to add the aliases in `searchIndex` after we finished filling it + // to not mess up indexes. + allAliases.push([crate, aliases, currentIndex]); } currentIndex += itemTypes.length; this.searchState.descShards.set(crate, descShardList); } + + for (const [crate, aliases, index] of allAliases) { + for (const [alias_name, alias_refs] of Object.entries(aliases)) { + if (!this.ALIASES.has(crate)) { + this.ALIASES.set(crate, new Map()); + } + const word = alias_name.toLowerCase(); + const crate_alias_map = this.ALIASES.get(crate); + if (!crate_alias_map.has(word)) { + crate_alias_map.set(word, []); + } + const aliases_map = crate_alias_map.get(word); + + const normalizedName = word.indexOf("_") === -1 ? word : word.replace(/_/g, ""); + for (const alias of alias_refs) { + const originalIndex = alias + index; + const original = searchIndex[originalIndex]; + /** @type {rustdoc.Row} */ + const row = { + crate, + name: alias_name, + normalizedName, + is_alias: true, + ty: original.ty, + type: original.type, + paramNames: [], + word, + id, + parent: undefined, + original, + path: "", + implDisambiguator: original.implDisambiguator, + // Needed to load the description of the original item. + // @ts-ignore + descShard: original.descShard, + descIndex: original.descIndex, + bitIndex: original.bitIndex, + }; + aliases_map.push(row); + this.nameTrie.insert(normalizedName, id, this.tailTable); + id += 1; + searchIndex.push(row); + } + } + } // Drop the (rather large) hash table used for reusing function items this.TYPES_POOL = new Map(); return searchIndex; @@ -2536,6 +2568,8 @@ class DocSearch { parsedQuery.elems.reduce((acc, next) => acc + next.pathLast.length, 0) + parsedQuery.returned.reduce((acc, next) => acc + next.pathLast.length, 0); const maxEditDistance = Math.floor(queryLen / 3); + // We reinitialize the `FOUND_ALIASES` map. + this.FOUND_ALIASES.clear(); /** * @type {Map<string, number>} @@ -2695,6 +2729,10 @@ class DocSearch { const buildHrefAndPath = item => { let displayPath; let href; + if (item.is_alias) { + this.FOUND_ALIASES.add(item.word); + item = item.original; + } const type = itemTypes[item.ty]; const name = item.name; let path = item.path; @@ -3198,8 +3236,7 @@ class DocSearch { result.item = this.searchIndex[result.id]; result.word = this.searchIndex[result.id].word; if (isReturnTypeQuery) { - // we are doing a return-type based search, - // deprioritize "clone-like" results, + // We are doing a return-type based search, deprioritize "clone-like" results, // ie. functions that also take the queried type as an argument. const resultItemType = result.item && result.item.type; if (!resultItemType) { @@ -4259,28 +4296,13 @@ class DocSearch { return false; } - // this does not yet have a type in `rustdoc.d.ts`. - // @ts-expect-error - function createAliasFromItem(item) { - return { - crate: item.crate, - name: item.name, - path: item.path, - descShard: item.descShard, - descIndex: item.descIndex, - exactPath: item.exactPath, - ty: item.ty, - parent: item.parent, - type: item.type, - is_alias: true, - bitIndex: item.bitIndex, - implDisambiguator: item.implDisambiguator, - }; - } - // @ts-expect-error const handleAliases = async(ret, query, filterCrates, currentCrate) => { const lowerQuery = query.toLowerCase(); + if (this.FOUND_ALIASES.has(lowerQuery)) { + return; + } + this.FOUND_ALIASES.add(lowerQuery); // We separate aliases and crate aliases because we want to have current crate // aliases to be before the others in the displayed results. // @ts-expect-error @@ -4292,7 +4314,7 @@ class DocSearch { && this.ALIASES.get(filterCrates).has(lowerQuery)) { const query_aliases = this.ALIASES.get(filterCrates).get(lowerQuery); for (const alias of query_aliases) { - aliases.push(createAliasFromItem(this.searchIndex[alias])); + aliases.push(alias); } } } else { @@ -4302,7 +4324,7 @@ class DocSearch { const pushTo = crate === currentCrate ? crateAliases : aliases; const query_aliases = crateAliasesIndex.get(lowerQuery); for (const alias of query_aliases) { - pushTo.push(createAliasFromItem(this.searchIndex[alias])); + pushTo.push(alias); } } } @@ -4310,9 +4332,9 @@ class DocSearch { // @ts-expect-error const sortFunc = (aaa, bbb) => { - if (aaa.path < bbb.path) { + if (aaa.original.path < bbb.original.path) { return 1; - } else if (aaa.path === bbb.path) { + } else if (aaa.original.path === bbb.original.path) { return 0; } return -1; @@ -4322,20 +4344,9 @@ class DocSearch { aliases.sort(sortFunc); // @ts-expect-error - const fetchDesc = alias => { - // @ts-expect-error - return this.searchIndexEmptyDesc.get(alias.crate).contains(alias.bitIndex) ? - "" : this.searchState.loadDesc(alias); - }; - const [crateDescs, descs] = await Promise.all([ - // @ts-expect-error - Promise.all(crateAliases.map(fetchDesc)), - Promise.all(aliases.map(fetchDesc)), - ]); - - // @ts-expect-error const pushFunc = alias => { - alias.alias = query; + // Cloning `alias` to prevent its fields to be updated. + alias = {...alias}; const res = buildHrefAndPath(alias); alias.displayPath = pathSplitter(res[0]); alias.fullPath = alias.displayPath + alias.name; @@ -4347,16 +4358,8 @@ class DocSearch { } }; - aliases.forEach((alias, i) => { - // @ts-expect-error - alias.desc = descs[i]; - }); aliases.forEach(pushFunc); // @ts-expect-error - crateAliases.forEach((alias, i) => { - alias.desc = crateDescs[i]; - }); - // @ts-expect-error crateAliases.forEach(pushFunc); }; @@ -4802,7 +4805,7 @@ async function addTab(array, query, display) { output.className = "search-results " + extraClass; const lis = Promise.all(array.map(async item => { - const name = item.name; + const name = item.is_alias ? item.original.name : item.name; const type = itemTypes[item.ty]; const longType = longItemTypes[item.ty]; const typeName = longType.length !== 0 ? `${longType}` : "?"; @@ -4822,7 +4825,7 @@ async function addTab(array, query, display) { let alias = " "; if (item.is_alias) { alias = ` <div class="alias">\ -<b>${item.alias}</b><i class="grey"> - see </i>\ +<b>${item.name}</b><i class="grey"> - see </i>\ </div>`; } resultName.insertAdjacentHTML( @@ -5201,6 +5204,7 @@ function registerSearchEvents() { if (searchState.input.value.length === 0) { searchState.hideResults(); } else { + // @ts-ignore searchState.timeout = setTimeout(search, 500); } }; @@ -5842,8 +5846,8 @@ Lev1TParametricDescription.prototype.offsetIncrs3 = /*2 bits per value */ new In // be called ONLY when the whole file has been parsed and loaded. // @ts-expect-error -function initSearch(searchIndx) { - rawSearchIndex = searchIndx; +function initSearch(searchIndex) { + rawSearchIndex = searchIndex; if (typeof window !== "undefined") { // @ts-expect-error docSearch = new DocSearch(rawSearchIndex, ROOT_PATH, searchState); diff --git a/src/librustdoc/json/conversions.rs b/src/librustdoc/json/conversions.rs index 0a84d8caa30..08bc0bb1950 100644 --- a/src/librustdoc/json/conversions.rs +++ b/src/librustdoc/json/conversions.rs @@ -50,7 +50,7 @@ impl JsonRenderer<'_> { let span = item.span(self.tcx); let visibility = item.visibility(self.tcx); let clean::ItemInner { name, item_id, .. } = *item.inner; - let id = self.id_from_item(&item); + let id = self.id_from_item(item); let inner = match item.kind { clean::KeywordItem => return None, clean::StrippedItem(ref inner) => { @@ -86,14 +86,14 @@ impl JsonRenderer<'_> { items .iter() .filter(|i| !i.is_stripped() && !i.is_keyword()) - .map(|i| self.id_from_item(&i)) + .map(|i| self.id_from_item(i)) .collect() } fn ids_keeping_stripped(&self, items: &[clean::Item]) -> Vec<Option<Id>> { items .iter() - .map(|i| (!i.is_stripped() && !i.is_keyword()).then(|| self.id_from_item(&i))) + .map(|i| (!i.is_stripped() && !i.is_keyword()).then(|| self.id_from_item(i))) .collect() } } @@ -358,12 +358,12 @@ impl FromClean<clean::Struct> for Struct { let clean::Struct { ctor_kind, generics, fields } = struct_; let kind = match ctor_kind { - Some(CtorKind::Fn) => StructKind::Tuple(renderer.ids_keeping_stripped(&fields)), + Some(CtorKind::Fn) => StructKind::Tuple(renderer.ids_keeping_stripped(fields)), Some(CtorKind::Const) => { assert!(fields.is_empty()); StructKind::Unit } - None => StructKind::Plain { fields: renderer.ids(&fields), has_stripped_fields }, + None => StructKind::Plain { fields: renderer.ids(fields), has_stripped_fields }, }; Struct { @@ -381,7 +381,7 @@ impl FromClean<clean::Union> for Union { Union { generics: generics.into_json(renderer), has_stripped_fields, - fields: renderer.ids(&fields), + fields: renderer.ids(fields), impls: Vec::new(), // Added in JsonRenderer::item } } @@ -659,7 +659,7 @@ impl FromClean<clean::FnDecl> for FunctionSignature { let clean::FnDecl { inputs, output, c_variadic } = decl; FunctionSignature { inputs: inputs - .into_iter() + .iter() .map(|param| { // `_` is the most sensible name for missing param names. let name = param.name.unwrap_or(kw::Underscore).to_string(); @@ -684,7 +684,7 @@ impl FromClean<clean::Trait> for Trait { is_auto, is_unsafe, is_dyn_compatible, - items: renderer.ids(&items), + items: renderer.ids(items), generics: generics.into_json(renderer), bounds: bounds.into_json(renderer), implementations: Vec::new(), // Added in JsonRenderer::item @@ -727,7 +727,7 @@ impl FromClean<clean::Impl> for Impl { .collect(), trait_: trait_.into_json(renderer), for_: for_.into_json(renderer), - items: renderer.ids(&items), + items: renderer.ids(items), is_negative, is_synthetic, blanket_impl: blanket_impl.map(|x| x.into_json(renderer)), @@ -770,7 +770,7 @@ impl FromClean<clean::Variant> for Variant { let kind = match &variant.kind { CLike => VariantKind::Plain, - Tuple(fields) => VariantKind::Tuple(renderer.ids_keeping_stripped(&fields)), + Tuple(fields) => VariantKind::Tuple(renderer.ids_keeping_stripped(fields)), Struct(s) => VariantKind::Struct { has_stripped_fields: s.has_stripped_entries(), fields: renderer.ids(&s.fields), diff --git a/src/librustdoc/json/mod.rs b/src/librustdoc/json/mod.rs index 600a4b429f3..760e48baffa 100644 --- a/src/librustdoc/json/mod.rs +++ b/src/librustdoc/json/mod.rs @@ -133,7 +133,7 @@ fn target(sess: &rustc_session::Session) -> types::Target { let feature_stability: FxHashMap<&str, Stability> = sess .target .rust_target_features() - .into_iter() + .iter() .copied() .map(|(name, stability, _)| (name, stability)) .collect(); @@ -143,7 +143,7 @@ fn target(sess: &rustc_session::Session) -> types::Target { target_features: sess .target .rust_target_features() - .into_iter() + .iter() .copied() .filter(|(_, stability, _)| { // Describe only target features which the user can toggle @@ -157,7 +157,7 @@ fn target(sess: &rustc_session::Session) -> types::Target { _ => None, }, implies_features: implied_features - .into_iter() + .iter() .copied() .filter(|name| { // Imply only target features which the user can toggle diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs index ca6f67eb6df..5a9aa2a94c8 100644 --- a/src/librustdoc/passes/collect_intra_doc_links.rs +++ b/src/librustdoc/passes/collect_intra_doc_links.rs @@ -274,7 +274,7 @@ impl From<DiagnosticInfo<'_>> for OwnedDiagnosticInfo { } impl OwnedDiagnosticInfo { - pub(crate) fn into_info(&self) -> DiagnosticInfo<'_> { + pub(crate) fn as_info(&self) -> DiagnosticInfo<'_> { DiagnosticInfo { item: &self.item, ori_link: &self.ori_link, @@ -1177,7 +1177,7 @@ impl LinkCollector<'_, '_> { // Primitive types are always valid. Res::Primitive(_) => true, }); - let diag_info = info.diag_info.into_info(); + let diag_info = info.diag_info.as_info(); match info.resolved.len() { 1 => { let (res, fragment) = info.resolved.pop().unwrap(); @@ -1243,17 +1243,16 @@ impl LinkCollector<'_, '_> { disambiguator, None | Some(Disambiguator::Namespace(Namespace::TypeNS) | Disambiguator::Primitive) ) && !matches!(res, Res::Primitive(_)) + && let Some(prim) = resolve_primitive(path_str, TypeNS) { - if let Some(prim) = resolve_primitive(path_str, TypeNS) { - // `prim@char` - if matches!(disambiguator, Some(Disambiguator::Primitive)) { - res = prim; - } else { - // `[char]` when a `char` module is in scope - let candidates = &[(res, res.def_id(self.cx.tcx)), (prim, None)]; - ambiguity_error(self.cx, &diag_info, path_str, candidates, true); - return None; - } + // `prim@char` + if matches!(disambiguator, Some(Disambiguator::Primitive)) { + res = prim; + } else { + // `[char]` when a `char` module is in scope + let candidates = &[(res, res.def_id(self.cx.tcx)), (prim, None)]; + ambiguity_error(self.cx, &diag_info, path_str, candidates, true); + return None; } } @@ -2233,7 +2232,7 @@ fn ambiguity_error( // proc macro can exist in multiple namespaces at once, so we need to compare `DefIds` // to remove the candidate in the fn namespace. let mut possible_proc_macro_id = None; - let is_proc_macro_crate = cx.tcx.crate_types() == &[CrateType::ProcMacro]; + let is_proc_macro_crate = cx.tcx.crate_types() == [CrateType::ProcMacro]; let mut kinds = candidates .iter() .map(|(res, def_id)| { diff --git a/src/librustdoc/passes/lint/redundant_explicit_links.rs b/src/librustdoc/passes/lint/redundant_explicit_links.rs index 5757b6a9740..e69cf87f957 100644 --- a/src/librustdoc/passes/lint/redundant_explicit_links.rs +++ b/src/librustdoc/passes/lint/redundant_explicit_links.rs @@ -93,14 +93,14 @@ fn check_redundant_explicit_link<'md>( if let Event::Start(Tag::Link { link_type, dest_url, .. }) = event { let link_data = collect_link_data(&mut offset_iter); - if let Some(resolvable_link) = link_data.resolvable_link.as_ref() { - if &link_data.display_link.replace('`', "") != resolvable_link { - // Skips if display link does not match to actual - // resolvable link, usually happens if display link - // has several segments, e.g. - // [this is just an `Option`](Option) - continue; - } + if let Some(resolvable_link) = link_data.resolvable_link.as_ref() + && &link_data.display_link.replace('`', "") != resolvable_link + { + // Skips if display link does not match to actual + // resolvable link, usually happens if display link + // has several segments, e.g. + // [this is just an `Option`](Option) + continue; } let explicit_link = dest_url.to_string(); diff --git a/src/librustdoc/passes/strip_aliased_non_local.rs b/src/librustdoc/passes/strip_aliased_non_local.rs index b53e3b4e3d7..bb13308e6c2 100644 --- a/src/librustdoc/passes/strip_aliased_non_local.rs +++ b/src/librustdoc/passes/strip_aliased_non_local.rs @@ -47,13 +47,11 @@ impl DocFolder for NonLocalStripper<'_> { // FIXME(#125009): Not-local should probably consider same Cargo workspace if let Some(def_id) = i.def_id() && !def_id.is_local() - { - if i.is_doc_hidden() + && (i.is_doc_hidden() // Default to *not* stripping items with inherited visibility. - || i.visibility(self.tcx).is_some_and(|viz| viz != Visibility::Public) - { - return Some(strip_item(i)); - } + || i.visibility(self.tcx).is_some_and(|viz| viz != Visibility::Public)) + { + return Some(strip_item(i)); } Some(self.fold_item_recur(i)) diff --git a/src/llvm-project b/src/llvm-project -Subproject d3c793b025645a4565ac59aceb30d2d116ff1a4 +Subproject e8a2ffcf322f45b8dce82c65ab27a3e2430a6b5 diff --git a/src/tools/clippy/clippy_lints/src/std_instead_of_core.rs b/src/tools/clippy/clippy_lints/src/std_instead_of_core.rs index cf70e883bd0..216f168471e 100644 --- a/src/tools/clippy/clippy_lints/src/std_instead_of_core.rs +++ b/src/tools/clippy/clippy_lints/src/std_instead_of_core.rs @@ -249,7 +249,7 @@ fn is_stable(cx: &LateContext<'_>, mut def_id: DefId, msrv: Msrv) -> bool { let stable = match since { StableSince::Version(v) => msrv.meets(cx, v), StableSince::Current => msrv.current(cx).is_none(), - StableSince::Err => false, + StableSince::Err(_) => false, }; if !stable { diff --git a/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs b/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs index 942c71ac33b..b3356450d38 100644 --- a/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs +++ b/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs @@ -432,7 +432,7 @@ pub fn is_stable_const_fn(cx: &LateContext<'_>, def_id: DefId, msrv: Msrv) -> bo let const_stab_rust_version = match since { StableSince::Version(version) => version, StableSince::Current => RustcVersion::CURRENT, - StableSince::Err => return false, + StableSince::Err(_) => return false, }; msrv.meets(cx, const_stab_rust_version) diff --git a/src/tools/compiletest/src/common.rs b/src/tools/compiletest/src/common.rs index 33da1a25db1..12084fa0b15 100644 --- a/src/tools/compiletest/src/common.rs +++ b/src/tools/compiletest/src/common.rs @@ -88,11 +88,37 @@ string_enum! { } } +string_enum! { + #[derive(Clone, Copy, PartialEq, Debug, Hash)] + pub enum RunResult { + Pass => "run-pass", + Fail => "run-fail", + Crash => "run-crash", + } +} + +#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)] +pub enum RunFailMode { + /// Running the program must make it exit with a regular failure exit code + /// in the range `1..=127`. If the program is terminated by e.g. a signal + /// the test will fail. + Fail, + /// Running the program must result in a crash, e.g. by `SIGABRT` or + /// `SIGSEGV` on Unix or on Windows by having an appropriate NTSTATUS high + /// bit in the exit code. + Crash, + /// Running the program must either fail or crash. Useful for e.g. sanitizer + /// tests since some sanitizer implementations exit the process with code 1 + /// to in the face of memory errors while others abort (crash) the process + /// in the face of memory errors. + FailOrCrash, +} + #[derive(Copy, Clone, Debug, PartialEq, PartialOrd)] pub enum FailMode { Check, Build, - Run, + Run(RunFailMode), } string_enum! { @@ -149,6 +175,36 @@ pub enum Sanitizer { Hwaddress, } +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum CodegenBackend { + Cranelift, + Gcc, + Llvm, +} + +impl<'a> TryFrom<&'a str> for CodegenBackend { + type Error = &'static str; + + fn try_from(value: &'a str) -> Result<Self, Self::Error> { + match value.to_lowercase().as_str() { + "cranelift" => Ok(Self::Cranelift), + "gcc" => Ok(Self::Gcc), + "llvm" => Ok(Self::Llvm), + _ => Err("unknown backend"), + } + } +} + +impl CodegenBackend { + pub fn as_str(self) -> &'static str { + match self { + Self::Cranelift => "cranelift", + Self::Gcc => "gcc", + Self::Llvm => "llvm", + } + } +} + /// Configuration for `compiletest` *per invocation*. /// /// In terms of `bootstrap`, this means that `./x test tests/ui tests/run-make` actually correspond @@ -625,6 +681,9 @@ pub struct Config { /// need `core` stubs in cross-compilation scenarios that do not otherwise want/need to /// `-Zbuild-std`. Used in e.g. ABI tests. pub minicore_path: Utf8PathBuf, + + /// Current codegen backend used. + pub codegen_backend: CodegenBackend, } impl Config { @@ -727,6 +786,7 @@ impl Config { profiler_runtime: Default::default(), diff_command: Default::default(), minicore_path: Default::default(), + codegen_backend: CodegenBackend::Llvm, } } diff --git a/src/tools/compiletest/src/directives.rs b/src/tools/compiletest/src/directives.rs index 93133ea0bfd..1397c87ab07 100644 --- a/src/tools/compiletest/src/directives.rs +++ b/src/tools/compiletest/src/directives.rs @@ -9,7 +9,7 @@ use camino::{Utf8Path, Utf8PathBuf}; use semver::Version; use tracing::*; -use crate::common::{Config, Debugger, FailMode, PassMode, TestMode}; +use crate::common::{CodegenBackend, Config, Debugger, FailMode, PassMode, RunFailMode, TestMode}; use crate::debuggers::{extract_cdb_version, extract_gdb_version}; use crate::directives::auxiliary::{AuxProps, parse_and_update_aux}; use crate::directives::needs::CachedNeedsConditions; @@ -654,7 +654,13 @@ impl TestProps { Some(FailMode::Build) } else if config.parse_name_directive(ln, "run-fail") { check_ui("run"); - Some(FailMode::Run) + Some(FailMode::Run(RunFailMode::Fail)) + } else if config.parse_name_directive(ln, "run-crash") { + check_ui("run"); + Some(FailMode::Run(RunFailMode::Crash)) + } else if config.parse_name_directive(ln, "run-fail-or-crash") { + check_ui("run"); + Some(FailMode::Run(RunFailMode::FailOrCrash)) } else { None }; @@ -812,6 +818,7 @@ const KNOWN_DIRECTIVE_NAMES: &[&str] = &[ "ignore-arm-unknown-linux-musleabihf", "ignore-auxiliary", "ignore-avr", + "ignore-backends", "ignore-beta", "ignore-cdb", "ignore-compare-mode-next-solver", @@ -901,6 +908,7 @@ const KNOWN_DIRECTIVE_NAMES: &[&str] = &[ "min-llvm-version", "min-system-llvm-version", "needs-asm-support", + "needs-backends", "needs-crate-type", "needs-deterministic-layouts", "needs-dlltool", @@ -1007,7 +1015,9 @@ const KNOWN_DIRECTIVE_NAMES: &[&str] = &[ "regex-error-pattern", "remap-src-base", "revisions", + "run-crash", "run-fail", + "run-fail-or-crash", "run-flags", "run-pass", "run-rustfix", @@ -1661,6 +1671,8 @@ pub(crate) fn make_test_description<R: Read>( decision!(cfg::handle_only(config, ln)); decision!(needs::handle_needs(&cache.needs, config, ln)); decision!(ignore_llvm(config, path, ln)); + decision!(ignore_backends(config, path, ln)); + decision!(needs_backends(config, path, ln)); decision!(ignore_cdb(config, ln)); decision!(ignore_gdb(config, ln)); decision!(ignore_lldb(config, ln)); @@ -1787,6 +1799,49 @@ fn ignore_lldb(config: &Config, line: &str) -> IgnoreDecision { IgnoreDecision::Continue } +fn ignore_backends(config: &Config, path: &Utf8Path, line: &str) -> IgnoreDecision { + if let Some(backends_to_ignore) = config.parse_name_value_directive(line, "ignore-backends") { + for backend in backends_to_ignore.split_whitespace().map(|backend| { + match CodegenBackend::try_from(backend) { + Ok(backend) => backend, + Err(error) => { + panic!("Invalid ignore-backends value `{backend}` in `{path}`: {error}") + } + } + }) { + if config.codegen_backend == backend { + return IgnoreDecision::Ignore { + reason: format!("{} backend is marked as ignore", backend.as_str()), + }; + } + } + } + IgnoreDecision::Continue +} + +fn needs_backends(config: &Config, path: &Utf8Path, line: &str) -> IgnoreDecision { + if let Some(needed_backends) = config.parse_name_value_directive(line, "needs-backends") { + if !needed_backends + .split_whitespace() + .map(|backend| match CodegenBackend::try_from(backend) { + Ok(backend) => backend, + Err(error) => { + panic!("Invalid needs-backends value `{backend}` in `{path}`: {error}") + } + }) + .any(|backend| config.codegen_backend == backend) + { + return IgnoreDecision::Ignore { + reason: format!( + "{} backend is not part of required backends", + config.codegen_backend.as_str() + ), + }; + } + } + IgnoreDecision::Continue +} + fn ignore_llvm(config: &Config, path: &Utf8Path, line: &str) -> IgnoreDecision { if let Some(needed_components) = config.parse_name_value_directive(line, "needs-llvm-components") diff --git a/src/tools/compiletest/src/lib.rs b/src/tools/compiletest/src/lib.rs index f3b3605a120..41bed8ed8a0 100644 --- a/src/tools/compiletest/src/lib.rs +++ b/src/tools/compiletest/src/lib.rs @@ -39,7 +39,7 @@ use walkdir::WalkDir; use self::directives::{EarlyProps, make_test_description}; use crate::common::{ - CompareMode, Config, Debugger, PassMode, TestMode, TestPaths, UI_EXTENSIONS, + CodegenBackend, CompareMode, Config, Debugger, PassMode, TestMode, TestPaths, UI_EXTENSIONS, expected_output_path, output_base_dir, output_relative_path, }; use crate::directives::DirectivesCache; @@ -203,6 +203,12 @@ pub fn parse_config(args: Vec<String>) -> Config { "debugger", "only test a specific debugger in debuginfo tests", "gdb | lldb | cdb", + ) + .optopt( + "", + "codegen-backend", + "the codegen backend currently used", + "CODEGEN BACKEND NAME", ); let (argv0, args_) = args.split_first().unwrap(); @@ -264,6 +270,15 @@ pub fn parse_config(args: Vec<String>) -> Config { || directives::extract_llvm_version_from_binary(&matches.opt_str("llvm-filecheck")?), ); + let codegen_backend = match matches.opt_str("codegen-backend").as_deref() { + Some(backend) => match CodegenBackend::try_from(backend) { + Ok(backend) => backend, + Err(error) => panic!("invalid value `{backend}` for `--codegen-backend`: {error}"), + }, + // By default, it's always llvm. + None => CodegenBackend::Llvm, + }; + let run_ignored = matches.opt_present("ignored"); let with_rustc_debug_assertions = matches.opt_present("with-rustc-debug-assertions"); let with_std_debug_assertions = matches.opt_present("with-std-debug-assertions"); @@ -449,6 +464,8 @@ pub fn parse_config(args: Vec<String>) -> Config { diff_command: matches.opt_str("compiletest-diff-tool"), minicore_path: opt_path(matches, "minicore-path"), + + codegen_backend, } } diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index cb8f593c9df..f66d4f98f1f 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -16,8 +16,8 @@ use regex::{Captures, Regex}; use tracing::*; use crate::common::{ - CompareMode, Config, Debugger, FailMode, PassMode, TestMode, TestPaths, TestSuite, - UI_EXTENSIONS, UI_FIXED, UI_RUN_STDERR, UI_RUN_STDOUT, UI_STDERR, UI_STDOUT, UI_SVG, + CompareMode, Config, Debugger, FailMode, PassMode, RunFailMode, RunResult, TestMode, TestPaths, + TestSuite, UI_EXTENSIONS, UI_FIXED, UI_RUN_STDERR, UI_RUN_STDOUT, UI_STDERR, UI_STDOUT, UI_SVG, UI_WINDOWS_SVG, expected_output_path, incremental_dir, output_base_dir, output_base_name, output_testname_unique, }; @@ -282,7 +282,8 @@ impl<'test> TestCx<'test> { fn should_run(&self, pm: Option<PassMode>) -> WillExecute { let test_should_run = match self.config.mode { TestMode::Ui - if pm == Some(PassMode::Run) || self.props.fail_mode == Some(FailMode::Run) => + if pm == Some(PassMode::Run) + || matches!(self.props.fail_mode, Some(FailMode::Run(_))) => { true } diff --git a/src/tools/compiletest/src/runtest/ui.rs b/src/tools/compiletest/src/runtest/ui.rs index f6bc85cd051..0507c2600ae 100644 --- a/src/tools/compiletest/src/runtest/ui.rs +++ b/src/tools/compiletest/src/runtest/ui.rs @@ -6,8 +6,8 @@ use rustfix::{Filter, apply_suggestions, get_suggestions_from_json}; use tracing::debug; use super::{ - AllowUnused, Emit, FailMode, LinkToAux, PassMode, TargetLocation, TestCx, TestOutput, - Truncated, UI_FIXED, WillExecute, + AllowUnused, Emit, FailMode, LinkToAux, PassMode, RunFailMode, RunResult, TargetLocation, + TestCx, TestOutput, Truncated, UI_FIXED, WillExecute, }; use crate::json; @@ -140,12 +140,53 @@ impl TestCx<'_> { &proc_res, ); } + let code = proc_res.status.code(); + let run_result = if proc_res.status.success() { + RunResult::Pass + } else if code.is_some_and(|c| c >= 1 && c <= 127) { + RunResult::Fail + } else { + RunResult::Crash + }; + // Help users understand why the test failed by including the actual + // exit code and actual run result in the failure message. + let pass_hint = format!("code={code:?} so test would pass with `{run_result}`"); if self.should_run_successfully(pm) { - if !proc_res.status.success() { - self.fatal_proc_rec("test run failed!", &proc_res); + if run_result != RunResult::Pass { + self.fatal_proc_rec( + &format!("test did not exit with success! {pass_hint}"), + &proc_res, + ); + } + } else if self.props.fail_mode == Some(FailMode::Run(RunFailMode::Fail)) { + // If the test is marked as `run-fail` but do not support + // unwinding we allow it to crash, since a panic will trigger an + // abort (crash) instead of unwind (exit with code 101). + let crash_ok = !self.config.can_unwind(); + if run_result != RunResult::Fail && !(crash_ok && run_result == RunResult::Crash) { + let err = if crash_ok { + format!( + "test did not exit with failure or crash (`{}` can't unwind)! {pass_hint}", + self.config.target + ) + } else { + format!("test did not exit with failure! {pass_hint}") + }; + self.fatal_proc_rec(&err, &proc_res); } - } else if proc_res.status.success() { - self.fatal_proc_rec("test run succeeded!", &proc_res); + } else if self.props.fail_mode == Some(FailMode::Run(RunFailMode::Crash)) { + if run_result != RunResult::Crash { + self.fatal_proc_rec(&format!("test did not crash! {pass_hint}"), &proc_res); + } + } else if self.props.fail_mode == Some(FailMode::Run(RunFailMode::FailOrCrash)) { + if run_result != RunResult::Fail && run_result != RunResult::Crash { + self.fatal_proc_rec( + &format!("test did not exit with failure or crash! {pass_hint}"), + &proc_res, + ); + } + } else { + unreachable!("run_ui_test() must not be called if the test should not run"); } self.get_output(&proc_res) diff --git a/src/tools/enzyme b/src/tools/enzyme -Subproject b5098d515d5e1bd0f5470553bc0d18da9794ca8 +Subproject 2cccfba93c1650f26f1cf8be8aa875a7c1d23fb diff --git a/src/tools/miri/CONTRIBUTING.md b/src/tools/miri/CONTRIBUTING.md index fef7f807e93..637c0dd2fdf 100644 --- a/src/tools/miri/CONTRIBUTING.md +++ b/src/tools/miri/CONTRIBUTING.md @@ -13,16 +13,20 @@ for a list of Miri maintainers. [Rust Zulip]: https://rust-lang.zulipchat.com -### Pull review process +### PR review process When you get a review, please take care of the requested changes in new commits. Do not amend existing commits. Generally avoid force-pushing. The only time you should force push is when there is a conflict with the master branch (in that case you should rebase across master, not merge), and all the way at the end of the review process when the reviewer tells you that the PR is done and you -should squash the commits. If you are unsure how to use `git rebase` to squash commits, use `./miri -squash` which automates the process but leaves little room for customization. (All this is to work -around the fact that Github is quite bad at dealing with force pushes and does not support `git -range-diff`. Maybe one day Github will be good at git and then life can become easier.) +should squash the commits. (All this is to work around the fact that Github is quite bad at +dealing with force pushes and does not support `git range-diff`.) + +The recommended way to squash commits is to use `./miri squash`, which will make everything into a +single commit. You will be asked for the commit message; please ensure it describes the entire PR. +You can also use `git rebase` manually if you need more control (e.g. if there should be more than +one commit at the end), but then please use `--keep-base` to ensure the PR remains based on the same +upstream commit. Most PRs bounce back and forth between the reviewer and the author several times, so it is good to keep track of who is expected to take the next step. We are using the `S-waiting-for-review` and @@ -348,6 +352,7 @@ https. Add the following to your `.gitconfig`: The following environment variables are relevant to `./miri`: +* `CARGO` sets the binary used to execute Cargo; if none is specified, defaults to `cargo`. * `MIRI_AUTO_OPS` indicates whether the automatic execution of rustfmt, clippy and toolchain setup (as controlled by the `./auto-*` files) should be skipped. If it is set to `no`, they are skipped. This is used to allow automated IDE actions to avoid the auto ops. diff --git a/src/tools/miri/Cargo.lock b/src/tools/miri/Cargo.lock index aa6f059cec2..0af4181dc15 100644 --- a/src/tools/miri/Cargo.lock +++ b/src/tools/miri/Cargo.lock @@ -4,18 +4,18 @@ version = 4 [[package]] name = "addr2line" -version = "0.21.0" +version = "0.24.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a30b2e23b9e17a9f90641c7ab1549cd9b44f296d3ccbf309d2863cfe398a0cb" +checksum = "dfbe277e56a376000877090da837660b4427aad530e3028d44e0bffe4f89a1c1" dependencies = [ "gimli", ] [[package]] -name = "adler" -version = "1.0.2" +name = "adler2" +version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "aes" @@ -44,40 +44,40 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "710e8eae58854cdc1790fcb56cca04d712a17be849eeb81da2a724bf4bae2bc4" dependencies = [ "anstyle", - "unicode-width 0.2.0", + "unicode-width 0.2.1", ] [[package]] name = "anstyle" -version = "1.0.10" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55cc3b69f167a1ef2e161439aa98aed94e6028e5f9a59be9a6ffb47aef1651f9" +checksum = "862ed96ca487e809f1c8e5a8447f6ee2cf102f846893800b20cebdf541fc6bbd" [[package]] name = "anyhow" -version = "1.0.97" +version = "1.0.98" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcfed56ad506cb2c684a14971b8861fdc3baaaae314b9e5f9bb532cbe3ba7a4f" +checksum = "e16d2d3311acee920a9eb8d33b8cbc1787ce4a264e85f964c2404b969bdcd487" [[package]] name = "autocfg" -version = "1.4.0" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" +checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" [[package]] name = "backtrace" -version = "0.3.71" +version = "0.3.75" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26b05800d2e817c8b3b4b54abd461726265fa9789ae34330622f2db9ee696f9d" +checksum = "6806a6321ec58106fea15becdad98371e28d92ccbc7c8f1b3b6dd724fe8f1002" dependencies = [ "addr2line", - "cc", "cfg-if", "libc", "miniz_oxide", "object", "rustc-demangle", + "windows-targets 0.52.6", ] [[package]] @@ -91,15 +91,15 @@ dependencies = [ [[package]] name = "bitflags" -version = "2.9.0" +version = "2.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd" +checksum = "1b8e56985ec62d17e9c1001dc89c88ecd7dc08e47eba5ec7c29c7b5eeecde967" [[package]] name = "bstr" -version = "1.11.3" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "531a9155a481e2ee699d4f98f43c0ca4ff8ee1bfd55c31e9e98fb29d2b176fe0" +checksum = "234113d19d0d7d613b40e86fb654acf958910802bcceab913a4f9e7cda03b1a4" dependencies = [ "memchr", "regex-automata", @@ -108,15 +108,15 @@ dependencies = [ [[package]] name = "bumpalo" -version = "3.17.0" +version = "3.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1628fb46dfa0b37568d12e5edd512553eccf6a22a78e8bde00bb4aed84d5bdbf" +checksum = "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43" [[package]] name = "camino" -version = "1.1.9" +version = "1.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b96ec4966b5813e2c0507c1f86115c8c5abaadc3980879c3424042a02fd1ad3" +checksum = "0da45bc31171d8d6960122e222a67740df867c1dd53b4d51caa297084c185cab" dependencies = [ "serde", ] @@ -166,18 +166,18 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.17" +version = "1.2.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fcb57c740ae1daf453ae85f16e37396f672b039e00d9d866e07ddb24e328e3a" +checksum = "deec109607ca693028562ed836a5f1c4b8bd77755c4e132fc5ce11b0b6211ae7" dependencies = [ "shlex", ] [[package]] name = "cfg-if" -version = "1.0.0" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" +checksum = "9555578bc9e57714c812a1f84e4fc5b4d21fcb063490c624de019f7464c91268" [[package]] name = "cfg_aliases" @@ -187,35 +187,24 @@ checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" [[package]] name = "chrono" -version = "0.4.40" +version = "0.4.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a7964611d71df112cb1730f2ee67324fcf4d0fc6606acbbe9bfe06df124637c" +checksum = "c469d952047f47f91b68d1cba3f10d63c11d73e4636f24f08daf0278abf01c4d" dependencies = [ "num-traits", ] [[package]] name = "chrono-tz" -version = "0.10.3" +version = "0.10.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "efdce149c370f133a071ca8ef6ea340b7b88748ab0810097a9e2976eaa34b4f3" +checksum = "a6139a8597ed92cf816dfb33f5dd6cf0bb93a6adc938f11039f371bc5bcd26c3" dependencies = [ "chrono", - "chrono-tz-build", "phf", ] [[package]] -name = "chrono-tz-build" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f10f8c9340e31fc120ff885fcdb54a0b48e474bbd77cab557f0c30a3e569402" -dependencies = [ - "parse-zoneinfo", - "phf_codegen", -] - -[[package]] name = "cipher" version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -227,27 +216,27 @@ dependencies = [ [[package]] name = "color-eyre" -version = "0.6.3" +version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55146f5e46f237f7423d74111267d4597b59b0dad0ffaf7303bce9945d843ad5" +checksum = "e5920befb47832a6d61ee3a3a846565cfa39b331331e68a3b1d1116630f2f26d" dependencies = [ "backtrace", "color-spantrace", "eyre", "indenter", "once_cell", - "owo-colors", + "owo-colors 4.2.2", "tracing-error", ] [[package]] name = "color-spantrace" -version = "0.2.1" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd6be1b2a7e382e2b98b43b2adcca6bb0e465af0bdd38123873ae61eb17a72c2" +checksum = "b8b88ea9df13354b55bc7234ebcce36e6ef896aca2e42a15de9e10edce01b427" dependencies = [ "once_cell", - "owo-colors", + "owo-colors 4.2.2", "tracing-core", "tracing-error", ] @@ -263,6 +252,15 @@ dependencies = [ ] [[package]] +name = "colored" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fde0e0ec90c9dfb3b4b1a0891a7dcd0e2bffde2f7efed5fe7c9bb00e5bfb915e" +dependencies = [ + "windows-sys 0.59.0", +] + +[[package]] name = "comma" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -277,7 +275,7 @@ dependencies = [ "encode_unicode", "libc", "once_cell", - "unicode-width 0.2.0", + "unicode-width 0.2.1", "windows-sys 0.59.0", ] @@ -333,7 +331,7 @@ dependencies = [ "libc", "option-ext", "redox_users", - "windows-sys 0.59.0", + "windows-sys 0.60.2", ] [[package]] @@ -344,12 +342,12 @@ checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" [[package]] name = "errno" -version = "0.3.11" +version = "0.3.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "976dd42dc7e85965fe702eb8164f21f450704bdde31faefd6471dba214cb594e" +checksum = "778e2ac28f6c47af28e4907f13ffd1e1ddbd400980a9abd7c8df189bf578a5ad" dependencies = [ "libc", - "windows-sys 0.59.0", + "windows-sys 0.60.2", ] [[package]] @@ -386,20 +384,20 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.2.15" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" +checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592" dependencies = [ "cfg-if", "libc", - "wasi 0.11.0+wasi-snapshot-preview1", + "wasi 0.11.1+wasi-snapshot-preview1", ] [[package]] name = "getrandom" -version = "0.3.2" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73fea8450eea4bac3940448fb7ae50d91f034f941199fcd9d909a5a07aa455f0" +checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4" dependencies = [ "cfg-if", "libc", @@ -409,9 +407,9 @@ dependencies = [ [[package]] name = "gimli" -version = "0.28.1" +version = "0.31.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4271d37baee1b8c7e4b708028c57d816cf9d2434acb33a549475f78c181f6253" +checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f" [[package]] name = "indenter" @@ -428,7 +426,7 @@ dependencies = [ "console", "number_prefix", "portable-atomic", - "unicode-width 0.2.0", + "unicode-width 0.2.1", "web-time", ] @@ -443,17 +441,16 @@ dependencies = [ [[package]] name = "ipc-channel" -version = "0.19.0" +version = "0.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fb8251fb7bcd9ccd3725ed8deae9fe7db8e586495c9eb5b0c52e6233e5e75ea" +checksum = "5b1c98b70019c830a1fc39cecfe1f60ff99c4122f0a189697c810c90ec545c14" dependencies = [ "bincode", "crossbeam-channel", "fnv", - "lazy_static", "libc", "mio", - "rand 0.8.5", + "rand", "serde", "tempfile", "uuid", @@ -490,15 +487,15 @@ checksum = "db13adb97ab515a3691f56e4dbab09283d0b86cb45abd991d8634a9d6f501760" [[package]] name = "libc" -version = "0.2.171" +version = "0.2.174" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c19937216e9d3aa9956d9bb8dfc0b0c8beb6058fc4f7a4dc4d850edf86a237d6" +checksum = "1171693293099992e19cddea4e8b849964e9846f4acee11b3948bcc337be8776" [[package]] name = "libffi" -version = "4.0.0" +version = "4.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a9434b6fc77375fb624698d5f8c49d7e80b10d59eb1219afda27d1f824d4074" +checksum = "e7681c6fab541f799a829e44a445a0666cf8d8a6cfebf89419e6aed52c604e87" dependencies = [ "libc", "libffi-sys", @@ -506,28 +503,28 @@ dependencies = [ [[package]] name = "libffi-sys" -version = "3.2.0" +version = "3.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ead36a2496acfc8edd6cc32352110e9478ac5b9b5f5b9856ebd3d28019addb84" +checksum = "7b0d828d367b4450ed08e7d510dc46636cd660055f50d67ac943bfe788767c29" dependencies = [ "cc", ] [[package]] name = "libloading" -version = "0.8.6" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc2f4eb4bc735547cfed7c0a4922cbd04a4655978c09b54f1f7b228750664c34" +checksum = "07033963ba89ebaf1584d767badaa2e8fcec21aedea6b8c0346d487d49c28667" dependencies = [ "cfg-if", - "windows-targets", + "windows-targets 0.53.2", ] [[package]] name = "libredox" -version = "0.1.3" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d" +checksum = "1580801010e535496706ba011c15f8532df6b42297d2e471fec38ceadd8c0638" dependencies = [ "bitflags", "libc", @@ -535,15 +532,15 @@ dependencies = [ [[package]] name = "linux-raw-sys" -version = "0.9.3" +version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe7db12097d22ec582439daf8618b8fdd1a7bef6270e9af3b1ebcd30893cf413" +checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12" [[package]] name = "lock_api" -version = "0.4.12" +version = "0.4.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17" +checksum = "96936507f153605bddfcda068dd804796c84324ed2510809e5b2a624c81da765" dependencies = [ "autocfg", "scopeguard", @@ -557,9 +554,9 @@ checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94" [[package]] name = "measureme" -version = "12.0.1" +version = "12.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "570a507d8948a66a97f42cbbaf8a6bb9516a51017d4ee949502ad7a10a864395" +checksum = "6ebd1ebda747ae161a4a377bf93f87e18d46faad2331cc0c7d25b84b1d445f49" dependencies = [ "log", "memmap2", @@ -571,9 +568,9 @@ dependencies = [ [[package]] name = "memchr" -version = "2.7.4" +version = "2.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" +checksum = "32a282da65faaf38286cf3be983213fcf1d2e2a58700e808f83f4ea9a4804bc0" [[package]] name = "memmap2" @@ -586,23 +583,22 @@ dependencies = [ [[package]] name = "miniz_oxide" -version = "0.7.4" +version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8a240ddb74feaf34a79a7add65a741f3167852fba007066dcac1ca548d89c08" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" dependencies = [ - "adler", + "adler2", ] [[package]] name = "mio" -version = "1.0.3" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2886843bf800fba2e3377cff24abf6379b4c4d5c6681eaf9ea5b0d15090450bd" +checksum = "78bed444cc8a2160f01cbcf811ef18cac863ad68ae8ca62092e8db51d51c761c" dependencies = [ "libc", - "log", - "wasi 0.11.0+wasi-snapshot-preview1", - "windows-sys 0.52.0", + "wasi 0.11.1+wasi-snapshot-preview1", + "windows-sys 0.59.0", ] [[package]] @@ -614,16 +610,16 @@ dependencies = [ "capstone", "chrono", "chrono-tz", - "colored", + "colored 3.0.0", "directories", - "getrandom 0.3.2", + "getrandom 0.3.3", "ipc-channel", "libc", "libffi", "libloading", "measureme", "nix", - "rand 0.9.0", + "rand", "regex", "rustc_version", "serde", @@ -663,9 +659,9 @@ checksum = "830b246a0e5f20af87141b25c173cd1b609bd7779a4617d6ec582abaf90870f3" [[package]] name = "object" -version = "0.32.2" +version = "0.36.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6a622008b6e321afc04970976f62ee297fdbaa6f95318ca343e3eebb9648441" +checksum = "62948e14d923ea95ea2c7c86c71013138b66525b86bdc08d2dcc262bdb497b87" dependencies = [ "memchr", ] @@ -689,6 +685,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1b04fb49957986fdce4d6ee7a65027d55d4b6d2265e5848bbb507b58ccfdb6f" [[package]] +name = "owo-colors" +version = "4.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48dd4f4a2c8405440fd0462561f0e5806bd0f77e86f51c761481bdd4018b545e" + +[[package]] name = "pad" version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -699,9 +701,9 @@ dependencies = [ [[package]] name = "parking_lot" -version = "0.12.3" +version = "0.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27" +checksum = "70d58bf43669b5795d1576d0641cfb6fbb2057bf629506267a92807158584a13" dependencies = [ "lock_api", "parking_lot_core", @@ -709,24 +711,15 @@ dependencies = [ [[package]] name = "parking_lot_core" -version = "0.9.10" +version = "0.9.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" +checksum = "bc838d2a56b5b1a6c25f55575dfc605fabb63bb2365f6c2353ef9159aa69e4a5" dependencies = [ "cfg-if", "libc", "redox_syscall", "smallvec", - "windows-targets", -] - -[[package]] -name = "parse-zoneinfo" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f2a05b18d44e2957b88f96ba460715e295bc1d7510468a2f3d3b44535d26c24" -dependencies = [ - "regex", + "windows-targets 0.52.6", ] [[package]] @@ -740,38 +733,18 @@ dependencies = [ [[package]] name = "phf" -version = "0.11.3" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" +checksum = "913273894cec178f401a31ec4b656318d95473527be05c0752cc41cdc32be8b7" dependencies = [ "phf_shared", ] [[package]] -name = "phf_codegen" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aef8048c789fa5e851558d709946d6d79a8ff88c0440c587967f8e94bfb1216a" -dependencies = [ - "phf_generator", - "phf_shared", -] - -[[package]] -name = "phf_generator" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" -dependencies = [ - "phf_shared", - "rand 0.8.5", -] - -[[package]] name = "phf_shared" -version = "0.11.3" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +checksum = "06005508882fb681fd97892ecff4b7fd0fee13ef1aa569f8695dae7ab9099981" dependencies = [ "siphasher", ] @@ -784,9 +757,9 @@ checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" [[package]] name = "portable-atomic" -version = "1.11.0" +version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "350e9b48cbc6b0e028b0473b114454c6316e57336ee184ceab6e53f72c178b3e" +checksum = "f84267b20a16ea918e43c6a88433c2d54fa145c92a811b5b047ccbe153674483" [[package]] name = "ppv-lite86" @@ -803,15 +776,15 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "abec3fb083c10660b3854367697da94c674e9e82aa7511014dc958beeb7215e9" dependencies = [ - "owo-colors", + "owo-colors 3.5.0", "pad", ] [[package]] name = "proc-macro2" -version = "1.0.94" +version = "1.0.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a31971752e70b8b2686d7e46ec17fb38dad4051d94024c88df49b667caea9c84" +checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778" dependencies = [ "unicode-ident", ] @@ -827,40 +800,18 @@ dependencies = [ [[package]] name = "r-efi" -version = "5.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74765f6d916ee2faa39bc8e68e4f3ed8949b48cccdac59983d287a7cb71ce9c5" - -[[package]] -name = "rand" -version = "0.8.5" +version = "5.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" -dependencies = [ - "libc", - "rand_chacha 0.3.1", - "rand_core 0.6.4", -] +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" [[package]] name = "rand" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3779b94aeb87e8bd4e834cee3650289ee9e0d5677f976ecdb6d219e5f4f6cd94" -dependencies = [ - "rand_chacha 0.9.0", - "rand_core 0.9.3", - "zerocopy", -] - -[[package]] -name = "rand_chacha" -version = "0.3.1" +version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +checksum = "9fbfd9d094a40bf3ae768db9361049ace4c0e04a4fd6b359518bd7b73a73dd97" dependencies = [ - "ppv-lite86", - "rand_core 0.6.4", + "rand_chacha", + "rand_core", ] [[package]] @@ -870,16 +821,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" dependencies = [ "ppv-lite86", - "rand_core 0.9.3", -] - -[[package]] -name = "rand_core" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" -dependencies = [ - "getrandom 0.2.15", + "rand_core", ] [[package]] @@ -888,14 +830,14 @@ version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38" dependencies = [ - "getrandom 0.3.2", + "getrandom 0.3.3", ] [[package]] name = "redox_syscall" -version = "0.5.10" +version = "0.5.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b8c0c260b63a8219631167be35e6a988e9554dbd323f8bd08439c8ed1302bd1" +checksum = "0d04b7d0ee6b4a0207a0a7adb104d23ecb0b47d6beae7152d0fa34b692b29fd6" dependencies = [ "bitflags", ] @@ -906,7 +848,7 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd6f9d3d47bdd2ad6945c5015a226ec6155d0bcdfd8f7cd29f86b71f8de99d2b" dependencies = [ - "getrandom 0.2.15", + "getrandom 0.2.16", "libredox", "thiserror 2.0.12", ] @@ -942,9 +884,9 @@ checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" [[package]] name = "rustc-demangle" -version = "0.1.24" +version = "0.1.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" +checksum = "989e6739f80c4ad5b13e0fd7fe89531180375b18520cc8c82080e4dc4035b84f" [[package]] name = "rustc-hash" @@ -975,18 +917,24 @@ dependencies = [ [[package]] name = "rustix" -version = "1.0.5" +version = "1.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d97817398dd4bb2e6da002002db259209759911da105da92bec29ccb12cf58bf" +checksum = "11181fbabf243db407ef8df94a6ce0b2f9a733bd8be4ad02b4eda9602296cac8" dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys", - "windows-sys 0.59.0", + "windows-sys 0.60.2", ] [[package]] +name = "rustversion" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a0d197bd2c9dc6e53b84da9556a69ba4cdfab8619eb41a8bd1cc2027a0f6b1d" + +[[package]] name = "ryu" version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -1029,9 +977,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.140" +version = "1.0.141" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373" +checksum = "30b9eff21ebe718216c6ec64e1d9ac57087aad11efc64e32002bce4a0d4c03d3" dependencies = [ "itoa", "memchr", @@ -1062,25 +1010,26 @@ checksum = "56199f7ddabf13fe5074ce809e7d3f42b42ae711800501b5b16ea82ad029c39d" [[package]] name = "smallvec" -version = "1.14.0" +version = "1.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fcf8323ef1faaee30a44a340193b1ac6814fd9b7b4e88e9d4519a3e4abe1cfd" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" [[package]] name = "spanned" -version = "0.3.0" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86af297923fbcfd107c20a189a6e9c872160df71a7190ae4a7a6c5dce4b2feb6" +checksum = "c92d4b0c055fde758f086eb4a6e73410247df8a3837fd606d2caeeaf72aa566d" dependencies = [ + "anyhow", "bstr", "color-eyre", ] [[package]] name = "syn" -version = "2.0.100" +version = "2.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b09a44accad81e1ba1cd74a32461ba89dee89095ba17b32f5d03683b1b1fc2a0" +checksum = "17b6f705963418cdb9927482fa304bc562ece2fdd4f616084c50b7023b435a40" dependencies = [ "proc-macro2", "quote", @@ -1089,12 +1038,12 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.19.1" +version = "3.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7437ac7763b9b123ccf33c338a5cc1bac6f69b45a136c19bdd8a65e3916435bf" +checksum = "e8a64e3985349f2441a1a9ef0b853f869006c3855f2cda6862a94d26ebb9d6a1" dependencies = [ "fastrand", - "getrandom 0.3.2", + "getrandom 0.3.3", "once_cell", "rustix", "windows-sys 0.59.0", @@ -1142,12 +1091,11 @@ dependencies = [ [[package]] name = "thread_local" -version = "1.1.8" +version = "1.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b9ef9bad013ada3808854ceac7b46812a6465ba368859a37e2100283d2d719c" +checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" dependencies = [ "cfg-if", - "once_cell", ] [[package]] @@ -1172,9 +1120,9 @@ dependencies = [ [[package]] name = "tracing-core" -version = "0.1.33" +version = "0.1.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e672c95779cf947c5311f83787af4fa8fffd12fb27e4993211a84bdfd9610f9c" +checksum = "b9d12581f227e93f094d3af2ae690a574abb8a2b9b7a96e7cfe9647b2b617678" dependencies = [ "once_cell", "valuable", @@ -1209,9 +1157,9 @@ checksum = "1dccffe3ce07af9386bfd29e80c0ab1a8205a2fc34e4bcd40364df902cfa8f3f" [[package]] name = "ui_test" -version = "0.29.2" +version = "0.30.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1211b1111c752c73b33073d2958072be08825fd97c9ab4d83444da361a06634b" +checksum = "b56a6897cc4bb6f8daf1939b0b39cd9645856997f46f4d0b3e3cb7122dfe9251" dependencies = [ "annotate-snippets", "anyhow", @@ -1219,7 +1167,7 @@ dependencies = [ "cargo-platform", "cargo_metadata", "color-eyre", - "colored", + "colored 2.2.0", "comma", "crossbeam-channel", "indicatif", @@ -1247,17 +1195,19 @@ checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" [[package]] name = "unicode-width" -version = "0.2.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fc81956842c57dac11422a97c3b8195a1ff727f06e85c84ed2e8aa277c9a0fd" +checksum = "4a1a07cc7db3810833284e8d372ccdc6da29741639ecc70c9ec107df0fa6154c" [[package]] name = "uuid" -version = "1.16.0" +version = "1.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "458f7a779bf54acc9f347480ac654f68407d3aab21269a6e3c9f922acd9e2da9" +checksum = "3cf4199d1e5d15ddd86a694e4d0dffa9c323ce759fea589f00fef9d81cc1931d" dependencies = [ - "getrandom 0.3.2", + "getrandom 0.3.3", + "js-sys", + "wasm-bindgen", ] [[package]] @@ -1274,9 +1224,9 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" [[package]] name = "wasi" -version = "0.11.0+wasi-snapshot-preview1" +version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" [[package]] name = "wasi" @@ -1295,6 +1245,7 @@ checksum = "1edc8929d7499fc4e8f0be2262a241556cfc54a0bea223790e71446f2aab1ef5" dependencies = [ "cfg-if", "once_cell", + "rustversion", "wasm-bindgen-macro", ] @@ -1361,7 +1312,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd04d41d93c4992d421894c18c8b43496aa748dd4c081bac0dc93eb0489272b6" dependencies = [ "windows-core", - "windows-targets", + "windows-targets 0.52.6", ] [[package]] @@ -1374,7 +1325,7 @@ dependencies = [ "windows-interface", "windows-result", "windows-strings", - "windows-targets", + "windows-targets 0.52.6", ] [[package]] @@ -1405,7 +1356,7 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d1043d8214f791817bab27572aaa8af63732e11bf84aa21a45a78d6c317ae0e" dependencies = [ - "windows-targets", + "windows-targets 0.52.6", ] [[package]] @@ -1415,25 +1366,25 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10" dependencies = [ "windows-result", - "windows-targets", + "windows-targets 0.52.6", ] [[package]] name = "windows-sys" -version = "0.52.0" +version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ - "windows-targets", + "windows-targets 0.52.6", ] [[package]] name = "windows-sys" -version = "0.59.0" +version = "0.60.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" dependencies = [ - "windows-targets", + "windows-targets 0.53.2", ] [[package]] @@ -1442,14 +1393,30 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c66f69fcc9ce11da9966ddb31a40968cad001c5bedeb5c2b82ede4253ab48aef" +dependencies = [ + "windows_aarch64_gnullvm 0.53.0", + "windows_aarch64_msvc 0.53.0", + "windows_i686_gnu 0.53.0", + "windows_i686_gnullvm 0.53.0", + "windows_i686_msvc 0.53.0", + "windows_x86_64_gnu 0.53.0", + "windows_x86_64_gnullvm 0.53.0", + "windows_x86_64_msvc 0.53.0", ] [[package]] @@ -1459,48 +1426,96 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" [[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86b8d5f90ddd19cb4a147a5fa63ca848db3df085e25fee3cc10b39b6eebae764" + +[[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" [[package]] +name = "windows_aarch64_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7651a1f62a11b8cbd5e0d42526e55f2c99886c77e007179efff86c2b137e66c" + +[[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" [[package]] +name = "windows_i686_gnu" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1dc67659d35f387f5f6c479dc4e28f1d4bb90ddd1a5d3da2e5d97b42d6272c3" + +[[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" [[package]] +name = "windows_i686_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce6ccbdedbf6d6354471319e781c0dfef054c81fbc7cf83f338a4296c0cae11" + +[[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" [[package]] +name = "windows_i686_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "581fee95406bb13382d2f65cd4a908ca7b1e4c2f1917f143ba16efe98a589b5d" + +[[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" [[package]] +name = "windows_x86_64_gnu" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e55b5ac9ea33f2fc1716d1742db15574fd6fc8dadc51caab1c16a3d3b4190ba" + +[[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" [[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a6e035dd0599267ce1ee132e51c27dd29437f63325753051e71dd9e42406c57" + +[[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] +name = "windows_x86_64_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486" + +[[package]] name = "wit-bindgen-rt" version = "0.39.0" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -1511,18 +1526,18 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.8.24" +version = "0.8.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2586fea28e186957ef732a5f8b3be2da217d65c5969d4b1e17f973ebbe876879" +checksum = "1039dd0d3c310cf05de012d8a39ff557cb0d23087fd44cad61df08fc31907a2f" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.24" +version = "0.8.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a996a8f63c5c4448cd959ac1bab0aaa3306ccfd060472f85943ee0750f0169be" +checksum = "9ecf5b4cc5364572d7f4c329661bcc82724222973f2cab6f050a4e5c22f75181" dependencies = [ "proc-macro2", "quote", diff --git a/src/tools/miri/Cargo.toml b/src/tools/miri/Cargo.toml index 75476d7923c..d293af5cea2 100644 --- a/src/tools/miri/Cargo.toml +++ b/src/tools/miri/Cargo.toml @@ -38,18 +38,19 @@ features = ['unprefixed_malloc_on_supported_platforms'] [target.'cfg(unix)'.dependencies] libc = "0.2" -libffi = "4.0.0" -libloading = "0.8" +# native-lib dependencies +libffi = { version = "4.0.0", optional = true } +libloading = { version = "0.8", optional = true } +serde = { version = "1.0.219", features = ["derive"], optional = true } [target.'cfg(target_os = "linux")'.dependencies] -nix = { version = "0.30.1", features = ["mman", "ptrace", "signal"] } -ipc-channel = "0.19.0" -serde = { version = "1.0.219", features = ["derive"] } -capstone = "0.13" +nix = { version = "0.30.1", features = ["mman", "ptrace", "signal"], optional = true } +ipc-channel = { version = "0.20.0", optional = true } +capstone = { version = "0.13", optional = true } [dev-dependencies] -ui_test = "0.29.1" -colored = "2" +ui_test = "0.30.2" +colored = "3" rustc_version = "0.4" regex = "1.5.5" tempfile = "3" @@ -64,11 +65,12 @@ name = "ui" harness = false [features] -default = ["stack-cache"] +default = ["stack-cache", "native-lib"] genmc = [] stack-cache = [] stack-cache-consistency-check = ["stack-cache"] tracing = ["serde_json"] +native-lib = ["dep:libffi", "dep:libloading", "dep:capstone", "dep:ipc-channel", "dep:nix", "dep:serde"] [lints.rust.unexpected_cfgs] level = "warn" diff --git a/src/tools/miri/README.md b/src/tools/miri/README.md index 7816ce1ac56..7ccd27d7b83 100644 --- a/src/tools/miri/README.md +++ b/src/tools/miri/README.md @@ -286,11 +286,6 @@ environment variable. We first document the most relevant and most commonly used specific circumstances, but Miri's behavior will also be more stable across versions and targets. This is equivalent to `-Zmiri-fixed-schedule -Zmiri-compare-exchange-weak-failure-rate=0.0 -Zmiri-address-reuse-cross-thread-rate=0.0 -Zmiri-disable-weak-memory-emulation`. -* `-Zmiri-deterministic-floats` makes Miri's floating-point behavior fully deterministic. This means - that operations will always return the preferred NaN, imprecise operations will not have any - random error applied to them, and `min`/`max` as "maybe fused" multiply-add all behave - deterministically. Note that Miri still uses host floats for some operations, so behavior can - still differ depending on the host target and setup. * `-Zmiri-disable-isolation` disables host isolation. As a consequence, the program has access to host resources such as environment variables, file systems, and randomness. @@ -324,6 +319,8 @@ environment variable. We first document the most relevant and most commonly used Can be used without a value; in that case the range defaults to `0..64`. * `-Zmiri-many-seeds-keep-going` tells Miri to really try all the seeds in the given range, even if a failing seed has already been found. This is useful to determine which fraction of seeds fails. +* `-Zmiri-no-extra-rounding-error` stops Miri from adding extra rounding errors to float operations + that do not have a guaranteed precision. * `-Zmiri-num-cpus` states the number of available CPUs to be reported by miri. By default, the number of available CPUs is `1`. Note that this flag does not affect how miri handles threads in any way. @@ -376,6 +373,12 @@ to Miri failing to detect cases of undefined behavior in a program. will always fail and `0.0` means it will never fail. Note that setting it to `1.0` will likely cause hangs, since it means programs using `compare_exchange_weak` cannot make progress. +* `-Zmiri-deterministic-floats` makes Miri's floating-point behavior fully deterministic. This means + that operations will always return the preferred NaN, imprecise operations will not have any + random error applied to them, and `min`/`max` and "maybe fused" multiply-add all behave + deterministically. Note that Miri still uses host floats for some operations, so behavior can + still differ depending on the host target and setup. See `-Zmiri-no-extra-rounding-error` for + a flag that specifically only disables the random error. * `-Zmiri-disable-alignment-check` disables checking pointer alignment, so you can focus on other failures, but it means Miri can miss bugs in your program. Using this flag is **unsound**. diff --git a/src/tools/miri/cargo-miri/Cargo.lock b/src/tools/miri/cargo-miri/Cargo.lock index d37f8750bde..b3f5dafab64 100644 --- a/src/tools/miri/cargo-miri/Cargo.lock +++ b/src/tools/miri/cargo-miri/Cargo.lock @@ -3,31 +3,28 @@ version = 4 [[package]] -name = "aho-corasick" -version = "1.1.3" +name = "anyhow" +version = "1.0.98" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" -dependencies = [ - "memchr", -] +checksum = "e16d2d3311acee920a9eb8d33b8cbc1787ce4a264e85f964c2404b969bdcd487" [[package]] -name = "anyhow" -version = "1.0.97" +name = "autocfg" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcfed56ad506cb2c684a14971b8861fdc3baaaae314b9e5f9bb532cbe3ba7a4f" +checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" [[package]] name = "bitflags" -version = "2.9.0" +version = "2.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd" +checksum = "1b8e56985ec62d17e9c1001dc89c88ecd7dc08e47eba5ec7c29c7b5eeecde967" [[package]] name = "camino" -version = "1.1.9" +version = "1.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b96ec4966b5813e2c0507c1f86115c8c5abaadc3980879c3424042a02fd1ad3" +checksum = "0da45bc31171d8d6960122e222a67740df867c1dd53b4d51caa297084c185cab" dependencies = [ "serde", ] @@ -47,21 +44,38 @@ dependencies = [ [[package]] name = "cargo-platform" -version = "0.1.9" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e35af189006b9c0f00a064685c727031e3ed2d8020f7ba284d78cc2671bd36ea" +checksum = "84982c6c0ae343635a3a4ee6dedef965513735c8b183caa7289fa6e27399ebd4" dependencies = [ "serde", ] [[package]] +name = "cargo-util-schemas" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dc1a6f7b5651af85774ae5a34b4e8be397d9cf4bc063b7e6dbd99a841837830" +dependencies = [ + "semver", + "serde", + "serde-untagged", + "serde-value", + "thiserror", + "toml", + "unicode-xid", + "url", +] + +[[package]] name = "cargo_metadata" -version = "0.19.2" +version = "0.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd5eb614ed4c27c5d706420e4320fbe3216ab31fa1c33cd8246ac36dae4479ba" +checksum = "5cfca2aaa699835ba88faf58a06342a314a950d2b9686165e038286c30316868" dependencies = [ "camino", "cargo-platform", + "cargo-util-schemas", "semver", "serde", "serde_json", @@ -70,9 +84,9 @@ dependencies = [ [[package]] name = "cfg-if" -version = "1.0.0" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" +checksum = "9555578bc9e57714c812a1f84e4fc5b4d21fcb063490c624de019f7464c91268" [[package]] name = "directories" @@ -92,17 +106,44 @@ dependencies = [ "libc", "option-ext", "redox_users", - "windows-sys", + "windows-sys 0.60.2", +] + +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "erased-serde" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e004d887f51fcb9fef17317a2f3525c887d8aa3f4f50fed920816a688284a5b7" +dependencies = [ + "serde", + "typeid", ] [[package]] name = "errno" -version = "0.3.11" +version = "0.3.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "976dd42dc7e85965fe702eb8164f21f450704bdde31faefd6471dba214cb594e" +checksum = "778e2ac28f6c47af28e4907f13ffd1e1ddbd400980a9abd7c8df189bf578a5ad" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.60.2", ] [[package]] @@ -112,21 +153,30 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" [[package]] +name = "form_urlencoded" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13624c2627564efccf4934284bdd98cbaa14e79b0b5a141218e507b3a823456" +dependencies = [ + "percent-encoding", +] + +[[package]] name = "getrandom" -version = "0.2.15" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" +checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592" dependencies = [ "cfg-if", "libc", - "wasi 0.11.0+wasi-snapshot-preview1", + "wasi 0.11.1+wasi-snapshot-preview1", ] [[package]] name = "getrandom" -version = "0.3.2" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73fea8450eea4bac3940448fb7ae50d91f034f941199fcd9d909a5a07aa455f0" +checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4" dependencies = [ "cfg-if", "libc", @@ -135,6 +185,129 @@ dependencies = [ ] [[package]] +name = "hashbrown" +version = "0.15.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5971ac85611da7067dbfcabef3c70ebb5606018acd9e2a3903a0da507521e0d5" + +[[package]] +name = "icu_collections" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "200072f5d0e3614556f94a9930d5dc3e0662a652823904c3a75dc3b0af7fee47" +dependencies = [ + "displaydoc", + "potential_utf", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cde2700ccaed3872079a65fb1a78f6c0a36c91570f28755dda67bc8f7d9f00a" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "436880e8e18df4d7bbc06d58432329d6458cc84531f7ac5f024e93deadb37979" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00210d6893afc98edb752b664b8890f0ef174c8adbb8d0be9710fa66fbbf72d3" + +[[package]] +name = "icu_properties" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "016c619c1eeb94efb86809b015c58f479963de65bdb6253345c1a1276f22e32b" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "potential_utf", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "298459143998310acd25ffe6810ed544932242d3f07083eee1084d83a71bd632" + +[[package]] +name = "icu_provider" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03c80da27b5f4187909049ee2d72f276f0d9f99a42c306bd0131ecfe04d8e5af" +dependencies = [ + "displaydoc", + "icu_locale_core", + "stable_deref_trait", + "tinystr", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "686f825264d630750a544639377bae737628043f20d38bbc029e8f29ea968a7e" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe4cd85333e22411419a0bcae1297d25e58c9443848b11dc6a86fefe8c78a661" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] name = "itoa" version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -142,15 +315,15 @@ checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" [[package]] name = "libc" -version = "0.2.171" +version = "0.2.174" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c19937216e9d3aa9956d9bb8dfc0b0c8beb6058fc4f7a4dc4d850edf86a237d6" +checksum = "1171693293099992e19cddea4e8b849964e9846f4acee11b3948bcc337be8776" [[package]] name = "libredox" -version = "0.1.3" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d" +checksum = "1580801010e535496706ba011c15f8532df6b42297d2e471fec38ceadd8c0638" dependencies = [ "bitflags", "libc", @@ -158,15 +331,30 @@ dependencies = [ [[package]] name = "linux-raw-sys" -version = "0.9.3" +version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe7db12097d22ec582439daf8618b8fdd1a7bef6270e9af3b1ebcd30893cf413" +checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12" + +[[package]] +name = "litemap" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "241eaef5fd12c88705a01fc1066c48c4b36e0dd4377dcdc7ec3942cea7a69956" [[package]] name = "memchr" -version = "2.7.4" +version = "2.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" +checksum = "32a282da65faaf38286cf3be983213fcf1d2e2a58700e808f83f4ea9a4804bc0" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] [[package]] name = "once_cell" @@ -181,10 +369,34 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" [[package]] +name = "ordered-float" +version = "2.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68f19d67e5a2795c94e73e0bb1cc1a7edeb2e28efd39e2e1c9b7a40c1108b11c" +dependencies = [ + "num-traits", +] + +[[package]] +name = "percent-encoding" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" + +[[package]] +name = "potential_utf" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5a7c30837279ca13e7c867e9e40053bc68740f988cb07f7ca6df43cc734b585" +dependencies = [ + "zerovec", +] + +[[package]] name = "proc-macro2" -version = "1.0.94" +version = "1.0.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a31971752e70b8b2686d7e46ec17fb38dad4051d94024c88df49b667caea9c84" +checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778" dependencies = [ "unicode-ident", ] @@ -200,9 +412,9 @@ dependencies = [ [[package]] name = "r-efi" -version = "5.2.0" +version = "5.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74765f6d916ee2faa39bc8e68e4f3ed8949b48cccdac59983d287a7cb71ce9c5" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" [[package]] name = "redox_users" @@ -210,50 +422,21 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd6f9d3d47bdd2ad6945c5015a226ec6155d0bcdfd8f7cd29f86b71f8de99d2b" dependencies = [ - "getrandom 0.2.15", + "getrandom 0.2.16", "libredox", "thiserror", ] [[package]] -name = "regex" -version = "1.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191" -dependencies = [ - "aho-corasick", - "memchr", - "regex-automata", - "regex-syntax", -] - -[[package]] -name = "regex-automata" -version = "0.4.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", -] - -[[package]] -name = "regex-syntax" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" - -[[package]] name = "rustc-build-sysroot" -version = "0.5.8" +version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16d115ad7e26e0d1337f64ae6598f758194696afc2e9f34c8a6f24582529c3dc" +checksum = "fdb13874a0e55baf4ac3d49d38206aecb31a55b75d6c4d04fd850b53942c8cc8" dependencies = [ "anyhow", - "regex", "rustc_version", "tempfile", + "toml", "walkdir", ] @@ -274,15 +457,15 @@ dependencies = [ [[package]] name = "rustix" -version = "1.0.5" +version = "1.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d97817398dd4bb2e6da002002db259209759911da105da92bec29ccb12cf58bf" +checksum = "11181fbabf243db407ef8df94a6ce0b2f9a733bd8be4ad02b4eda9602296cac8" dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys", - "windows-sys", + "windows-sys 0.60.2", ] [[package]] @@ -319,6 +502,27 @@ dependencies = [ ] [[package]] +name = "serde-untagged" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "299d9c19d7d466db4ab10addd5703e4c615dec2a5a16dbbafe191045e87ee66e" +dependencies = [ + "erased-serde", + "serde", + "typeid", +] + +[[package]] +name = "serde-value" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3a1a3341211875ef120e117ea7fd5228530ae7e7036a779fdc9117be6b3282c" +dependencies = [ + "ordered-float", + "serde", +] + +[[package]] name = "serde_derive" version = "1.0.219" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -331,9 +535,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.140" +version = "1.0.141" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373" +checksum = "30b9eff21ebe718216c6ec64e1d9ac57087aad11efc64e32002bce4a0d4c03d3" dependencies = [ "itoa", "memchr", @@ -342,10 +546,31 @@ dependencies = [ ] [[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + +[[package]] +name = "smallvec" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" + +[[package]] +name = "stable_deref_trait" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" + +[[package]] name = "syn" -version = "2.0.100" +version = "2.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b09a44accad81e1ba1cd74a32461ba89dee89095ba17b32f5d03683b1b1fc2a0" +checksum = "17b6f705963418cdb9927482fa304bc562ece2fdd4f616084c50b7023b435a40" dependencies = [ "proc-macro2", "quote", @@ -353,16 +578,27 @@ dependencies = [ ] [[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] name = "tempfile" -version = "3.19.1" +version = "3.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7437ac7763b9b123ccf33c338a5cc1bac6f69b45a136c19bdd8a65e3916435bf" +checksum = "e8a64e3985349f2441a1a9ef0b853f869006c3855f2cda6862a94d26ebb9d6a1" dependencies = [ "fastrand", - "getrandom 0.3.2", + "getrandom 0.3.3", "once_cell", "rustix", - "windows-sys", + "windows-sys 0.59.0", ] [[package]] @@ -386,12 +622,93 @@ dependencies = [ ] [[package]] +name = "tinystr" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d4f6d1145dcb577acf783d4e601bc1d76a13337bb54e6233add580b07344c8b" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "indexmap", + "serde", + "serde_spanned", + "toml_datetime", + "toml_edit", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap", + "serde", + "serde_spanned", + "toml_datetime", + "toml_write", + "winnow", +] + +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + +[[package]] +name = "typeid" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" + +[[package]] name = "unicode-ident" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512" [[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "url" +version = "2.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32f8b686cadd1473f4bd0117a5d28d36b1ade384ea9b5069a1c40aefed7fda60" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] name = "walkdir" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -403,9 +720,9 @@ dependencies = [ [[package]] name = "wasi" -version = "0.11.0+wasi-snapshot-preview1" +version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" [[package]] name = "wasi" @@ -422,7 +739,7 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb" dependencies = [ - "windows-sys", + "windows-sys 0.59.0", ] [[package]] @@ -431,7 +748,16 @@ version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ - "windows-targets", + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.2", ] [[package]] @@ -440,14 +766,30 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c66f69fcc9ce11da9966ddb31a40968cad001c5bedeb5c2b82ede4253ab48aef" +dependencies = [ + "windows_aarch64_gnullvm 0.53.0", + "windows_aarch64_msvc 0.53.0", + "windows_i686_gnu 0.53.0", + "windows_i686_gnullvm 0.53.0", + "windows_i686_msvc 0.53.0", + "windows_x86_64_gnu 0.53.0", + "windows_x86_64_gnullvm 0.53.0", + "windows_x86_64_msvc 0.53.0", ] [[package]] @@ -457,48 +799,105 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" [[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86b8d5f90ddd19cb4a147a5fa63ca848db3df085e25fee3cc10b39b6eebae764" + +[[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" [[package]] +name = "windows_aarch64_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7651a1f62a11b8cbd5e0d42526e55f2c99886c77e007179efff86c2b137e66c" + +[[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" [[package]] +name = "windows_i686_gnu" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1dc67659d35f387f5f6c479dc4e28f1d4bb90ddd1a5d3da2e5d97b42d6272c3" + +[[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" [[package]] +name = "windows_i686_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce6ccbdedbf6d6354471319e781c0dfef054c81fbc7cf83f338a4296c0cae11" + +[[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" [[package]] +name = "windows_i686_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "581fee95406bb13382d2f65cd4a908ca7b1e4c2f1917f143ba16efe98a589b5d" + +[[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" [[package]] +name = "windows_x86_64_gnu" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e55b5ac9ea33f2fc1716d1742db15574fd6fc8dadc51caab1c16a3d3b4190ba" + +[[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" [[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a6e035dd0599267ce1ee132e51c27dd29437f63325753051e71dd9e42406c57" + +[[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] +name = "windows_x86_64_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486" + +[[package]] +name = "winnow" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3edebf492c8125044983378ecb5766203ad3b4c2f7a922bd7dd207f6d443e95" +dependencies = [ + "memchr", +] + +[[package]] name = "wit-bindgen-rt" version = "0.39.0" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -506,3 +905,87 @@ checksum = "6f42320e61fe2cfd34354ecb597f86f413484a798ba44a8ca1165c58d42da6c1" dependencies = [ "bitflags", ] + +[[package]] +name = "writeable" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea2f10b9bb0928dfb1b42b65e1f9e36f7f54dbdf08457afefb38afcdec4fa2bb" + +[[package]] +name = "yoke" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f41bb01b8226ef4bfd589436a297c53d118f65921786300e427be8d487695cc" +dependencies = [ + "serde", + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38da3c9736e16c5d3c8c597a9aaa5d1fa565d0532ae05e27c24aa62fb32c0ab6" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerotrie" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36f0bbd478583f79edad978b407914f61b2972f5af6fa089686016be8f9af595" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a05eb080e015ba39cc9e23bbe5e7fb04d5fb040350f99f34e338d5fdd294428" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b96237efa0c878c64bd89c436f661be4e46b2f3eff1ebb976f7ef2321d2f58f" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] diff --git a/src/tools/miri/cargo-miri/Cargo.toml b/src/tools/miri/cargo-miri/Cargo.toml index e08733959cc..77cb1df8e74 100644 --- a/src/tools/miri/cargo-miri/Cargo.toml +++ b/src/tools/miri/cargo-miri/Cargo.toml @@ -17,7 +17,7 @@ doctest = false # and no doc tests directories = "6" rustc_version = "0.4" serde_json = "1.0.40" -cargo_metadata = "0.19" +cargo_metadata = "0.21" rustc-build-sysroot = "0.5.8" # Enable some feature flags that dev-dependencies need but dependencies diff --git a/src/tools/miri/cargo-miri/src/util.rs b/src/tools/miri/cargo-miri/src/util.rs index 43b2a1b6173..82c6a929357 100644 --- a/src/tools/miri/cargo-miri/src/util.rs +++ b/src/tools/miri/cargo-miri/src/util.rs @@ -129,7 +129,8 @@ pub fn exec(mut cmd: Command) -> ! { // On non-Unix imitate POSIX exec as closely as we can #[cfg(not(unix))] { - let exit_status = cmd.status().expect("failed to run command"); + let exit_status = + cmd.status().unwrap_or_else(|err| panic!("failed to run `{cmd:?}`:\n{err}")); std::process::exit(exit_status.code().unwrap_or(-1)) } // On Unix targets, actually exec. @@ -138,8 +139,8 @@ pub fn exec(mut cmd: Command) -> ! { #[cfg(unix)] { use std::os::unix::process::CommandExt; - let error = cmd.exec(); - panic!("failed to run command: {error}") + let err = cmd.exec(); + panic!("failed to run `{cmd:?}`:\n{err}") } } diff --git a/src/tools/miri/etc/rust_analyzer_helix.toml b/src/tools/miri/etc/rust_analyzer_helix.toml index 9bfb09120d8..91e4070478c 100644 --- a/src/tools/miri/etc/rust_analyzer_helix.toml +++ b/src/tools/miri/etc/rust_analyzer_helix.toml @@ -26,5 +26,6 @@ invocationStrategy = "once" overrideCommand = [ "./miri", "check", + "--no-default-features", "--message-format=json", ] diff --git a/src/tools/miri/etc/rust_analyzer_vscode.json b/src/tools/miri/etc/rust_analyzer_vscode.json index c646953e92b..6917c6a1fd8 100644 --- a/src/tools/miri/etc/rust_analyzer_vscode.json +++ b/src/tools/miri/etc/rust_analyzer_vscode.json @@ -20,6 +20,7 @@ "rust-analyzer.cargo.buildScripts.overrideCommand": [ "./miri", "check", + "--no-default-features", "--message-format=json", ], } diff --git a/src/tools/miri/miri b/src/tools/miri/miri index 549998ae44a..a5f2bb1550a 100755 --- a/src/tools/miri/miri +++ b/src/tools/miri/miri @@ -15,8 +15,9 @@ if [ -n "$MIRI_IN_RA" ]; then CARGO_FLAGS+=("--message-format=json" "-Zroot-dir=$ROOT_DIR") TARGET_DIR="$ROOT_DIR"/target fi + # Run cargo. -cargo $TOOLCHAIN build --manifest-path "$ROOT_DIR"/miri-script/Cargo.toml \ +${CARGO:-cargo} $TOOLCHAIN build --manifest-path "$ROOT_DIR"/miri-script/Cargo.toml \ --target-dir "$TARGET_DIR" "${CARGO_FLAGS[@]}" || \ ( echo "Failed to build miri-script. Is the 'stable' toolchain installed?"; exit 1 ) # Instead of doing just `cargo run --manifest-path .. $@`, we invoke miri-script binary directly. diff --git a/src/tools/miri/miri-script/Cargo.lock b/src/tools/miri/miri-script/Cargo.lock index 3494a241ec5..a049bfcbccd 100644 --- a/src/tools/miri/miri-script/Cargo.lock +++ b/src/tools/miri/miri-script/Cargo.lock @@ -4,9 +4,9 @@ version = 4 [[package]] name = "anstream" -version = "0.6.18" +version = "0.6.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8acc5369981196006228e28809f761875c0327210a891e941f4c683b3a99529b" +checksum = "301af1932e46185686725e0fad2f8f2aa7da69dd70bf6ecc44d6b703844a3933" dependencies = [ "anstyle", "anstyle-parse", @@ -19,62 +19,62 @@ dependencies = [ [[package]] name = "anstyle" -version = "1.0.10" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55cc3b69f167a1ef2e161439aa98aed94e6028e5f9a59be9a6ffb47aef1651f9" +checksum = "862ed96ca487e809f1c8e5a8447f6ee2cf102f846893800b20cebdf541fc6bbd" [[package]] name = "anstyle-parse" -version = "0.2.6" +version = "0.2.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b2d16507662817a6a20a9ea92df6652ee4f94f914589377d69f3b21bc5798a9" +checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2" dependencies = [ "utf8parse", ] [[package]] name = "anstyle-query" -version = "1.1.2" +version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79947af37f4177cfead1110013d678905c37501914fba0efea834c3fe9a8d60c" +checksum = "6c8bdeb6047d8983be085bab0ba1472e6dc604e7041dbf6fcd5e71523014fae9" dependencies = [ - "windows-sys", + "windows-sys 0.59.0", ] [[package]] name = "anstyle-wincon" -version = "3.0.7" +version = "3.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca3534e77181a9cc07539ad51f2141fe32f6c3ffd4df76db8ad92346b003ae4e" +checksum = "403f75924867bb1033c59fbf0797484329750cfbe3c4325cd33127941fabc882" dependencies = [ "anstyle", - "once_cell", - "windows-sys", + "once_cell_polyfill", + "windows-sys 0.59.0", ] [[package]] name = "anyhow" -version = "1.0.97" +version = "1.0.98" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcfed56ad506cb2c684a14971b8861fdc3baaaae314b9e5f9bb532cbe3ba7a4f" +checksum = "e16d2d3311acee920a9eb8d33b8cbc1787ce4a264e85f964c2404b969bdcd487" [[package]] name = "bitflags" -version = "2.9.0" +version = "2.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd" +checksum = "1b8e56985ec62d17e9c1001dc89c88ecd7dc08e47eba5ec7c29c7b5eeecde967" [[package]] name = "cfg-if" -version = "1.0.0" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" +checksum = "9555578bc9e57714c812a1f84e4fc5b4d21fcb063490c624de019f7464c91268" [[package]] name = "clap" -version = "4.5.35" +version = "4.5.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8aa86934b44c19c50f87cc2790e19f54f7a67aedb64101c2e1a2e5ecfb73944" +checksum = "be92d32e80243a54711e5d7ce823c35c41c9d929dc4ab58e1276f625841aadf9" dependencies = [ "clap_builder", "clap_derive", @@ -82,9 +82,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.35" +version = "4.5.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2414dbb2dd0695280da6ea9261e327479e9d37b0630f6b53ba2a11c60c679fd9" +checksum = "707eab41e9622f9139419d573eca0900137718000c517d47da73045f54331c3d" dependencies = [ "anstream", "anstyle", @@ -94,9 +94,9 @@ dependencies = [ [[package]] name = "clap_derive" -version = "4.5.32" +version = "4.5.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09176aae279615badda0765c0c0b3f6ed53f4709118af73cf4655d85d1530cd7" +checksum = "ef4f52386a59ca4c860f7393bcf8abd8dfd91ecccc0f774635ff68e92eeef491" dependencies = [ "heck", "proc-macro2", @@ -106,15 +106,15 @@ dependencies = [ [[package]] name = "clap_lex" -version = "0.7.4" +version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f46ad14479a25103f283c0f10005961cf086d8dc42205bb44c46ac563475dca6" +checksum = "b94f61472cee1439c0b966b47e3aca9ae07e45d070759512cd390ea2bebc6675" [[package]] name = "colorchoice" -version = "1.0.3" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b63caa9aa9397e2d9480a9b13673856c78d8ac123288526c37d7839f2a86990" +checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" [[package]] name = "directories" @@ -134,7 +134,7 @@ dependencies = [ "libc", "option-ext", "redox_users", - "windows-sys", + "windows-sys 0.60.2", ] [[package]] @@ -150,19 +150,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" [[package]] -name = "env_home" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7f84e12ccf0a7ddc17a6c41c93326024c42920d7ee630d04950e6926645c0fe" - -[[package]] name = "errno" -version = "0.3.11" +version = "0.3.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "976dd42dc7e85965fe702eb8164f21f450704bdde31faefd6471dba214cb594e" +checksum = "778e2ac28f6c47af28e4907f13ffd1e1ddbd400980a9abd7c8df189bf578a5ad" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.60.2", ] [[package]] @@ -173,20 +167,20 @@ checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" [[package]] name = "getrandom" -version = "0.2.15" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" +checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592" dependencies = [ "cfg-if", "libc", - "wasi 0.11.0+wasi-snapshot-preview1", + "wasi 0.11.1+wasi-snapshot-preview1", ] [[package]] name = "getrandom" -version = "0.3.2" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73fea8450eea4bac3940448fb7ae50d91f034f941199fcd9d909a5a07aa455f0" +checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4" dependencies = [ "cfg-if", "libc", @@ -223,15 +217,15 @@ checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" [[package]] name = "libc" -version = "0.2.171" +version = "0.2.174" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c19937216e9d3aa9956d9bb8dfc0b0c8beb6058fc4f7a4dc4d850edf86a237d6" +checksum = "1171693293099992e19cddea4e8b849964e9846f4acee11b3948bcc337be8776" [[package]] name = "libredox" -version = "0.1.3" +version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d" +checksum = "1580801010e535496706ba011c15f8532df6b42297d2e471fec38ceadd8c0638" dependencies = [ "bitflags", "libc", @@ -239,21 +233,15 @@ dependencies = [ [[package]] name = "linux-raw-sys" -version = "0.4.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" - -[[package]] -name = "linux-raw-sys" -version = "0.9.3" +version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe7db12097d22ec582439daf8618b8fdd1a7bef6270e9af3b1ebcd30893cf413" +checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12" [[package]] name = "memchr" -version = "2.7.4" +version = "2.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" +checksum = "32a282da65faaf38286cf3be983213fcf1d2e2a58700e808f83f4ea9a4804bc0" [[package]] name = "miri-script" @@ -272,7 +260,6 @@ dependencies = [ "shell-words", "tempfile", "walkdir", - "which", "xshell", ] @@ -283,6 +270,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" [[package]] +name = "once_cell_polyfill" +version = "1.70.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4895175b425cb1f87721b59f0f286c2092bd4af812243672510e1ac53e2e0ad" + +[[package]] name = "option-ext" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -296,9 +289,9 @@ checksum = "a6e819bbd49d5939f682638fa54826bf1650abddcd65d000923de8ad63cc7d15" [[package]] name = "proc-macro2" -version = "1.0.94" +version = "1.0.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a31971752e70b8b2686d7e46ec17fb38dad4051d94024c88df49b667caea9c84" +checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778" dependencies = [ "unicode-ident", ] @@ -314,9 +307,9 @@ dependencies = [ [[package]] name = "r-efi" -version = "5.2.0" +version = "5.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74765f6d916ee2faa39bc8e68e4f3ed8949b48cccdac59983d287a7cb71ce9c5" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" [[package]] name = "redox_users" @@ -324,7 +317,7 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd6f9d3d47bdd2ad6945c5015a226ec6155d0bcdfd8f7cd29f86b71f8de99d2b" dependencies = [ - "getrandom 0.2.15", + "getrandom 0.2.16", "libredox", "thiserror", ] @@ -340,28 +333,15 @@ dependencies = [ [[package]] name = "rustix" -version = "0.38.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" -dependencies = [ - "bitflags", - "errno", - "libc", - "linux-raw-sys 0.4.15", - "windows-sys", -] - -[[package]] -name = "rustix" -version = "1.0.5" +version = "1.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d97817398dd4bb2e6da002002db259209759911da105da92bec29ccb12cf58bf" +checksum = "11181fbabf243db407ef8df94a6ce0b2f9a733bd8be4ad02b4eda9602296cac8" dependencies = [ "bitflags", "errno", "libc", - "linux-raw-sys 0.9.3", - "windows-sys", + "linux-raw-sys", + "windows-sys 0.60.2", ] [[package]] @@ -407,9 +387,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.140" +version = "1.0.141" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373" +checksum = "30b9eff21ebe718216c6ec64e1d9ac57087aad11efc64e32002bce4a0d4c03d3" dependencies = [ "itoa", "memchr", @@ -431,9 +411,9 @@ checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" [[package]] name = "syn" -version = "2.0.100" +version = "2.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b09a44accad81e1ba1cd74a32461ba89dee89095ba17b32f5d03683b1b1fc2a0" +checksum = "17b6f705963418cdb9927482fa304bc562ece2fdd4f616084c50b7023b435a40" dependencies = [ "proc-macro2", "quote", @@ -442,15 +422,15 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.19.1" +version = "3.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7437ac7763b9b123ccf33c338a5cc1bac6f69b45a136c19bdd8a65e3916435bf" +checksum = "e8a64e3985349f2441a1a9ef0b853f869006c3855f2cda6862a94d26ebb9d6a1" dependencies = [ "fastrand", - "getrandom 0.3.2", + "getrandom 0.3.3", "once_cell", - "rustix 1.0.5", - "windows-sys", + "rustix", + "windows-sys 0.59.0", ] [[package]] @@ -497,9 +477,9 @@ dependencies = [ [[package]] name = "wasi" -version = "0.11.0+wasi-snapshot-preview1" +version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" [[package]] name = "wasi" @@ -511,24 +491,12 @@ dependencies = [ ] [[package]] -name = "which" -version = "7.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2774c861e1f072b3aadc02f8ba886c26ad6321567ecc294c935434cad06f1283" -dependencies = [ - "either", - "env_home", - "rustix 0.38.44", - "winsafe", -] - -[[package]] name = "winapi-util" version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf221c93e13a30d793f7645a0e7762c55d169dbb0a49671918a2319d289b10bb" dependencies = [ - "windows-sys", + "windows-sys 0.59.0", ] [[package]] @@ -537,7 +505,16 @@ version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ - "windows-targets", + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.2", ] [[package]] @@ -546,14 +523,30 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c66f69fcc9ce11da9966ddb31a40968cad001c5bedeb5c2b82ede4253ab48aef" +dependencies = [ + "windows_aarch64_gnullvm 0.53.0", + "windows_aarch64_msvc 0.53.0", + "windows_i686_gnu 0.53.0", + "windows_i686_gnullvm 0.53.0", + "windows_i686_msvc 0.53.0", + "windows_x86_64_gnu 0.53.0", + "windows_x86_64_gnullvm 0.53.0", + "windows_x86_64_msvc 0.53.0", ] [[package]] @@ -563,52 +556,94 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" [[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86b8d5f90ddd19cb4a147a5fa63ca848db3df085e25fee3cc10b39b6eebae764" + +[[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" [[package]] +name = "windows_aarch64_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7651a1f62a11b8cbd5e0d42526e55f2c99886c77e007179efff86c2b137e66c" + +[[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" [[package]] +name = "windows_i686_gnu" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1dc67659d35f387f5f6c479dc4e28f1d4bb90ddd1a5d3da2e5d97b42d6272c3" + +[[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" [[package]] +name = "windows_i686_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce6ccbdedbf6d6354471319e781c0dfef054c81fbc7cf83f338a4296c0cae11" + +[[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" [[package]] +name = "windows_i686_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "581fee95406bb13382d2f65cd4a908ca7b1e4c2f1917f143ba16efe98a589b5d" + +[[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" [[package]] +name = "windows_x86_64_gnu" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e55b5ac9ea33f2fc1716d1742db15574fd6fc8dadc51caab1c16a3d3b4190ba" + +[[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" [[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a6e035dd0599267ce1ee132e51c27dd29437f63325753051e71dd9e42406c57" + +[[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] -name = "winsafe" -version = "0.0.19" +name = "windows_x86_64_msvc" +version = "0.53.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904" +checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486" [[package]] name = "wit-bindgen-rt" diff --git a/src/tools/miri/miri-script/Cargo.toml b/src/tools/miri/miri-script/Cargo.toml index 9240788d6bc..b3f82cd1d50 100644 --- a/src/tools/miri/miri-script/Cargo.toml +++ b/src/tools/miri/miri-script/Cargo.toml @@ -14,7 +14,6 @@ rust-version = "1.85" # This is needed to make this package build on stable when the parent package uses unstable cargo features. [dependencies] -which = "7" walkdir = "2.3" itertools = "0.14" path_macro = "1.0" diff --git a/src/tools/miri/miri-script/src/commands.rs b/src/tools/miri/miri-script/src/commands.rs index e6ebdf54e38..9aaad9ca04a 100644 --- a/src/tools/miri/miri-script/src/commands.rs +++ b/src/tools/miri/miri-script/src/commands.rs @@ -198,9 +198,6 @@ impl Command { } fn toolchain(flags: Vec<String>) -> Result<()> { - // Make sure rustup-toolchain-install-master is installed. - which::which("rustup-toolchain-install-master") - .context("Please install rustup-toolchain-install-master by running 'cargo install rustup-toolchain-install-master'")?; let sh = Shell::new()?; sh.change_dir(miri_dir()?); let new_commit = sh.read_file("rust-version")?.trim().to_owned(); @@ -227,7 +224,9 @@ impl Command { // Install and setup new toolchain. cmd!(sh, "rustup toolchain uninstall miri").run()?; - cmd!(sh, "rustup-toolchain-install-master -n miri -c cargo -c rust-src -c rustc-dev -c llvm-tools -c rustfmt -c clippy {flags...} -- {new_commit}").run()?; + cmd!(sh, "rustup-toolchain-install-master -n miri -c cargo -c rust-src -c rustc-dev -c llvm-tools -c rustfmt -c clippy {flags...} -- {new_commit}") + .run() + .context("Failed to run rustup-toolchain-install-master. If it is not installed, run 'cargo install rustup-toolchain-install-master'.")?; cmd!(sh, "rustup override set miri").run()?; // Cleanup. cmd!(sh, "cargo clean").run()?; diff --git a/src/tools/miri/miri-script/src/main.rs b/src/tools/miri/miri-script/src/main.rs index 673d658cf1d..e41df662ca2 100644 --- a/src/tools/miri/miri-script/src/main.rs +++ b/src/tools/miri/miri-script/src/main.rs @@ -75,7 +75,7 @@ pub enum Command { /// /// Also respects MIRIFLAGS environment variable. Run { - /// Build the program with the dependencies declared in `test_dependencies/Cargo.toml`. + /// Build the program with the dependencies declared in `tests/deps/Cargo.toml`. #[arg(long)] dep: bool, /// Show build progress. diff --git a/src/tools/miri/miri-script/src/util.rs b/src/tools/miri/miri-script/src/util.rs index c100cf195ba..6121096f823 100644 --- a/src/tools/miri/miri-script/src/util.rs +++ b/src/tools/miri/miri-script/src/util.rs @@ -38,6 +38,8 @@ pub struct MiriEnv { pub miri_dir: PathBuf, /// active_toolchain is passed as `+toolchain` argument to cargo/rustc invocations. toolchain: String, + /// The cargo binary to use. + cargo_bin: String, /// Extra flags to pass to cargo. cargo_extra_flags: Vec<String>, /// The rustc sysroot @@ -106,6 +108,9 @@ impl MiriEnv { sh.set_var("PATH", new_path); } + // Get the cargo binary to use, if one is set. + let cargo_bin = std::env::var("CARGO").unwrap_or_else(|_| "cargo".to_string()); + // Get extra flags for cargo. let cargo_extra_flags = std::env::var("CARGO_EXTRA_FLAGS").unwrap_or_default(); let mut cargo_extra_flags = flagsplit(&cargo_extra_flags); @@ -119,7 +124,7 @@ impl MiriEnv { // Also set `-Zroot-dir` for cargo, to print diagnostics relative to the miri dir. cargo_extra_flags.push(format!("-Zroot-dir={}", miri_dir.display())); - Ok(MiriEnv { miri_dir, toolchain, sh, sysroot, cargo_extra_flags, libdir }) + Ok(MiriEnv { miri_dir, toolchain, sh, sysroot, cargo_bin, cargo_extra_flags, libdir }) } /// Make sure the `features` you pass here exist for the specified `crate_dir`. For example, the @@ -130,12 +135,12 @@ impl MiriEnv { cmd: &str, features: &[String], ) -> Cmd<'_> { - let MiriEnv { toolchain, cargo_extra_flags, .. } = self; + let MiriEnv { toolchain, cargo_extra_flags, cargo_bin, .. } = self; let manifest_path = path!(self.miri_dir / crate_dir.as_ref() / "Cargo.toml"); let features = features_to_args(features); cmd!( self.sh, - "cargo +{toolchain} {cmd} {cargo_extra_flags...} --manifest-path {manifest_path} {features...}" + "{cargo_bin} +{toolchain} {cmd} {cargo_extra_flags...} --manifest-path {manifest_path} {features...}" ) } @@ -147,12 +152,12 @@ impl MiriEnv { features: &[String], args: impl IntoIterator<Item = impl AsRef<OsStr>>, ) -> Result<()> { - let MiriEnv { sysroot, toolchain, cargo_extra_flags, .. } = self; + let MiriEnv { sysroot, toolchain, cargo_extra_flags, cargo_bin, .. } = self; let path = path!(self.miri_dir / crate_dir.as_ref()); let features = features_to_args(features); // Install binaries to the miri toolchain's `sysroot` so they do not interact with other toolchains. // (Not using `cargo_cmd` as `install` is special and doesn't use `--manifest-path`.) - cmd!(self.sh, "cargo +{toolchain} install {cargo_extra_flags...} --path {path} --force --root {sysroot} {features...} {args...}").run()?; + cmd!(self.sh, "{cargo_bin} +{toolchain} install {cargo_extra_flags...} --path {path} --force --root {sysroot} {features...} {args...}").run()?; Ok(()) } diff --git a/src/tools/miri/rust-version b/src/tools/miri/rust-version index 67f27e7aa2c..d734ec333a5 100644 --- a/src/tools/miri/rust-version +++ b/src/tools/miri/rust-version @@ -1 +1 @@ -7f2065a4bae1faed5bab928c670964eafbf43b55 +6707bf0f59485cf054ac1095725df43220e4be20 diff --git a/src/tools/miri/src/alloc/alloc_bytes.rs b/src/tools/miri/src/alloc/alloc_bytes.rs index 2a253952b27..5d00d3eafcb 100644 --- a/src/tools/miri/src/alloc/alloc_bytes.rs +++ b/src/tools/miri/src/alloc/alloc_bytes.rs @@ -1,20 +1,18 @@ use std::alloc::Layout; use std::borrow::Cow; +use std::cell::RefCell; +use std::rc::Rc; use std::{alloc, slice}; -#[cfg(target_os = "linux")] -use std::{cell::RefCell, rc::Rc}; use rustc_abi::{Align, Size}; use rustc_middle::mir::interpret::AllocBytes; -#[cfg(target_os = "linux")] use crate::alloc::isolated_alloc::IsolatedAlloc; use crate::helpers::ToU64 as _; #[derive(Clone, Debug)] pub enum MiriAllocParams { Global, - #[cfg(target_os = "linux")] Isolated(Rc<RefCell<IsolatedAlloc>>), } @@ -56,7 +54,6 @@ impl Drop for MiriAllocBytes { unsafe { match self.params.clone() { MiriAllocParams::Global => alloc::dealloc(self.ptr, alloc_layout), - #[cfg(target_os = "linux")] MiriAllocParams::Isolated(alloc) => alloc.borrow_mut().dealloc(self.ptr, alloc_layout), } @@ -123,7 +120,6 @@ impl AllocBytes for MiriAllocBytes { let alloc_fn = |layout, params: &MiriAllocParams| unsafe { match params { MiriAllocParams::Global => alloc::alloc(layout), - #[cfg(target_os = "linux")] MiriAllocParams::Isolated(alloc) => alloc.borrow_mut().alloc(layout), } }; @@ -144,7 +140,6 @@ impl AllocBytes for MiriAllocBytes { let alloc_fn = |layout, params: &MiriAllocParams| unsafe { match params { MiriAllocParams::Global => alloc::alloc_zeroed(layout), - #[cfg(target_os = "linux")] MiriAllocParams::Isolated(alloc) => alloc.borrow_mut().alloc_zeroed(layout), } }; diff --git a/src/tools/miri/src/alloc/isolated_alloc.rs b/src/tools/miri/src/alloc/isolated_alloc.rs index 7b2f1a3eebf..1745727b16b 100644 --- a/src/tools/miri/src/alloc/isolated_alloc.rs +++ b/src/tools/miri/src/alloc/isolated_alloc.rs @@ -1,7 +1,6 @@ use std::alloc::Layout; use std::ptr::NonNull; -use nix::sys::mman; use rustc_index::bit_set::DenseBitSet; /// How many bytes of memory each bit in the bitset represents. @@ -44,6 +43,10 @@ impl IsolatedAlloc { } } + pub fn page_size(&self) -> usize { + self.page_size + } + /// For simplicity, we serve small allocations in multiples of COMPRESSION_FACTOR /// bytes with at least that alignment. #[inline] @@ -302,50 +305,11 @@ impl IsolatedAlloc { } } - /// Returns a list of page addresses managed by the allocator. - pub fn pages(&self) -> impl Iterator<Item = usize> { - let pages = self.page_ptrs.iter().map(|p| p.expose_provenance().get()); - pages.chain(self.huge_ptrs.iter().flat_map(|(ptr, size)| { - (0..size / self.page_size) - .map(|i| ptr.expose_provenance().get().strict_add(i * self.page_size)) - })) - } - - /// Protects all owned memory as `PROT_NONE`, preventing accesses. - /// - /// SAFETY: Accessing memory after this point will result in a segfault - /// unless it is first unprotected. - pub unsafe fn start_ffi(&mut self) -> Result<(), nix::errno::Errno> { - let prot = mman::ProtFlags::PROT_NONE; - unsafe { self.mprotect(prot) } - } - - /// Deprotects all owned memory by setting it to RW. Erroring here is very - /// likely unrecoverable, so it may panic if applying those permissions - /// fails. - pub fn end_ffi(&mut self) { - let prot = mman::ProtFlags::PROT_READ | mman::ProtFlags::PROT_WRITE; - unsafe { - self.mprotect(prot).unwrap(); - } - } - - /// Applies `prot` to every page managed by the allocator. - /// - /// SAFETY: Accessing memory in violation of the protection flags will - /// trigger a segfault. - unsafe fn mprotect(&mut self, prot: mman::ProtFlags) -> Result<(), nix::errno::Errno> { - for &pg in &self.page_ptrs { - unsafe { - mman::mprotect(pg.cast(), self.page_size, prot)?; - } - } - for &(hpg, size) in &self.huge_ptrs { - unsafe { - mman::mprotect(hpg.cast(), size.next_multiple_of(self.page_size), prot)?; - } - } - Ok(()) + /// Returns a list of page ranges managed by the allocator, given in terms of pointers + /// and size (in bytes). + pub fn pages(&self) -> impl Iterator<Item = (NonNull<u8>, usize)> { + let pages = self.page_ptrs.iter().map(|&p| (p, self.page_size)); + pages.chain(self.huge_ptrs.iter().copied()) } } diff --git a/src/tools/miri/src/alloc/mod.rs b/src/tools/miri/src/alloc/mod.rs index 3be885920d2..35158f50a8f 100644 --- a/src/tools/miri/src/alloc/mod.rs +++ b/src/tools/miri/src/alloc/mod.rs @@ -1,5 +1,31 @@ mod alloc_bytes; -#[cfg(target_os = "linux")] +#[cfg(all(unix, feature = "native-lib"))] pub mod isolated_alloc; +#[cfg(not(all(unix, feature = "native-lib")))] +pub mod isolated_alloc { + use std::alloc::Layout; + + /// Stub allocator to avoid `cfg`s in the rest of Miri. + #[derive(Debug)] + pub struct IsolatedAlloc(!); + + impl IsolatedAlloc { + pub fn new() -> Self { + unreachable!() + } + + pub unsafe fn alloc(&mut self, _layout: Layout) -> *mut u8 { + match self.0 {} + } + + pub unsafe fn alloc_zeroed(&mut self, _layout: Layout) -> *mut u8 { + match self.0 {} + } + + pub unsafe fn dealloc(&mut self, _ptr: *mut u8, _layout: Layout) { + match self.0 {} + } + } +} pub use self::alloc_bytes::{MiriAllocBytes, MiriAllocParams}; diff --git a/src/tools/miri/src/alloc_addresses/mod.rs b/src/tools/miri/src/alloc_addresses/mod.rs index 3cc38fa087c..10339928ac2 100644 --- a/src/tools/miri/src/alloc_addresses/mod.rs +++ b/src/tools/miri/src/alloc_addresses/mod.rs @@ -157,7 +157,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { this.get_alloc_bytes_unchecked_raw(alloc_id)? } } - AllocKind::Function | AllocKind::VTable => { + AllocKind::Function | AllocKind::Virtual => { // Allocate some dummy memory to get a unique address for this function/vtable. let alloc_bytes = MiriAllocBytes::from_bytes( &[0u8; 1], diff --git a/src/tools/miri/src/bin/miri.rs b/src/tools/miri/src/bin/miri.rs index 61cebedf081..89fa980ff64 100644 --- a/src/tools/miri/src/bin/miri.rs +++ b/src/tools/miri/src/bin/miri.rs @@ -335,9 +335,10 @@ impl rustc_driver::Callbacks for MiriBeRustCompilerCalls { fn exit(exit_code: i32) -> ! { // Drop the tracing guard before exiting, so tracing calls are flushed correctly. deinit_loggers(); - // Make sure the supervisor knows about the code code. - #[cfg(target_os = "linux")] + // Make sure the supervisor knows about the exit code. + #[cfg(all(unix, feature = "native-lib"))] miri::native_lib::register_retcode_sv(exit_code); + // Actually exit. std::process::exit(exit_code); } @@ -561,6 +562,8 @@ fn main() { miri_config.force_intrinsic_fallback = true; } else if arg == "-Zmiri-deterministic-floats" { miri_config.float_nondet = false; + } else if arg == "-Zmiri-no-extra-rounding-error" { + miri_config.float_rounding_error = false; } else if arg == "-Zmiri-strict-provenance" { miri_config.provenance_mode = ProvenanceMode::Strict; } else if arg == "-Zmiri-permissive-provenance" { @@ -754,7 +757,7 @@ fn main() { debug!("crate arguments: {:?}", miri_config.args); if !miri_config.native_lib.is_empty() && miri_config.native_lib_enable_tracing { // SAFETY: No other threads are running - #[cfg(target_os = "linux")] + #[cfg(all(unix, feature = "native-lib"))] if unsafe { miri::native_lib::init_sv() }.is_err() { eprintln!( "warning: The native-lib tracer could not be started. Is this an x86 Linux system, and does Miri have permissions to ptrace?\n\ diff --git a/src/tools/miri/src/borrow_tracker/stacked_borrows/mod.rs b/src/tools/miri/src/borrow_tracker/stacked_borrows/mod.rs index 834a4b41f22..e834fdffdd1 100644 --- a/src/tools/miri/src/borrow_tracker/stacked_borrows/mod.rs +++ b/src/tools/miri/src/borrow_tracker/stacked_borrows/mod.rs @@ -650,7 +650,7 @@ trait EvalContextPrivExt<'tcx, 'ecx>: crate::MiriInterpCxExt<'tcx> { dcx.log_protector(); } }, - AllocKind::Function | AllocKind::VTable | AllocKind::Dead => { + AllocKind::Function | AllocKind::Virtual | AllocKind::Dead => { // No stacked borrows on these allocations. } } @@ -1021,7 +1021,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { trace!("Stacked Borrows tag {tag:?} exposed in {alloc_id:?}"); alloc_extra.borrow_tracker_sb().borrow_mut().exposed_tags.insert(tag); } - AllocKind::Function | AllocKind::VTable | AllocKind::Dead => { + AllocKind::Function | AllocKind::Virtual | AllocKind::Dead => { // No stacked borrows on these allocations. } } diff --git a/src/tools/miri/src/borrow_tracker/tree_borrows/mod.rs b/src/tools/miri/src/borrow_tracker/tree_borrows/mod.rs index c157c69d7c8..aa92f8a8c30 100644 --- a/src/tools/miri/src/borrow_tracker/tree_borrows/mod.rs +++ b/src/tools/miri/src/borrow_tracker/tree_borrows/mod.rs @@ -673,7 +673,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { trace!("Tree Borrows tag {tag:?} exposed in {alloc_id:?}"); alloc_extra.borrow_tracker_tb().borrow_mut().expose_tag(tag); } - AllocKind::Function | AllocKind::VTable | AllocKind::Dead => { + AllocKind::Function | AllocKind::Virtual | AllocKind::Dead => { // No tree borrows on these allocations. } } diff --git a/src/tools/miri/src/eval.rs b/src/tools/miri/src/eval.rs index be6404f64e8..3c80e60b772 100644 --- a/src/tools/miri/src/eval.rs +++ b/src/tools/miri/src/eval.rs @@ -170,6 +170,8 @@ pub struct MiriConfig { pub force_intrinsic_fallback: bool, /// Whether floating-point operations can behave non-deterministically. pub float_nondet: bool, + /// Whether floating-point operations can have a non-deterministic rounding error. + pub float_rounding_error: bool, } impl Default for MiriConfig { @@ -211,6 +213,7 @@ impl Default for MiriConfig { fixed_scheduling: false, force_intrinsic_fallback: false, float_nondet: true, + float_rounding_error: true, } } } diff --git a/src/tools/miri/src/lib.rs b/src/tools/miri/src/lib.rs index a591d21071d..ae70257653c 100644 --- a/src/tools/miri/src/lib.rs +++ b/src/tools/miri/src/lib.rs @@ -1,3 +1,4 @@ +#![feature(abort_unwind)] #![feature(cfg_select)] #![feature(rustc_private)] #![feature(float_gamma)] @@ -97,7 +98,7 @@ pub use rustc_const_eval::interpret::{self, AllocMap, Provenance as _}; use rustc_middle::{bug, span_bug}; use tracing::{info, trace}; -#[cfg(target_os = "linux")] +#[cfg(all(unix, feature = "native-lib"))] pub mod native_lib { pub use crate::shims::{init_sv, register_retcode_sv}; } diff --git a/src/tools/miri/src/machine.rs b/src/tools/miri/src/machine.rs index f309e34c75b..ce33c870b4b 100644 --- a/src/tools/miri/src/machine.rs +++ b/src/tools/miri/src/machine.rs @@ -530,7 +530,6 @@ pub struct MiriMachine<'tcx> { pub(crate) rng: RefCell<StdRng>, /// The allocator used for the machine's `AllocBytes` in native-libs mode. - #[cfg(target_os = "linux")] pub(crate) allocator: Option<Rc<RefCell<crate::alloc::isolated_alloc::IsolatedAlloc>>>, /// The allocation IDs to report when they are being allocated @@ -554,9 +553,9 @@ pub struct MiriMachine<'tcx> { pub(crate) basic_block_count: u64, /// Handle of the optional shared object file for native functions. - #[cfg(unix)] + #[cfg(all(unix, feature = "native-lib"))] pub native_lib: Vec<(libloading::Library, std::path::PathBuf)>, - #[cfg(not(unix))] + #[cfg(not(all(unix, feature = "native-lib")))] pub native_lib: Vec<!>, /// Run a garbage collector for BorTags every N basic blocks. @@ -603,7 +602,7 @@ pub struct MiriMachine<'tcx> { /// Remembers whether we already warned about an extern type with Stacked Borrows. pub(crate) sb_extern_type_warned: Cell<bool>, /// Remember whether we already warned about sharing memory with a native call. - #[cfg(unix)] + #[allow(unused)] pub(crate) native_call_mem_warned: Cell<bool>, /// Remembers which shims have already shown the warning about erroring in isolation. pub(crate) reject_in_isolation_warned: RefCell<FxHashSet<String>>, @@ -618,6 +617,8 @@ pub struct MiriMachine<'tcx> { /// Whether floating-point operations can behave non-deterministically. pub float_nondet: bool, + /// Whether floating-point operations can have a non-deterministic rounding error. + pub float_rounding_error: bool, } impl<'tcx> MiriMachine<'tcx> { @@ -718,7 +719,6 @@ impl<'tcx> MiriMachine<'tcx> { local_crates, extern_statics: FxHashMap::default(), rng: RefCell::new(rng), - #[cfg(target_os = "linux")] allocator: if !config.native_lib.is_empty() { Some(Rc::new(RefCell::new(crate::alloc::isolated_alloc::IsolatedAlloc::new()))) } else { None }, @@ -730,7 +730,7 @@ impl<'tcx> MiriMachine<'tcx> { report_progress: config.report_progress, basic_block_count: 0, monotonic_clock: MonotonicClock::new(config.isolated_op == IsolatedOp::Allow), - #[cfg(unix)] + #[cfg(all(unix, feature = "native-lib"))] native_lib: config.native_lib.iter().map(|lib_file_path| { let host_triple = rustc_session::config::host_tuple(); let target_triple = tcx.sess.opts.target_triple.tuple(); @@ -752,9 +752,9 @@ impl<'tcx> MiriMachine<'tcx> { lib_file_path.clone(), ) }).collect(), - #[cfg(not(unix))] + #[cfg(not(all(unix, feature = "native-lib")))] native_lib: config.native_lib.iter().map(|_| { - panic!("calling functions from native libraries via FFI is only supported on Unix") + panic!("calling functions from native libraries via FFI is not supported in this build of Miri") }).collect(), gc_interval: config.gc_interval, since_gc: 0, @@ -771,13 +771,13 @@ impl<'tcx> MiriMachine<'tcx> { pthread_rwlock_sanity: Cell::new(false), pthread_condvar_sanity: Cell::new(false), sb_extern_type_warned: Cell::new(false), - #[cfg(unix)] native_call_mem_warned: Cell::new(false), reject_in_isolation_warned: Default::default(), int2ptr_warned: Default::default(), mangle_internal_symbol_cache: Default::default(), force_intrinsic_fallback: config.force_intrinsic_fallback, float_nondet: config.float_nondet, + float_rounding_error: config.float_rounding_error, } } @@ -924,7 +924,6 @@ impl VisitProvenance for MiriMachine<'_> { backtrace_style: _, local_crates: _, rng: _, - #[cfg(target_os = "linux")] allocator: _, tracked_alloc_ids: _, track_alloc_accesses: _, @@ -949,13 +948,13 @@ impl VisitProvenance for MiriMachine<'_> { pthread_rwlock_sanity: _, pthread_condvar_sanity: _, sb_extern_type_warned: _, - #[cfg(unix)] native_call_mem_warned: _, reject_in_isolation_warned: _, int2ptr_warned: _, mangle_internal_symbol_cache: _, force_intrinsic_fallback: _, float_nondet: _, + float_rounding_error: _, } = self; threads.visit_provenance(visit); @@ -1817,13 +1816,10 @@ impl<'tcx> Machine<'tcx> for MiriMachine<'tcx> { fn get_default_alloc_params(&self) -> <Self::Bytes as AllocBytes>::AllocParams { use crate::alloc::MiriAllocParams; - #[cfg(target_os = "linux")] match &self.allocator { Some(alloc) => MiriAllocParams::Isolated(alloc.clone()), None => MiriAllocParams::Global, } - #[cfg(not(target_os = "linux"))] - MiriAllocParams::Global } fn enter_trace_span(span: impl FnOnce() -> tracing::Span) -> impl EnteredTraceSpan { diff --git a/src/tools/miri/src/math.rs b/src/tools/miri/src/math.rs index cf16a5676d6..e9e5a1070c9 100644 --- a/src/tools/miri/src/math.rs +++ b/src/tools/miri/src/math.rs @@ -15,7 +15,7 @@ pub(crate) fn apply_random_float_error<F: rustc_apfloat::Float>( val: F, err_scale: i32, ) -> F { - if !ecx.machine.float_nondet { + if !ecx.machine.float_nondet || !ecx.machine.float_rounding_error { return val; } diff --git a/src/tools/miri/src/shims/foreign_items.rs b/src/tools/miri/src/shims/foreign_items.rs index 9ddba8c2b48..94cda57658a 100644 --- a/src/tools/miri/src/shims/foreign_items.rs +++ b/src/tools/miri/src/shims/foreign_items.rs @@ -237,7 +237,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { let this = self.eval_context_mut(); // First deal with any external C functions in linked .so file. - #[cfg(unix)] + #[cfg(all(unix, feature = "native-lib"))] if !this.machine.native_lib.is_empty() { use crate::shims::native_lib::EvalContextExt as _; // An Ok(false) here means that the function being called was not exported diff --git a/src/tools/miri/src/shims/mod.rs b/src/tools/miri/src/shims/mod.rs index 75540f6f150..2a7709829ee 100644 --- a/src/tools/miri/src/shims/mod.rs +++ b/src/tools/miri/src/shims/mod.rs @@ -4,7 +4,7 @@ mod aarch64; mod alloc; mod backtrace; mod files; -#[cfg(unix)] +#[cfg(all(unix, feature = "native-lib"))] mod native_lib; mod unix; mod wasi; @@ -23,7 +23,7 @@ pub mod tls; pub mod unwind; pub use self::files::FdTable; -#[cfg(target_os = "linux")] +#[cfg(all(unix, feature = "native-lib"))] pub use self::native_lib::trace::{init_sv, register_retcode_sv}; pub use self::unix::{DirTable, EpollInterestTable}; diff --git a/src/tools/miri/src/shims/native_lib/mod.rs b/src/tools/miri/src/shims/native_lib/mod.rs index fb7b1df41a4..2827ed997a7 100644 --- a/src/tools/miri/src/shims/native_lib/mod.rs +++ b/src/tools/miri/src/shims/native_lib/mod.rs @@ -8,6 +8,7 @@ use rustc_abi::{BackendRepr, HasDataLayout, Size}; use rustc_middle::mir::interpret::Pointer; use rustc_middle::ty::{self as ty, IntTy, UintTy}; use rustc_span::Symbol; +use serde::{Deserialize, Serialize}; #[cfg_attr( not(all( @@ -23,18 +24,14 @@ use crate::*; /// The final results of an FFI trace, containing every relevant event detected /// by the tracer. -#[allow(dead_code)] -#[cfg_attr(target_os = "linux", derive(serde::Serialize, serde::Deserialize))] -#[derive(Debug)] +#[derive(Serialize, Deserialize, Debug)] pub struct MemEvents { /// An list of memory accesses that occurred, in the order they occurred in. pub acc_events: Vec<AccessEvent>, } /// A single memory access. -#[allow(dead_code)] -#[cfg_attr(target_os = "linux", derive(serde::Serialize, serde::Deserialize))] -#[derive(Clone, Debug)] +#[derive(Serialize, Deserialize, Clone, Debug)] pub enum AccessEvent { /// A read occurred on this memory range. Read(AccessRange), @@ -56,9 +53,7 @@ impl AccessEvent { } /// The memory touched by a given access. -#[allow(dead_code)] -#[cfg_attr(target_os = "linux", derive(serde::Serialize, serde::Deserialize))] -#[derive(Clone, Debug)] +#[derive(Serialize, Deserialize, Clone, Debug)] pub struct AccessRange { /// The base address in memory where an access occurred. pub addr: usize, diff --git a/src/tools/miri/src/shims/native_lib/trace/child.rs b/src/tools/miri/src/shims/native_lib/trace/child.rs index de26cb0fe55..b998ba822dd 100644 --- a/src/tools/miri/src/shims/native_lib/trace/child.rs +++ b/src/tools/miri/src/shims/native_lib/trace/child.rs @@ -1,8 +1,9 @@ use std::cell::RefCell; +use std::ptr::NonNull; use std::rc::Rc; use ipc_channel::ipc; -use nix::sys::{ptrace, signal}; +use nix::sys::{mman, ptrace, signal}; use nix::unistd; use rustc_const_eval::interpret::InterpResult; @@ -44,6 +45,16 @@ impl Supervisor { SUPERVISOR.lock().unwrap().is_some() } + unsafe fn protect_pages( + pages: impl Iterator<Item = (NonNull<u8>, usize)>, + prot: mman::ProtFlags, + ) -> Result<(), nix::errno::Errno> { + for (pg, sz) in pages { + unsafe { mman::mprotect(pg.cast(), sz, prot)? }; + } + Ok(()) + } + /// Performs an arbitrary FFI call, enabling tracing from the supervisor. /// As this locks the supervisor via a mutex, no other threads may enter FFI /// until this function returns. @@ -60,47 +71,67 @@ impl Supervisor { // Get pointers to all the pages the supervisor must allow accesses in // and prepare the callback stack. - let page_ptrs = alloc.borrow().pages().collect(); + let alloc = alloc.borrow(); + let page_size = alloc.page_size(); + let page_ptrs = alloc + .pages() + .flat_map(|(pg, sz)| { + // Convert (page, size) pair into list of pages. + let start = pg.expose_provenance().get(); + (0..sz.strict_div(alloc.page_size())) + .map(move |i| start.strict_add(i.strict_mul(page_size))) + }) + .collect(); let raw_stack_ptr: *mut [u8; CALLBACK_STACK_SIZE] = Box::leak(Box::new([0u8; CALLBACK_STACK_SIZE])).as_mut_ptr().cast(); let stack_ptr = raw_stack_ptr.expose_provenance(); let start_info = StartFfiInfo { page_ptrs, stack_ptr }; - // SAFETY: We do not access machine memory past this point until the - // supervisor is ready to allow it. - unsafe { - if alloc.borrow_mut().start_ffi().is_err() { - // Don't mess up unwinding by maybe leaving the memory partly protected - alloc.borrow_mut().end_ffi(); - panic!("Cannot protect memory for FFI call!"); + // Unwinding might be messed up due to partly protected memory, so let's abort if something + // breaks inside here. + let res = std::panic::abort_unwind(|| { + // SAFETY: We do not access machine memory past this point until the + // supervisor is ready to allow it. + // FIXME: this is sketchy, as technically the memory is still in the Rust Abstract Machine, + // and the compiler would be allowed to reorder accesses below this block... + unsafe { + Self::protect_pages(alloc.pages(), mman::ProtFlags::PROT_NONE).unwrap(); } - } - // Send over the info. - // NB: if we do not wait to receive a blank confirmation response, it is - // possible that the supervisor is alerted of the SIGSTOP *before* it has - // actually received the start_info, thus deadlocking! This way, we can - // enforce an ordering for these events. - sv.message_tx.send(TraceRequest::StartFfi(start_info)).unwrap(); - sv.confirm_rx.recv().unwrap(); - // We need to be stopped for the supervisor to be able to make certain - // modifications to our memory - simply waiting on the recv() doesn't - // count. - signal::raise(signal::SIGSTOP).unwrap(); - - let res = f(); - - // We can't use IPC channels here to signal that FFI mode has ended, - // since they might allocate memory which could get us stuck in a SIGTRAP - // with no easy way out! While this could be worked around, it is much - // simpler and more robust to simply use the signals which are left for - // arbitrary usage. Since this will block until we are continued by the - // supervisor, we can assume past this point that everything is back to - // normal. - signal::raise(signal::SIGUSR1).unwrap(); - - // This is safe! It just sets memory to normal expected permissions. - alloc.borrow_mut().end_ffi(); + // Send over the info. + // NB: if we do not wait to receive a blank confirmation response, it is + // possible that the supervisor is alerted of the SIGSTOP *before* it has + // actually received the start_info, thus deadlocking! This way, we can + // enforce an ordering for these events. + sv.message_tx.send(TraceRequest::StartFfi(start_info)).unwrap(); + sv.confirm_rx.recv().unwrap(); + // We need to be stopped for the supervisor to be able to make certain + // modifications to our memory - simply waiting on the recv() doesn't + // count. + signal::raise(signal::SIGSTOP).unwrap(); + + let res = f(); + + // We can't use IPC channels here to signal that FFI mode has ended, + // since they might allocate memory which could get us stuck in a SIGTRAP + // with no easy way out! While this could be worked around, it is much + // simpler and more robust to simply use the signals which are left for + // arbitrary usage. Since this will block until we are continued by the + // supervisor, we can assume past this point that everything is back to + // normal. + signal::raise(signal::SIGUSR1).unwrap(); + + // SAFETY: We set memory back to normal, so this is safe. + unsafe { + Self::protect_pages( + alloc.pages(), + mman::ProtFlags::PROT_READ | mman::ProtFlags::PROT_WRITE, + ) + .unwrap(); + } + + res + }); // SAFETY: Caller upholds that this pointer was allocated as a box with // this type. diff --git a/src/tools/miri/src/shims/native_lib/trace/messages.rs b/src/tools/miri/src/shims/native_lib/trace/messages.rs index 1f9df556b57..bef6cc1b2f3 100644 --- a/src/tools/miri/src/shims/native_lib/trace/messages.rs +++ b/src/tools/miri/src/shims/native_lib/trace/messages.rs @@ -45,8 +45,7 @@ pub enum TraceRequest { /// Information needed to begin tracing. #[derive(serde::Serialize, serde::Deserialize, Debug, Clone)] pub struct StartFfiInfo { - /// A vector of page addresses. These should have been automatically obtained - /// with `IsolatedAlloc::pages` and prepared with `IsolatedAlloc::start_ffi`. + /// A vector of page addresses that store the miri heap which is accessible from C. pub page_ptrs: Vec<usize>, /// The address of an allocation that can serve as a temporary stack. /// This should be a leaked `Box<[u8; CALLBACK_STACK_SIZE]>` cast to an int. diff --git a/src/tools/miri/test_dependencies/Cargo.lock b/src/tools/miri/tests/deps/Cargo.lock index 276c518e74f..4b783ebdc4e 100644 --- a/src/tools/miri/test_dependencies/Cargo.lock +++ b/src/tools/miri/tests/deps/Cargo.lock @@ -13,15 +13,15 @@ dependencies = [ [[package]] name = "adler2" -version = "2.0.0" +version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "backtrace" -version = "0.3.74" +version = "0.3.75" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d82cb332cdfaed17ae235a638438ac4d4839913cc2af585c3c6746e8f8bee1a" +checksum = "6806a6321ec58106fea15becdad98371e28d92ccbc7c8f1b3b6dd724fe8f1002" dependencies = [ "addr2line", "cfg-if", @@ -29,20 +29,20 @@ dependencies = [ "miniz_oxide", "object", "rustc-demangle", - "windows-targets", + "windows-targets 0.52.6", ] [[package]] name = "bitflags" -version = "2.9.0" +version = "2.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd" +checksum = "1b8e56985ec62d17e9c1001dc89c88ecd7dc08e47eba5ec7c29c7b5eeecde967" [[package]] name = "bumpalo" -version = "3.17.0" +version = "3.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1628fb46dfa0b37568d12e5edd512553eccf6a22a78e8bde00bb4aed84d5bdbf" +checksum = "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43" [[package]] name = "bytes" @@ -52,18 +52,18 @@ checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a" [[package]] name = "cfg-if" -version = "1.0.0" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" +checksum = "9555578bc9e57714c812a1f84e4fc5b4d21fcb063490c624de019f7464c91268" [[package]] name = "errno" -version = "0.3.11" +version = "0.3.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "976dd42dc7e85965fe702eb8164f21f450704bdde31faefd6471dba214cb594e" +checksum = "778e2ac28f6c47af28e4907f13ffd1e1ddbd400980a9abd7c8df189bf578a5ad" dependencies = [ "libc", - "windows-sys 0.59.0", + "windows-sys 0.60.2", ] [[package]] @@ -85,22 +85,22 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.2.15" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" +checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592" dependencies = [ "cfg-if", "js-sys", "libc", - "wasi 0.11.0+wasi-snapshot-preview1", + "wasi 0.11.1+wasi-snapshot-preview1", "wasm-bindgen", ] [[package]] name = "getrandom" -version = "0.3.2" +version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73fea8450eea4bac3940448fb7ae50d91f034f941199fcd9d909a5a07aa455f0" +checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4" dependencies = [ "cfg-if", "libc", @@ -116,9 +116,20 @@ checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f" [[package]] name = "hermit-abi" -version = "0.3.9" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" + +[[package]] +name = "io-uring" +version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" +checksum = "b86e202f00093dcba4275d4636b93ef9dd75d025ae560d2521b45ea28ab49013" +dependencies = [ + "bitflags", + "cfg-if", + "libc", +] [[package]] name = "js-sys" @@ -132,15 +143,15 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.171" +version = "0.2.174" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c19937216e9d3aa9956d9bb8dfc0b0c8beb6058fc4f7a4dc4d850edf86a237d6" +checksum = "1171693293099992e19cddea4e8b849964e9846f4acee11b3948bcc337be8776" [[package]] name = "linux-raw-sys" -version = "0.9.3" +version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe7db12097d22ec582439daf8618b8fdd1a7bef6270e9af3b1ebcd30893cf413" +checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12" [[package]] name = "log" @@ -150,28 +161,28 @@ checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94" [[package]] name = "memchr" -version = "2.7.4" +version = "2.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" +checksum = "32a282da65faaf38286cf3be983213fcf1d2e2a58700e808f83f4ea9a4804bc0" [[package]] name = "miniz_oxide" -version = "0.8.8" +version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3be647b768db090acb35d5ec5db2b0e1f1de11133ca123b9eacf5137868f892a" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" dependencies = [ "adler2", ] [[package]] name = "mio" -version = "1.0.3" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2886843bf800fba2e3377cff24abf6379b4c4d5c6681eaf9ea5b0d15090450bd" +checksum = "78bed444cc8a2160f01cbcf811ef18cac863ad68ae8ca62092e8db51d51c761c" dependencies = [ "libc", - "wasi 0.11.0+wasi-snapshot-preview1", - "windows-sys 0.52.0", + "wasi 0.11.1+wasi-snapshot-preview1", + "windows-sys 0.59.0", ] [[package]] @@ -180,21 +191,21 @@ version = "0.1.0" dependencies = [ "cfg-if", "getrandom 0.1.16", - "getrandom 0.2.15", - "getrandom 0.3.2", + "getrandom 0.2.16", + "getrandom 0.3.3", "libc", "num_cpus", "page_size", "tempfile", "tokio", - "windows-sys 0.59.0", + "windows-sys 0.60.2", ] [[package]] name = "num_cpus" -version = "1.16.0" +version = "1.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43" +checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" dependencies = [ "hermit-abi", "libc", @@ -233,9 +244,9 @@ checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" [[package]] name = "proc-macro2" -version = "1.0.94" +version = "1.0.95" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a31971752e70b8b2686d7e46ec17fb38dad4051d94024c88df49b667caea9c84" +checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778" dependencies = [ "unicode-ident", ] @@ -251,43 +262,49 @@ dependencies = [ [[package]] name = "r-efi" -version = "5.2.0" +version = "5.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74765f6d916ee2faa39bc8e68e4f3ed8949b48cccdac59983d287a7cb71ce9c5" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" [[package]] name = "rustc-demangle" -version = "0.1.24" +version = "0.1.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" +checksum = "989e6739f80c4ad5b13e0fd7fe89531180375b18520cc8c82080e4dc4035b84f" [[package]] name = "rustix" -version = "1.0.5" +version = "1.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d97817398dd4bb2e6da002002db259209759911da105da92bec29ccb12cf58bf" +checksum = "11181fbabf243db407ef8df94a6ce0b2f9a733bd8be4ad02b4eda9602296cac8" dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys", - "windows-sys 0.59.0", + "windows-sys 0.60.2", ] [[package]] name = "signal-hook-registry" -version = "1.4.2" +version = "1.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1" +checksum = "9203b8055f63a2a00e2f593bb0510367fe707d7ff1e5c872de2f537b339e5410" dependencies = [ "libc", ] [[package]] +name = "slab" +version = "0.4.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04dc19736151f35336d325007ac991178d504a119863a2fcb3758cdb5e52c50d" + +[[package]] name = "socket2" -version = "0.5.9" +version = "0.5.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f5fd57c80058a56cf5c777ab8a126398ece8e442983605d280a44ce79d0edef" +checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678" dependencies = [ "libc", "windows-sys 0.52.0", @@ -295,9 +312,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.100" +version = "2.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b09a44accad81e1ba1cd74a32461ba89dee89095ba17b32f5d03683b1b1fc2a0" +checksum = "17b6f705963418cdb9927482fa304bc562ece2fdd4f616084c50b7023b435a40" dependencies = [ "proc-macro2", "quote", @@ -306,12 +323,12 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.19.1" +version = "3.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7437ac7763b9b123ccf33c338a5cc1bac6f69b45a136c19bdd8a65e3916435bf" +checksum = "e8a64e3985349f2441a1a9ef0b853f869006c3855f2cda6862a94d26ebb9d6a1" dependencies = [ "fastrand", - "getrandom 0.3.2", + "getrandom 0.3.3", "once_cell", "rustix", "windows-sys 0.59.0", @@ -319,16 +336,18 @@ dependencies = [ [[package]] name = "tokio" -version = "1.44.2" +version = "1.46.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6b88822cbe49de4185e3a4cbf8321dd487cf5fe0c5c65695fef6346371e9c48" +checksum = "0cc3a2344dafbe23a245241fe8b09735b521110d30fcefbbd5feb1797ca35d17" dependencies = [ "backtrace", "bytes", + "io-uring", "libc", "mio", "pin-project-lite", "signal-hook-registry", + "slab", "socket2", "tokio-macros", "windows-sys 0.52.0", @@ -359,9 +378,9 @@ checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" [[package]] name = "wasi" -version = "0.11.0+wasi-snapshot-preview1" +version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" [[package]] name = "wasi" @@ -457,7 +476,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets", + "windows-targets 0.52.6", ] [[package]] @@ -466,7 +485,16 @@ version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ - "windows-targets", + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.2", ] [[package]] @@ -475,14 +503,30 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c66f69fcc9ce11da9966ddb31a40968cad001c5bedeb5c2b82ede4253ab48aef" +dependencies = [ + "windows_aarch64_gnullvm 0.53.0", + "windows_aarch64_msvc 0.53.0", + "windows_i686_gnu 0.53.0", + "windows_i686_gnullvm 0.53.0", + "windows_i686_msvc 0.53.0", + "windows_x86_64_gnu 0.53.0", + "windows_x86_64_gnullvm 0.53.0", + "windows_x86_64_msvc 0.53.0", ] [[package]] @@ -492,48 +536,96 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" [[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86b8d5f90ddd19cb4a147a5fa63ca848db3df085e25fee3cc10b39b6eebae764" + +[[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" [[package]] +name = "windows_aarch64_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7651a1f62a11b8cbd5e0d42526e55f2c99886c77e007179efff86c2b137e66c" + +[[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" [[package]] +name = "windows_i686_gnu" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1dc67659d35f387f5f6c479dc4e28f1d4bb90ddd1a5d3da2e5d97b42d6272c3" + +[[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" [[package]] +name = "windows_i686_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce6ccbdedbf6d6354471319e781c0dfef054c81fbc7cf83f338a4296c0cae11" + +[[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" [[package]] +name = "windows_i686_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "581fee95406bb13382d2f65cd4a908ca7b1e4c2f1917f143ba16efe98a589b5d" + +[[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" [[package]] +name = "windows_x86_64_gnu" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e55b5ac9ea33f2fc1716d1742db15574fd6fc8dadc51caab1c16a3d3b4190ba" + +[[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" [[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a6e035dd0599267ce1ee132e51c27dd29437f63325753051e71dd9e42406c57" + +[[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] +name = "windows_x86_64_msvc" +version = "0.53.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486" + +[[package]] name = "wit-bindgen-rt" version = "0.39.0" source = "registry+https://github.com/rust-lang/crates.io-index" diff --git a/src/tools/miri/test_dependencies/Cargo.toml b/src/tools/miri/tests/deps/Cargo.toml index 35555723f5d..d85723f0915 100644 --- a/src/tools/miri/test_dependencies/Cargo.toml +++ b/src/tools/miri/tests/deps/Cargo.toml @@ -25,7 +25,7 @@ page_size = "0.6" tokio = { version = "1", features = ["macros", "rt-multi-thread", "time", "net", "fs", "sync", "signal", "io-util"] } [target.'cfg(windows)'.dependencies] -windows-sys = { version = "0.59", features = [ +windows-sys = { version = "0.60", features = [ "Win32_Foundation", "Win32_System_Threading", "Win32_Storage_FileSystem", diff --git a/src/tools/miri/test_dependencies/src/main.rs b/src/tools/miri/tests/deps/src/main.rs index f328e4d9d04..f328e4d9d04 100644 --- a/src/tools/miri/test_dependencies/src/main.rs +++ b/src/tools/miri/tests/deps/src/main.rs diff --git a/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_cond_double_destroy.rs b/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_cond_double_destroy.rs index 047fe07df14..5778765589d 100644 --- a/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_cond_double_destroy.rs +++ b/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_cond_double_destroy.rs @@ -1,4 +1,6 @@ //@ignore-target: windows # No pthreads on Windows +//@ normalize-stderr-test: "(\n)ALLOC \(.*\) \{\n(.*\n)*\}(\n)" -> "${1}ALLOC DUMP${3}" +//@ normalize-stderr-test: "\[0x[0-9a-z]..0x[0-9a-z]\]" -> "[0xX..0xY]" /// Test that destroying a pthread_cond twice fails, even without a check for number validity @@ -15,6 +17,6 @@ fn main() { libc::pthread_cond_destroy(cond.as_mut_ptr()); libc::pthread_cond_destroy(cond.as_mut_ptr()); - //~^ ERROR: Undefined Behavior: using uninitialized data, but this operation requires initialized memory + //~^ ERROR: /Undefined Behavior: reading memory .*, but memory is uninitialized/ } } diff --git a/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_cond_double_destroy.stderr b/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_cond_double_destroy.stderr index 7abdfa87f75..6156070cf95 100644 --- a/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_cond_double_destroy.stderr +++ b/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_cond_double_destroy.stderr @@ -1,4 +1,4 @@ -error: Undefined Behavior: using uninitialized data, but this operation requires initialized memory +error: Undefined Behavior: reading memory at ALLOC[0xX..0xY], but memory is uninitialized at [0xX..0xY], and this operation requires initialized memory --> tests/fail-dep/concurrency/libc_pthread_cond_double_destroy.rs:LL:CC | LL | libc::pthread_cond_destroy(cond.as_mut_ptr()); @@ -9,6 +9,9 @@ LL | libc::pthread_cond_destroy(cond.as_mut_ptr()); = note: BACKTRACE: = note: inside `main` at tests/fail-dep/concurrency/libc_pthread_cond_double_destroy.rs:LL:CC +Uninitialized memory occurred at ALLOC[0xX..0xY], in this allocation: +ALLOC DUMP + note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace error: aborting due to 1 previous error diff --git a/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_condattr_double_destroy.rs b/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_condattr_double_destroy.rs index 90e33d58673..91169660491 100644 --- a/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_condattr_double_destroy.rs +++ b/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_condattr_double_destroy.rs @@ -1,5 +1,7 @@ //@ignore-target: windows # No pthreads on Windows //@ignore-target: apple # Our macOS condattr don't have any fields so we do not notice this. +//@ normalize-stderr-test: "(\n)ALLOC \(.*\) \{\n(.*\n)*\}(\n)" -> "${1}ALLOC DUMP${3}" +//@ normalize-stderr-test: "\[0x[0-9a-z]..0x[0-9a-z]\]" -> "[0xX..0xY]" /// Test that destroying a pthread_condattr twice fails, even without a check for number validity @@ -13,6 +15,6 @@ fn main() { libc::pthread_condattr_destroy(attr.as_mut_ptr()); libc::pthread_condattr_destroy(attr.as_mut_ptr()); - //~^ ERROR: Undefined Behavior: using uninitialized data, but this operation requires initialized memory + //~^ ERROR: /Undefined Behavior: reading memory .*, but memory is uninitialized/ } } diff --git a/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_condattr_double_destroy.stderr b/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_condattr_double_destroy.stderr index 28a66253ae8..da64970ff2e 100644 --- a/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_condattr_double_destroy.stderr +++ b/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_condattr_double_destroy.stderr @@ -1,4 +1,4 @@ -error: Undefined Behavior: using uninitialized data, but this operation requires initialized memory +error: Undefined Behavior: reading memory at ALLOC[0xX..0xY], but memory is uninitialized at [0xX..0xY], and this operation requires initialized memory --> tests/fail-dep/concurrency/libc_pthread_condattr_double_destroy.rs:LL:CC | LL | libc::pthread_condattr_destroy(attr.as_mut_ptr()); @@ -9,6 +9,9 @@ LL | libc::pthread_condattr_destroy(attr.as_mut_ptr()); = note: BACKTRACE: = note: inside `main` at tests/fail-dep/concurrency/libc_pthread_condattr_double_destroy.rs:LL:CC +Uninitialized memory occurred at ALLOC[0xX..0xY], in this allocation: +ALLOC DUMP + note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace error: aborting due to 1 previous error diff --git a/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_mutex_double_destroy.rs b/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_mutex_double_destroy.rs index 1792c227e13..f04fe8be6b3 100644 --- a/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_mutex_double_destroy.rs +++ b/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_mutex_double_destroy.rs @@ -1,4 +1,6 @@ //@ignore-target: windows # No pthreads on Windows +//@ normalize-stderr-test: "(\n)ALLOC \(.*\) \{\n(.*\n)*\}(\n)" -> "${1}ALLOC DUMP${3}" +//@ normalize-stderr-test: "\[0x[0-9a-z]..0x[0-9a-z]\]" -> "[0xX..0xY]" /// Test that destroying a pthread_mutex twice fails, even without a check for number validity @@ -16,6 +18,6 @@ fn main() { libc::pthread_mutex_destroy(mutex.as_mut_ptr()); libc::pthread_mutex_destroy(mutex.as_mut_ptr()); - //~^ ERROR: Undefined Behavior: using uninitialized data, but this operation requires initialized memory + //~^ ERROR: /Undefined Behavior: reading memory .*, but memory is uninitialized/ } } diff --git a/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_mutex_double_destroy.stderr b/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_mutex_double_destroy.stderr index e7a6dee0203..05db823b252 100644 --- a/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_mutex_double_destroy.stderr +++ b/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_mutex_double_destroy.stderr @@ -1,4 +1,4 @@ -error: Undefined Behavior: using uninitialized data, but this operation requires initialized memory +error: Undefined Behavior: reading memory at ALLOC[0xX..0xY], but memory is uninitialized at [0xX..0xY], and this operation requires initialized memory --> tests/fail-dep/concurrency/libc_pthread_mutex_double_destroy.rs:LL:CC | LL | libc::pthread_mutex_destroy(mutex.as_mut_ptr()); @@ -9,6 +9,9 @@ LL | libc::pthread_mutex_destroy(mutex.as_mut_ptr()); = note: BACKTRACE: = note: inside `main` at tests/fail-dep/concurrency/libc_pthread_mutex_double_destroy.rs:LL:CC +Uninitialized memory occurred at ALLOC[0xX..0xY], in this allocation: +ALLOC DUMP + note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace error: aborting due to 1 previous error diff --git a/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_mutexattr_double_destroy.rs b/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_mutexattr_double_destroy.rs index 3711c1f8dc1..d9daf5259bb 100644 --- a/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_mutexattr_double_destroy.rs +++ b/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_mutexattr_double_destroy.rs @@ -1,4 +1,6 @@ //@ignore-target: windows # No pthreads on Windows +//@ normalize-stderr-test: "(\n)ALLOC \(.*\) \{\n(.*\n)*\}(\n)" -> "${1}ALLOC DUMP${3}" +//@ normalize-stderr-test: "\[0x[0-9a-z]..0x[0-9a-z]\]" -> "[0xX..0xY]" /// Test that destroying a pthread_mutexattr twice fails, even without a check for number validity @@ -12,6 +14,6 @@ fn main() { libc::pthread_mutexattr_destroy(attr.as_mut_ptr()); libc::pthread_mutexattr_destroy(attr.as_mut_ptr()); - //~^ ERROR: Undefined Behavior: using uninitialized data, but this operation requires initialized memory + //~^ ERROR: /Undefined Behavior: reading memory .*, but memory is uninitialized/ } } diff --git a/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_mutexattr_double_destroy.stderr b/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_mutexattr_double_destroy.stderr index 0c9ee71de45..ee3883de36b 100644 --- a/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_mutexattr_double_destroy.stderr +++ b/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_mutexattr_double_destroy.stderr @@ -1,4 +1,4 @@ -error: Undefined Behavior: using uninitialized data, but this operation requires initialized memory +error: Undefined Behavior: reading memory at ALLOC[0xX..0xY], but memory is uninitialized at [0xX..0xY], and this operation requires initialized memory --> tests/fail-dep/concurrency/libc_pthread_mutexattr_double_destroy.rs:LL:CC | LL | libc::pthread_mutexattr_destroy(attr.as_mut_ptr()); @@ -9,6 +9,9 @@ LL | libc::pthread_mutexattr_destroy(attr.as_mut_ptr()); = note: BACKTRACE: = note: inside `main` at tests/fail-dep/concurrency/libc_pthread_mutexattr_double_destroy.rs:LL:CC +Uninitialized memory occurred at ALLOC[0xX..0xY], in this allocation: +ALLOC DUMP + note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace error: aborting due to 1 previous error diff --git a/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_rwlock_double_destroy.rs b/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_rwlock_double_destroy.rs index 6a31e972e68..720ba71d238 100644 --- a/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_rwlock_double_destroy.rs +++ b/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_rwlock_double_destroy.rs @@ -1,4 +1,6 @@ //@ignore-target: windows # No pthreads on Windows +//@ normalize-stderr-test: "(\n)ALLOC \(.*\) \{\n(.*\n)*\}(\n)" -> "${1}ALLOC DUMP${3}" +//@ normalize-stderr-test: "\[0x[0-9a-z]..0x[0-9a-z]\]" -> "[0xX..0xY]" /// Test that destroying a pthread_rwlock twice fails, even without a check for number validity @@ -9,6 +11,6 @@ fn main() { libc::pthread_rwlock_destroy(&mut lock); libc::pthread_rwlock_destroy(&mut lock); - //~^ ERROR: Undefined Behavior: using uninitialized data, but this operation requires initialized memory + //~^ ERROR: /Undefined Behavior: reading memory .*, but memory is uninitialized/ } } diff --git a/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_rwlock_double_destroy.stderr b/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_rwlock_double_destroy.stderr index 836f0d060bd..430398dc8fd 100644 --- a/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_rwlock_double_destroy.stderr +++ b/src/tools/miri/tests/fail-dep/concurrency/libc_pthread_rwlock_double_destroy.stderr @@ -1,4 +1,4 @@ -error: Undefined Behavior: using uninitialized data, but this operation requires initialized memory +error: Undefined Behavior: reading memory at ALLOC[0xX..0xY], but memory is uninitialized at [0xX..0xY], and this operation requires initialized memory --> tests/fail-dep/concurrency/libc_pthread_rwlock_double_destroy.rs:LL:CC | LL | libc::pthread_rwlock_destroy(&mut lock); @@ -9,6 +9,9 @@ LL | libc::pthread_rwlock_destroy(&mut lock); = note: BACKTRACE: = note: inside `main` at tests/fail-dep/concurrency/libc_pthread_rwlock_double_destroy.rs:LL:CC +Uninitialized memory occurred at ALLOC[0xX..0xY], in this allocation: +ALLOC DUMP + note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace error: aborting due to 1 previous error diff --git a/src/tools/miri/tests/fail/function_calls/arg_inplace_observe_after.stderr b/src/tools/miri/tests/fail/function_calls/arg_inplace_observe_after.stderr index 6a7d9a495f9..3252368ea6d 100644 --- a/src/tools/miri/tests/fail/function_calls/arg_inplace_observe_after.stderr +++ b/src/tools/miri/tests/fail/function_calls/arg_inplace_observe_after.stderr @@ -1,4 +1,4 @@ -error: Undefined Behavior: using uninitialized data, but this operation requires initialized memory +error: Undefined Behavior: reading memory at ALLOC[0x0..0x4], but memory is uninitialized at [0x0..0x4], and this operation requires initialized memory --> tests/fail/function_calls/arg_inplace_observe_after.rs:LL:CC | LL | _observe = non_copy.0; @@ -9,6 +9,11 @@ LL | _observe = non_copy.0; = note: BACKTRACE: = note: inside `main` at tests/fail/function_calls/arg_inplace_observe_after.rs:LL:CC +Uninitialized memory occurred at ALLOC[0x0..0x4], in this allocation: +ALLOC (stack variable, size: 4, align: 4) { + __ __ __ __ │ ░░░░ +} + note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace error: aborting due to 1 previous error diff --git a/src/tools/miri/tests/fail/function_calls/arg_inplace_observe_during.none.stderr b/src/tools/miri/tests/fail/function_calls/arg_inplace_observe_during.none.stderr index 0fc634bb7fc..09a5b9a6496 100644 --- a/src/tools/miri/tests/fail/function_calls/arg_inplace_observe_during.none.stderr +++ b/src/tools/miri/tests/fail/function_calls/arg_inplace_observe_during.none.stderr @@ -1,4 +1,4 @@ -error: Undefined Behavior: using uninitialized data, but this operation requires initialized memory +error: Undefined Behavior: reading memory at ALLOC[0x0..0x4], but memory is uninitialized at [0x0..0x4], and this operation requires initialized memory --> tests/fail/function_calls/arg_inplace_observe_during.rs:LL:CC | LL | unsafe { ptr.read() }; @@ -14,6 +14,11 @@ note: inside `main` LL | Call(_unit = change_arg(Move(*ptr), ptr), ReturnTo(after_call), UnwindContinue()) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Uninitialized memory occurred at ALLOC[0x0..0x4], in this allocation: +ALLOC (stack variable, size: 4, align: 4) { + __ __ __ __ │ ░░░░ +} + note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace error: aborting due to 1 previous error diff --git a/src/tools/miri/tests/fail/function_calls/return_pointer_aliasing_read.none.stderr b/src/tools/miri/tests/fail/function_calls/return_pointer_aliasing_read.none.stderr index 746ab2e59ca..24091547258 100644 --- a/src/tools/miri/tests/fail/function_calls/return_pointer_aliasing_read.none.stderr +++ b/src/tools/miri/tests/fail/function_calls/return_pointer_aliasing_read.none.stderr @@ -1,4 +1,4 @@ -error: Undefined Behavior: using uninitialized data, but this operation requires initialized memory +error: Undefined Behavior: reading memory at ALLOC[0x0..0x4], but memory is uninitialized at [0x0..0x4], and this operation requires initialized memory --> tests/fail/function_calls/return_pointer_aliasing_read.rs:LL:CC | LL | unsafe { ptr.read() }; @@ -14,6 +14,11 @@ note: inside `main` LL | Call(*ptr = myfun(ptr), ReturnTo(after_call), UnwindContinue()) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Uninitialized memory occurred at ALLOC[0x0..0x4], in this allocation: +ALLOC (stack variable, size: 4, align: 4) { + __ __ __ __ │ ░░░░ +} + note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace error: aborting due to 1 previous error diff --git a/src/tools/miri/tests/fail/function_calls/return_pointer_on_unwind.stderr b/src/tools/miri/tests/fail/function_calls/return_pointer_on_unwind.stderr index 7747a75d1cf..93720ca7d27 100644 --- a/src/tools/miri/tests/fail/function_calls/return_pointer_on_unwind.stderr +++ b/src/tools/miri/tests/fail/function_calls/return_pointer_on_unwind.stderr @@ -3,7 +3,7 @@ thread 'main' panicked at tests/fail/function_calls/return_pointer_on_unwind.rs: explicit panic note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace note: in Miri, you may have to set `MIRIFLAGS=-Zmiri-env-forward=RUST_BACKTRACE` for the environment variable to have an effect -error: Undefined Behavior: using uninitialized data, but this operation requires initialized memory +error: Undefined Behavior: reading memory at ALLOC[0x0..0x4], but memory is uninitialized at [0x0..0x4], and this operation requires initialized memory --> tests/fail/function_calls/return_pointer_on_unwind.rs:LL:CC | LL | dbg!(x.0); @@ -15,6 +15,19 @@ LL | dbg!(x.0); = note: inside `main` at RUSTLIB/std/src/macros.rs:LL:CC = note: this error originates in the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info) +Uninitialized memory occurred at ALLOC[0x0..0x4], in this allocation: +ALLOC (stack variable, size: 132, align: 4) { + 0x00 │ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ │ ░░░░░░░░░░░░░░░░ + 0x10 │ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ │ ░░░░░░░░░░░░░░░░ + 0x20 │ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ │ ░░░░░░░░░░░░░░░░ + 0x30 │ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ │ ░░░░░░░░░░░░░░░░ + 0x40 │ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ │ ░░░░░░░░░░░░░░░░ + 0x50 │ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ │ ░░░░░░░░░░░░░░░░ + 0x60 │ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ │ ░░░░░░░░░░░░░░░░ + 0x70 │ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ __ │ ░░░░░░░░░░░░░░░░ + 0x80 │ __ __ __ __ │ ░░░░ +} + note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace error: aborting due to 1 previous error diff --git a/src/tools/miri/tests/fail/intrinsics/ptr_metadata_uninit_slice_data.rs b/src/tools/miri/tests/fail/intrinsics/ptr_metadata_uninit_slice_data.rs index 0c305eed6e1..c03e468cfba 100644 --- a/src/tools/miri/tests/fail/intrinsics/ptr_metadata_uninit_slice_data.rs +++ b/src/tools/miri/tests/fail/intrinsics/ptr_metadata_uninit_slice_data.rs @@ -1,4 +1,7 @@ //@compile-flags: -Zmiri-disable-validation +//@ normalize-stderr-test: "(\n)ALLOC \(.*\) \{\n(.*\n)*\}(\n)" -> "${1}ALLOC DUMP${3}" +//@ normalize-stderr-test: "\[0x[0-9a-z]..0x[0-9a-z]\]" -> "[0xX..0xY]" + #![feature(core_intrinsics, custom_mir)] use std::intrinsics::mir::*; @@ -9,7 +12,7 @@ use std::intrinsics::mir::*; pub unsafe fn deref_meta(p: *const *const [i32]) -> usize { mir! { { - RET = PtrMetadata(*p); //~ ERROR: Undefined Behavior: using uninitialized data + RET = PtrMetadata(*p); //~ ERROR: /Undefined Behavior: .* but memory is uninitialized/ Return() } } diff --git a/src/tools/miri/tests/fail/intrinsics/ptr_metadata_uninit_slice_data.stderr b/src/tools/miri/tests/fail/intrinsics/ptr_metadata_uninit_slice_data.stderr index 1c22876ba43..1e7f500edb2 100644 --- a/src/tools/miri/tests/fail/intrinsics/ptr_metadata_uninit_slice_data.stderr +++ b/src/tools/miri/tests/fail/intrinsics/ptr_metadata_uninit_slice_data.stderr @@ -1,4 +1,4 @@ -error: Undefined Behavior: using uninitialized data, but this operation requires initialized memory +error: Undefined Behavior: reading memory at ALLOC[0xX..0xY], but memory is uninitialized at [0xX..0xY], and this operation requires initialized memory --> tests/fail/intrinsics/ptr_metadata_uninit_slice_data.rs:LL:CC | LL | RET = PtrMetadata(*p); @@ -14,6 +14,9 @@ note: inside `main` LL | let _meta = deref_meta(p.as_ptr().cast()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Uninitialized memory occurred at ALLOC[0xX..0xY], in this allocation: +ALLOC DUMP + note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace error: aborting due to 1 previous error diff --git a/src/tools/miri/tests/fail/intrinsics/ptr_metadata_uninit_slice_len.rs b/src/tools/miri/tests/fail/intrinsics/ptr_metadata_uninit_slice_len.rs index a2ffdc92c4e..7053c0f6e18 100644 --- a/src/tools/miri/tests/fail/intrinsics/ptr_metadata_uninit_slice_len.rs +++ b/src/tools/miri/tests/fail/intrinsics/ptr_metadata_uninit_slice_len.rs @@ -1,4 +1,7 @@ //@compile-flags: -Zmiri-disable-validation +//@ normalize-stderr-test: "(\n)ALLOC \(.*\) \{\n(.*\n)*\}(\n)" -> "${1}ALLOC DUMP${3}" +//@ normalize-stderr-test: "\[0x[0-9a-z]+..0x[0-9a-z]+\]" -> "[0xX..0xY]" + #![feature(core_intrinsics, custom_mir)] use std::intrinsics::mir::*; @@ -9,7 +12,7 @@ use std::intrinsics::mir::*; pub unsafe fn deref_meta(p: *const *const [i32]) -> usize { mir! { { - RET = PtrMetadata(*p); //~ ERROR: Undefined Behavior: using uninitialized data + RET = PtrMetadata(*p); //~ ERROR: /Undefined Behavior: .* but memory is uninitialized/ Return() } } diff --git a/src/tools/miri/tests/fail/intrinsics/ptr_metadata_uninit_slice_len.stderr b/src/tools/miri/tests/fail/intrinsics/ptr_metadata_uninit_slice_len.stderr index 00e63b1275f..80b4c8bec0d 100644 --- a/src/tools/miri/tests/fail/intrinsics/ptr_metadata_uninit_slice_len.stderr +++ b/src/tools/miri/tests/fail/intrinsics/ptr_metadata_uninit_slice_len.stderr @@ -12,7 +12,7 @@ LL | (*p.as_mut_ptr().cast::<[*const i32; 2]>())[0] = 4 as *const i32; = note: BACKTRACE: = note: inside `main` at tests/fail/intrinsics/ptr_metadata_uninit_slice_len.rs:LL:CC -error: Undefined Behavior: using uninitialized data, but this operation requires initialized memory +error: Undefined Behavior: reading memory at ALLOC[0xX..0xY], but memory is uninitialized at [0xX..0xY], and this operation requires initialized memory --> tests/fail/intrinsics/ptr_metadata_uninit_slice_len.rs:LL:CC | LL | RET = PtrMetadata(*p); @@ -28,6 +28,9 @@ note: inside `main` LL | let _meta = deref_meta(p.as_ptr().cast()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Uninitialized memory occurred at ALLOC[0xX..0xY], in this allocation: +ALLOC DUMP + note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace error: aborting due to 1 previous error; 1 warning emitted diff --git a/src/tools/miri/tests/fail/intrinsics/ptr_metadata_uninit_thin.rs b/src/tools/miri/tests/fail/intrinsics/ptr_metadata_uninit_thin.rs index e5a51289a8a..3ba29847337 100644 --- a/src/tools/miri/tests/fail/intrinsics/ptr_metadata_uninit_thin.rs +++ b/src/tools/miri/tests/fail/intrinsics/ptr_metadata_uninit_thin.rs @@ -1,4 +1,7 @@ //@compile-flags: -Zmiri-disable-validation +//@ normalize-stderr-test: "(\n)ALLOC \(.*\) \{\n(.*\n)*\}(\n)" -> "${1}ALLOC DUMP${3}" +//@ normalize-stderr-test: "\[0x[0-9a-z]..0x[0-9a-z]\]" -> "[0xX..0xY]" + #![feature(core_intrinsics, custom_mir)] use std::intrinsics::mir::*; @@ -9,7 +12,7 @@ use std::intrinsics::mir::*; pub unsafe fn deref_meta(p: *const *const i32) -> () { mir! { { - RET = PtrMetadata(*p); //~ ERROR: Undefined Behavior: using uninitialized data + RET = PtrMetadata(*p); //~ ERROR: /Undefined Behavior: .*, but memory is uninitialized/ Return() } } diff --git a/src/tools/miri/tests/fail/intrinsics/ptr_metadata_uninit_thin.stderr b/src/tools/miri/tests/fail/intrinsics/ptr_metadata_uninit_thin.stderr index 24066953d79..7a1f3d6ea84 100644 --- a/src/tools/miri/tests/fail/intrinsics/ptr_metadata_uninit_thin.stderr +++ b/src/tools/miri/tests/fail/intrinsics/ptr_metadata_uninit_thin.stderr @@ -1,4 +1,4 @@ -error: Undefined Behavior: using uninitialized data, but this operation requires initialized memory +error: Undefined Behavior: reading memory at ALLOC[0xX..0xY], but memory is uninitialized at [0xX..0xY], and this operation requires initialized memory --> tests/fail/intrinsics/ptr_metadata_uninit_thin.rs:LL:CC | LL | RET = PtrMetadata(*p); @@ -14,6 +14,9 @@ note: inside `main` LL | let _meta = deref_meta(p.as_ptr()); | ^^^^^^^^^^^^^^^^^^^^^^ +Uninitialized memory occurred at ALLOC[0xX..0xY], in this allocation: +ALLOC DUMP + note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace error: aborting due to 1 previous error diff --git a/src/tools/miri/tests/fail/read_from_trivial_switch.rs b/src/tools/miri/tests/fail/read_from_trivial_switch.rs index d34b1cd5820..2696c42aeae 100644 --- a/src/tools/miri/tests/fail/read_from_trivial_switch.rs +++ b/src/tools/miri/tests/fail/read_from_trivial_switch.rs @@ -4,11 +4,14 @@ // // See <https://github.com/rust-lang/miri/issues/4237>. +//@ normalize-stderr-test: "(\n)ALLOC \(.*\) \{\n(.*\n)*\}(\n)" -> "${1}ALLOC DUMP${3}" +//@ normalize-stderr-test: "\[0x[0-9a-z]..0x[0-9a-z]\]" -> "[0xX..0xY]" + use std::mem::MaybeUninit; fn main() { let uninit: MaybeUninit<i32> = MaybeUninit::uninit(); let bad_ref: &i32 = unsafe { uninit.assume_init_ref() }; let &(0 | _) = bad_ref; - //~^ ERROR: Undefined Behavior: using uninitialized data, but this operation requires initialized memory + //~^ ERROR: /Undefined Behavior: .*, but memory is uninitialized .* requires initialized memory/ } diff --git a/src/tools/miri/tests/fail/read_from_trivial_switch.stderr b/src/tools/miri/tests/fail/read_from_trivial_switch.stderr index 923d836ee0c..1dcc341b7e6 100644 --- a/src/tools/miri/tests/fail/read_from_trivial_switch.stderr +++ b/src/tools/miri/tests/fail/read_from_trivial_switch.stderr @@ -1,4 +1,4 @@ -error: Undefined Behavior: using uninitialized data, but this operation requires initialized memory +error: Undefined Behavior: reading memory at ALLOC[0xX..0xY], but memory is uninitialized at [0xX..0xY], and this operation requires initialized memory --> tests/fail/read_from_trivial_switch.rs:LL:CC | LL | let &(0 | _) = bad_ref; @@ -9,6 +9,9 @@ LL | let &(0 | _) = bad_ref; = note: BACKTRACE: = note: inside `main` at tests/fail/read_from_trivial_switch.rs:LL:CC +Uninitialized memory occurred at ALLOC[0xX..0xY], in this allocation: +ALLOC DUMP + note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace error: aborting due to 1 previous error diff --git a/src/tools/miri/tests/fail/uninit/padding-enum.rs b/src/tools/miri/tests/fail/uninit/padding-enum.rs index e1a16bea23c..606fa21016f 100644 --- a/src/tools/miri/tests/fail/uninit/padding-enum.rs +++ b/src/tools/miri/tests/fail/uninit/padding-enum.rs @@ -1,3 +1,6 @@ +//@ normalize-stderr-test: "(\n)ALLOC \(.*\) \{\n(.*\n)*\}(\n)" -> "${1}ALLOC DUMP${3}" +//@ normalize-stderr-test: "\[0x[0-9a-z]..0x[0-9a-z]\]" -> "[0xX..0xY]" + use std::mem; // We have three fields to avoid the ScalarPair optimization. diff --git a/src/tools/miri/tests/fail/uninit/padding-enum.stderr b/src/tools/miri/tests/fail/uninit/padding-enum.stderr index a9a5568f4e8..64229ac8817 100644 --- a/src/tools/miri/tests/fail/uninit/padding-enum.stderr +++ b/src/tools/miri/tests/fail/uninit/padding-enum.stderr @@ -1,4 +1,4 @@ -error: Undefined Behavior: using uninitialized data, but this operation requires initialized memory +error: Undefined Behavior: reading memory at ALLOC[0xX..0xY], but memory is uninitialized at [0xX..0xY], and this operation requires initialized memory --> tests/fail/uninit/padding-enum.rs:LL:CC | LL | let _val = *c.add(padding_offset); @@ -9,6 +9,9 @@ LL | let _val = *c.add(padding_offset); = note: BACKTRACE: = note: inside `main` at tests/fail/uninit/padding-enum.rs:LL:CC +Uninitialized memory occurred at ALLOC[0xX..0xY], in this allocation: +ALLOC DUMP + note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace error: aborting due to 1 previous error diff --git a/src/tools/miri/tests/fail/uninit/padding-pair.rs b/src/tools/miri/tests/fail/uninit/padding-pair.rs index c8c00b3c65a..70ae48ff77d 100644 --- a/src/tools/miri/tests/fail/uninit/padding-pair.rs +++ b/src/tools/miri/tests/fail/uninit/padding-pair.rs @@ -1,3 +1,6 @@ +//@ normalize-stderr-test: "(\n)ALLOC \(.*\) \{\n(.*\n)*\}(\n)" -> "${1}ALLOC DUMP${3}" +//@ normalize-stderr-test: "\[0x[0-9a-z]..0x[0-9a-z]\]" -> "[0xX..0xY]" + #![feature(core_intrinsics)] use std::mem::{self, MaybeUninit}; diff --git a/src/tools/miri/tests/fail/uninit/padding-pair.stderr b/src/tools/miri/tests/fail/uninit/padding-pair.stderr index d281a351d41..2e7a577f204 100644 --- a/src/tools/miri/tests/fail/uninit/padding-pair.stderr +++ b/src/tools/miri/tests/fail/uninit/padding-pair.stderr @@ -1,4 +1,4 @@ -error: Undefined Behavior: using uninitialized data, but this operation requires initialized memory +error: Undefined Behavior: reading memory at ALLOC[0xX..0xY], but memory is uninitialized at [0xX..0xY], and this operation requires initialized memory --> tests/fail/uninit/padding-pair.rs:LL:CC | LL | let v = unsafe { *z.offset(first_undef) }; @@ -9,6 +9,9 @@ LL | let v = unsafe { *z.offset(first_undef) }; = note: BACKTRACE: = note: inside `main` at tests/fail/uninit/padding-pair.rs:LL:CC +Uninitialized memory occurred at ALLOC[0xX..0xY], in this allocation: +ALLOC DUMP + note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace error: aborting due to 1 previous error diff --git a/src/tools/miri/tests/fail/uninit/padding-struct.stderr b/src/tools/miri/tests/fail/uninit/padding-struct.stderr index 3298f6a4510..05d754625d3 100644 --- a/src/tools/miri/tests/fail/uninit/padding-struct.stderr +++ b/src/tools/miri/tests/fail/uninit/padding-struct.stderr @@ -1,4 +1,4 @@ -error: Undefined Behavior: using uninitialized data, but this operation requires initialized memory +error: Undefined Behavior: reading memory at ALLOC[0x1..0x2], but memory is uninitialized at [0x1..0x2], and this operation requires initialized memory --> tests/fail/uninit/padding-struct.rs:LL:CC | LL | let _val = *c.add(1); @@ -9,6 +9,11 @@ LL | let _val = *c.add(1); = note: BACKTRACE: = note: inside `main` at tests/fail/uninit/padding-struct.rs:LL:CC +Uninitialized memory occurred at ALLOC[0x1..0x2], in this allocation: +ALLOC (stack variable, size: 4, align: 2) { + 00 __ 00 00 │ .░.. +} + note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace error: aborting due to 1 previous error diff --git a/src/tools/miri/tests/fail/uninit/padding-wide-ptr.rs b/src/tools/miri/tests/fail/uninit/padding-wide-ptr.rs index 4e363dbf81e..549785e0223 100644 --- a/src/tools/miri/tests/fail/uninit/padding-wide-ptr.rs +++ b/src/tools/miri/tests/fail/uninit/padding-wide-ptr.rs @@ -1,3 +1,6 @@ +//@ normalize-stderr-test: "(\n)ALLOC \(.*\) \{\n(.*\n)*\}(\n)" -> "${1}ALLOC DUMP${3}" +//@ normalize-stderr-test: "\[0x[0-9a-z]..0x[0-9a-z]\]" -> "[0xX..0xY]" + use std::mem; // If this is `None`, the metadata becomes padding. diff --git a/src/tools/miri/tests/fail/uninit/padding-wide-ptr.stderr b/src/tools/miri/tests/fail/uninit/padding-wide-ptr.stderr index d92d05ae631..ce11320ca1b 100644 --- a/src/tools/miri/tests/fail/uninit/padding-wide-ptr.stderr +++ b/src/tools/miri/tests/fail/uninit/padding-wide-ptr.stderr @@ -1,4 +1,4 @@ -error: Undefined Behavior: using uninitialized data, but this operation requires initialized memory +error: Undefined Behavior: reading memory at ALLOC[0xX..0xY], but memory is uninitialized at [0xX..0xY], and this operation requires initialized memory --> tests/fail/uninit/padding-wide-ptr.rs:LL:CC | LL | let _val = *c.add(mem::size_of::<*const u8>()); @@ -9,6 +9,9 @@ LL | let _val = *c.add(mem::size_of::<*const u8>()); = note: BACKTRACE: = note: inside `main` at tests/fail/uninit/padding-wide-ptr.rs:LL:CC +Uninitialized memory occurred at ALLOC[0xX..0xY], in this allocation: +ALLOC DUMP + note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace error: aborting due to 1 previous error diff --git a/src/tools/miri/tests/fail/uninit/transmute-pair-uninit.rs b/src/tools/miri/tests/fail/uninit/transmute-pair-uninit.rs index 0ba5520a544..c1d284c7057 100644 --- a/src/tools/miri/tests/fail/uninit/transmute-pair-uninit.rs +++ b/src/tools/miri/tests/fail/uninit/transmute-pair-uninit.rs @@ -1,3 +1,6 @@ +//@ normalize-stderr-test: "(\n)ALLOC \(.*\) \{\n(.*\n)*\}(\n)" -> "${1}ALLOC DUMP${3}" +//@ normalize-stderr-test: "\[0x[0-9a-z]..0x[0-9a-z]\]" -> "[0xX..0xY]" + #![feature(core_intrinsics)] use std::mem::{self, MaybeUninit}; diff --git a/src/tools/miri/tests/fail/uninit/transmute-pair-uninit.stderr b/src/tools/miri/tests/fail/uninit/transmute-pair-uninit.stderr index 0ae0ce5de9c..eb049dd41ec 100644 --- a/src/tools/miri/tests/fail/uninit/transmute-pair-uninit.stderr +++ b/src/tools/miri/tests/fail/uninit/transmute-pair-uninit.stderr @@ -1,4 +1,4 @@ -error: Undefined Behavior: using uninitialized data, but this operation requires initialized memory +error: Undefined Behavior: reading memory at ALLOC[0xX..0xY], but memory is uninitialized at [0xX..0xY], and this operation requires initialized memory --> tests/fail/uninit/transmute-pair-uninit.rs:LL:CC | LL | let v = unsafe { *z.offset(first_undef) }; @@ -9,6 +9,9 @@ LL | let v = unsafe { *z.offset(first_undef) }; = note: BACKTRACE: = note: inside `main` at tests/fail/uninit/transmute-pair-uninit.rs:LL:CC +Uninitialized memory occurred at ALLOC[0xX..0xY], in this allocation: +ALLOC DUMP + note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace error: aborting due to 1 previous error diff --git a/src/tools/miri/tests/fail/uninit/uninit_byte_read.stderr b/src/tools/miri/tests/fail/uninit/uninit_byte_read.stderr index d2a5a2d3831..5a5aa12987c 100644 --- a/src/tools/miri/tests/fail/uninit/uninit_byte_read.stderr +++ b/src/tools/miri/tests/fail/uninit/uninit_byte_read.stderr @@ -1,4 +1,4 @@ -error: Undefined Behavior: using uninitialized data, but this operation requires initialized memory +error: Undefined Behavior: reading memory at ALLOC[0x5..0x6], but memory is uninitialized at [0x5..0x6], and this operation requires initialized memory --> tests/fail/uninit/uninit_byte_read.rs:LL:CC | LL | let undef = unsafe { *v.as_ptr().add(5) }; @@ -9,6 +9,11 @@ LL | let undef = unsafe { *v.as_ptr().add(5) }; = note: BACKTRACE: = note: inside `main` at tests/fail/uninit/uninit_byte_read.rs:LL:CC +Uninitialized memory occurred at ALLOC[0x5..0x6], in this allocation: +ALLOC (Rust heap, size: 10, align: 1) { + __ __ __ __ __ __ __ __ __ __ │ ░░░░░░░░░░ +} + note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace error: aborting due to 1 previous error diff --git a/src/tools/miri/tests/fail/validity/invalid_int_op.stderr b/src/tools/miri/tests/fail/validity/invalid_int_op.stderr index 6e24cadfc20..0b1915621b2 100644 --- a/src/tools/miri/tests/fail/validity/invalid_int_op.stderr +++ b/src/tools/miri/tests/fail/validity/invalid_int_op.stderr @@ -1,4 +1,4 @@ -error: Undefined Behavior: using uninitialized data, but this operation requires initialized memory +error: Undefined Behavior: reading memory at ALLOC[0x0..0x4], but memory is uninitialized at [0x0..0x4], and this operation requires initialized memory --> tests/fail/validity/invalid_int_op.rs:LL:CC | LL | let i = unsafe { std::mem::MaybeUninit::<i32>::uninit().assume_init() }; @@ -9,6 +9,11 @@ LL | let i = unsafe { std::mem::MaybeUninit::<i32>::uninit().assume_init() } = note: BACKTRACE: = note: inside `main` at tests/fail/validity/invalid_int_op.rs:LL:CC +Uninitialized memory occurred at ALLOC[0x0..0x4], in this allocation: +ALLOC (stack variable, size: 4, align: 4) { + __ __ __ __ │ ░░░░ +} + note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace error: aborting due to 1 previous error diff --git a/src/tools/miri/tests/native-lib/fail/tracing/partial_init.rs b/src/tools/miri/tests/native-lib/fail/tracing/partial_init.rs index e267f82e215..7ab160773ff 100644 --- a/src/tools/miri/tests/native-lib/fail/tracing/partial_init.rs +++ b/src/tools/miri/tests/native-lib/fail/tracing/partial_init.rs @@ -20,6 +20,6 @@ fn partial_init() { assert!(*slice_ptr == 0); assert!(*slice_ptr.offset(1) == 0); // Reading the third is UB! - let _val = *slice_ptr.offset(2); //~ ERROR: Undefined Behavior: using uninitialized data + let _val = *slice_ptr.offset(2); //~ ERROR: /Undefined Behavior: reading memory.*, but memory is uninitialized/ } } diff --git a/src/tools/miri/tests/native-lib/fail/tracing/partial_init.stderr b/src/tools/miri/tests/native-lib/fail/tracing/partial_init.stderr index 84fd913b5e5..74a599ede5c 100644 --- a/src/tools/miri/tests/native-lib/fail/tracing/partial_init.stderr +++ b/src/tools/miri/tests/native-lib/fail/tracing/partial_init.stderr @@ -17,7 +17,7 @@ note: inside `main` LL | partial_init(); | ^^^^^^^^^^^^^^ -error: Undefined Behavior: using uninitialized data, but this operation requires initialized memory +error: Undefined Behavior: reading memory at ALLOC[0x2..0x3], but memory is uninitialized at [0x2..0x3], and this operation requires initialized memory --> tests/native-lib/fail/tracing/partial_init.rs:LL:CC | LL | let _val = *slice_ptr.offset(2); @@ -33,6 +33,11 @@ note: inside `main` LL | partial_init(); | ^^^^^^^^^^^^^^ +Uninitialized memory occurred at ALLOC[0x2..0x3], in this allocation: +ALLOC (stack variable, size: 3, align: 1) { + ╾00[wildcard] (1 ptr byte)╼ ╾00[wildcard] (1 ptr byte)╼ __ │ ━━░ +} + note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace error: aborting due to 1 previous error; 1 warning emitted diff --git a/src/tools/miri/tests/panic/mir-validation.stderr b/src/tools/miri/tests/panic/mir-validation.stderr index dc70d129da3..f801ac907e6 100644 --- a/src/tools/miri/tests/panic/mir-validation.stderr +++ b/src/tools/miri/tests/panic/mir-validation.stderr @@ -1,11 +1,15 @@ +error: internal compiler error: compiler/rustc_mir_transform/src/validate.rs:LL:CC: broken MIR in Item(DefId) (after phase change to runtime-optimized) at bb0[1]: + place (*(_2.0: *mut i32)) has deref as a later projection (it is only permitted as the first projection) + --> tests/panic/mir-validation.rs:LL:CC + | +LL | *(tuple.0) = 1; + | ^^^^^^^^^^^^^^ + thread 'rustc' panicked at compiler/rustc_mir_transform/src/validate.rs:LL:CC: -broken MIR in Item(DefId) (after phase change to runtime-optimized) at bb0[1]: -place (*(_2.0: *mut i32)) has deref as a later projection (it is only permitted as the first projection) +Box<dyn Any> stack backtrace: -error: the compiler unexpectedly panicked. this is a bug. - @@ -20,3 +24,5 @@ LL | extern "rust-call" fn call_once(self, args: Args) -> Self::Output; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | +error: aborting due to 1 previous error + diff --git a/src/tools/miri/tests/pass-dep/libc/libc-time.rs b/src/tools/miri/tests/pass-dep/libc/libc-time.rs index e8957846ad5..9e9fadfca9e 100644 --- a/src/tools/miri/tests/pass-dep/libc/libc-time.rs +++ b/src/tools/miri/tests/pass-dep/libc/libc-time.rs @@ -336,7 +336,7 @@ fn test_nanosleep() { let remainder = ptr::null_mut::<libc::timespec>(); let is_error = unsafe { libc::nanosleep(&duration_zero, remainder) }; assert_eq!(is_error, 0); - assert!(start_test_sleep.elapsed() < Duration::from_millis(10)); + assert!(start_test_sleep.elapsed() < Duration::from_millis(100)); let start_test_sleep = Instant::now(); let duration_100_millis = libc::timespec { tv_sec: 0, tv_nsec: 1_000_000_000 / 10 }; @@ -390,7 +390,7 @@ mod test_clock_nanosleep { ) }; assert_eq!(error, 0); - assert!(start_test_sleep.elapsed() < Duration::from_millis(10)); + assert!(start_test_sleep.elapsed() < Duration::from_millis(100)); let start_test_sleep = Instant::now(); let hunderd_millis_after_start = add_100_millis(timespec_now(libc::CLOCK_MONOTONIC)); @@ -417,7 +417,7 @@ mod test_clock_nanosleep { libc::clock_nanosleep(libc::CLOCK_MONOTONIC, NO_FLAGS, &duration_zero, remainder) }; assert_eq!(error, 0); - assert!(start_test_sleep.elapsed() < Duration::from_millis(10)); + assert!(start_test_sleep.elapsed() < Duration::from_millis(100)); let start_test_sleep = Instant::now(); let duration_100_millis = libc::timespec { tv_sec: 0, tv_nsec: 1_000_000_000 / 10 }; diff --git a/src/tools/miri/tests/pass/intrinsics/portable-simd.rs b/src/tools/miri/tests/pass/intrinsics/portable-simd.rs index 726d4c01cc3..e2cd08733af 100644 --- a/src/tools/miri/tests/pass/intrinsics/portable-simd.rs +++ b/src/tools/miri/tests/pass/intrinsics/portable-simd.rs @@ -349,12 +349,15 @@ fn simd_mask() { // Non-power-of-2 multi-byte mask. #[repr(simd, packed)] #[allow(non_camel_case_types)] - #[derive(Copy, Clone, Debug, PartialEq)] + #[derive(Copy, Clone)] struct i32x10([i32; 10]); impl i32x10 { fn splat(x: i32) -> Self { Self([x; 10]) } + fn into_array(self) -> [i32; 10] { + unsafe { std::mem::transmute(self) } + } } unsafe { let mask = i32x10([!0, !0, 0, !0, 0, 0, !0, 0, !0, 0]); @@ -377,19 +380,22 @@ fn simd_mask() { i32x10::splat(!0), // yes i32x10::splat(0), // no ); - assert_eq!(selected1, mask); - assert_eq!(selected2, mask); + assert_eq!(selected1.into_array(), mask.into_array()); + assert_eq!(selected2.into_array(), mask.into_array()); } // Test for a mask where the next multiple of 8 is not a power of two. #[repr(simd, packed)] #[allow(non_camel_case_types)] - #[derive(Copy, Clone, Debug, PartialEq)] + #[derive(Copy, Clone)] struct i32x20([i32; 20]); impl i32x20 { fn splat(x: i32) -> Self { Self([x; 20]) } + fn into_array(self) -> [i32; 20] { + unsafe { std::mem::transmute(self) } + } } unsafe { let mask = i32x20([!0, !0, 0, !0, 0, 0, !0, 0, !0, 0, 0, 0, 0, !0, !0, !0, !0, !0, !0, !0]); @@ -419,8 +425,8 @@ fn simd_mask() { i32x20::splat(!0), // yes i32x20::splat(0), // no ); - assert_eq!(selected1, mask); - assert_eq!(selected2, mask); + assert_eq!(selected1.into_array(), mask.into_array()); + assert_eq!(selected2.into_array(), mask.into_array()); } } @@ -708,12 +714,12 @@ fn simd_ops_non_pow2() { let x = SimdPacked([1u32; 3]); let y = SimdPacked([2u32; 3]); let z = unsafe { intrinsics::simd_add(x, y) }; - assert_eq!({ z.0 }, [3u32; 3]); + assert_eq!(unsafe { *(&raw const z).cast::<[u32; 3]>() }, [3u32; 3]); let x = SimdPadded([1u32; 3]); let y = SimdPadded([2u32; 3]); let z = unsafe { intrinsics::simd_add(x, y) }; - assert_eq!(z.0, [3u32; 3]); + assert_eq!(unsafe { *(&raw const z).cast::<[u32; 3]>() }, [3u32; 3]); } fn main() { diff --git a/src/tools/miri/tests/pass/intrinsics/type-id.rs b/src/tools/miri/tests/pass/intrinsics/type-id.rs new file mode 100644 index 00000000000..123fdbdc9ce --- /dev/null +++ b/src/tools/miri/tests/pass/intrinsics/type-id.rs @@ -0,0 +1,19 @@ +use std::any::{Any, TypeId}; + +fn main() { + let t1 = TypeId::of::<u64>(); + let t2 = TypeId::of::<u64>(); + assert_eq!(t1, t2); + let t3 = TypeId::of::<usize>(); + assert_ne!(t1, t3); + + let _ = format!("{t1:?}"); // test that we can debug-print + + let b = Box::new(0u64) as Box<dyn Any>; + assert_eq!(*b.downcast_ref::<u64>().unwrap(), 0); + assert!(b.downcast_ref::<usize>().is_none()); + + // Get the first pointer chunk and try to make it a ZST ref. + // This used to trigger an error because TypeId allocs got misclassified as "LiveData". + let _raw_chunk = unsafe { (&raw const t1).cast::<&()>().read() }; +} diff --git a/src/tools/miri/tests/ui.rs b/src/tools/miri/tests/ui.rs index 43f855d57dd..cb915b11b67 100644 --- a/src/tools/miri/tests/ui.rs +++ b/src/tools/miri/tests/ui.rs @@ -13,7 +13,8 @@ use ui_test::custom_flags::edition::Edition; use ui_test::dependencies::DependencyBuilder; use ui_test::per_test_config::TestConfig; use ui_test::spanned::Spanned; -use ui_test::{CommandBuilder, Config, Format, Match, ignore_output_conflict, status_emitter}; +use ui_test::status_emitter::StatusEmitter; +use ui_test::{CommandBuilder, Config, Match, ignore_output_conflict}; #[derive(Copy, Clone, Debug)] enum Mode { @@ -141,7 +142,7 @@ fn miri_config( envs: vec![("RUSTFLAGS".into(), None)], ..CommandBuilder::cargo() }, - crate_manifest_path: Path::new("test_dependencies").join("Cargo.toml"), + crate_manifest_path: Path::new("tests/deps").join("Cargo.toml"), build_std: None, bless_lockfile: bless, }, @@ -216,10 +217,7 @@ fn run_tests( // This could be used to overwrite the `Config` on a per-test basis. |_, _| {}, // No GHA output as that would also show in the main rustc repo. - match args.format { - Format::Terse => status_emitter::Text::quiet(), - Format::Pretty => status_emitter::Text::verbose(), - }, + Box::<dyn StatusEmitter>::from(args.format), ) } @@ -335,7 +333,7 @@ fn main() -> Result<()> { ui(Mode::Panic, "tests/panic", &target, WithDependencies, tmpdir.path())?; ui(Mode::Fail, "tests/fail", &target, WithoutDependencies, tmpdir.path())?; ui(Mode::Fail, "tests/fail-dep", &target, WithDependencies, tmpdir.path())?; - if cfg!(unix) && target == host { + if cfg!(all(unix, feature = "native-lib")) && target == host { ui(Mode::Pass, "tests/native-lib/pass", &target, WithoutDependencies, tmpdir.path())?; ui(Mode::Fail, "tests/native-lib/fail", &target, WithoutDependencies, tmpdir.path())?; } diff --git a/src/tools/miri/triagebot.toml b/src/tools/miri/triagebot.toml index 60e80c3f673..a0ce9f80024 100644 --- a/src/tools/miri/triagebot.toml +++ b/src/tools/miri/triagebot.toml @@ -16,7 +16,13 @@ allow-unauthenticated = [ # Enables assigning users to issues and PRs. [assign] warn_non_default_branch = true -contributing_url = "https://github.com/rust-lang/miri/blob/master/CONTRIBUTING.md" +contributing_url = "https://github.com/rust-lang/miri/blob/master/CONTRIBUTING.md#pr-review-process" +[assign.custom_welcome_messages] +welcome-message = "(unused)" +welcome-message-no-reviewer = """ +Thank you for contributing to Miri! +Please remember to not force-push to the PR branch except when you need to rebase due to a conflict or when the reviewer asks you for it. +""" [no-merges] exclude_titles = ["Rustup"] @@ -38,6 +44,12 @@ remove = [] add = ["S-waiting-on-author"] unless = ["S-blocked", "S-waiting-on-team", "S-waiting-on-review"] +[autolabel."S-waiting-on-review"] +new_pr = true + +[autolabel."S-waiting-on-author"] +new_draft = true + # Automatically close and reopen PRs made by bots to run CI on them [bot-pull-requests] diff --git a/src/tools/opt-dist/src/environment.rs b/src/tools/opt-dist/src/environment.rs index 946e926a3c0..e6e4c711c0c 100644 --- a/src/tools/opt-dist/src/environment.rs +++ b/src/tools/opt-dist/src/environment.rs @@ -27,6 +27,7 @@ pub struct Environment { shared_llvm: bool, run_tests: bool, fast_try_build: bool, + build_llvm: bool, } impl Environment { @@ -47,7 +48,7 @@ impl Environment { } pub fn build_artifacts(&self) -> Utf8PathBuf { - self.build_root().join("build").join(&self.host_tuple) + self.build_root().join(&self.host_tuple) } pub fn artifact_dir(&self) -> Utf8PathBuf { @@ -111,6 +112,10 @@ impl Environment { pub fn is_fast_try_build(&self) -> bool { self.fast_try_build } + + pub fn build_llvm(&self) -> bool { + self.build_llvm + } } /// What is the extension of binary executables on this platform? diff --git a/src/tools/opt-dist/src/exec.rs b/src/tools/opt-dist/src/exec.rs index 0dc6e56b9d5..a8d4c93d160 100644 --- a/src/tools/opt-dist/src/exec.rs +++ b/src/tools/opt-dist/src/exec.rs @@ -99,7 +99,7 @@ pub struct Bootstrap { impl Bootstrap { pub fn build(env: &Environment) -> Self { - let metrics_path = env.build_root().join("build").join("metrics.json"); + let metrics_path = env.build_root().join("metrics.json"); let cmd = cmd(&[ env.python_binary(), env.checkout_path().join("x.py").as_str(), @@ -119,7 +119,7 @@ impl Bootstrap { } pub fn dist(env: &Environment, dist_args: &[String]) -> Self { - let metrics_path = env.build_root().join("build").join("metrics.json"); + let metrics_path = env.build_root().join("metrics.json"); let args = dist_args.iter().map(|arg| arg.as_str()).collect::<Vec<_>>(); let cmd = cmd(&args).env("RUST_BACKTRACE", "full"); let mut cmd = add_shared_x_flags(env, cmd); @@ -139,8 +139,10 @@ impl Bootstrap { self } - pub fn llvm_pgo_optimize(mut self, profile: &LlvmPGOProfile) -> Self { - self.cmd = self.cmd.arg("--llvm-profile-use").arg(profile.0.as_str()); + pub fn llvm_pgo_optimize(mut self, profile: Option<&LlvmPGOProfile>) -> Self { + if let Some(prof) = profile { + self.cmd = self.cmd.arg("--llvm-profile-use").arg(prof.0.as_str()); + } self } @@ -174,8 +176,10 @@ impl Bootstrap { self } - pub fn with_bolt_profile(mut self, profile: BoltProfile) -> Self { - self.cmd = self.cmd.arg("--reproducible-artifact").arg(profile.0.as_str()); + pub fn with_bolt_profile(mut self, profile: Option<BoltProfile>) -> Self { + if let Some(prof) = profile { + self.cmd = self.cmd.arg("--reproducible-artifact").arg(prof.0.as_str()); + } self } diff --git a/src/tools/opt-dist/src/main.rs b/src/tools/opt-dist/src/main.rs index 9c8a6637a3b..d0e6badede6 100644 --- a/src/tools/opt-dist/src/main.rs +++ b/src/tools/opt-dist/src/main.rs @@ -98,6 +98,15 @@ enum EnvironmentCmd { /// Perform tests after final build if it's not a fast try build #[arg(long)] run_tests: bool, + + /// Will be LLVM built during the run? + #[arg(long, default_value_t = true, action(clap::ArgAction::Set))] + build_llvm: bool, + + /// Set build artifacts dir. Relative to `checkout_dir`, should point to the directory set + /// in bootstrap.toml via `build.build-dir` option + #[arg(long, default_value = "build")] + build_dir: Utf8PathBuf, }, /// Perform an optimized build on Linux CI, from inside Docker. LinuxCi { @@ -133,6 +142,8 @@ fn create_environment(args: Args) -> anyhow::Result<(Environment, Vec<String>)> benchmark_cargo_config, shared, run_tests, + build_llvm, + build_dir, } => { let env = EnvironmentBuilder::default() .host_tuple(target_triple) @@ -140,7 +151,7 @@ fn create_environment(args: Args) -> anyhow::Result<(Environment, Vec<String>)> .checkout_dir(checkout_dir.clone()) .host_llvm_dir(llvm_dir) .artifact_dir(artifact_dir) - .build_dir(checkout_dir) + .build_dir(checkout_dir.join(build_dir)) .prebuilt_rustc_perf(rustc_perf_checkout_dir) .shared_llvm(llvm_shared) .use_bolt(use_bolt) @@ -148,6 +159,7 @@ fn create_environment(args: Args) -> anyhow::Result<(Environment, Vec<String>)> .benchmark_cargo_config(benchmark_cargo_config) .run_tests(run_tests) .fast_try_build(is_fast_try_build) + .build_llvm(build_llvm) .build()?; (env, shared.build_args) @@ -165,13 +177,14 @@ fn create_environment(args: Args) -> anyhow::Result<(Environment, Vec<String>)> .checkout_dir(checkout_dir.clone()) .host_llvm_dir(Utf8PathBuf::from("/rustroot")) .artifact_dir(Utf8PathBuf::from("/tmp/tmp-multistage/opt-artifacts")) - .build_dir(checkout_dir.join("obj")) + .build_dir(checkout_dir.join("obj").join("build")) .shared_llvm(true) // FIXME: Enable bolt for aarch64 once it's fixed upstream. Broken as of December 2024. .use_bolt(!is_aarch64) .skipped_tests(vec![]) .run_tests(true) .fast_try_build(is_fast_try_build) + .build_llvm(true) .build()?; (env, shared.build_args) @@ -187,12 +200,13 @@ fn create_environment(args: Args) -> anyhow::Result<(Environment, Vec<String>)> .checkout_dir(checkout_dir.clone()) .host_llvm_dir(checkout_dir.join("citools").join("clang-rust")) .artifact_dir(checkout_dir.join("opt-artifacts")) - .build_dir(checkout_dir) + .build_dir(checkout_dir.join("build")) .shared_llvm(false) .use_bolt(false) .skipped_tests(vec![]) .run_tests(true) .fast_try_build(is_fast_try_build) + .build_llvm(true) .build()?; (env, shared.build_args) @@ -255,30 +269,35 @@ fn execute_pipeline( // Stage 2: Gather LLVM PGO profiles // Here we build a PGO instrumented LLVM, reusing the previously PGO optimized rustc. // Then we use the instrumented LLVM to gather LLVM PGO profiles. - let llvm_pgo_profile = timer.section("Stage 2 (LLVM PGO)", |stage| { - // Remove the previous, uninstrumented build of LLVM. - clear_llvm_files(env)?; + let llvm_pgo_profile = if env.build_llvm() { + timer.section("Stage 2 (LLVM PGO)", |stage| { + // Remove the previous, uninstrumented build of LLVM. + clear_llvm_files(env)?; - let llvm_profile_dir_root = env.artifact_dir().join("llvm-pgo"); + let llvm_profile_dir_root = env.artifact_dir().join("llvm-pgo"); - stage.section("Build PGO instrumented LLVM", |section| { - Bootstrap::build(env) - .llvm_pgo_instrument(&llvm_profile_dir_root) - .avoid_rustc_rebuild() - .run(section) - })?; + stage.section("Build PGO instrumented LLVM", |section| { + Bootstrap::build(env) + .llvm_pgo_instrument(&llvm_profile_dir_root) + .avoid_rustc_rebuild() + .run(section) + })?; - let profile = stage - .section("Gather profiles", |_| gather_llvm_profiles(env, &llvm_profile_dir_root))?; + let profile = stage.section("Gather profiles", |_| { + gather_llvm_profiles(env, &llvm_profile_dir_root) + })?; - print_free_disk_space()?; + print_free_disk_space()?; - // Proactively delete the instrumented artifacts, to avoid using them by accident in - // follow-up stages. - clear_llvm_files(env)?; + // Proactively delete the instrumented artifacts, to avoid using them by accident in + // follow-up stages. + clear_llvm_files(env)?; - Ok(profile) - })?; + Ok(Some(profile)) + })? + } else { + None + }; let bolt_profiles = if env.use_bolt() { // Stage 3: Build BOLT instrumented LLVM @@ -286,37 +305,43 @@ fn execute_pipeline( // Note that we don't remove LLVM artifacts after this step, so that they are reused in the final dist build. // BOLT instrumentation is performed "on-the-fly" when the LLVM library is copied to the sysroot of rustc, // therefore the LLVM artifacts on disk are not "tainted" with BOLT instrumentation and they can be reused. + let libdir = env.build_artifacts().join("stage2").join("lib"); timer.section("Stage 3 (BOLT)", |stage| { - stage.section("Build PGO optimized LLVM", |stage| { - Bootstrap::build(env) - .with_llvm_bolt_ldflags() - .llvm_pgo_optimize(&llvm_pgo_profile) - .avoid_rustc_rebuild() - .run(stage) - })?; - - let libdir = env.build_artifacts().join("stage2").join("lib"); - // The actual name will be something like libLLVM.so.18.1-rust-dev. - let llvm_lib = io::find_file_in_dir(&libdir, "libLLVM.so", "")?; - - log::info!("Optimizing {llvm_lib} with BOLT"); - - // FIXME(kobzol): try gather profiles together, at once for LLVM and rustc - // Instrument the libraries and gather profiles - let llvm_profile = with_bolt_instrumented(&llvm_lib, |llvm_profile_dir| { - stage.section("Gather profiles", |_| { - gather_bolt_profiles(env, "LLVM", llvm_benchmarks(env), llvm_profile_dir) - }) - })?; - print_free_disk_space()?; - - // Now optimize the library with BOLT. The `libLLVM-XXX.so` library is actually hard-linked - // from several places, and this specific path (`llvm_lib`) will *not* be packaged into - // the final dist build. However, when BOLT optimizes an artifact, it does so *in-place*, - // therefore it will actually optimize all the hard links, which means that the final - // packaged `libLLVM.so` file *will* be BOLT optimized. - bolt_optimize(&llvm_lib, &llvm_profile, env) - .context("Could not optimize LLVM with BOLT")?; + let llvm_profile = if env.build_llvm() { + stage.section("Build PGO optimized LLVM", |stage| { + Bootstrap::build(env) + .with_llvm_bolt_ldflags() + .llvm_pgo_optimize(llvm_pgo_profile.as_ref()) + .avoid_rustc_rebuild() + .run(stage) + })?; + + // The actual name will be something like libLLVM.so.18.1-rust-dev. + let llvm_lib = io::find_file_in_dir(&libdir, "libLLVM.so", "")?; + + log::info!("Optimizing {llvm_lib} with BOLT"); + + // FIXME(kobzol): try gather profiles together, at once for LLVM and rustc + // Instrument the libraries and gather profiles + let llvm_profile = with_bolt_instrumented(&llvm_lib, |llvm_profile_dir| { + stage.section("Gather profiles", |_| { + gather_bolt_profiles(env, "LLVM", llvm_benchmarks(env), llvm_profile_dir) + }) + })?; + print_free_disk_space()?; + + // Now optimize the library with BOLT. The `libLLVM-XXX.so` library is actually hard-linked + // from several places, and this specific path (`llvm_lib`) will *not* be packaged into + // the final dist build. However, when BOLT optimizes an artifact, it does so *in-place*, + // therefore it will actually optimize all the hard links, which means that the final + // packaged `libLLVM.so` file *will* be BOLT optimized. + bolt_optimize(&llvm_lib, &llvm_profile, env) + .context("Could not optimize LLVM with BOLT")?; + + Some(llvm_profile) + } else { + None + }; let rustc_lib = io::find_file_in_dir(&libdir, "librustc_driver", ".so")?; @@ -334,15 +359,16 @@ fn execute_pipeline( bolt_optimize(&rustc_lib, &rustc_profile, env) .context("Could not optimize rustc with BOLT")?; - // LLVM is not being cleared here, we want to use the BOLT-optimized LLVM - Ok(vec![llvm_profile, rustc_profile]) + // LLVM is not being cleared here. Either we built it and we want to use the BOLT-optimized LLVM, or we + // didn't build it, so we don't want to remove it. + Ok(vec![llvm_profile, Some(rustc_profile)]) })? } else { vec![] }; let mut dist = Bootstrap::dist(env, &dist_args) - .llvm_pgo_optimize(&llvm_pgo_profile) + .llvm_pgo_optimize(llvm_pgo_profile.as_ref()) .rustc_pgo_optimize(&rustc_pgo_profile) .avoid_rustc_rebuild(); diff --git a/src/tools/opt-dist/src/tests.rs b/src/tools/opt-dist/src/tests.rs index 2d2aab86eda..c3c45d262dd 100644 --- a/src/tools/opt-dist/src/tests.rs +++ b/src/tools/opt-dist/src/tests.rs @@ -13,7 +13,7 @@ pub fn run_tests(env: &Environment) -> anyhow::Result<()> { // and then use that extracted rustc as a stage0 compiler. // Then we run a subset of tests using that compiler, to have a basic smoke test which checks // whether the optimization pipeline hasn't broken something. - let build_dir = env.build_root().join("build"); + let build_dir = env.build_root(); let dist_dir = build_dir.join("dist"); let unpacked_dist_dir = build_dir.join("unpacked-dist"); std::fs::create_dir_all(&unpacked_dist_dir)?; diff --git a/src/tools/opt-dist/src/training.rs b/src/tools/opt-dist/src/training.rs index 36a7d6a7cba..ae062d5c60c 100644 --- a/src/tools/opt-dist/src/training.rs +++ b/src/tools/opt-dist/src/training.rs @@ -163,7 +163,9 @@ pub fn gather_rustc_profiles( let merged_profile = env.artifact_dir().join("rustc-pgo.profdata"); log::info!("Merging Rustc PGO profiles to {merged_profile}"); - merge_llvm_profiles(env, &merged_profile, profile_root, LlvmProfdata::Target)?; + let llvm_profdata = if env.build_llvm() { LlvmProfdata::Target } else { LlvmProfdata::Host }; + + merge_llvm_profiles(env, &merged_profile, profile_root, llvm_profdata)?; log_profile_stats("Rustc", &merged_profile, profile_root)?; // We don't need the individual .profraw files now that they have been merged diff --git a/src/tools/run-make-support/src/external_deps/rustc.rs b/src/tools/run-make-support/src/external_deps/rustc.rs index 1ea549ca7ea..08ba1388dc1 100644 --- a/src/tools/run-make-support/src/external_deps/rustc.rs +++ b/src/tools/run-make-support/src/external_deps/rustc.rs @@ -52,13 +52,20 @@ impl Rustc { // `rustc` invocation constructor methods /// Construct a new `rustc` invocation. This will automatically set the library - /// search path as `-L cwd()` and also the compilation target. + /// search path as `-L cwd()`, configure the compilation target and enable + /// dynamic linkage by default on musl hosts. /// Use [`bare_rustc`] to avoid this. #[track_caller] pub fn new() -> Self { let mut cmd = setup_common(); cmd.arg("-L").arg(cwd()); + // FIXME: On musl hosts, we currently default to static linkage, while + // for running run-make tests, we rely on dynamic linkage by default + if std::env::var("IS_MUSL_HOST").is_ok_and(|i| i == "1") { + cmd.arg("-Ctarget-feature=-crt-static"); + } + // Automatically default to cross-compilation Self { cmd, target: Some(target()) } } diff --git a/src/tools/rustbook/Cargo.lock b/src/tools/rustbook/Cargo.lock index 27798d6aeb0..e363668d462 100644 --- a/src/tools/rustbook/Cargo.lock +++ b/src/tools/rustbook/Cargo.lock @@ -19,9 +19,9 @@ dependencies = [ [[package]] name = "ammonia" -version = "4.1.0" +version = "4.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ada2ee439075a3e70b6992fce18ac4e407cd05aea9ca3f75d2c0b0c20bbb364" +checksum = "d6b346764dd0814805de8abf899fe03065bcee69bb1a4771c785817e39f3978f" dependencies = [ "cssparser", "html5ever", @@ -156,9 +156,9 @@ checksum = "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43" [[package]] name = "cc" -version = "1.2.29" +version = "1.2.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c1599538de2394445747c8cf7935946e3cc27e9625f889d979bfb2aaf569362" +checksum = "deec109607ca693028562ed836a5f1c4b8bd77755c4e132fc5ce11b0b6211ae7" dependencies = [ "shlex", ] @@ -185,9 +185,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.40" +version = "4.5.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40b6887a1d8685cebccf115538db5c0efe625ccac9696ad45c409d96566e910f" +checksum = "be92d32e80243a54711e5d7ce823c35c41c9d929dc4ab58e1276f625841aadf9" dependencies = [ "clap_builder", "clap_derive", @@ -195,9 +195,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.40" +version = "4.5.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0c66c08ce9f0c698cbce5c0279d0bb6ac936d8674174fe48f736533b964f59e" +checksum = "707eab41e9622f9139419d573eca0900137718000c517d47da73045f54331c3d" dependencies = [ "anstream", "anstyle", @@ -208,18 +208,18 @@ dependencies = [ [[package]] name = "clap_complete" -version = "4.5.54" +version = "4.5.55" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aad5b1b4de04fead402672b48897030eec1f3bfe1550776322f59f6d6e6a5677" +checksum = "a5abde44486daf70c5be8b8f8f1b66c49f86236edf6fa2abadb4d961c4c6229a" dependencies = [ "clap", ] [[package]] name = "clap_derive" -version = "4.5.40" +version = "4.5.41" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2c7947ae4cc3d851207c1adb5b5e260ff0cca11446b1d6d1423788e442257ce" +checksum = "ef4f52386a59ca4c860f7393bcf8abd8dfd91ecccc0f774635ff68e92eeef491" dependencies = [ "heck", "proc-macro2", @@ -256,9 +256,9 @@ dependencies = [ [[package]] name = "crc32fast" -version = "1.4.2" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a97769d94ddab943e4510d138150169a2758b5ef3eb191a9ee688de3e23ef7b3" +checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" dependencies = [ "cfg-if", ] @@ -582,12 +582,11 @@ checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" [[package]] name = "html5ever" -version = "0.31.0" +version = "0.35.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "953cbbe631aae7fc0a112702ad5d3aaf09da38beaf45ea84610d6e1c358f569c" +checksum = "55d958c2f74b664487a2035fe1dadb032c48718a03b63f3ab0b8537db8549ed4" dependencies = [ "log", - "mac", "markup5ever", "match_token", ] @@ -863,9 +862,9 @@ checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d" [[package]] name = "markup5ever" -version = "0.16.2" +version = "0.35.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e4cd8c02f18a011991a039855480c64d74291c5792fcc160d55d77dc4de4a39" +checksum = "311fe69c934650f8f19652b3946075f0fc41ad8757dbb68f1ca14e7900ecc1c3" dependencies = [ "log", "tendril", @@ -874,9 +873,9 @@ dependencies = [ [[package]] name = "match_token" -version = "0.1.0" +version = "0.35.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88a9689d8d44bf9964484516275f5cd4c9b59457a6940c1d5d0ecbb94510a36b" +checksum = "ac84fd3f360fcc43dc5f5d186f02a94192761a080e8bc58621ad4d12296a58cf" dependencies = [ "proc-macro2", "quote", @@ -1394,15 +1393,15 @@ dependencies = [ [[package]] name = "rustix" -version = "1.0.7" +version = "1.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c71e83d6afe7ff64890ec6b71d6a69bb8a610ab78ce364b3352876bb4c801266" +checksum = "11181fbabf243db407ef8df94a6ce0b2f9a733bd8be4ad02b4eda9602296cac8" dependencies = [ "bitflags 2.9.1", "errno", "libc", "linux-raw-sys", - "windows-sys 0.59.0", + "windows-sys 0.60.2", ] [[package]] @@ -1460,9 +1459,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.140" +version = "1.0.141" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373" +checksum = "30b9eff21ebe718216c6ec64e1d9ac57087aad11efc64e32002bce4a0d4c03d3" dependencies = [ "itoa", "memchr", @@ -2103,9 +2102,9 @@ checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486" [[package]] name = "winnow" -version = "0.7.11" +version = "0.7.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74c7b26e3480b707944fc872477815d29a8e429d2f93a1ce000f5fa84a15cbcd" +checksum = "f3edebf492c8125044983378ecb5766203ad3b4c2f7a922bd7dd207f6d443e95" dependencies = [ "memchr", ] diff --git a/src/tools/rustdoc-js/tester.js b/src/tools/rustdoc-js/tester.js index f70fc917770..0baa179e16b 100644 --- a/src/tools/rustdoc-js/tester.js +++ b/src/tools/rustdoc-js/tester.js @@ -28,7 +28,14 @@ function readFile(filePath) { } function contentToDiffLine(key, value) { - return `"${key}": "${value}",`; + if (typeof value === "object" && !Array.isArray(value) && value !== null) { + const out = Object.entries(value) + .filter(([subKey, _]) => ["path", "name"].includes(subKey)) + .map(([subKey, subValue]) => `"${subKey}": ${JSON.stringify(subValue)}`) + .join(", "); + return `"${key}": ${out},`; + } + return `"${key}": ${JSON.stringify(value)},`; } function shouldIgnoreField(fieldName) { @@ -37,47 +44,61 @@ function shouldIgnoreField(fieldName) { fieldName === "proposeCorrectionTo"; } +function valueMapper(key, testOutput) { + const isAlias = testOutput["is_alias"]; + let value = testOutput[key]; + // To make our life easier, if there is a "parent" type, we add it to the path. + if (key === "path") { + if (testOutput["parent"] !== undefined) { + if (value.length > 0) { + value += "::" + testOutput["parent"]["name"]; + } else { + value = testOutput["parent"]["name"]; + } + } else if (testOutput["is_alias"]) { + value = valueMapper(key, testOutput["original"]); + } + } else if (isAlias && key === "alias") { + value = testOutput["name"]; + } else if (isAlias && ["name"].includes(key)) { + value = testOutput["original"][key]; + } + return value; +} + // This function is only called when no matching result was found and therefore will only display // the diff between the two items. -function betterLookingDiff(entry, data) { +function betterLookingDiff(expected, testOutput) { let output = " {\n"; - const spaces = " "; - for (const key in entry) { - if (!Object.prototype.hasOwnProperty.call(entry, key)) { + const spaces = " "; + for (const key in expected) { + if (!Object.prototype.hasOwnProperty.call(expected, key)) { continue; } - if (!data || !Object.prototype.hasOwnProperty.call(data, key)) { - output += "-" + spaces + contentToDiffLine(key, entry[key]) + "\n"; + if (!testOutput || !Object.prototype.hasOwnProperty.call(testOutput, key)) { + output += "-" + spaces + contentToDiffLine(key, expected[key]) + "\n"; continue; } - const value = data[key]; - if (value !== entry[key]) { - output += "-" + spaces + contentToDiffLine(key, entry[key]) + "\n"; + const value = valueMapper(key, testOutput); + if (value !== expected[key]) { + output += "-" + spaces + contentToDiffLine(key, expected[key]) + "\n"; output += "+" + spaces + contentToDiffLine(key, value) + "\n"; } else { - output += spaces + contentToDiffLine(key, value) + "\n"; + output += spaces + " " + contentToDiffLine(key, value) + "\n"; } } return output + " }"; } -function lookForEntry(entry, data) { - return data.findIndex(data_entry => { +function lookForEntry(expected, testOutput) { + return testOutput.findIndex(testOutputEntry => { let allGood = true; - for (const key in entry) { - if (!Object.prototype.hasOwnProperty.call(entry, key)) { + for (const key in expected) { + if (!Object.prototype.hasOwnProperty.call(expected, key)) { continue; } - let value = data_entry[key]; - // To make our life easier, if there is a "parent" type, we add it to the path. - if (key === "path" && data_entry["parent"] !== undefined) { - if (value.length > 0) { - value += "::" + data_entry["parent"]["name"]; - } else { - value = data_entry["parent"]["name"]; - } - } - if (value !== entry[key]) { + const value = valueMapper(key, testOutputEntry); + if (value !== expected[key]) { allGood = false; break; } diff --git a/src/tools/tidy/src/features.rs b/src/tools/tidy/src/features.rs index e83b47e1380..fb00b3a943f 100644 --- a/src/tools/tidy/src/features.rs +++ b/src/tools/tidy/src/features.rs @@ -331,11 +331,9 @@ fn collect_lang_features_in(features: &mut Features, base: &Path, file: &str, ba continue; } - if in_feature_group { - if let Some(doc_comment) = line.strip_prefix("///") { - doc_comments.push(doc_comment.trim().to_string()); - continue; - } + if in_feature_group && let Some(doc_comment) = line.strip_prefix("///") { + doc_comments.push(doc_comment.trim().to_string()); + continue; } let mut parts = line.split(','); @@ -465,19 +463,20 @@ fn get_and_check_lib_features( map_lib_features(base_src_path, &mut |res, file, line| match res { Ok((name, f)) => { let mut check_features = |f: &Feature, list: &Features, display: &str| { - if let Some(s) = list.get(name) { - if f.tracking_issue != s.tracking_issue && f.level != Status::Accepted { - tidy_error!( - bad, - "{}:{}: feature gate {} has inconsistent `issue`: \"{}\" mismatches the {} `issue` of \"{}\"", - file.display(), - line, - name, - f.tracking_issue_display(), - display, - s.tracking_issue_display(), - ); - } + if let Some(s) = list.get(name) + && f.tracking_issue != s.tracking_issue + && f.level != Status::Accepted + { + tidy_error!( + bad, + "{}:{}: feature gate {} has inconsistent `issue`: \"{}\" mismatches the {} `issue` of \"{}\"", + file.display(), + line, + name, + f.tracking_issue_display(), + display, + s.tracking_issue_display(), + ); } }; check_features(&f, lang_features, "corresponding lang feature"); diff --git a/src/tools/tidy/src/fluent_period.rs b/src/tools/tidy/src/fluent_period.rs index 85c1ef6166a..836b5699289 100644 --- a/src/tools/tidy/src/fluent_period.rs +++ b/src/tools/tidy/src/fluent_period.rs @@ -33,14 +33,14 @@ fn check_period(filename: &str, contents: &str, bad: &mut bool) { continue; } - if let Some(pat) = &m.value { - if let Some(PatternElement::TextElement { value }) = pat.elements.last() { - // We don't care about ellipses. - if value.ends_with(".") && !value.ends_with("...") { - let ll = find_line(contents, value); - let name = m.id.name; - tidy_error!(bad, "{filename}:{ll}: message `{name}` ends in a period"); - } + if let Some(pat) = &m.value + && let Some(PatternElement::TextElement { value }) = pat.elements.last() + { + // We don't care about ellipses. + if value.ends_with(".") && !value.ends_with("...") { + let ll = find_line(contents, value); + let name = m.id.name; + tidy_error!(bad, "{filename}:{ll}: message `{name}` ends in a period"); } } @@ -50,12 +50,13 @@ fn check_period(filename: &str, contents: &str, bad: &mut bool) { continue; } - if let Some(PatternElement::TextElement { value }) = attr.value.elements.last() { - if value.ends_with(".") && !value.ends_with("...") { - let ll = find_line(contents, value); - let name = attr.id.name; - tidy_error!(bad, "{filename}:{ll}: attr `{name}` ends in a period"); - } + if let Some(PatternElement::TextElement { value }) = attr.value.elements.last() + && value.ends_with(".") + && !value.ends_with("...") + { + let ll = find_line(contents, value); + let name = attr.id.name; + tidy_error!(bad, "{filename}:{ll}: attr `{name}` ends in a period"); } } } diff --git a/src/tools/tidy/src/fluent_used.rs b/src/tools/tidy/src/fluent_used.rs index 12fafd9a7ff..909bf482ddf 100644 --- a/src/tools/tidy/src/fluent_used.rs +++ b/src/tools/tidy/src/fluent_used.rs @@ -12,7 +12,7 @@ fn filter_used_messages( ) { // we don't just check messages never appear in Rust files, // because messages can be used as parts of other fluent messages in Fluent files, - // so we do checking messages appear only once in all Rust and Fluent files. + // so we check messages appear only once in all Rust and Fluent files. let matches = static_regex!(r"\w+").find_iter(contents); for name in matches { if let Some((name, filename)) = msgs_not_appeared_yet.remove_entry(name.as_str()) { diff --git a/src/tools/tidy/src/lib.rs b/src/tools/tidy/src/lib.rs index ade4055b5bd..cb875504e1e 100644 --- a/src/tools/tidy/src/lib.rs +++ b/src/tools/tidy/src/lib.rs @@ -13,8 +13,9 @@ use termcolor::WriteColor; macro_rules! static_regex { ($re:literal) => {{ - static RE: ::std::sync::OnceLock<::regex::Regex> = ::std::sync::OnceLock::new(); - RE.get_or_init(|| ::regex::Regex::new($re).unwrap()) + static RE: ::std::sync::LazyLock<::regex::Regex> = + ::std::sync::LazyLock::new(|| ::regex::Regex::new($re).unwrap()); + &*RE }}; } @@ -134,7 +135,7 @@ pub fn files_modified(ci_info: &CiInfo, pred: impl Fn(&str) -> bool) -> bool { eprintln!("No base commit, assuming all files are modified"); return true; }; - match crate::git_diff(&base_commit, "--name-status") { + match crate::git_diff(base_commit, "--name-status") { Some(output) => { let modified_files = output.lines().filter_map(|ln| { let (status, name) = ln diff --git a/src/tools/tidy/src/mir_opt_tests.rs b/src/tools/tidy/src/mir_opt_tests.rs index 1efe71b1687..6119eb58383 100644 --- a/src/tools/tidy/src/mir_opt_tests.rs +++ b/src/tools/tidy/src/mir_opt_tests.rs @@ -55,22 +55,21 @@ fn check_dash_files(path: &Path, bless: bool, bad: &mut bool) { .filter(|e| e.file_type().is_file()) { let path = file.path(); - if path.extension() == Some("rs".as_ref()) { - if let Some(name) = path.file_name().and_then(|s| s.to_str()) { - if name.contains('-') { - if !bless { - tidy_error!( - bad, - "mir-opt test files should not have dashes in them: {}", - path.display() - ); - } else { - let new_name = name.replace('-', "_"); - let mut new_path = path.to_owned(); - new_path.set_file_name(new_name); - let _ = std::fs::rename(path, new_path); - } - } + if path.extension() == Some("rs".as_ref()) + && let Some(name) = path.file_name().and_then(|s| s.to_str()) + && name.contains('-') + { + if !bless { + tidy_error!( + bad, + "mir-opt test files should not have dashes in them: {}", + path.display() + ); + } else { + let new_name = name.replace('-', "_"); + let mut new_path = path.to_owned(); + new_path.set_file_name(new_name); + let _ = std::fs::rename(path, new_path); } } } diff --git a/src/tools/tidy/src/rustdoc_templates.rs b/src/tools/tidy/src/rustdoc_templates.rs index dca3e8d9d25..597290a6a9a 100644 --- a/src/tools/tidy/src/rustdoc_templates.rs +++ b/src/tools/tidy/src/rustdoc_templates.rs @@ -26,7 +26,7 @@ pub fn check(librustdoc_path: &Path, bad: &mut bool) { None // Then we check if this a comment tag. } else if *tag != "{#" { - return Some(false); + Some(false) // And finally we check if the comment is empty (ie, only there to strip // extra whitespace characters). } else if let Some(start_pos) = line.rfind(tag) { diff --git a/src/tools/tidy/src/style.rs b/src/tools/tidy/src/style.rs index 8dde4618ce5..35ed61eacc7 100644 --- a/src/tools/tidy/src/style.rs +++ b/src/tools/tidy/src/style.rs @@ -417,10 +417,10 @@ pub fn check(path: &Path, bad: &mut bool) { return; } // Shell completions are automatically generated - if let Some(p) = file.parent() { - if p.ends_with(Path::new("src/etc/completions")) { - return; - } + if let Some(p) = file.parent() + && p.ends_with(Path::new("src/etc/completions")) + { + return; } let [ mut skip_cr, @@ -604,25 +604,25 @@ pub fn check(path: &Path, bad: &mut bool) { backtick_count += comment_text.chars().filter(|ch| *ch == '`').count(); } comment_block = Some((start_line, backtick_count)); - } else if let Some((start_line, backtick_count)) = comment_block.take() { - if backtick_count % 2 == 1 { - let mut err = |msg: &str| { - tidy_error!(bad, "{}:{start_line}: {msg}", file.display()); - }; - let block_len = (i + 1) - start_line; - if block_len == 1 { - suppressible_tidy_err!( - err, - skip_odd_backticks, - "comment with odd number of backticks" - ); - } else { - suppressible_tidy_err!( - err, - skip_odd_backticks, - "{block_len}-line comment block with odd number of backticks" - ); - } + } else if let Some((start_line, backtick_count)) = comment_block.take() + && backtick_count % 2 == 1 + { + let mut err = |msg: &str| { + tidy_error!(bad, "{}:{start_line}: {msg}", file.display()); + }; + let block_len = (i + 1) - start_line; + if block_len == 1 { + suppressible_tidy_err!( + err, + skip_odd_backticks, + "comment with odd number of backticks" + ); + } else { + suppressible_tidy_err!( + err, + skip_odd_backticks, + "{block_len}-line comment block with odd number of backticks" + ); } } } diff --git a/src/tools/tidy/src/target_specific_tests.rs b/src/tools/tidy/src/target_specific_tests.rs index 1a6fd3eaf2d..f4a6783abb6 100644 --- a/src/tools/tidy/src/target_specific_tests.rs +++ b/src/tools/tidy/src/target_specific_tests.rs @@ -30,17 +30,17 @@ pub fn check(tests_path: &Path, bad: &mut bool) { comp_vec.push(component); } } - } else if let Some(compile_flags) = directive.strip_prefix(COMPILE_FLAGS_HEADER) { - if let Some((_, v)) = compile_flags.split_once("--target") { - let v = v.trim_start_matches([' ', '=']); - let v = if v == "{{target}}" { Some((v, v)) } else { v.split_once("-") }; - if let Some((arch, _)) = v { - let info = header_map.entry(revision).or_insert(RevisionInfo::default()); - info.target_arch.replace(arch); - } else { - eprintln!("{file}: seems to have a malformed --target value"); - *bad = true; - } + } else if let Some(compile_flags) = directive.strip_prefix(COMPILE_FLAGS_HEADER) + && let Some((_, v)) = compile_flags.split_once("--target") + { + let v = v.trim_start_matches([' ', '=']); + let v = if v == "{{target}}" { Some((v, v)) } else { v.split_once("-") }; + if let Some((arch, _)) = v { + let info = header_map.entry(revision).or_insert(RevisionInfo::default()); + info.target_arch.replace(arch); + } else { + eprintln!("{file}: seems to have a malformed --target value"); + *bad = true; } } }); diff --git a/src/tools/tidy/src/ui_tests.rs b/src/tools/tidy/src/ui_tests.rs index 7e295731c56..b9d22ece597 100644 --- a/src/tools/tidy/src/ui_tests.rs +++ b/src/tools/tidy/src/ui_tests.rs @@ -161,31 +161,30 @@ pub fn check(root_path: &Path, bless: bool, bad: &mut bool) { tidy_error!(bad, "Stray file with UI testing output: {:?}", file_path); } - if let Ok(metadata) = fs::metadata(file_path) { - if metadata.len() == 0 { - tidy_error!(bad, "Empty file with UI testing output: {:?}", file_path); - } + if let Ok(metadata) = fs::metadata(file_path) + && metadata.len() == 0 + { + tidy_error!(bad, "Empty file with UI testing output: {:?}", file_path); } } - if ext == "rs" { - if let Some(test_name) = static_regex!(r"^issues?[-_]?(\d{3,})").captures(testname) - { - // these paths are always relative to the passed `path` and always UTF8 - let stripped_path = file_path - .strip_prefix(path) - .unwrap() - .to_str() - .unwrap() - .replace(std::path::MAIN_SEPARATOR_STR, "/"); - - if !remaining_issue_names.remove(stripped_path.as_str()) { - tidy_error!( - bad, - "file `tests/{stripped_path}` must begin with a descriptive name, consider `{{reason}}-issue-{issue_n}.rs`", - issue_n = &test_name[1], - ); - } + if ext == "rs" + && let Some(test_name) = static_regex!(r"^issues?[-_]?(\d{3,})").captures(testname) + { + // these paths are always relative to the passed `path` and always UTF8 + let stripped_path = file_path + .strip_prefix(path) + .unwrap() + .to_str() + .unwrap() + .replace(std::path::MAIN_SEPARATOR_STR, "/"); + + if !remaining_issue_names.remove(stripped_path.as_str()) { + tidy_error!( + bad, + "file `tests/{stripped_path}` must begin with a descriptive name, consider `{{reason}}-issue-{issue_n}.rs`", + issue_n = &test_name[1], + ); } } } diff --git a/src/tools/tidy/src/x_version.rs b/src/tools/tidy/src/x_version.rs index 6a5e9eca813..9f7f43c4000 100644 --- a/src/tools/tidy/src/x_version.rs +++ b/src/tools/tidy/src/x_version.rs @@ -25,12 +25,12 @@ pub fn check(root: &Path, cargo: &Path, bad: &mut bool) { if let Some(version) = iter.next() { // Check this is the rust-lang/rust x tool installation since it should be // installed at a path containing `src/tools/x`. - if let Some(path) = iter.next() { - if path.contains("src/tools/x") { - let version = version.strip_prefix("v").unwrap(); - installed = Some(Version::parse(version).unwrap()); - break; - } + if let Some(path) = iter.next() + && path.contains("src/tools/x") + { + let version = version.strip_prefix("v").unwrap(); + installed = Some(Version::parse(version).unwrap()); + break; }; } } else { diff --git a/src/tools/unicode-table-generator/Cargo.toml b/src/tools/unicode-table-generator/Cargo.toml index f8a500922d0..3ca6e9e316f 100644 --- a/src/tools/unicode-table-generator/Cargo.toml +++ b/src/tools/unicode-table-generator/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "unicode-table-generator" version = "0.1.0" -edition = "2021" +edition = "2024" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/src/tools/unicode-table-generator/src/cascading_map.rs b/src/tools/unicode-table-generator/src/cascading_map.rs index 1eb35e819c0..78a7bba3208 100644 --- a/src/tools/unicode-table-generator/src/cascading_map.rs +++ b/src/tools/unicode-table-generator/src/cascading_map.rs @@ -21,7 +21,7 @@ impl RawEmitter { let points = ranges .iter() - .flat_map(|r| (r.start..r.end).into_iter().collect::<Vec<u32>>()) + .flat_map(|r| (r.start..r.end).collect::<Vec<u32>>()) .collect::<Vec<u32>>(); println!("there are {} points", points.len()); @@ -32,21 +32,20 @@ impl RawEmitter { // assert that there is no whitespace over the 0x3000 range. assert!(point <= 0x3000, "the highest unicode whitespace value has changed"); let high_bytes = point as usize >> 8; - let codepoints = codepoints_by_high_bytes.entry(high_bytes).or_insert_with(Vec::new); + let codepoints = codepoints_by_high_bytes.entry(high_bytes).or_default(); codepoints.push(point); } let mut bit_for_high_byte = 1u8; let mut arms = Vec::<String>::new(); - let mut high_bytes: Vec<usize> = - codepoints_by_high_bytes.keys().map(|k| k.clone()).collect(); + let mut high_bytes: Vec<usize> = codepoints_by_high_bytes.keys().copied().collect(); high_bytes.sort(); for high_byte in high_bytes { let codepoints = codepoints_by_high_bytes.get_mut(&high_byte).unwrap(); if codepoints.len() == 1 { let ch = codepoints.pop().unwrap(); - arms.push(format!("{} => c as u32 == {:#04x}", high_byte, ch)); + arms.push(format!("{high_byte} => c as u32 == {ch:#04x}")); continue; } // more than 1 codepoint in this arm @@ -54,8 +53,7 @@ impl RawEmitter { map[(*codepoint & 0xff) as usize] |= bit_for_high_byte; } arms.push(format!( - "{} => WHITESPACE_MAP[c as usize & 0xff] & {} != 0", - high_byte, bit_for_high_byte + "{high_byte} => WHITESPACE_MAP[c as usize & 0xff] & {bit_for_high_byte} != 0" )); bit_for_high_byte <<= 1; } @@ -68,7 +66,7 @@ impl RawEmitter { writeln!(&mut self.file, "pub const fn lookup(c: char) -> bool {{").unwrap(); writeln!(&mut self.file, " match c as u32 >> 8 {{").unwrap(); for arm in arms { - writeln!(&mut self.file, " {},", arm).unwrap(); + writeln!(&mut self.file, " {arm},").unwrap(); } writeln!(&mut self.file, " _ => false,").unwrap(); writeln!(&mut self.file, " }}").unwrap(); diff --git a/src/tools/unicode-table-generator/src/case_mapping.rs b/src/tools/unicode-table-generator/src/case_mapping.rs index 00241b7ee0e..9c6454492e7 100644 --- a/src/tools/unicode-table-generator/src/case_mapping.rs +++ b/src/tools/unicode-table-generator/src/case_mapping.rs @@ -9,7 +9,7 @@ const INDEX_MASK: u32 = 1 << 22; pub(crate) fn generate_case_mapping(data: &UnicodeData) -> String { let mut file = String::new(); - write!(file, "const INDEX_MASK: u32 = 0x{:x};", INDEX_MASK).unwrap(); + write!(file, "const INDEX_MASK: u32 = 0x{INDEX_MASK:x};").unwrap(); file.push_str("\n\n"); file.push_str(HEADER.trim_start()); file.push('\n'); diff --git a/src/tools/unicode-table-generator/src/main.rs b/src/tools/unicode-table-generator/src/main.rs index 415db2c4dbc..6cdb82a87bd 100644 --- a/src/tools/unicode-table-generator/src/main.rs +++ b/src/tools/unicode-table-generator/src/main.rs @@ -160,15 +160,15 @@ fn load_data() -> UnicodeData { .push(Codepoints::Single(row.codepoint)); } - if let Some(mapped) = row.simple_lowercase_mapping { - if mapped != row.codepoint { - to_lower.insert(row.codepoint.value(), (mapped.value(), 0, 0)); - } + if let Some(mapped) = row.simple_lowercase_mapping + && mapped != row.codepoint + { + to_lower.insert(row.codepoint.value(), (mapped.value(), 0, 0)); } - if let Some(mapped) = row.simple_uppercase_mapping { - if mapped != row.codepoint { - to_upper.insert(row.codepoint.value(), (mapped.value(), 0, 0)); - } + if let Some(mapped) = row.simple_uppercase_mapping + && mapped != row.codepoint + { + to_upper.insert(row.codepoint.value(), (mapped.value(), 0, 0)); } } @@ -196,12 +196,12 @@ fn load_data() -> UnicodeData { .flat_map(|codepoints| match codepoints { Codepoints::Single(c) => c .scalar() - .map(|ch| (ch as u32..ch as u32 + 1)) + .map(|ch| ch as u32..ch as u32 + 1) .into_iter() .collect::<Vec<_>>(), Codepoints::Range(c) => c .into_iter() - .flat_map(|c| c.scalar().map(|ch| (ch as u32..ch as u32 + 1))) + .flat_map(|c| c.scalar().map(|ch| ch as u32..ch as u32 + 1)) .collect::<Vec<_>>(), }) .collect::<Vec<Range<u32>>>(), @@ -236,7 +236,7 @@ fn main() { let ranges_by_property = &unicode_data.ranges; if let Some(path) = test_path { - std::fs::write(&path, generate_tests(&write_location, &ranges_by_property)).unwrap(); + std::fs::write(&path, generate_tests(&write_location, ranges_by_property)).unwrap(); } let mut total_bytes = 0; @@ -246,9 +246,9 @@ fn main() { let mut emitter = RawEmitter::new(); if property == &"White_Space" { - emit_whitespace(&mut emitter, &ranges); + emit_whitespace(&mut emitter, ranges); } else { - emit_codepoints(&mut emitter, &ranges); + emit_codepoints(&mut emitter, ranges); } modules.push((property.to_lowercase().to_string(), emitter.file)); @@ -288,7 +288,7 @@ fn main() { for line in contents.lines() { if !line.trim().is_empty() { table_file.push_str(" "); - table_file.push_str(&line); + table_file.push_str(line); } table_file.push('\n'); } @@ -312,7 +312,7 @@ fn version() -> String { let start = readme.find(prefix).unwrap() + prefix.len(); let end = readme.find(" of the Unicode Standard.").unwrap(); let version = - readme[start..end].split('.').map(|v| v.parse::<u32>().expect(&v)).collect::<Vec<_>>(); + readme[start..end].split('.').map(|v| v.parse::<u32>().expect(v)).collect::<Vec<_>>(); let [major, minor, micro] = [version[0], version[1], version[2]]; out.push_str(&format!("({major}, {minor}, {micro});\n")); @@ -320,7 +320,7 @@ fn version() -> String { } fn fmt_list<V: std::fmt::Debug>(values: impl IntoIterator<Item = V>) -> String { - let pieces = values.into_iter().map(|b| format!("{:?}, ", b)).collect::<Vec<_>>(); + let pieces = values.into_iter().map(|b| format!("{b:?}, ")).collect::<Vec<_>>(); let mut out = String::new(); let mut line = String::from("\n "); for piece in pieces { @@ -348,7 +348,7 @@ fn generate_tests(data_path: &str, ranges: &[(&str, Vec<Range<u32>>)]) -> String s.push_str("\nfn main() {\n"); for (property, ranges) in ranges { - s.push_str(&format!(r#" println!("Testing {}");"#, property)); + s.push_str(&format!(r#" println!("Testing {property}");"#)); s.push('\n'); s.push_str(&format!(" {}_true();\n", property.to_lowercase())); s.push_str(&format!(" {}_false();\n", property.to_lowercase())); @@ -373,7 +373,7 @@ fn generate_tests(data_path: &str, ranges: &[(&str, Vec<Range<u32>>)]) -> String s.push_str(" }\n\n"); } - s.push_str("}"); + s.push('}'); s } @@ -388,7 +388,7 @@ fn generate_asserts(s: &mut String, property: &str, points: &[u32], truthy: bool range.start, )); } else { - s.push_str(&format!(" for chn in {:?}u32 {{\n", range)); + s.push_str(&format!(" for chn in {range:?}u32 {{\n")); s.push_str(&format!( " assert!({}unicode_data::{}::lookup(std::char::from_u32(chn).unwrap()), \"{{:?}}\", chn);\n", if truthy { "" } else { "!" }, @@ -439,7 +439,7 @@ fn merge_ranges(ranges: &mut Vec<Range<u32>>) { let mut last_end = None; for range in ranges { if let Some(last) = last_end { - assert!(range.start > last, "{:?}", range); + assert!(range.start > last, "{range:?}"); } last_end = Some(range.end); } diff --git a/src/tools/unicode-table-generator/src/raw_emitter.rs b/src/tools/unicode-table-generator/src/raw_emitter.rs index ee94d3c93a6..e9e0efc4594 100644 --- a/src/tools/unicode-table-generator/src/raw_emitter.rs +++ b/src/tools/unicode-table-generator/src/raw_emitter.rs @@ -156,10 +156,10 @@ pub fn emit_codepoints(emitter: &mut RawEmitter, ranges: &[Range<u32>]) { emitter.blank_line(); let mut bitset = emitter.clone(); - let bitset_ok = bitset.emit_bitset(&ranges).is_ok(); + let bitset_ok = bitset.emit_bitset(ranges).is_ok(); let mut skiplist = emitter.clone(); - skiplist.emit_skiplist(&ranges); + skiplist.emit_skiplist(ranges); if bitset_ok && bitset.bytes_used <= skiplist.bytes_used { *emitter = bitset; @@ -174,7 +174,7 @@ pub fn emit_whitespace(emitter: &mut RawEmitter, ranges: &[Range<u32>]) { emitter.blank_line(); let mut cascading = emitter.clone(); - cascading.emit_cascading_map(&ranges); + cascading.emit_cascading_map(ranges); *emitter = cascading; emitter.desc = String::from("cascading"); } @@ -272,7 +272,7 @@ impl Canonicalized { // for canonical when possible. while let Some((&to, _)) = mappings .iter() - .find(|(&to, _)| to == 0) + .find(|&(&to, _)| to == 0) .or_else(|| mappings.iter().max_by_key(|m| m.1.len())) { // Get the mapping with the most entries. Currently, no mapping can @@ -311,10 +311,9 @@ impl Canonicalized { } } } - assert!( - unique_mapping - .insert(to, UniqueMapping::Canonical(canonical_words.len())) - .is_none() + assert_eq!( + unique_mapping.insert(to, UniqueMapping::Canonical(canonical_words.len())), + None ); canonical_words.push(to); @@ -340,14 +339,10 @@ impl Canonicalized { // We'll probably always have some slack though so this loop will still // be needed. for &w in unique_words { - if !unique_mapping.contains_key(&w) { - assert!( - unique_mapping - .insert(w, UniqueMapping::Canonical(canonical_words.len())) - .is_none() - ); + unique_mapping.entry(w).or_insert_with(|| { canonical_words.push(w); - } + UniqueMapping::Canonical(canonical_words.len()) + }); } assert_eq!(canonicalized_words.len() + canonical_words.len(), unique_words.len()); assert_eq!(unique_mapping.len(), unique_words.len()); diff --git a/tests/assembly/cstring-merging.rs b/tests/assembly/cstring-merging.rs index f7d0775f7af..03688e0068b 100644 --- a/tests/assembly/cstring-merging.rs +++ b/tests/assembly/cstring-merging.rs @@ -2,7 +2,7 @@ // other architectures (including ARM and x86-64) use the prefix `.Lanon.` //@ only-linux //@ assembly-output: emit-asm -//@ compile-flags: --crate-type=lib -Copt-level=3 +//@ compile-flags: --crate-type=lib -Copt-level=3 -Cllvm-args=-enable-global-merge=0 //@ edition: 2024 use std::ffi::CStr; diff --git a/tests/assembly/sanitizer/kcfi/emit-arity-indicator.rs b/tests/assembly/sanitizer/kcfi/emit-arity-indicator.rs index b3b623b509b..f9966a23446 100644 --- a/tests/assembly/sanitizer/kcfi/emit-arity-indicator.rs +++ b/tests/assembly/sanitizer/kcfi/emit-arity-indicator.rs @@ -8,6 +8,14 @@ //@ min-llvm-version: 21.0.0 #![crate_type = "lib"] +#![feature(no_core)] +#![no_core] + +extern crate minicore; + +unsafe extern "C" { + safe fn add(x: i32, y: i32) -> i32; +} pub fn add_one(x: i32) -> i32 { // CHECK-LABEL: __cfi__{{.*}}7add_one{{.*}}: @@ -23,7 +31,7 @@ pub fn add_one(x: i32) -> i32 { // CHECK-NEXT: nop // CHECK-NEXT: nop // CHECK-NEXT: mov ecx, 2628068948 - x + 1 + add(x, 1) } pub fn add_two(x: i32, _y: i32) -> i32 { @@ -40,7 +48,7 @@ pub fn add_two(x: i32, _y: i32) -> i32 { // CHECK-NEXT: nop // CHECK-NEXT: nop // CHECK-NEXT: mov edx, 2505940310 - x + 2 + add(x, 2) } pub fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 { @@ -57,5 +65,5 @@ pub fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 { // CHECK-NEXT: nop // CHECK-NEXT: nop // CHECK-NEXT: mov edx, 653723426 - f(arg) + f(arg) + add(f(arg), f(arg)) } diff --git a/tests/assembly/wasm_exceptions.rs b/tests/assembly/wasm_exceptions.rs index f05ccfadc58..704e8026f3f 100644 --- a/tests/assembly/wasm_exceptions.rs +++ b/tests/assembly/wasm_exceptions.rs @@ -2,7 +2,6 @@ //@ assembly-output: emit-asm //@ compile-flags: -C target-feature=+exception-handling //@ compile-flags: -C panic=unwind -//@ compile-flags: -C llvm-args=-wasm-enable-eh #![crate_type = "lib"] #![feature(core_intrinsics)] diff --git a/tests/auxiliary/minisimd.rs b/tests/auxiliary/minisimd.rs new file mode 100644 index 00000000000..ff0c996de1c --- /dev/null +++ b/tests/auxiliary/minisimd.rs @@ -0,0 +1,160 @@ +//! Auxiliary crate for tests that need SIMD types. +//! +//! Historically the tests just made their own, but projections into simd types +//! was banned by <https://github.com/rust-lang/compiler-team/issues/838>, which +//! breaks `derive(Clone)`, so this exists to give easily-usable types that can +//! be used without copy-pasting the definitions of the helpers everywhere. +//! +//! This makes no attempt to guard against ICEs. Using it with proper types +//! and such is your responsibility in the tests you write. + +#![allow(unused)] +#![allow(non_camel_case_types)] + +// The field is currently left `pub` for convenience in porting tests, many of +// which attempt to just construct it directly. That still works; it's just the +// `.0` projection that doesn't. +#[repr(simd)] +#[derive(Copy, Eq)] +pub struct Simd<T, const N: usize>(pub [T; N]); + +impl<T: Copy, const N: usize> Clone for Simd<T, N> { + fn clone(&self) -> Self { + *self + } +} + +impl<T: PartialEq, const N: usize> PartialEq for Simd<T, N> { + fn eq(&self, other: &Self) -> bool { + self.as_array() == other.as_array() + } +} + +impl<T: core::fmt::Debug, const N: usize> core::fmt::Debug for Simd<T, N> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> { + <[T; N] as core::fmt::Debug>::fmt(self.as_array(), f) + } +} + +impl<T, const N: usize> core::ops::Index<usize> for Simd<T, N> { + type Output = T; + fn index(&self, i: usize) -> &T { + &self.as_array()[i] + } +} + +impl<T, const N: usize> Simd<T, N> { + pub const fn from_array(a: [T; N]) -> Self { + Simd(a) + } + pub fn as_array(&self) -> &[T; N] { + let p: *const Self = self; + unsafe { &*p.cast::<[T; N]>() } + } + pub fn into_array(self) -> [T; N] + where + T: Copy, + { + *self.as_array() + } +} + +pub type u8x2 = Simd<u8, 2>; +pub type u8x4 = Simd<u8, 4>; +pub type u8x8 = Simd<u8, 8>; +pub type u8x16 = Simd<u8, 16>; +pub type u8x32 = Simd<u8, 32>; +pub type u8x64 = Simd<u8, 64>; + +pub type u16x2 = Simd<u16, 2>; +pub type u16x4 = Simd<u16, 4>; +pub type u16x8 = Simd<u16, 8>; +pub type u16x16 = Simd<u16, 16>; +pub type u16x32 = Simd<u16, 32>; + +pub type u32x2 = Simd<u32, 2>; +pub type u32x4 = Simd<u32, 4>; +pub type u32x8 = Simd<u32, 8>; +pub type u32x16 = Simd<u32, 16>; + +pub type u64x2 = Simd<u64, 2>; +pub type u64x4 = Simd<u64, 4>; +pub type u64x8 = Simd<u64, 8>; + +pub type u128x2 = Simd<u128, 2>; +pub type u128x4 = Simd<u128, 4>; + +pub type i8x2 = Simd<i8, 2>; +pub type i8x4 = Simd<i8, 4>; +pub type i8x8 = Simd<i8, 8>; +pub type i8x16 = Simd<i8, 16>; +pub type i8x32 = Simd<i8, 32>; +pub type i8x64 = Simd<i8, 64>; + +pub type i16x2 = Simd<i16, 2>; +pub type i16x4 = Simd<i16, 4>; +pub type i16x8 = Simd<i16, 8>; +pub type i16x16 = Simd<i16, 16>; +pub type i16x32 = Simd<i16, 32>; + +pub type i32x2 = Simd<i32, 2>; +pub type i32x4 = Simd<i32, 4>; +pub type i32x8 = Simd<i32, 8>; +pub type i32x16 = Simd<i32, 16>; + +pub type i64x2 = Simd<i64, 2>; +pub type i64x4 = Simd<i64, 4>; +pub type i64x8 = Simd<i64, 8>; + +pub type i128x2 = Simd<i128, 2>; +pub type i128x4 = Simd<i128, 4>; + +pub type f32x2 = Simd<f32, 2>; +pub type f32x4 = Simd<f32, 4>; +pub type f32x8 = Simd<f32, 8>; +pub type f32x16 = Simd<f32, 16>; + +pub type f64x2 = Simd<f64, 2>; +pub type f64x4 = Simd<f64, 4>; +pub type f64x8 = Simd<f64, 8>; + +// The field is currently left `pub` for convenience in porting tests, many of +// which attempt to just construct it directly. That still works; it's just the +// `.0` projection that doesn't. +#[repr(simd, packed)] +#[derive(Copy)] +pub struct PackedSimd<T, const N: usize>(pub [T; N]); + +impl<T: Copy, const N: usize> Clone for PackedSimd<T, N> { + fn clone(&self) -> Self { + *self + } +} + +impl<T: PartialEq, const N: usize> PartialEq for PackedSimd<T, N> { + fn eq(&self, other: &Self) -> bool { + self.as_array() == other.as_array() + } +} + +impl<T: core::fmt::Debug, const N: usize> core::fmt::Debug for PackedSimd<T, N> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> { + <[T; N] as core::fmt::Debug>::fmt(self.as_array(), f) + } +} + +impl<T, const N: usize> PackedSimd<T, N> { + pub const fn from_array(a: [T; N]) -> Self { + PackedSimd(a) + } + pub fn as_array(&self) -> &[T; N] { + let p: *const Self = self; + unsafe { &*p.cast::<[T; N]>() } + } + pub fn into_array(self) -> [T; N] + where + T: Copy, + { + *self.as_array() + } +} diff --git a/tests/codegen/const-vector.rs b/tests/codegen/const-vector.rs index 42921442e03..a2249f4fff7 100644 --- a/tests/codegen/const-vector.rs +++ b/tests/codegen/const-vector.rs @@ -16,18 +16,9 @@ #![feature(mips_target_feature)] #![allow(non_camel_case_types)] -// Setting up structs that can be used as const vectors -#[repr(simd)] -#[derive(Clone)] -pub struct i8x2([i8; 2]); - -#[repr(simd)] -#[derive(Clone)] -pub struct f32x2([f32; 2]); - -#[repr(simd, packed)] -#[derive(Copy, Clone)] -pub struct Simd<T, const N: usize>([T; N]); +#[path = "../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::{PackedSimd as Simd, f32x2, i8x2}; // The following functions are required for the tests to ensure // that they are called with a const vector @@ -45,7 +36,7 @@ extern "unadjusted" { // Ensure the packed variant of the simd struct does not become a const vector // if the size is not a power of 2 -// CHECK: %"Simd<i32, 3>" = type { [3 x i32] } +// CHECK: %"minisimd::PackedSimd<i32, 3>" = type { [3 x i32] } #[cfg_attr(target_family = "wasm", target_feature(enable = "simd128"))] #[cfg_attr(target_arch = "arm", target_feature(enable = "neon"))] @@ -54,27 +45,34 @@ extern "unadjusted" { pub fn do_call() { unsafe { // CHECK: call void @test_i8x2(<2 x i8> <i8 32, i8 64> - test_i8x2(const { i8x2([32, 64]) }); + test_i8x2(const { i8x2::from_array([32, 64]) }); // CHECK: call void @test_i8x2_two_args(<2 x i8> <i8 32, i8 64>, <2 x i8> <i8 8, i8 16> - test_i8x2_two_args(const { i8x2([32, 64]) }, const { i8x2([8, 16]) }); + test_i8x2_two_args( + const { i8x2::from_array([32, 64]) }, + const { i8x2::from_array([8, 16]) }, + ); // CHECK: call void @test_i8x2_mixed_args(<2 x i8> <i8 32, i8 64>, i32 43, <2 x i8> <i8 8, i8 16> - test_i8x2_mixed_args(const { i8x2([32, 64]) }, 43, const { i8x2([8, 16]) }); + test_i8x2_mixed_args( + const { i8x2::from_array([32, 64]) }, + 43, + const { i8x2::from_array([8, 16]) }, + ); // CHECK: call void @test_i8x2_arr(<2 x i8> <i8 32, i8 64> - test_i8x2_arr(const { i8x2([32, 64]) }); + test_i8x2_arr(const { i8x2::from_array([32, 64]) }); // CHECK: call void @test_f32x2(<2 x float> <float 0x3FD47AE140000000, float 0x3FE47AE140000000> - test_f32x2(const { f32x2([0.32, 0.64]) }); + test_f32x2(const { f32x2::from_array([0.32, 0.64]) }); // CHECK: void @test_f32x2_arr(<2 x float> <float 0x3FD47AE140000000, float 0x3FE47AE140000000> - test_f32x2_arr(const { f32x2([0.32, 0.64]) }); + test_f32x2_arr(const { f32x2::from_array([0.32, 0.64]) }); // CHECK: call void @test_simd(<4 x i32> <i32 2, i32 4, i32 6, i32 8> test_simd(const { Simd::<i32, 4>([2, 4, 6, 8]) }); - // CHECK: call void @test_simd_unaligned(%"Simd<i32, 3>" %1 + // CHECK: call void @test_simd_unaligned(%"minisimd::PackedSimd<i32, 3>" %1 test_simd_unaligned(const { Simd::<i32, 3>([2, 4, 6]) }); } } diff --git a/tests/codegen/enum/enum-discriminant-eq.rs b/tests/codegen/enum/enum-discriminant-eq.rs new file mode 100644 index 00000000000..0494c5f551b --- /dev/null +++ b/tests/codegen/enum/enum-discriminant-eq.rs @@ -0,0 +1,223 @@ +//@ compile-flags: -Copt-level=3 -Zmerge-functions=disabled +//@ min-llvm-version: 20 +//@ only-64bit + +// The `derive(PartialEq)` on enums with field-less variants compares discriminants, +// so make sure we emit that in some reasonable way. + +#![crate_type = "lib"] +#![feature(ascii_char)] +#![feature(core_intrinsics)] +#![feature(repr128)] + +use std::ascii::Char as AC; +use std::cmp::Ordering; +use std::intrinsics::discriminant_value; +use std::num::NonZero; + +// A type that's bigger than `isize`, unlike the usual cases that have small tags. +#[repr(u128)] +pub enum Giant { + Two = 2, + Three = 3, + Four = 4, +} + +#[unsafe(no_mangle)] +pub fn opt_bool_eq_discr(a: Option<bool>, b: Option<bool>) -> bool { + // CHECK-LABEL: @opt_bool_eq_discr( + // CHECK: %[[A:.+]] = icmp ne i8 %a, 2 + // CHECK: %[[B:.+]] = icmp eq i8 %b, 2 + // CHECK: %[[R:.+]] = xor i1 %[[A]], %[[B]] + // CHECK: ret i1 %[[R]] + + discriminant_value(&a) == discriminant_value(&b) +} + +#[unsafe(no_mangle)] +pub fn opt_ord_eq_discr(a: Option<Ordering>, b: Option<Ordering>) -> bool { + // CHECK-LABEL: @opt_ord_eq_discr( + // CHECK: %[[A:.+]] = icmp ne i8 %a, 2 + // CHECK: %[[B:.+]] = icmp eq i8 %b, 2 + // CHECK: %[[R:.+]] = xor i1 %[[A]], %[[B]] + // CHECK: ret i1 %[[R]] + + discriminant_value(&a) == discriminant_value(&b) +} + +#[unsafe(no_mangle)] +pub fn opt_nz32_eq_discr(a: Option<NonZero<u32>>, b: Option<NonZero<u32>>) -> bool { + // CHECK-LABEL: @opt_nz32_eq_discr( + // CHECK: %[[A:.+]] = icmp ne i32 %a, 0 + // CHECK: %[[B:.+]] = icmp eq i32 %b, 0 + // CHECK: %[[R:.+]] = xor i1 %[[A]], %[[B]] + // CHECK: ret i1 %[[R]] + + discriminant_value(&a) == discriminant_value(&b) +} + +#[unsafe(no_mangle)] +pub fn opt_ac_eq_discr(a: Option<AC>, b: Option<AC>) -> bool { + // CHECK-LABEL: @opt_ac_eq_discr( + // CHECK: %[[A:.+]] = icmp ne i8 %a, -128 + // CHECK: %[[B:.+]] = icmp eq i8 %b, -128 + // CHECK: %[[R:.+]] = xor i1 %[[A]], %[[B]] + // CHECK: ret i1 %[[R]] + + discriminant_value(&a) == discriminant_value(&b) +} + +#[unsafe(no_mangle)] +pub fn opt_giant_eq_discr(a: Option<Giant>, b: Option<Giant>) -> bool { + // CHECK-LABEL: @opt_giant_eq_discr( + // CHECK: %[[A:.+]] = icmp ne i128 %a, 1 + // CHECK: %[[B:.+]] = icmp eq i128 %b, 1 + // CHECK: %[[R:.+]] = xor i1 %[[A]], %[[B]] + // CHECK: ret i1 %[[R]] + + discriminant_value(&a) == discriminant_value(&b) +} + +pub enum Mid<T> { + Before, + Thing(T), + After, +} + +#[unsafe(no_mangle)] +pub fn mid_bool_eq_discr(a: Mid<bool>, b: Mid<bool>) -> bool { + // CHECK-LABEL: @mid_bool_eq_discr( + + // CHECK: %[[A_REL_DISCR:.+]] = add nsw i8 %a, -2 + // CHECK: %[[A_IS_NICHE:.+]] = icmp samesign ugt i8 %a, 1 + // CHECK: %[[A_NOT_HOLE:.+]] = icmp ne i8 %[[A_REL_DISCR]], 1 + // CHECK: tail call void @llvm.assume(i1 %[[A_NOT_HOLE]]) + // CHECK: %[[A_DISCR:.+]] = select i1 %[[A_IS_NICHE]], i8 %[[A_REL_DISCR]], i8 1 + + // CHECK: %[[B_REL_DISCR:.+]] = add nsw i8 %b, -2 + // CHECK: %[[B_IS_NICHE:.+]] = icmp samesign ugt i8 %b, 1 + // CHECK: %[[B_NOT_HOLE:.+]] = icmp ne i8 %[[B_REL_DISCR]], 1 + // CHECK: tail call void @llvm.assume(i1 %[[B_NOT_HOLE]]) + // CHECK: %[[B_DISCR:.+]] = select i1 %[[B_IS_NICHE]], i8 %[[B_REL_DISCR]], i8 1 + + // CHECK: ret i1 %[[R]] + discriminant_value(&a) == discriminant_value(&b) +} + +#[unsafe(no_mangle)] +pub fn mid_ord_eq_discr(a: Mid<Ordering>, b: Mid<Ordering>) -> bool { + // CHECK-LABEL: @mid_ord_eq_discr( + + // CHECK: %[[A_REL_DISCR:.+]] = add nsw i8 %a, -2 + // CHECK: %[[A_IS_NICHE:.+]] = icmp sgt i8 %a, 1 + // CHECK: %[[A_NOT_HOLE:.+]] = icmp ne i8 %[[A_REL_DISCR]], 1 + // CHECK: tail call void @llvm.assume(i1 %[[A_NOT_HOLE]]) + // CHECK: %[[A_DISCR:.+]] = select i1 %[[A_IS_NICHE]], i8 %[[A_REL_DISCR]], i8 1 + + // CHECK: %[[B_REL_DISCR:.+]] = add nsw i8 %b, -2 + // CHECK: %[[B_IS_NICHE:.+]] = icmp sgt i8 %b, 1 + // CHECK: %[[B_NOT_HOLE:.+]] = icmp ne i8 %[[B_REL_DISCR]], 1 + // CHECK: tail call void @llvm.assume(i1 %[[B_NOT_HOLE]]) + // CHECK: %[[B_DISCR:.+]] = select i1 %[[B_IS_NICHE]], i8 %[[B_REL_DISCR]], i8 1 + + // CHECK: %[[R:.+]] = icmp eq i8 %[[A_DISCR]], %[[B_DISCR]] + // CHECK: ret i1 %[[R]] + discriminant_value(&a) == discriminant_value(&b) +} + +#[unsafe(no_mangle)] +pub fn mid_nz32_eq_discr(a: Mid<NonZero<u32>>, b: Mid<NonZero<u32>>) -> bool { + // CHECK-LABEL: @mid_nz32_eq_discr( + // CHECK: %[[R:.+]] = icmp eq i32 %a.0, %b.0 + // CHECK: ret i1 %[[R]] + discriminant_value(&a) == discriminant_value(&b) +} + +#[unsafe(no_mangle)] +pub fn mid_ac_eq_discr(a: Mid<AC>, b: Mid<AC>) -> bool { + // CHECK-LABEL: @mid_ac_eq_discr( + + // CHECK: %[[A_REL_DISCR:.+]] = xor i8 %a, -128 + // CHECK: %[[A_IS_NICHE:.+]] = icmp slt i8 %a, 0 + // CHECK: %[[A_NOT_HOLE:.+]] = icmp ne i8 %a, -127 + // CHECK: tail call void @llvm.assume(i1 %[[A_NOT_HOLE]]) + // CHECK: %[[A_DISCR:.+]] = select i1 %[[A_IS_NICHE]], i8 %[[A_REL_DISCR]], i8 1 + + // CHECK: %[[B_REL_DISCR:.+]] = xor i8 %b, -128 + // CHECK: %[[B_IS_NICHE:.+]] = icmp slt i8 %b, 0 + // CHECK: %[[B_NOT_HOLE:.+]] = icmp ne i8 %b, -127 + // CHECK: tail call void @llvm.assume(i1 %[[B_NOT_HOLE]]) + // CHECK: %[[B_DISCR:.+]] = select i1 %[[B_IS_NICHE]], i8 %[[B_REL_DISCR]], i8 1 + + // CHECK: %[[R:.+]] = icmp eq i8 %[[A_DISCR]], %[[B_DISCR]] + // CHECK: ret i1 %[[R]] + discriminant_value(&a) == discriminant_value(&b) +} + +// FIXME: This should be improved once our LLVM fork picks up the fix for +// <https://github.com/llvm/llvm-project/issues/134024> +#[unsafe(no_mangle)] +pub fn mid_giant_eq_discr(a: Mid<Giant>, b: Mid<Giant>) -> bool { + // CHECK-LABEL: @mid_giant_eq_discr( + + // CHECK: %[[A_TRUNC:.+]] = trunc nuw nsw i128 %a to i64 + // CHECK: %[[A_REL_DISCR:.+]] = add nsw i64 %[[A_TRUNC]], -5 + // CHECK: %[[A_IS_NICHE:.+]] = icmp samesign ugt i128 %a, 4 + // CHECK: %[[A_NOT_HOLE:.+]] = icmp ne i64 %[[A_REL_DISCR]], 1 + // CHECK: tail call void @llvm.assume(i1 %[[A_NOT_HOLE]]) + // CHECK: %[[A_DISCR:.+]] = select i1 %[[A_IS_NICHE]], i64 %[[A_REL_DISCR]], i64 1 + + // CHECK: %[[B_TRUNC:.+]] = trunc nuw nsw i128 %b to i64 + // CHECK: %[[B_REL_DISCR:.+]] = add nsw i64 %[[B_TRUNC]], -5 + // CHECK: %[[B_IS_NICHE:.+]] = icmp samesign ugt i128 %b, 4 + // CHECK: %[[B_NOT_HOLE:.+]] = icmp ne i64 %[[B_REL_DISCR]], 1 + // CHECK: tail call void @llvm.assume(i1 %[[B_NOT_HOLE]]) + // CHECK: %[[B_DISCR:.+]] = select i1 %[[B_IS_NICHE]], i64 %[[B_REL_DISCR]], i64 1 + + // CHECK: %[[R:.+]] = icmp eq i64 %[[A_DISCR]], %[[B_DISCR]] + // CHECK: ret i1 %[[R]] + discriminant_value(&a) == discriminant_value(&b) +} + +// In niche-encoded enums, testing for the untagged variant should optimize to a +// straight-forward comparison looking for the natural range of the payload value. + +#[unsafe(no_mangle)] +pub fn mid_bool_is_thing(a: Mid<bool>) -> bool { + // CHECK-LABEL: @mid_bool_is_thing( + // CHECK: %[[R:.+]] = icmp samesign ult i8 %a, 2 + // CHECK: ret i1 %[[R]] + discriminant_value(&a) == 1 +} + +#[unsafe(no_mangle)] +pub fn mid_ord_is_thing(a: Mid<Ordering>) -> bool { + // CHECK-LABEL: @mid_ord_is_thing( + // CHECK: %[[R:.+]] = icmp slt i8 %a, 2 + // CHECK: ret i1 %[[R]] + discriminant_value(&a) == 1 +} + +#[unsafe(no_mangle)] +pub fn mid_nz32_is_thing(a: Mid<NonZero<u32>>) -> bool { + // CHECK-LABEL: @mid_nz32_is_thing( + // CHECK: %[[R:.+]] = icmp eq i32 %a.0, 1 + // CHECK: ret i1 %[[R]] + discriminant_value(&a) == 1 +} + +#[unsafe(no_mangle)] +pub fn mid_ac_is_thing(a: Mid<AC>) -> bool { + // CHECK-LABEL: @mid_ac_is_thing( + // CHECK: %[[R:.+]] = icmp sgt i8 %a, -1 + // CHECK: ret i1 %[[R]] + discriminant_value(&a) == 1 +} + +#[unsafe(no_mangle)] +pub fn mid_giant_is_thing(a: Mid<Giant>) -> bool { + // CHECK-LABEL: @mid_giant_is_thing( + // CHECK: %[[R:.+]] = icmp samesign ult i128 %a, 5 + // CHECK: ret i1 %[[R]] + discriminant_value(&a) == 1 +} diff --git a/tests/codegen/enum/enum-match.rs b/tests/codegen/enum/enum-match.rs index 98635008d06..57db44ec74e 100644 --- a/tests/codegen/enum/enum-match.rs +++ b/tests/codegen/enum/enum-match.rs @@ -41,7 +41,7 @@ pub enum Enum1 { // CHECK-NEXT: start: // CHECK-NEXT: %[[REL_VAR:.+]] = add{{( nsw)?}} i8 %0, -2 // CHECK-NEXT: %[[REL_VAR_WIDE:.+]] = zext i8 %[[REL_VAR]] to i64 -// CHECK-NEXT: %[[IS_NICHE:.+]] = icmp ult i8 %[[REL_VAR]], 2 +// CHECK-NEXT: %[[IS_NICHE:.+]] = icmp{{( samesign)?}} ugt i8 %0, 1 // CHECK-NEXT: %[[NICHE_DISCR:.+]] = add nuw nsw i64 %[[REL_VAR_WIDE]], 1 // CHECK-NEXT: %[[DISCR:.+]] = select i1 %[[IS_NICHE]], i64 %[[NICHE_DISCR]], i64 0 // CHECK-NEXT: switch i64 %[[DISCR]] @@ -148,10 +148,10 @@ pub enum MiddleNiche { // CHECK-LABEL: define{{( dso_local)?}} noundef{{( range\(i8 -?[0-9]+, -?[0-9]+\))?}} i8 @match4(i8{{.+}}%0) // CHECK-NEXT: start: // CHECK-NEXT: %[[REL_VAR:.+]] = add{{( nsw)?}} i8 %0, -2 -// CHECK-NEXT: %[[IS_NICHE:.+]] = icmp ult i8 %[[REL_VAR]], 5 // CHECK-NEXT: %[[NOT_IMPOSSIBLE:.+]] = icmp ne i8 %[[REL_VAR]], 2 // CHECK-NEXT: call void @llvm.assume(i1 %[[NOT_IMPOSSIBLE]]) -// CHECK-NEXT: %[[DISCR:.+]] = select i1 %[[IS_NICHE]], i8 %[[REL_VAR]], i8 2 +// CHECK-NEXT: %[[NOT_NICHE:.+]] = icmp{{( samesign)?}} ult i8 %0, 2 +// CHECK-NEXT: %[[DISCR:.+]] = select i1 %[[NOT_NICHE]], i8 2, i8 %[[REL_VAR]] // CHECK-NEXT: switch i8 %[[DISCR]] #[no_mangle] pub fn match4(e: MiddleNiche) -> u8 { @@ -167,11 +167,10 @@ pub fn match4(e: MiddleNiche) -> u8 { // CHECK-LABEL: define{{.+}}i1 @match4_is_c(i8{{.+}}%e) // CHECK-NEXT: start -// CHECK-NEXT: %[[REL_VAR:.+]] = add{{( nsw)?}} i8 %e, -2 -// CHECK-NEXT: %[[NOT_NICHE:.+]] = icmp ugt i8 %[[REL_VAR]], 4 -// CHECK-NEXT: %[[NOT_IMPOSSIBLE:.+]] = icmp ne i8 %[[REL_VAR]], 2 +// CHECK-NEXT: %[[NOT_IMPOSSIBLE:.+]] = icmp ne i8 %e, 4 // CHECK-NEXT: call void @llvm.assume(i1 %[[NOT_IMPOSSIBLE]]) -// CHECK-NEXT: ret i1 %[[NOT_NICHE]] +// CHECK-NEXT: %[[IS_C:.+]] = icmp{{( samesign)?}} ult i8 %e, 2 +// CHECK-NEXT: ret i1 %[[IS_C]] #[no_mangle] pub fn match4_is_c(e: MiddleNiche) -> bool { // Before #139098, this couldn't optimize out the `select` because it looked @@ -453,10 +452,10 @@ pub enum HugeVariantIndex { // CHECK-NEXT: start: // CHECK-NEXT: %[[REL_VAR:.+]] = add{{( nsw)?}} i8 %0, -2 // CHECK-NEXT: %[[REL_VAR_WIDE:.+]] = zext i8 %[[REL_VAR]] to i64 -// CHECK-NEXT: %[[IS_NICHE:.+]] = icmp ult i8 %[[REL_VAR]], 3 -// CHECK-NEXT: %[[NOT_IMPOSSIBLE:.+]] = icmp ne i8 %[[REL_VAR]], 1 -// CHECK-NEXT: call void @llvm.assume(i1 %[[NOT_IMPOSSIBLE]]) +// CHECK-NEXT: %[[IS_NICHE:.+]] = icmp{{( samesign)?}} ugt i8 %0, 1 // CHECK-NEXT: %[[NICHE_DISCR:.+]] = add nuw nsw i64 %[[REL_VAR_WIDE]], 257 +// CHECK-NEXT: %[[NOT_IMPOSSIBLE:.+]] = icmp ne i64 %[[NICHE_DISCR]], 258 +// CHECK-NEXT: call void @llvm.assume(i1 %[[NOT_IMPOSSIBLE]]) // CHECK-NEXT: %[[DISCR:.+]] = select i1 %[[IS_NICHE]], i64 %[[NICHE_DISCR]], i64 258 // CHECK-NEXT: switch i64 %[[DISCR]], // CHECK-NEXT: i64 257, @@ -471,3 +470,310 @@ pub fn match5(e: HugeVariantIndex) -> u8 { Possible259 => 100, } } + +// Make an enum where the niche tags wrap both as signed and as unsigned, to hit +// the most-fallback case where there's just nothing smart to do. + +pub enum E10Through65 { + D10 = 10, + D11 = 11, + D12 = 12, + D13 = 13, + D14 = 14, + D15 = 15, + D16 = 16, + D17 = 17, + D18 = 18, + D19 = 19, + D20 = 20, + D21 = 21, + D22 = 22, + D23 = 23, + D24 = 24, + D25 = 25, + D26 = 26, + D27 = 27, + D28 = 28, + D29 = 29, + D30 = 30, + D31 = 31, + D32 = 32, + D33 = 33, + D34 = 34, + D35 = 35, + D36 = 36, + D37 = 37, + D38 = 38, + D39 = 39, + D40 = 40, + D41 = 41, + D42 = 42, + D43 = 43, + D44 = 44, + D45 = 45, + D46 = 46, + D47 = 47, + D48 = 48, + D49 = 49, + D50 = 50, + D51 = 51, + D52 = 52, + D53 = 53, + D54 = 54, + D55 = 55, + D56 = 56, + D57 = 57, + D58 = 58, + D59 = 59, + D60 = 60, + D61 = 61, + D62 = 62, + D63 = 63, + D64 = 64, + D65 = 65, +} + +pub enum Tricky { + Untagged(E10Through65), + V001, + V002, + V003, + V004, + V005, + V006, + V007, + V008, + V009, + V010, + V011, + V012, + V013, + V014, + V015, + V016, + V017, + V018, + V019, + V020, + V021, + V022, + V023, + V024, + V025, + V026, + V027, + V028, + V029, + V030, + V031, + V032, + V033, + V034, + V035, + V036, + V037, + V038, + V039, + V040, + V041, + V042, + V043, + V044, + V045, + V046, + V047, + V048, + V049, + V050, + V051, + V052, + V053, + V054, + V055, + V056, + V057, + V058, + V059, + V060, + V061, + V062, + V063, + V064, + V065, + V066, + V067, + V068, + V069, + V070, + V071, + V072, + V073, + V074, + V075, + V076, + V077, + V078, + V079, + V080, + V081, + V082, + V083, + V084, + V085, + V086, + V087, + V088, + V089, + V090, + V091, + V092, + V093, + V094, + V095, + V096, + V097, + V098, + V099, + V100, + V101, + V102, + V103, + V104, + V105, + V106, + V107, + V108, + V109, + V110, + V111, + V112, + V113, + V114, + V115, + V116, + V117, + V118, + V119, + V120, + V121, + V122, + V123, + V124, + V125, + V126, + V127, + V128, + V129, + V130, + V131, + V132, + V133, + V134, + V135, + V136, + V137, + V138, + V139, + V140, + V141, + V142, + V143, + V144, + V145, + V146, + V147, + V148, + V149, + V150, + V151, + V152, + V153, + V154, + V155, + V156, + V157, + V158, + V159, + V160, + V161, + V162, + V163, + V164, + V165, + V166, + V167, + V168, + V169, + V170, + V171, + V172, + V173, + V174, + V175, + V176, + V177, + V178, + V179, + V180, + V181, + V182, + V183, + V184, + V185, + V186, + V187, + V188, + V189, + V190, + V191, + V192, + V193, + V194, + V195, + V196, + V197, + V198, + V199, + V200, +} + +const _: () = assert!(std::intrinsics::discriminant_value(&Tricky::V100) == 100); + +// CHECK-LABEL: define noundef{{( range\(i8 [0-9]+, [0-9]+\))?}} i8 @discriminant6(i8 noundef %e) +// CHECK-NEXT: start: +// CHECK-NEXT: %[[REL_VAR:.+]] = add i8 %e, -66 +// CHECK-NEXT: %[[IS_NICHE:.+]] = icmp ult i8 %[[REL_VAR]], -56 +// CHECK-NEXT: %[[TAGGED_DISCR:.+]] = add i8 %e, -65 +// CHECK-NEXT: %[[DISCR:.+]] = select i1 %[[IS_NICHE]], i8 %[[TAGGED_DISCR]], i8 0 +// CHECK-NEXT: ret i8 %[[DISCR]] +#[no_mangle] +pub fn discriminant6(e: Tricky) -> u8 { + std::intrinsics::discriminant_value(&e) as _ +} + +// Case from <https://github.com/rust-lang/rust/issues/104519>, +// where sign-extension is important. + +pub enum OpenResult { + Ok(()), + Err(()), + TransportErr(TransportErr), +} + +#[repr(i32)] +pub enum TransportErr { + UnknownMethod = -2, +} + +#[no_mangle] +pub fn match7(result: OpenResult) -> u8 { + // CHECK-LABEL: define noundef{{( range\(i8 [0-9]+, [0-9]+\))?}} i8 @match7(i32{{.+}}%result) + // CHECK-NEXT: start: + // CHECK-NEXT: %[[NOT_OK:.+]] = icmp ne i32 %result, -1 + // CHECK-NEXT: %[[RET:.+]] = zext i1 %[[NOT_OK]] to i8 + // CHECK-NEXT: ret i8 %[[RET]] + match result { + OpenResult::Ok(()) => 0, + _ => 1, + } +} diff --git a/tests/codegen/gpu_offload/gpu_host.rs b/tests/codegen/gpu_offload/gpu_host.rs new file mode 100644 index 00000000000..513e27426bc --- /dev/null +++ b/tests/codegen/gpu_offload/gpu_host.rs @@ -0,0 +1,80 @@ +//@ compile-flags: -Zoffload=Enable -Zunstable-options -C opt-level=3 -Clto=fat +//@ no-prefer-dynamic +//@ needs-enzyme + +// This test is verifying that we generate __tgt_target_data_*_mapper before and after a call to the +// kernel_1. Better documentation to what each global or variable means is available in the gpu +// offlaod code, or the LLVM offload documentation. This code does not launch any GPU kernels yet, +// and will be rewritten once a proper offload frontend has landed. +// +// We currently only handle memory transfer for specific calls to functions named `kernel_{num}`, +// when inside of a function called main. This, too, is a temporary workaround for not having a +// frontend. + +#![no_main] + +#[unsafe(no_mangle)] +fn main() { + let mut x = [3.0; 256]; + kernel_1(&mut x); + core::hint::black_box(&x); +} + +// CHECK: %struct.__tgt_offload_entry = type { i64, i16, i16, i32, ptr, ptr, i64, i64, ptr } +// CHECK: %struct.__tgt_kernel_arguments = type { i32, i32, ptr, ptr, ptr, ptr, ptr, ptr, i64, i64, [3 x i32], [3 x i32], i32 } +// CHECK: %struct.ident_t = type { i32, i32, i32, i32, ptr } +// CHECK: %struct.__tgt_bin_desc = type { i32, ptr, ptr, ptr } + +// CHECK: @.offload_sizes.1 = private unnamed_addr constant [1 x i64] [i64 1024] +// CHECK: @.offload_maptypes.1 = private unnamed_addr constant [1 x i64] [i64 3] +// CHECK: @.kernel_1.region_id = weak unnamed_addr constant i8 0 +// CHECK: @.offloading.entry_name.1 = internal unnamed_addr constant [9 x i8] c"kernel_1\00", section ".llvm.rodata.offloading", align 1 +// CHECK: @.offloading.entry.kernel_1 = weak constant %struct.__tgt_offload_entry { i64 0, i16 1, i16 1, i32 0, ptr @.kernel_1.region_id, ptr @.offloading.entry_name.1, i64 0, i64 0, ptr null }, section ".omp_offloading_entries", align 1 +// CHECK: @my_struct_global2 = external global %struct.__tgt_kernel_arguments +// CHECK: @0 = private unnamed_addr constant [23 x i8] c";unknown;unknown;0;0;;\00", align 1 +// CHECK: @1 = private unnamed_addr constant %struct.ident_t { i32 0, i32 2, i32 0, i32 22, ptr @0 }, align 8 + +// CHECK: Function Attrs: +// CHECK-NEXT: define{{( dso_local)?}} void @main() +// CHECK-NEXT: start: +// CHECK-NEXT: %0 = alloca [8 x i8], align 8 +// CHECK-NEXT: %x = alloca [1024 x i8], align 16 +// CHECK-NEXT: %EmptyDesc = alloca %struct.__tgt_bin_desc, align 8 +// CHECK-NEXT: %.offload_baseptrs = alloca [1 x ptr], align 8 +// CHECK-NEXT: %.offload_ptrs = alloca [1 x ptr], align 8 +// CHECK-NEXT: %.offload_sizes = alloca [1 x i64], align 8 +// CHECK-NEXT: %x.addr = alloca ptr, align 8 +// CHECK-NEXT: store ptr %x, ptr %x.addr, align 8 +// CHECK-NEXT: %1 = load ptr, ptr %x.addr, align 8 +// CHECK-NEXT: %2 = getelementptr inbounds float, ptr %1, i32 0 +// CHECK: call void @llvm.memset.p0.i64(ptr align 8 %EmptyDesc, i8 0, i64 32, i1 false) +// CHECK-NEXT: call void @__tgt_register_lib(ptr %EmptyDesc) +// CHECK-NEXT: call void @__tgt_init_all_rtls() +// CHECK-NEXT: %3 = getelementptr inbounds [1 x ptr], ptr %.offload_baseptrs, i32 0, i32 0 +// CHECK-NEXT: store ptr %1, ptr %3, align 8 +// CHECK-NEXT: %4 = getelementptr inbounds [1 x ptr], ptr %.offload_ptrs, i32 0, i32 0 +// CHECK-NEXT: store ptr %2, ptr %4, align 8 +// CHECK-NEXT: %5 = getelementptr inbounds [1 x i64], ptr %.offload_sizes, i32 0, i32 0 +// CHECK-NEXT: store i64 1024, ptr %5, align 8 +// CHECK-NEXT: %6 = getelementptr inbounds [1 x ptr], ptr %.offload_baseptrs, i32 0, i32 0 +// CHECK-NEXT: %7 = getelementptr inbounds [1 x ptr], ptr %.offload_ptrs, i32 0, i32 0 +// CHECK-NEXT: %8 = getelementptr inbounds [1 x i64], ptr %.offload_sizes, i32 0, i32 0 +// CHECK-NEXT: call void @__tgt_target_data_begin_mapper(ptr @1, i64 -1, i32 1, ptr %6, ptr %7, ptr %8, ptr @.offload_maptypes.1, ptr null, ptr null) +// CHECK-NEXT: call void @kernel_1(ptr noalias noundef nonnull align 4 dereferenceable(1024) %x) +// CHECK-NEXT: %9 = getelementptr inbounds [1 x ptr], ptr %.offload_baseptrs, i32 0, i32 0 +// CHECK-NEXT: %10 = getelementptr inbounds [1 x ptr], ptr %.offload_ptrs, i32 0, i32 0 +// CHECK-NEXT: %11 = getelementptr inbounds [1 x i64], ptr %.offload_sizes, i32 0, i32 0 +// CHECK-NEXT: call void @__tgt_target_data_end_mapper(ptr @1, i64 -1, i32 1, ptr %9, ptr %10, ptr %11, ptr @.offload_maptypes.1, ptr null, ptr null) +// CHECK-NEXT: call void @__tgt_unregister_lib(ptr %EmptyDesc) +// CHECK: store ptr %x, ptr %0, align 8 +// CHECK-NEXT: call void asm sideeffect "", "r,~{memory}"(ptr nonnull %0) +// CHECK: ret void +// CHECK-NEXT: } + +#[unsafe(no_mangle)] +#[inline(never)] +pub fn kernel_1(x: &mut [f32; 256]) { + for i in 0..256 { + x[i] = 21.0; + } +} diff --git a/tests/codegen/repeat-operand-zero-len.rs b/tests/codegen/repeat-operand-zero-len.rs new file mode 100644 index 00000000000..b4cec42a07c --- /dev/null +++ b/tests/codegen/repeat-operand-zero-len.rs @@ -0,0 +1,28 @@ +//@ compile-flags: -Copt-level=1 -Cno-prepopulate-passes + +// This test is here to hit the `Rvalue::Repeat` case in `codegen_rvalue_operand`. +// It only applies when the resulting array is a ZST, so the test is written in +// such a way as to keep MIR optimizations from seeing that fact and removing +// the local and statement altogether. (At the time of writing, no other codegen +// test hit that code path, nor did a stage 2 build of the compiler.) + +#![crate_type = "lib"] + +#[repr(transparent)] +pub struct Wrapper<T, const N: usize>([T; N]); + +// CHECK-LABEL: define {{.+}}do_repeat{{.+}}(i32 noundef %x) +// CHECK-NEXT: start: +// CHECK-NOT: alloca +// CHECK-NEXT: ret void +#[inline(never)] +pub fn do_repeat<T: Copy, const N: usize>(x: T) -> Wrapper<T, N> { + Wrapper([x; N]) +} + +// CHECK-LABEL: @trigger_repeat_zero_len +#[no_mangle] +pub fn trigger_repeat_zero_len() -> Wrapper<u32, 0> { + // CHECK: call void {{.+}}do_repeat{{.+}}(i32 noundef 4) + do_repeat(4) +} diff --git a/tests/codegen/repeat-operand-zst-elem.rs b/tests/codegen/repeat-operand-zst-elem.rs new file mode 100644 index 00000000000..c3637759afa --- /dev/null +++ b/tests/codegen/repeat-operand-zst-elem.rs @@ -0,0 +1,28 @@ +//@ compile-flags: -Copt-level=1 -Cno-prepopulate-passes + +// This test is here to hit the `Rvalue::Repeat` case in `codegen_rvalue_operand`. +// It only applies when the resulting array is a ZST, so the test is written in +// such a way as to keep MIR optimizations from seeing that fact and removing +// the local and statement altogether. (At the time of writing, no other codegen +// test hit that code path, nor did a stage 2 build of the compiler.) + +#![crate_type = "lib"] + +#[repr(transparent)] +pub struct Wrapper<T, const N: usize>([T; N]); + +// CHECK-LABEL: define {{.+}}do_repeat{{.+}}() +// CHECK-NEXT: start: +// CHECK-NOT: alloca +// CHECK-NEXT: ret void +#[inline(never)] +pub fn do_repeat<T: Copy, const N: usize>(x: T) -> Wrapper<T, N> { + Wrapper([x; N]) +} + +// CHECK-LABEL: @trigger_repeat_zst_elem +#[no_mangle] +pub fn trigger_repeat_zst_elem() -> Wrapper<(), 8> { + // CHECK: call void {{.+}}do_repeat{{.+}}() + do_repeat(()) +} diff --git a/tests/codegen/simd-intrinsic/simd-intrinsic-float-abs.rs b/tests/codegen/simd-intrinsic/simd-intrinsic-float-abs.rs index 485ba92272d..baf445d0a1b 100644 --- a/tests/codegen/simd-intrinsic/simd-intrinsic-float-abs.rs +++ b/tests/codegen/simd-intrinsic/simd-intrinsic-float-abs.rs @@ -4,23 +4,11 @@ #![feature(repr_simd, core_intrinsics)] #![allow(non_camel_case_types)] -use std::intrinsics::simd::simd_fabs; - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x2(pub [f32; 2]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x4(pub [f32; 4]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x8(pub [f32; 8]); +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x16(pub [f32; 16]); +use std::intrinsics::simd::simd_fabs; // CHECK-LABEL: @fabs_32x2 #[no_mangle] @@ -50,18 +38,6 @@ pub unsafe fn fabs_32x16(a: f32x16) -> f32x16 { simd_fabs(a) } -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x2(pub [f64; 2]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x4(pub [f64; 4]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x8(pub [f64; 8]); - // CHECK-LABEL: @fabs_64x4 #[no_mangle] pub unsafe fn fabs_64x4(a: f64x4) -> f64x4 { diff --git a/tests/codegen/simd-intrinsic/simd-intrinsic-float-ceil.rs b/tests/codegen/simd-intrinsic/simd-intrinsic-float-ceil.rs index e8bda7c29c4..096de569274 100644 --- a/tests/codegen/simd-intrinsic/simd-intrinsic-float-ceil.rs +++ b/tests/codegen/simd-intrinsic/simd-intrinsic-float-ceil.rs @@ -4,23 +4,11 @@ #![feature(repr_simd, core_intrinsics)] #![allow(non_camel_case_types)] -use std::intrinsics::simd::simd_ceil; - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x2(pub [f32; 2]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x4(pub [f32; 4]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x8(pub [f32; 8]); +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x16(pub [f32; 16]); +use std::intrinsics::simd::simd_ceil; // CHECK-LABEL: @ceil_32x2 #[no_mangle] @@ -50,18 +38,6 @@ pub unsafe fn ceil_32x16(a: f32x16) -> f32x16 { simd_ceil(a) } -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x2(pub [f64; 2]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x4(pub [f64; 4]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x8(pub [f64; 8]); - // CHECK-LABEL: @ceil_64x4 #[no_mangle] pub unsafe fn ceil_64x4(a: f64x4) -> f64x4 { diff --git a/tests/codegen/simd-intrinsic/simd-intrinsic-float-cos.rs b/tests/codegen/simd-intrinsic/simd-intrinsic-float-cos.rs index 8dc967bc3ad..5b2197924bc 100644 --- a/tests/codegen/simd-intrinsic/simd-intrinsic-float-cos.rs +++ b/tests/codegen/simd-intrinsic/simd-intrinsic-float-cos.rs @@ -4,23 +4,11 @@ #![feature(repr_simd, core_intrinsics)] #![allow(non_camel_case_types)] -use std::intrinsics::simd::simd_fcos; - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x2(pub [f32; 2]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x4(pub [f32; 4]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x8(pub [f32; 8]); +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x16(pub [f32; 16]); +use std::intrinsics::simd::simd_fcos; // CHECK-LABEL: @fcos_32x2 #[no_mangle] @@ -50,18 +38,6 @@ pub unsafe fn fcos_32x16(a: f32x16) -> f32x16 { simd_fcos(a) } -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x2(pub [f64; 2]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x4(pub [f64; 4]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x8(pub [f64; 8]); - // CHECK-LABEL: @fcos_64x4 #[no_mangle] pub unsafe fn fcos_64x4(a: f64x4) -> f64x4 { diff --git a/tests/codegen/simd-intrinsic/simd-intrinsic-float-exp.rs b/tests/codegen/simd-intrinsic/simd-intrinsic-float-exp.rs index 00caca2f294..d4eadb36c65 100644 --- a/tests/codegen/simd-intrinsic/simd-intrinsic-float-exp.rs +++ b/tests/codegen/simd-intrinsic/simd-intrinsic-float-exp.rs @@ -4,23 +4,11 @@ #![feature(repr_simd, core_intrinsics)] #![allow(non_camel_case_types)] -use std::intrinsics::simd::simd_fexp; - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x2(pub [f32; 2]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x4(pub [f32; 4]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x8(pub [f32; 8]); +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x16(pub [f32; 16]); +use std::intrinsics::simd::simd_fexp; // CHECK-LABEL: @exp_32x2 #[no_mangle] @@ -50,18 +38,6 @@ pub unsafe fn exp_32x16(a: f32x16) -> f32x16 { simd_fexp(a) } -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x2(pub [f64; 2]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x4(pub [f64; 4]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x8(pub [f64; 8]); - // CHECK-LABEL: @exp_64x4 #[no_mangle] pub unsafe fn exp_64x4(a: f64x4) -> f64x4 { diff --git a/tests/codegen/simd-intrinsic/simd-intrinsic-float-exp2.rs b/tests/codegen/simd-intrinsic/simd-intrinsic-float-exp2.rs index eda4053189c..d32015b7990 100644 --- a/tests/codegen/simd-intrinsic/simd-intrinsic-float-exp2.rs +++ b/tests/codegen/simd-intrinsic/simd-intrinsic-float-exp2.rs @@ -4,23 +4,11 @@ #![feature(repr_simd, core_intrinsics)] #![allow(non_camel_case_types)] -use std::intrinsics::simd::simd_fexp2; - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x2(pub [f32; 2]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x4(pub [f32; 4]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x8(pub [f32; 8]); +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x16(pub [f32; 16]); +use std::intrinsics::simd::simd_fexp2; // CHECK-LABEL: @exp2_32x2 #[no_mangle] @@ -50,18 +38,6 @@ pub unsafe fn exp2_32x16(a: f32x16) -> f32x16 { simd_fexp2(a) } -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x2(pub [f64; 2]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x4(pub [f64; 4]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x8(pub [f64; 8]); - // CHECK-LABEL: @exp2_64x4 #[no_mangle] pub unsafe fn exp2_64x4(a: f64x4) -> f64x4 { diff --git a/tests/codegen/simd-intrinsic/simd-intrinsic-float-floor.rs b/tests/codegen/simd-intrinsic/simd-intrinsic-float-floor.rs index ad69d4cdd88..1e1c8ce0c35 100644 --- a/tests/codegen/simd-intrinsic/simd-intrinsic-float-floor.rs +++ b/tests/codegen/simd-intrinsic/simd-intrinsic-float-floor.rs @@ -4,23 +4,11 @@ #![feature(repr_simd, core_intrinsics)] #![allow(non_camel_case_types)] -use std::intrinsics::simd::simd_floor; - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x2(pub [f32; 2]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x4(pub [f32; 4]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x8(pub [f32; 8]); +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x16(pub [f32; 16]); +use std::intrinsics::simd::simd_floor; // CHECK-LABEL: @floor_32x2 #[no_mangle] @@ -50,18 +38,6 @@ pub unsafe fn floor_32x16(a: f32x16) -> f32x16 { simd_floor(a) } -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x2(pub [f64; 2]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x4(pub [f64; 4]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x8(pub [f64; 8]); - // CHECK-LABEL: @floor_64x4 #[no_mangle] pub unsafe fn floor_64x4(a: f64x4) -> f64x4 { diff --git a/tests/codegen/simd-intrinsic/simd-intrinsic-float-fma.rs b/tests/codegen/simd-intrinsic/simd-intrinsic-float-fma.rs index cbeefdc31c0..982077d81f9 100644 --- a/tests/codegen/simd-intrinsic/simd-intrinsic-float-fma.rs +++ b/tests/codegen/simd-intrinsic/simd-intrinsic-float-fma.rs @@ -4,23 +4,11 @@ #![feature(repr_simd, core_intrinsics)] #![allow(non_camel_case_types)] -use std::intrinsics::simd::simd_fma; - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x2(pub [f32; 2]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x4(pub [f32; 4]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x8(pub [f32; 8]); +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x16(pub [f32; 16]); +use std::intrinsics::simd::simd_fma; // CHECK-LABEL: @fma_32x2 #[no_mangle] @@ -50,18 +38,6 @@ pub unsafe fn fma_32x16(a: f32x16, b: f32x16, c: f32x16) -> f32x16 { simd_fma(a, b, c) } -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x2(pub [f64; 2]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x4(pub [f64; 4]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x8(pub [f64; 8]); - // CHECK-LABEL: @fma_64x4 #[no_mangle] pub unsafe fn fma_64x4(a: f64x4, b: f64x4, c: f64x4) -> f64x4 { diff --git a/tests/codegen/simd-intrinsic/simd-intrinsic-float-fsqrt.rs b/tests/codegen/simd-intrinsic/simd-intrinsic-float-fsqrt.rs index 618daa4b44d..e20a591f573 100644 --- a/tests/codegen/simd-intrinsic/simd-intrinsic-float-fsqrt.rs +++ b/tests/codegen/simd-intrinsic/simd-intrinsic-float-fsqrt.rs @@ -4,23 +4,11 @@ #![feature(repr_simd, core_intrinsics)] #![allow(non_camel_case_types)] -use std::intrinsics::simd::simd_fsqrt; - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x2(pub [f32; 2]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x4(pub [f32; 4]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x8(pub [f32; 8]); +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x16(pub [f32; 16]); +use std::intrinsics::simd::simd_fsqrt; // CHECK-LABEL: @fsqrt_32x2 #[no_mangle] @@ -50,18 +38,6 @@ pub unsafe fn fsqrt_32x16(a: f32x16) -> f32x16 { simd_fsqrt(a) } -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x2(pub [f64; 2]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x4(pub [f64; 4]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x8(pub [f64; 8]); - // CHECK-LABEL: @fsqrt_64x4 #[no_mangle] pub unsafe fn fsqrt_64x4(a: f64x4) -> f64x4 { diff --git a/tests/codegen/simd-intrinsic/simd-intrinsic-float-log.rs b/tests/codegen/simd-intrinsic/simd-intrinsic-float-log.rs index 98a481e4004..bf1ffc76330 100644 --- a/tests/codegen/simd-intrinsic/simd-intrinsic-float-log.rs +++ b/tests/codegen/simd-intrinsic/simd-intrinsic-float-log.rs @@ -4,23 +4,11 @@ #![feature(repr_simd, core_intrinsics)] #![allow(non_camel_case_types)] -use std::intrinsics::simd::simd_flog; - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x2(pub [f32; 2]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x4(pub [f32; 4]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x8(pub [f32; 8]); +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x16(pub [f32; 16]); +use std::intrinsics::simd::simd_flog; // CHECK-LABEL: @log_32x2 #[no_mangle] @@ -50,18 +38,6 @@ pub unsafe fn log_32x16(a: f32x16) -> f32x16 { simd_flog(a) } -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x2(pub [f64; 2]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x4(pub [f64; 4]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x8(pub [f64; 8]); - // CHECK-LABEL: @log_64x4 #[no_mangle] pub unsafe fn log_64x4(a: f64x4) -> f64x4 { diff --git a/tests/codegen/simd-intrinsic/simd-intrinsic-float-log10.rs b/tests/codegen/simd-intrinsic/simd-intrinsic-float-log10.rs index 9108cd963f0..ccf484e0e41 100644 --- a/tests/codegen/simd-intrinsic/simd-intrinsic-float-log10.rs +++ b/tests/codegen/simd-intrinsic/simd-intrinsic-float-log10.rs @@ -4,23 +4,11 @@ #![feature(repr_simd, core_intrinsics)] #![allow(non_camel_case_types)] -use std::intrinsics::simd::simd_flog10; - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x2(pub [f32; 2]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x4(pub [f32; 4]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x8(pub [f32; 8]); +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x16(pub [f32; 16]); +use std::intrinsics::simd::simd_flog10; // CHECK-LABEL: @log10_32x2 #[no_mangle] @@ -50,18 +38,6 @@ pub unsafe fn log10_32x16(a: f32x16) -> f32x16 { simd_flog10(a) } -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x2(pub [f64; 2]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x4(pub [f64; 4]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x8(pub [f64; 8]); - // CHECK-LABEL: @log10_64x4 #[no_mangle] pub unsafe fn log10_64x4(a: f64x4) -> f64x4 { diff --git a/tests/codegen/simd-intrinsic/simd-intrinsic-float-log2.rs b/tests/codegen/simd-intrinsic/simd-intrinsic-float-log2.rs index 2b20850dbd9..677d8b01e84 100644 --- a/tests/codegen/simd-intrinsic/simd-intrinsic-float-log2.rs +++ b/tests/codegen/simd-intrinsic/simd-intrinsic-float-log2.rs @@ -4,23 +4,11 @@ #![feature(repr_simd, core_intrinsics)] #![allow(non_camel_case_types)] -use std::intrinsics::simd::simd_flog2; - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x2(pub [f32; 2]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x4(pub [f32; 4]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x8(pub [f32; 8]); +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x16(pub [f32; 16]); +use std::intrinsics::simd::simd_flog2; // CHECK-LABEL: @log2_32x2 #[no_mangle] @@ -50,18 +38,6 @@ pub unsafe fn log2_32x16(a: f32x16) -> f32x16 { simd_flog2(a) } -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x2(pub [f64; 2]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x4(pub [f64; 4]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x8(pub [f64; 8]); - // CHECK-LABEL: @log2_64x4 #[no_mangle] pub unsafe fn log2_64x4(a: f64x4) -> f64x4 { diff --git a/tests/codegen/simd-intrinsic/simd-intrinsic-float-minmax.rs b/tests/codegen/simd-intrinsic/simd-intrinsic-float-minmax.rs index ce07b212e84..8dd464a1bff 100644 --- a/tests/codegen/simd-intrinsic/simd-intrinsic-float-minmax.rs +++ b/tests/codegen/simd-intrinsic/simd-intrinsic-float-minmax.rs @@ -4,11 +4,11 @@ #![feature(repr_simd, core_intrinsics)] #![allow(non_camel_case_types)] -use std::intrinsics::simd::{simd_fmax, simd_fmin}; +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x4(pub [f32; 4]); +use std::intrinsics::simd::{simd_fmax, simd_fmin}; // CHECK-LABEL: @fmin #[no_mangle] diff --git a/tests/codegen/simd-intrinsic/simd-intrinsic-float-sin.rs b/tests/codegen/simd-intrinsic/simd-intrinsic-float-sin.rs index 7de26b415bb..48becc72c0b 100644 --- a/tests/codegen/simd-intrinsic/simd-intrinsic-float-sin.rs +++ b/tests/codegen/simd-intrinsic/simd-intrinsic-float-sin.rs @@ -4,23 +4,11 @@ #![feature(repr_simd, core_intrinsics)] #![allow(non_camel_case_types)] -use std::intrinsics::simd::simd_fsin; - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x2(pub [f32; 2]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x4(pub [f32; 4]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x8(pub [f32; 8]); +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x16(pub [f32; 16]); +use std::intrinsics::simd::simd_fsin; // CHECK-LABEL: @fsin_32x2 #[no_mangle] @@ -50,18 +38,6 @@ pub unsafe fn fsin_32x16(a: f32x16) -> f32x16 { simd_fsin(a) } -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x2(pub [f64; 2]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x4(pub [f64; 4]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f64x8(pub [f64; 8]); - // CHECK-LABEL: @fsin_64x4 #[no_mangle] pub unsafe fn fsin_64x4(a: f64x4) -> f64x4 { diff --git a/tests/codegen/simd-intrinsic/simd-intrinsic-generic-arithmetic-saturating.rs b/tests/codegen/simd-intrinsic/simd-intrinsic-generic-arithmetic-saturating.rs index ecf5eb24ee5..06d46889715 100644 --- a/tests/codegen/simd-intrinsic/simd-intrinsic-generic-arithmetic-saturating.rs +++ b/tests/codegen/simd-intrinsic/simd-intrinsic-generic-arithmetic-saturating.rs @@ -5,66 +5,11 @@ #![allow(non_camel_case_types)] #![deny(unused)] -use std::intrinsics::simd::{simd_saturating_add, simd_saturating_sub}; - -#[rustfmt::skip] -mod types { - // signed integer types - - #[repr(simd)] #[derive(Copy, Clone)] pub struct i8x2([i8; 2]); - #[repr(simd)] #[derive(Copy, Clone)] pub struct i8x4([i8; 4]); - #[repr(simd)] #[derive(Copy, Clone)] pub struct i8x8([i8; 8]); - #[repr(simd)] #[derive(Copy, Clone)] pub struct i8x16([i8; 16]); - #[repr(simd)] #[derive(Copy, Clone)] pub struct i8x32([i8; 32]); - #[repr(simd)] #[derive(Copy, Clone)] pub struct i8x64([i8; 64]); - - #[repr(simd)] #[derive(Copy, Clone)] pub struct i16x2([i16; 2]); - #[repr(simd)] #[derive(Copy, Clone)] pub struct i16x4([i16; 4]); - #[repr(simd)] #[derive(Copy, Clone)] pub struct i16x8([i16; 8]); - #[repr(simd)] #[derive(Copy, Clone)] pub struct i16x16([i16; 16]); - #[repr(simd)] #[derive(Copy, Clone)] pub struct i16x32([i16; 32]); - - #[repr(simd)] #[derive(Copy, Clone)] pub struct i32x2([i32; 2]); - #[repr(simd)] #[derive(Copy, Clone)] pub struct i32x4([i32; 4]); - #[repr(simd)] #[derive(Copy, Clone)] pub struct i32x8([i32; 8]); - #[repr(simd)] #[derive(Copy, Clone)] pub struct i32x16([i32; 16]); - - #[repr(simd)] #[derive(Copy, Clone)] pub struct i64x2([i64; 2]); - #[repr(simd)] #[derive(Copy, Clone)] pub struct i64x4([i64; 4]); - #[repr(simd)] #[derive(Copy, Clone)] pub struct i64x8([i64; 8]); - - #[repr(simd)] #[derive(Copy, Clone)] pub struct i128x2([i128; 2]); - #[repr(simd)] #[derive(Copy, Clone)] pub struct i128x4([i128; 4]); - - // unsigned integer types +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; - #[repr(simd)] #[derive(Copy, Clone)] pub struct u8x2([u8; 2]); - #[repr(simd)] #[derive(Copy, Clone)] pub struct u8x4([u8; 4]); - #[repr(simd)] #[derive(Copy, Clone)] pub struct u8x8([u8; 8]); - #[repr(simd)] #[derive(Copy, Clone)] pub struct u8x16([u8; 16]); - #[repr(simd)] #[derive(Copy, Clone)] pub struct u8x32([u8; 32]); - #[repr(simd)] #[derive(Copy, Clone)] pub struct u8x64([u8; 64]); - - #[repr(simd)] #[derive(Copy, Clone)] pub struct u16x2([u16; 2]); - #[repr(simd)] #[derive(Copy, Clone)] pub struct u16x4([u16; 4]); - #[repr(simd)] #[derive(Copy, Clone)] pub struct u16x8([u16; 8]); - #[repr(simd)] #[derive(Copy, Clone)] pub struct u16x16([u16; 16]); - #[repr(simd)] #[derive(Copy, Clone)] pub struct u16x32([u16; 32]); - - #[repr(simd)] #[derive(Copy, Clone)] pub struct u32x2([u32; 2]); - #[repr(simd)] #[derive(Copy, Clone)] pub struct u32x4([u32; 4]); - #[repr(simd)] #[derive(Copy, Clone)] pub struct u32x8([u32; 8]); - #[repr(simd)] #[derive(Copy, Clone)] pub struct u32x16([u32; 16]); - - #[repr(simd)] #[derive(Copy, Clone)] pub struct u64x2([u64; 2]); - #[repr(simd)] #[derive(Copy, Clone)] pub struct u64x4([u64; 4]); - #[repr(simd)] #[derive(Copy, Clone)] pub struct u64x8([u64; 8]); - - #[repr(simd)] #[derive(Copy, Clone)] pub struct u128x2([u128; 2]); - #[repr(simd)] #[derive(Copy, Clone)] pub struct u128x4([u128; 4]); -} - -use types::*; +use std::intrinsics::simd::{simd_saturating_add, simd_saturating_sub}; // NOTE(eddyb) `%{{x|0}}` is used because on some targets (e.g. WASM) // SIMD vectors are passed directly, resulting in `%x` being a vector, diff --git a/tests/codegen/simd-intrinsic/simd-intrinsic-generic-bitmask.rs b/tests/codegen/simd-intrinsic/simd-intrinsic-generic-bitmask.rs index a2c40aa91b5..294262d8152 100644 --- a/tests/codegen/simd-intrinsic/simd-intrinsic-generic-bitmask.rs +++ b/tests/codegen/simd-intrinsic/simd-intrinsic-generic-bitmask.rs @@ -5,19 +5,11 @@ #![feature(repr_simd, core_intrinsics)] #![allow(non_camel_case_types)] -use std::intrinsics::simd::simd_bitmask; - -#[repr(simd)] -#[derive(Copy, Clone)] -pub struct u32x2([u32; 2]); +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; -#[repr(simd)] -#[derive(Copy, Clone)] -pub struct i32x2([i32; 2]); - -#[repr(simd)] -#[derive(Copy, Clone)] -pub struct i8x16([i8; 16]); +use std::intrinsics::simd::simd_bitmask; // NOTE(eddyb) `%{{x|1}}` is used because on some targets (e.g. WASM) // SIMD vectors are passed directly, resulting in `%x` being a vector, diff --git a/tests/codegen/simd-intrinsic/simd-intrinsic-generic-gather.rs b/tests/codegen/simd-intrinsic/simd-intrinsic-generic-gather.rs index c06b36d68b9..690bfb432f9 100644 --- a/tests/codegen/simd-intrinsic/simd-intrinsic-generic-gather.rs +++ b/tests/codegen/simd-intrinsic/simd-intrinsic-generic-gather.rs @@ -6,15 +6,14 @@ #![feature(repr_simd, core_intrinsics)] #![allow(non_camel_case_types)] -use std::intrinsics::simd::simd_gather; +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct Vec2<T>(pub [T; 2]); +use std::intrinsics::simd::simd_gather; -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct Vec4<T>(pub [T; 4]); +pub type Vec2<T> = Simd<T, 2>; +pub type Vec4<T> = Simd<T, 4>; // CHECK-LABEL: @gather_f32x2 #[no_mangle] diff --git a/tests/codegen/simd-intrinsic/simd-intrinsic-generic-masked-load.rs b/tests/codegen/simd-intrinsic/simd-intrinsic-generic-masked-load.rs index 21578e67cff..fda315dc66c 100644 --- a/tests/codegen/simd-intrinsic/simd-intrinsic-generic-masked-load.rs +++ b/tests/codegen/simd-intrinsic/simd-intrinsic-generic-masked-load.rs @@ -4,15 +4,14 @@ #![feature(repr_simd, core_intrinsics)] #![allow(non_camel_case_types)] -use std::intrinsics::simd::simd_masked_load; +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct Vec2<T>(pub [T; 2]); +use std::intrinsics::simd::simd_masked_load; -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct Vec4<T>(pub [T; 4]); +pub type Vec2<T> = Simd<T, 2>; +pub type Vec4<T> = Simd<T, 4>; // CHECK-LABEL: @load_f32x2 #[no_mangle] diff --git a/tests/codegen/simd-intrinsic/simd-intrinsic-generic-masked-store.rs b/tests/codegen/simd-intrinsic/simd-intrinsic-generic-masked-store.rs index 22a8f7e54bd..6ca7388d464 100644 --- a/tests/codegen/simd-intrinsic/simd-intrinsic-generic-masked-store.rs +++ b/tests/codegen/simd-intrinsic/simd-intrinsic-generic-masked-store.rs @@ -4,15 +4,14 @@ #![feature(repr_simd, core_intrinsics)] #![allow(non_camel_case_types)] -use std::intrinsics::simd::simd_masked_store; +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct Vec2<T>(pub [T; 2]); +use std::intrinsics::simd::simd_masked_store; -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct Vec4<T>(pub [T; 4]); +pub type Vec2<T> = Simd<T, 2>; +pub type Vec4<T> = Simd<T, 4>; // CHECK-LABEL: @store_f32x2 #[no_mangle] diff --git a/tests/codegen/simd-intrinsic/simd-intrinsic-generic-scatter.rs b/tests/codegen/simd-intrinsic/simd-intrinsic-generic-scatter.rs index 0cc9e6ae59a..743652966e1 100644 --- a/tests/codegen/simd-intrinsic/simd-intrinsic-generic-scatter.rs +++ b/tests/codegen/simd-intrinsic/simd-intrinsic-generic-scatter.rs @@ -6,15 +6,14 @@ #![feature(repr_simd, core_intrinsics)] #![allow(non_camel_case_types)] -use std::intrinsics::simd::simd_scatter; +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct Vec2<T>(pub [T; 2]); +use std::intrinsics::simd::simd_scatter; -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct Vec4<T>(pub [T; 4]); +pub type Vec2<T> = Simd<T, 2>; +pub type Vec4<T> = Simd<T, 4>; // CHECK-LABEL: @scatter_f32x2 #[no_mangle] diff --git a/tests/codegen/simd-intrinsic/simd-intrinsic-generic-select.rs b/tests/codegen/simd-intrinsic/simd-intrinsic-generic-select.rs index f6531c1b23a..2c0bad21f44 100644 --- a/tests/codegen/simd-intrinsic/simd-intrinsic-generic-select.rs +++ b/tests/codegen/simd-intrinsic/simd-intrinsic-generic-select.rs @@ -4,27 +4,13 @@ #![feature(repr_simd, core_intrinsics)] #![allow(non_camel_case_types)] -use std::intrinsics::simd::{simd_select, simd_select_bitmask}; - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x4(pub [f32; 4]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct f32x8([f32; 8]); +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct b8x4(pub [i8; 4]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct i32x4([i32; 4]); +use std::intrinsics::simd::{simd_select, simd_select_bitmask}; -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -pub struct u32x4([u32; 4]); +pub type b8x4 = i8x4; // CHECK-LABEL: @select_m8 #[no_mangle] diff --git a/tests/codegen/simd-intrinsic/simd-intrinsic-mask-reduce.rs b/tests/codegen/simd-intrinsic/simd-intrinsic-mask-reduce.rs index 269fe41225e..79f00a6ed60 100644 --- a/tests/codegen/simd-intrinsic/simd-intrinsic-mask-reduce.rs +++ b/tests/codegen/simd-intrinsic/simd-intrinsic-mask-reduce.rs @@ -4,15 +4,14 @@ #![feature(repr_simd, core_intrinsics)] #![allow(non_camel_case_types)] -use std::intrinsics::simd::{simd_reduce_all, simd_reduce_any}; +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; -#[repr(simd)] -#[derive(Copy, Clone)] -pub struct mask32x2([i32; 2]); +use std::intrinsics::simd::{simd_reduce_all, simd_reduce_any}; -#[repr(simd)] -#[derive(Copy, Clone)] -pub struct mask8x16([i8; 16]); +pub type mask32x2 = Simd<i32, 2>; +pub type mask8x16 = Simd<i8, 16>; // NOTE(eddyb) `%{{x|1}}` is used because on some targets (e.g. WASM) // SIMD vectors are passed directly, resulting in `%x` being a vector, diff --git a/tests/codegen/simd-intrinsic/simd-intrinsic-transmute-array.rs b/tests/codegen/simd-intrinsic/simd-intrinsic-transmute-array.rs index 301f06c2d74..05c2f7e1bdf 100644 --- a/tests/codegen/simd-intrinsic/simd-intrinsic-transmute-array.rs +++ b/tests/codegen/simd-intrinsic/simd-intrinsic-transmute-array.rs @@ -8,13 +8,12 @@ #![allow(non_camel_case_types)] #![feature(repr_simd, core_intrinsics)] -#[repr(simd)] -#[derive(Copy, Clone)] -pub struct S<const N: usize>([f32; N]); +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; -#[repr(simd)] -#[derive(Copy, Clone)] -pub struct T([f32; 4]); +pub type S<const N: usize> = Simd<f32, N>; +pub type T = Simd<f32, 4>; // CHECK-LABEL: @array_align( #[no_mangle] @@ -34,7 +33,7 @@ pub fn vector_align() -> usize { #[no_mangle] pub fn build_array_s(x: [f32; 4]) -> S<4> { // CHECK: call void @llvm.memcpy.{{.+}}({{.*}} align [[VECTOR_ALIGN]] {{.*}} align [[ARRAY_ALIGN]] {{.*}}, [[USIZE]] 16, i1 false) - S::<4>(x) + Simd(x) } // CHECK-LABEL: @build_array_transmute_s @@ -48,7 +47,7 @@ pub fn build_array_transmute_s(x: [f32; 4]) -> S<4> { #[no_mangle] pub fn build_array_t(x: [f32; 4]) -> T { // CHECK: call void @llvm.memcpy.{{.+}}({{.*}} align [[VECTOR_ALIGN]] {{.*}} align [[ARRAY_ALIGN]] {{.*}}, [[USIZE]] 16, i1 false) - T(x) + Simd(x) } // CHECK-LABEL: @build_array_transmute_t diff --git a/tests/codegen/simd/aggregate-simd.rs b/tests/codegen/simd/aggregate-simd.rs index 065e429a4c7..57a301d634c 100644 --- a/tests/codegen/simd/aggregate-simd.rs +++ b/tests/codegen/simd/aggregate-simd.rs @@ -5,15 +5,11 @@ #![no_std] #![crate_type = "lib"] +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; use core::intrinsics::simd::{simd_add, simd_extract}; -#[repr(simd)] -#[derive(Clone, Copy)] -pub struct Simd<T, const N: usize>([T; N]); - -#[repr(simd, packed)] -#[derive(Clone, Copy)] -pub struct PackedSimd<T, const N: usize>([T; N]); +use minisimd::*; #[repr(transparent)] pub struct Transparent<T>(T); diff --git a/tests/codegen/simd/packed-simd.rs b/tests/codegen/simd/packed-simd.rs index 73e0d29d7d6..70c03fcc955 100644 --- a/tests/codegen/simd/packed-simd.rs +++ b/tests/codegen/simd/packed-simd.rs @@ -9,18 +9,14 @@ use core::intrinsics::simd as intrinsics; use core::{mem, ptr}; +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::{PackedSimd, Simd as FullSimd}; + // Test codegen for not only "packed" but also "fully aligned" SIMD types, and conversion between // them. A repr(packed,simd) type with 3 elements can't exceed its element alignment, whereas the // same type as repr(simd) will instead have padding. -#[repr(simd, packed)] -#[derive(Copy, Clone)] -pub struct PackedSimd<T, const N: usize>([T; N]); - -#[repr(simd)] -#[derive(Copy, Clone)] -pub struct FullSimd<T, const N: usize>([T; N]); - // non-powers-of-two have padding and need to be expanded to full vectors fn load<T, const N: usize>(v: PackedSimd<T, N>) -> FullSimd<T, N> { unsafe { diff --git a/tests/codegen/simd/project-to-simd-array-field.rs b/tests/codegen/simd/project-to-simd-array-field.rs deleted file mode 100644 index 29fab640633..00000000000 --- a/tests/codegen/simd/project-to-simd-array-field.rs +++ /dev/null @@ -1,31 +0,0 @@ -//@compile-flags: -Copt-level=3 - -#![crate_type = "lib"] -#![feature(repr_simd, core_intrinsics)] - -#[allow(non_camel_case_types)] -#[derive(Clone, Copy)] -#[repr(simd)] -struct i32x4([i32; 4]); - -#[inline(always)] -fn to_array4(a: i32x4) -> [i32; 4] { - a.0 -} - -// CHECK-LABEL: simd_add_self_then_return_array( -// CHECK-SAME: ptr{{.+}}sret{{.+}}%[[RET:.+]], -// CHECK-SAME: ptr{{.+}}%a) -#[no_mangle] -pub fn simd_add_self_then_return_array(a: &i32x4) -> [i32; 4] { - // It would be nice to just ban `.0` into simd types, - // but until we do this has to keep working. - // See also <https://github.com/rust-lang/rust/issues/105439> - - // CHECK: %[[T1:.+]] = load <4 x i32>, ptr %a - // CHECK: %[[T2:.+]] = shl <4 x i32> %[[T1]], {{splat \(i32 1\)|<i32 1, i32 1, i32 1, i32 1>}} - // CHECK: store <4 x i32> %[[T2]], ptr %[[RET]] - let a = *a; - let b = unsafe { core::intrinsics::simd::simd_add(a, a) }; - to_array4(b) -} diff --git a/tests/codegen/simd/simd_arith_offset.rs b/tests/codegen/simd/simd_arith_offset.rs index b8af6fce332..210b4e9bb50 100644 --- a/tests/codegen/simd/simd_arith_offset.rs +++ b/tests/codegen/simd/simd_arith_offset.rs @@ -5,16 +5,14 @@ #![crate_type = "lib"] #![feature(repr_simd, core_intrinsics)] +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; use std::intrinsics::simd::simd_arith_offset; -/// A vector of *const T. -#[derive(Debug, Copy, Clone)] -#[repr(simd)] -pub struct SimdConstPtr<T, const LANES: usize>([*const T; LANES]); +use minisimd::*; -#[derive(Debug, Copy, Clone)] -#[repr(simd)] -pub struct Simd<T, const LANES: usize>([T; LANES]); +/// A vector of *const T. +pub type SimdConstPtr<T, const LANES: usize> = Simd<*const T, LANES>; // CHECK-LABEL: smoke #[no_mangle] diff --git a/tests/mir-opt/inline_double_cycle.a.Inline.panic-abort.diff b/tests/mir-opt/inline_double_cycle.a.Inline.panic-abort.diff new file mode 100644 index 00000000000..90a4a509ac1 --- /dev/null +++ b/tests/mir-opt/inline_double_cycle.a.Inline.panic-abort.diff @@ -0,0 +1,48 @@ +- // MIR for `a` before Inline ++ // MIR for `a` after Inline + + fn a() -> () { + let mut _0: (); + let _1: (); + let mut _2: (); + let _3: (); + let mut _4: (); ++ let mut _5: fn() {a}; ++ let mut _6: fn() {b}; ++ scope 1 (inlined <fn() {a} as FnOnce<()>>::call_once - shim(fn() {a})) { ++ } ++ scope 2 (inlined <fn() {b} as FnOnce<()>>::call_once - shim(fn() {b})) { ++ } + + bb0: { + StorageLive(_1); + StorageLive(_2); + _2 = (); +- _1 = <fn() {a} as FnOnce<()>>::call_once(a, move _2) -> [return: bb1, unwind unreachable]; ++ StorageLive(_5); ++ _5 = a; ++ _1 = move _5() -> [return: bb1, unwind unreachable]; + } + + bb1: { ++ StorageDead(_5); + StorageDead(_2); + StorageDead(_1); + StorageLive(_3); + StorageLive(_4); + _4 = (); +- _3 = <fn() {b} as FnOnce<()>>::call_once(b, move _4) -> [return: bb2, unwind unreachable]; ++ StorageLive(_6); ++ _6 = b; ++ _3 = move _6() -> [return: bb2, unwind unreachable]; + } + + bb2: { ++ StorageDead(_6); + StorageDead(_4); + StorageDead(_3); + _0 = const (); + return; + } + } + diff --git a/tests/mir-opt/inline_double_cycle.a.Inline.panic-unwind.diff b/tests/mir-opt/inline_double_cycle.a.Inline.panic-unwind.diff new file mode 100644 index 00000000000..55da685a3d4 --- /dev/null +++ b/tests/mir-opt/inline_double_cycle.a.Inline.panic-unwind.diff @@ -0,0 +1,48 @@ +- // MIR for `a` before Inline ++ // MIR for `a` after Inline + + fn a() -> () { + let mut _0: (); + let _1: (); + let mut _2: (); + let _3: (); + let mut _4: (); ++ let mut _5: fn() {a}; ++ let mut _6: fn() {b}; ++ scope 1 (inlined <fn() {a} as FnOnce<()>>::call_once - shim(fn() {a})) { ++ } ++ scope 2 (inlined <fn() {b} as FnOnce<()>>::call_once - shim(fn() {b})) { ++ } + + bb0: { + StorageLive(_1); + StorageLive(_2); + _2 = (); +- _1 = <fn() {a} as FnOnce<()>>::call_once(a, move _2) -> [return: bb1, unwind continue]; ++ StorageLive(_5); ++ _5 = a; ++ _1 = move _5() -> [return: bb1, unwind continue]; + } + + bb1: { ++ StorageDead(_5); + StorageDead(_2); + StorageDead(_1); + StorageLive(_3); + StorageLive(_4); + _4 = (); +- _3 = <fn() {b} as FnOnce<()>>::call_once(b, move _4) -> [return: bb2, unwind continue]; ++ StorageLive(_6); ++ _6 = b; ++ _3 = move _6() -> [return: bb2, unwind continue]; + } + + bb2: { ++ StorageDead(_6); + StorageDead(_4); + StorageDead(_3); + _0 = const (); + return; + } + } + diff --git a/tests/mir-opt/inline_double_cycle.b.Inline.panic-abort.diff b/tests/mir-opt/inline_double_cycle.b.Inline.panic-abort.diff new file mode 100644 index 00000000000..2090411276c --- /dev/null +++ b/tests/mir-opt/inline_double_cycle.b.Inline.panic-abort.diff @@ -0,0 +1,48 @@ +- // MIR for `b` before Inline ++ // MIR for `b` after Inline + + fn b() -> () { + let mut _0: (); + let _1: (); + let mut _2: (); + let _3: (); + let mut _4: (); ++ let mut _5: fn() {b}; ++ let mut _6: fn() {a}; ++ scope 1 (inlined <fn() {b} as FnOnce<()>>::call_once - shim(fn() {b})) { ++ } ++ scope 2 (inlined <fn() {a} as FnOnce<()>>::call_once - shim(fn() {a})) { ++ } + + bb0: { + StorageLive(_1); + StorageLive(_2); + _2 = (); +- _1 = <fn() {b} as FnOnce<()>>::call_once(b, move _2) -> [return: bb1, unwind unreachable]; ++ StorageLive(_5); ++ _5 = b; ++ _1 = move _5() -> [return: bb1, unwind unreachable]; + } + + bb1: { ++ StorageDead(_5); + StorageDead(_2); + StorageDead(_1); + StorageLive(_3); + StorageLive(_4); + _4 = (); +- _3 = <fn() {a} as FnOnce<()>>::call_once(a, move _4) -> [return: bb2, unwind unreachable]; ++ StorageLive(_6); ++ _6 = a; ++ _3 = move _6() -> [return: bb2, unwind unreachable]; + } + + bb2: { ++ StorageDead(_6); + StorageDead(_4); + StorageDead(_3); + _0 = const (); + return; + } + } + diff --git a/tests/mir-opt/inline_double_cycle.b.Inline.panic-unwind.diff b/tests/mir-opt/inline_double_cycle.b.Inline.panic-unwind.diff new file mode 100644 index 00000000000..9e6eef1fa30 --- /dev/null +++ b/tests/mir-opt/inline_double_cycle.b.Inline.panic-unwind.diff @@ -0,0 +1,48 @@ +- // MIR for `b` before Inline ++ // MIR for `b` after Inline + + fn b() -> () { + let mut _0: (); + let _1: (); + let mut _2: (); + let _3: (); + let mut _4: (); ++ let mut _5: fn() {b}; ++ let mut _6: fn() {a}; ++ scope 1 (inlined <fn() {b} as FnOnce<()>>::call_once - shim(fn() {b})) { ++ } ++ scope 2 (inlined <fn() {a} as FnOnce<()>>::call_once - shim(fn() {a})) { ++ } + + bb0: { + StorageLive(_1); + StorageLive(_2); + _2 = (); +- _1 = <fn() {b} as FnOnce<()>>::call_once(b, move _2) -> [return: bb1, unwind continue]; ++ StorageLive(_5); ++ _5 = b; ++ _1 = move _5() -> [return: bb1, unwind continue]; + } + + bb1: { ++ StorageDead(_5); + StorageDead(_2); + StorageDead(_1); + StorageLive(_3); + StorageLive(_4); + _4 = (); +- _3 = <fn() {a} as FnOnce<()>>::call_once(a, move _4) -> [return: bb2, unwind continue]; ++ StorageLive(_6); ++ _6 = a; ++ _3 = move _6() -> [return: bb2, unwind continue]; + } + + bb2: { ++ StorageDead(_6); + StorageDead(_4); + StorageDead(_3); + _0 = const (); + return; + } + } + diff --git a/tests/mir-opt/inline_double_cycle.rs b/tests/mir-opt/inline_double_cycle.rs new file mode 100644 index 00000000000..cf3b87cf0ad --- /dev/null +++ b/tests/mir-opt/inline_double_cycle.rs @@ -0,0 +1,22 @@ +// EMIT_MIR_FOR_EACH_PANIC_STRATEGY +// skip-filecheck +//@ test-mir-pass: Inline +//@ edition: 2021 +//@ compile-flags: -Zinline-mir --crate-type=lib + +// EMIT_MIR inline_double_cycle.a.Inline.diff +// EMIT_MIR inline_double_cycle.b.Inline.diff + +#![feature(fn_traits)] + +#[inline] +pub fn a() { + FnOnce::call_once(a, ()); + FnOnce::call_once(b, ()); +} + +#[inline] +pub fn b() { + FnOnce::call_once(b, ()); + FnOnce::call_once(a, ()); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/README.md b/tests/run-make/autodiff/type-trees/type-analysis/README.md new file mode 100644 index 00000000000..c712edfaf50 --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/README.md @@ -0,0 +1,13 @@ +# Autodiff Type-Trees Type Analysis Tests + +This directory contains run-make tests for the autodiff type-trees type analysis functionality. These tests verify that the autodiff compiler correctly analyzes and tracks type information for different Rust types during automatic differentiation. + +## What These Tests Do + +Each test compiles a simple Rust function with the `#[autodiff_reverse]` attribute and verifies that the compiler: + +1. **Correctly identifies type information** in the generated LLVM IR +2. **Tracks type annotations** for variables and operations +3. **Preserves type context** through the autodiff transformation process + +The tests capture the stdout from the autodiff compiler (which contains type analysis information) and verify it matches expected patterns using FileCheck. diff --git a/tests/run-make/autodiff/type-trees/type-analysis/array/array.check b/tests/run-make/autodiff/type-trees/type-analysis/array/array.check new file mode 100644 index 00000000000..6e4197692a7 --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/array/array.check @@ -0,0 +1,26 @@ +// CHECK: callee - {[-1]:Float@float} |{[-1]:Pointer}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Float@float, [-1,4]:Float@float, [-1,8]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = load float, ptr %{{[0-9]+}}, align 4, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = fmul float %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = getelementptr inbounds nuw i8, ptr %{{[0-9]+}}, i64 4, !dbg !{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Float@float, [-1,4]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = load float, ptr %{{[0-9]+}}, align 4, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = fmul float %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = fadd float %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = getelementptr inbounds nuw i8, ptr %{{[0-9]+}}, i64 8, !dbg !{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = load float, ptr %{{[0-9]+}}, align 4, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = fmul float %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = fadd float %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: ret float %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK: callee - {[-1]:Float@float} |{[-1]:Pointer, [-1,0]:Float@float, [-1,4]:Float@float, [-1,8]:Float@float}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Float@float, [-1,4]:Float@float, [-1,8]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = load float, ptr %{{[0-9]+}}, align 4, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = fmul float %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = getelementptr inbounds nuw i8, ptr %{{[0-9]+}}, i64 4, !dbg !{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Float@float, [-1,4]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = load float, ptr %{{[0-9]+}}, align 4, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = fmul float %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = fadd float %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = getelementptr inbounds nuw i8, ptr %{{[0-9]+}}, i64 8, !dbg !{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = load float, ptr %{{[0-9]+}}, align 4, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = fmul float %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = fadd float %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: ret float %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} \ No newline at end of file diff --git a/tests/run-make/autodiff/type-trees/type-analysis/array/array.rs b/tests/run-make/autodiff/type-trees/type-analysis/array/array.rs new file mode 100644 index 00000000000..9a859418b10 --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/array/array.rs @@ -0,0 +1,20 @@ +#![feature(autodiff)] + +use std::autodiff::autodiff_reverse; + +#[autodiff_reverse(d_square, Duplicated, Active)] +#[no_mangle] +fn callee(x: &[f32; 3]) -> f32 { + x[0] * x[0] + x[1] * x[1] + x[2] * x[2] +} + +fn main() { + let x = [1.0f32, 2.0, 3.0]; + let mut df_dx = [0.0f32; 3]; + let out = callee(&x); + let out_ = d_square(&x, &mut df_dx, 1.0); + assert_eq!(out, out_); + assert_eq!(2.0, df_dx[0]); + assert_eq!(4.0, df_dx[1]); + assert_eq!(6.0, df_dx[2]); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/array/rmake.rs b/tests/run-make/autodiff/type-trees/type-analysis/array/rmake.rs new file mode 100644 index 00000000000..d68ab46bb94 --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/array/rmake.rs @@ -0,0 +1,28 @@ +//@ needs-enzyme +//@ ignore-cross-compile + +use std::fs; + +use run_make_support::{llvm_filecheck, rfs, rustc}; + +fn main() { + // Compile the Rust file with the required flags, capturing both stdout and stderr + let output = rustc() + .input("array.rs") + .arg("-Zautodiff=Enable,PrintTAFn=callee") + .arg("-Zautodiff=NoPostopt") + .opt_level("3") + .arg("-Clto=fat") + .arg("-g") + .run(); + + let stdout = output.stdout_utf8(); + let stderr = output.stderr_utf8(); + + // Write the outputs to files + rfs::write("array.stdout", stdout); + rfs::write("array.stderr", stderr); + + // Run FileCheck on the stdout using the check file + llvm_filecheck().patterns("array.check").stdin_buf(rfs::read("array.stdout")).run(); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/array3d/array3d.check b/tests/run-make/autodiff/type-trees/type-analysis/array3d/array3d.check new file mode 100644 index 00000000000..ed81ad4869a --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/array3d/array3d.check @@ -0,0 +1,54 @@ +// CHECK: callee - {[-1]:Float@float} |{[-1]:Pointer}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Float@float} +// CHECK-DAG: br label %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK-DAG: %{{[0-9]+}} = phi float [ %{{[0-9]+}}, %{{[0-9]+}} ], !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: br i1 %{{[0-9]+}}, label %{{[0-9]+}}, label %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK-DAG: %{{[0-9]+}} = phi float [ %{{[0-9]+}}, %{{[0-9]+}} ], !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: ret float %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK-DAG: %{{[0-9]+}} = phi float [ 0.000000e+00, %{{[0-9]+}} ], [ %{{[0-9]+}}, %{{[0-9]+}} ]: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = phi i1 [ true, %{{[0-9]+}} ], [ false, %{{[0-9]+}} ]: {[-1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = phi i64 [ 0, %{{[0-9]+}} ], [ 1, %{{[0-9]+}} ]: {[-1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = getelementptr inbounds nuw [2 x [2 x float]], ptr %{{[0-9]+}}, i64 %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Float@float} +// CHECK-DAG: br label %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK-DAG: %{{[0-9]+}} = phi float [ %{{[0-9]+}}, %{{[0-9]+}} ], !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: br i1 %{{[0-9]+}}, label %{{[0-9]+}}, label %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK-DAG: %{{[0-9]+}} = phi float [ %{{[0-9]+}}, %{{[0-9]+}} ], [ %{{[0-9]+}}, %{{[0-9]+}} ]: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = phi i1 [ true, %{{[0-9]+}} ], [ false, %{{[0-9]+}} ]: {[-1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = phi i64 [ 0, %{{[0-9]+}} ], [ 1, %{{[0-9]+}} ]: {[-1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = getelementptr inbounds nuw [2 x float], ptr %{{[0-9]+}}, i64 %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Float@float} +// CHECK-DAG: br label %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK-DAG: %{{[0-9]+}} = phi float [ %{{[0-9]+}}, %{{[0-9]+}} ], [ %{{[0-9]+}}, %{{[0-9]+}} ]: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = phi i1 [ true, %{{[0-9]+}} ], [ false, %{{[0-9]+}} ]: {[-1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = phi i64 [ 0, %{{[0-9]+}} ], [ 1, %{{[0-9]+}} ]: {[-1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = getelementptr inbounds nuw float, ptr %{{[0-9]+}}, i64 %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = load float, ptr %{{[0-9]+}}, align 4, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = fmul float %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = fadd float %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: br i1 %{{[0-9]+}}, label %{{[0-9]+}}, label %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK: callee - {[-1]:Float@float} |{[-1]:Pointer, [-1,0]:Float@float}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Float@float} +// CHECK-DAG: br label %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK-DAG: %{{[0-9]+}} = phi float [ %{{[0-9]+}}, %{{[0-9]+}} ], !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: br i1 %{{[0-9]+}}, label %{{[0-9]+}}, label %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK-DAG: %{{[0-9]+}} = phi float [ %{{[0-9]+}}, %{{[0-9]+}} ], !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: ret float %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK-DAG: %{{[0-9]+}} = phi float [ 0.000000e+00, %{{[0-9]+}} ], [ %{{[0-9]+}}, %{{[0-9]+}} ]: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = phi i1 [ true, %{{[0-9]+}} ], [ false, %{{[0-9]+}} ]: {[-1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = phi i64 [ 0, %{{[0-9]+}} ], [ 1, %{{[0-9]+}} ]: {[-1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = getelementptr inbounds nuw [2 x [2 x float]], ptr %{{[0-9]+}}, i64 %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Float@float} +// CHECK-DAG: br label %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK-DAG: %{{[0-9]+}} = phi float [ %{{[0-9]+}}, %{{[0-9]+}} ], !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: br i1 %{{[0-9]+}}, label %{{[0-9]+}}, label %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK-DAG: %{{[0-9]+}} = phi float [ %{{[0-9]+}}, %{{[0-9]+}} ], [ %{{[0-9]+}}, %{{[0-9]+}} ]: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = phi i1 [ true, %{{[0-9]+}} ], [ false, %{{[0-9]+}} ]: {[-1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = phi i64 [ 0, %{{[0-9]+}} ], [ 1, %{{[0-9]+}} ]: {[-1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = getelementptr inbounds nuw [2 x float], ptr %{{[0-9]+}}, i64 %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Float@float} +// CHECK-DAG: br label %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK-DAG: %{{[0-9]+}} = phi float [ %{{[0-9]+}}, %{{[0-9]+}} ], [ %{{[0-9]+}}, %{{[0-9]+}} ]: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = phi i1 [ true, %{{[0-9]+}} ], [ false, %{{[0-9]+}} ]: {[-1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = phi i64 [ 0, %{{[0-9]+}} ], [ 1, %{{[0-9]+}} ]: {[-1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = getelementptr inbounds nuw float, ptr %{{[0-9]+}}, i64 %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = load float, ptr %{{[0-9]+}}, align 4, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = fmul float %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = fadd float %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: br i1 %{{[0-9]+}}, label %{{[0-9]+}}, label %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} \ No newline at end of file diff --git a/tests/run-make/autodiff/type-trees/type-analysis/array3d/array3d.rs b/tests/run-make/autodiff/type-trees/type-analysis/array3d/array3d.rs new file mode 100644 index 00000000000..a95111a0dae --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/array3d/array3d.rs @@ -0,0 +1,32 @@ +#![feature(autodiff)] + +use std::autodiff::autodiff_reverse; + +#[autodiff_reverse(d_square, Duplicated, Active)] +#[no_mangle] +fn callee(x: &[[[f32; 2]; 2]; 2]) -> f32 { + let mut sum = 0.0; + for i in 0..2 { + for j in 0..2 { + for k in 0..2 { + sum += x[i][j][k] * x[i][j][k]; + } + } + } + sum +} + +fn main() { + let x = [[[1.0f32, 2.0], [3.0, 4.0]], [[5.0, 6.0], [7.0, 8.0]]]; + let mut df_dx = [[[0.0f32; 2]; 2]; 2]; + let out = callee(&x); + let out_ = d_square(&x, &mut df_dx, 1.0); + assert_eq!(out, out_); + for i in 0..2 { + for j in 0..2 { + for k in 0..2 { + assert_eq!(df_dx[i][j][k], 2.0 * x[i][j][k]); + } + } + } +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/array3d/rmake.rs b/tests/run-make/autodiff/type-trees/type-analysis/array3d/rmake.rs new file mode 100644 index 00000000000..8e75c21c9d6 --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/array3d/rmake.rs @@ -0,0 +1,28 @@ +//@ needs-enzyme +//@ ignore-cross-compile + +use std::fs; + +use run_make_support::{llvm_filecheck, rfs, rustc}; + +fn main() { + // Compile the Rust file with the required flags, capturing both stdout and stderr + let output = rustc() + .input("array3d.rs") + .arg("-Zautodiff=Enable,PrintTAFn=callee") + .arg("-Zautodiff=NoPostopt") + .opt_level("3") + .arg("-Clto=fat") + .arg("-g") + .run(); + + let stdout = output.stdout_utf8(); + let stderr = output.stderr_utf8(); + + // Write the outputs to files + rfs::write("array3d.stdout", stdout); + rfs::write("array3d.stderr", stderr); + + // Run FileCheck on the stdout using the check file + llvm_filecheck().patterns("array3d.check").stdin_buf(rfs::read("array3d.stdout")).run(); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/box/box.check b/tests/run-make/autodiff/type-trees/type-analysis/box/box.check new file mode 100644 index 00000000000..1911e18a137 --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/box/box.check @@ -0,0 +1,12 @@ +// CHECK: callee - {[-1]:Float@float} |{[-1]:Pointer}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Pointer, [-1,0,0]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = load ptr, ptr %{{[0-9]+}}, align 8, !dbg !{{[0-9]+}}, !nonnull !{{[0-9]+}}, !align !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = load float, ptr %{{[0-9]+}}, align 4, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = fmul float %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: ret float %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK: callee - {[-1]:Float@float} |{[-1]:Pointer, [-1,0]:Pointer, [-1,0,0]:Float@float}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Pointer, [-1,0,0]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = load ptr, ptr %{{[0-9]+}}, align 8, !dbg !{{[0-9]+}}, !nonnull !{{[0-9]+}}, !align !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = load float, ptr %{{[0-9]+}}, align 4, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = fmul float %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: ret float %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} \ No newline at end of file diff --git a/tests/run-make/autodiff/type-trees/type-analysis/box/box.rs b/tests/run-make/autodiff/type-trees/type-analysis/box/box.rs new file mode 100644 index 00000000000..658ccffc74e --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/box/box.rs @@ -0,0 +1,18 @@ +#![feature(autodiff)] + +use std::autodiff::autodiff_reverse; + +#[autodiff_reverse(d_square, Duplicated, Active)] +#[no_mangle] +fn callee(x: &Box<f32>) -> f32 { + **x * **x +} + +fn main() { + let x = Box::new(7.0f32); + let mut df_dx = Box::new(0.0f32); + let out = callee(&x); + let out_ = d_square(&x, &mut df_dx, 1.0); + assert_eq!(out, out_); + assert_eq!(14.0, *df_dx); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/box/rmake.rs b/tests/run-make/autodiff/type-trees/type-analysis/box/rmake.rs new file mode 100644 index 00000000000..1e8c8f9ccbd --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/box/rmake.rs @@ -0,0 +1,28 @@ +//@ needs-enzyme +//@ ignore-cross-compile + +use std::fs; + +use run_make_support::{llvm_filecheck, rfs, rustc}; + +fn main() { + // Compile the Rust file with the required flags, capturing both stdout and stderr + let output = rustc() + .input("box.rs") + .arg("-Zautodiff=Enable,PrintTAFn=callee") + .arg("-Zautodiff=NoPostopt") + .opt_level("3") + .arg("-Clto=fat") + .arg("-g") + .run(); + + let stdout = output.stdout_utf8(); + let stderr = output.stderr_utf8(); + + // Write the outputs to files + rfs::write("box.stdout", stdout); + rfs::write("box.stderr", stderr); + + // Run FileCheck on the stdout using the check file + llvm_filecheck().patterns("box.check").stdin_buf(rfs::read("box.stdout")).run(); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/const_pointer/const_pointer.check b/tests/run-make/autodiff/type-trees/type-analysis/const_pointer/const_pointer.check new file mode 100644 index 00000000000..e7503453f8e --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/const_pointer/const_pointer.check @@ -0,0 +1,10 @@ +// CHECK: callee - {[-1]:Float@float} |{[-1]:Pointer}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = load float, ptr %{{[0-9]+}}, align 4, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = fmul float %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: ret float %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK: callee - {[-1]:Float@float} |{[-1]:Pointer, [-1,0]:Float@float}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = load float, ptr %{{[0-9]+}}, align 4, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = fmul float %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: ret float %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} \ No newline at end of file diff --git a/tests/run-make/autodiff/type-trees/type-analysis/const_pointer/const_pointer.rs b/tests/run-make/autodiff/type-trees/type-analysis/const_pointer/const_pointer.rs new file mode 100644 index 00000000000..8c877bfec05 --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/const_pointer/const_pointer.rs @@ -0,0 +1,18 @@ +#![feature(autodiff)] + +use std::autodiff::autodiff_reverse; + +#[autodiff_reverse(d_square, Duplicated, Active)] +#[no_mangle] +fn callee(x: *const f32) -> f32 { + unsafe { *x * *x } +} + +fn main() { + let x: f32 = 7.0; + let out = callee(&x as *const f32); + let mut df_dx: f32 = 0.0; + let out_ = d_square(&x as *const f32, &mut df_dx, 1.0); + assert_eq!(out, out_); + assert_eq!(14.0, df_dx); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/const_pointer/rmake.rs b/tests/run-make/autodiff/type-trees/type-analysis/const_pointer/rmake.rs new file mode 100644 index 00000000000..ce38c6bd2ae --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/const_pointer/rmake.rs @@ -0,0 +1,31 @@ +//@ needs-enzyme +//@ ignore-cross-compile + +use std::fs; + +use run_make_support::{llvm_filecheck, rfs, rustc}; + +fn main() { + // Compile the Rust file with the required flags, capturing both stdout and stderr + let output = rustc() + .input("const_pointer.rs") + .arg("-Zautodiff=Enable,PrintTAFn=callee") + .arg("-Zautodiff=NoPostopt") + .opt_level("3") + .arg("-Clto=fat") + .arg("-g") + .run(); + + let stdout = output.stdout_utf8(); + let stderr = output.stderr_utf8(); + + // Write the outputs to files + rfs::write("const_pointer.stdout", stdout); + rfs::write("const_pointer.stderr", stderr); + + // Run FileCheck on the stdout using the check file + llvm_filecheck() + .patterns("const_pointer.check") + .stdin_buf(rfs::read("const_pointer.stdout")) + .run(); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/f32/f32.check b/tests/run-make/autodiff/type-trees/type-analysis/f32/f32.check new file mode 100644 index 00000000000..0cc0ffda43d --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/f32/f32.check @@ -0,0 +1,12 @@ +// CHECK: callee - {[-1]:Float@float} |{[-1]:Pointer}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Float@float} + +// CHECK-DAG: %{{[0-9]+}} = load float, ptr %{{[0-9]+}}, align 4, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = fmul float %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: ret float %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK: callee - {[-1]:Float@float} |{[-1]:Pointer, [-1,0]:Float@float}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Float@float} + +// CHECK-DAG: %{{[0-9]+}} = load float, ptr %{{[0-9]+}}, align 4, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = fmul float %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: ret float %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} \ No newline at end of file diff --git a/tests/run-make/autodiff/type-trees/type-analysis/f32/f32.rs b/tests/run-make/autodiff/type-trees/type-analysis/f32/f32.rs new file mode 100644 index 00000000000..b945821934a --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/f32/f32.rs @@ -0,0 +1,19 @@ +#![feature(autodiff)] + +use std::autodiff::autodiff_reverse; + +#[autodiff_reverse(d_square, Duplicated, Active)] +#[no_mangle] +fn callee(x: &f32) -> f32 { + *x * *x +} + +fn main() { + let x: f32 = 7.0; + let mut df_dx: f32 = 0.0; + let out = callee(&x); + let out_ = d_square(&x, &mut df_dx, 1.0); + + assert_eq!(out, out_); + assert_eq!(14.0, df_dx); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/f32/rmake.rs b/tests/run-make/autodiff/type-trees/type-analysis/f32/rmake.rs new file mode 100644 index 00000000000..d7e49219da6 --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/f32/rmake.rs @@ -0,0 +1,28 @@ +//@ needs-enzyme +//@ ignore-cross-compile + +use std::fs; + +use run_make_support::{llvm_filecheck, rfs, rustc}; + +fn main() { + // Compile the Rust file with the required flags, capturing both stdout and stderr + let output = rustc() + .input("f32.rs") + .arg("-Zautodiff=Enable,PrintTAFn=callee") + .arg("-Zautodiff=NoPostopt") + .opt_level("3") + .arg("-Clto=fat") + .arg("-g") + .run(); + + let stdout = output.stdout_utf8(); + let stderr = output.stderr_utf8(); + + // Write the outputs to files + rfs::write("f32.stdout", stdout); + rfs::write("f32.stderr", stderr); + + // Run FileCheck on the stdout using the check file + llvm_filecheck().patterns("f32.check").stdin_buf(rfs::read("f32.stdout")).run(); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/f64/f64.check b/tests/run-make/autodiff/type-trees/type-analysis/f64/f64.check new file mode 100644 index 00000000000..efc49da5ffc --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/f64/f64.check @@ -0,0 +1,10 @@ +// CHECK: callee - {[-1]:Float@double} |{[-1]:Pointer}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Float@double} +// CHECK-DAG: %{{[0-9]+}} = load double, ptr %{{[0-9]+}}, align 8, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Float@double} +// CHECK-DAG: %{{[0-9]+}} = fmul double %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Float@double} +// CHECK-DAG: ret double %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK: callee - {[-1]:Float@double} |{[-1]:Pointer, [-1,0]:Float@double}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Float@double} +// CHECK-DAG: %{{[0-9]+}} = load double, ptr %{{[0-9]+}}, align 8, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Float@double} +// CHECK-DAG: %{{[0-9]+}} = fmul double %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Float@double} +// CHECK-DAG: ret double %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} \ No newline at end of file diff --git a/tests/run-make/autodiff/type-trees/type-analysis/f64/f64.rs b/tests/run-make/autodiff/type-trees/type-analysis/f64/f64.rs new file mode 100644 index 00000000000..9b47569652e --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/f64/f64.rs @@ -0,0 +1,20 @@ +#![feature(autodiff)] +use std::autodiff::autodiff_reverse; + +#[autodiff_reverse(d_callee, Duplicated, Active)] +#[no_mangle] +fn callee(x: &f64) -> f64 { + x * x +} + +fn main() { + let x = std::hint::black_box(3.0); + + let output = callee(&x); + assert_eq!(9.0, output); + + let mut df_dx = 0.0; + let output_ = d_callee(&x, &mut df_dx, 1.0); + assert_eq!(output, output_); + assert_eq!(6.0, df_dx); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/f64/rmake.rs b/tests/run-make/autodiff/type-trees/type-analysis/f64/rmake.rs new file mode 100644 index 00000000000..8bf92b8c1bd --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/f64/rmake.rs @@ -0,0 +1,28 @@ +//@ needs-enzyme +//@ ignore-cross-compile + +use std::fs; + +use run_make_support::{llvm_filecheck, rfs, rustc}; + +fn main() { + // Compile the Rust file with the required flags, capturing both stdout and stderr + let output = rustc() + .input("f64.rs") + .arg("-Zautodiff=Enable,PrintTAFn=callee") + .arg("-Zautodiff=NoPostopt") + .opt_level("3") + .arg("-Clto=fat") + .arg("-g") + .run(); + + let stdout = output.stdout_utf8(); + let stderr = output.stderr_utf8(); + + // Write the outputs to files + rfs::write("f64.stdout", stdout); + rfs::write("f64.stderr", stderr); + + // Run FileCheck on the stdout using the check file + llvm_filecheck().patterns("f64.check").stdin_buf(rfs::read("f64.stdout")).run(); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/i128/i128.check b/tests/run-make/autodiff/type-trees/type-analysis/i128/i128.check new file mode 100644 index 00000000000..31a07219e74 --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/i128/i128.check @@ -0,0 +1,10 @@ +// CHECK: callee - {[-1]:Integer} |{[-1]:Pointer}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Integer, [-1,1]:Integer, [-1,2]:Integer, [-1,3]:Integer, [-1,4]:Integer, [-1,5]:Integer, [-1,6]:Integer, [-1,7]:Integer, [-1,8]:Integer, [-1,9]:Integer, [-1,10]:Integer, [-1,11]:Integer, [-1,12]:Integer, [-1,13]:Integer, [-1,14]:Integer, [-1,15]:Integer} +// CHECK-DAG: %{{[0-9]+}} = load i128, ptr %{{[0-9]+}}, align 16, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = mul i128 %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: ret i128 %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK: callee - {[-1]:Integer} |{[-1]:Pointer, [-1,0]:Integer, [-1,1]:Integer, [-1,2]:Integer, [-1,3]:Integer, [-1,4]:Integer, [-1,5]:Integer, [-1,6]:Integer, [-1,7]:Integer, [-1,8]:Integer, [-1,9]:Integer, [-1,10]:Integer, [-1,11]:Integer, [-1,12]:Integer, [-1,13]:Integer, [-1,14]:Integer, [-1,15]:Integer}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Integer, [-1,1]:Integer, [-1,2]:Integer, [-1,3]:Integer, [-1,4]:Integer, [-1,5]:Integer, [-1,6]:Integer, [-1,7]:Integer, [-1,8]:Integer, [-1,9]:Integer, [-1,10]:Integer, [-1,11]:Integer, [-1,12]:Integer, [-1,13]:Integer, [-1,14]:Integer, [-1,15]:Integer} +// CHECK-DAG: %{{[0-9]+}} = load i128, ptr %{{[0-9]+}}, align 16, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = mul i128 %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: ret i128 %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} \ No newline at end of file diff --git a/tests/run-make/autodiff/type-trees/type-analysis/i128/i128.rs b/tests/run-make/autodiff/type-trees/type-analysis/i128/i128.rs new file mode 100644 index 00000000000..19dfbbb22db --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/i128/i128.rs @@ -0,0 +1,14 @@ +#![feature(autodiff)] + +use std::autodiff::autodiff_reverse; + +#[autodiff_reverse(d_square, Duplicated, Active)] +#[no_mangle] +fn callee(x: &i128) -> i128 { + *x * *x +} + +fn main() { + let x: i128 = 7; + let _ = callee(&x); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/i128/rmake.rs b/tests/run-make/autodiff/type-trees/type-analysis/i128/rmake.rs new file mode 100644 index 00000000000..21e8698634f --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/i128/rmake.rs @@ -0,0 +1,28 @@ +//@ needs-enzyme +//@ ignore-cross-compile + +use std::fs; + +use run_make_support::{llvm_filecheck, rfs, rustc}; + +fn main() { + // Compile the Rust file with the required flags, capturing both stdout and stderr + let output = rustc() + .input("i128.rs") + .arg("-Zautodiff=Enable,PrintTAFn=callee") + .arg("-Zautodiff=NoPostopt") + .opt_level("3") + .arg("-Clto=fat") + .arg("-g") + .run(); + + let stdout = output.stdout_utf8(); + let stderr = output.stderr_utf8(); + + // Write the outputs to files + rfs::write("i128.stdout", stdout); + rfs::write("i128.stderr", stderr); + + // Run FileCheck on the stdout using the check file + llvm_filecheck().patterns("i128.check").stdin_buf(rfs::read("i128.stdout")).run(); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/i16/i16.check b/tests/run-make/autodiff/type-trees/type-analysis/i16/i16.check new file mode 100644 index 00000000000..8cc299532c5 --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/i16/i16.check @@ -0,0 +1,10 @@ +// CHECK: callee - {[-1]:Integer} |{[-1]:Pointer}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Integer, [-1,1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = load i16, ptr %{{[0-9]+}}, align 2, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = mul i16 %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: ret i16 %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK: callee - {[-1]:Integer} |{[-1]:Pointer, [-1,0]:Integer, [-1,1]:Integer}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Integer, [-1,1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = load i16, ptr %{{[0-9]+}}, align 2, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = mul i16 %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: ret i16 %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} \ No newline at end of file diff --git a/tests/run-make/autodiff/type-trees/type-analysis/i16/i16.rs b/tests/run-make/autodiff/type-trees/type-analysis/i16/i16.rs new file mode 100644 index 00000000000..82099198a2e --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/i16/i16.rs @@ -0,0 +1,14 @@ +#![feature(autodiff)] + +use std::autodiff::autodiff_reverse; + +#[autodiff_reverse(d_square, Duplicated, Active)] +#[no_mangle] +fn callee(x: &i16) -> i16 { + *x * *x +} + +fn main() { + let x: i16 = 7; + let _ = callee(&x); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/i16/rmake.rs b/tests/run-make/autodiff/type-trees/type-analysis/i16/rmake.rs new file mode 100644 index 00000000000..a2875a8c573 --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/i16/rmake.rs @@ -0,0 +1,28 @@ +//@ needs-enzyme +//@ ignore-cross-compile + +use std::fs; + +use run_make_support::{llvm_filecheck, rfs, rustc}; + +fn main() { + // Compile the Rust file with the required flags, capturing both stdout and stderr + let output = rustc() + .input("i16.rs") + .arg("-Zautodiff=Enable,PrintTAFn=callee") + .arg("-Zautodiff=NoPostopt") + .opt_level("3") + .arg("-Clto=fat") + .arg("-g") + .run(); + + let stdout = output.stdout_utf8(); + let stderr = output.stderr_utf8(); + + // Write the outputs to files + rfs::write("i16.stdout", stdout); + rfs::write("i16.stderr", stderr); + + // Run FileCheck on the stdout using the check file + llvm_filecheck().patterns("i16.check").stdin_buf(rfs::read("i16.stdout")).run(); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/i32/i32.check b/tests/run-make/autodiff/type-trees/type-analysis/i32/i32.check new file mode 100644 index 00000000000..4df982887d7 --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/i32/i32.check @@ -0,0 +1,10 @@ +// CHECK: callee - {[-1]:Integer} |{[-1]:Pointer}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Integer, [-1,1]:Integer, [-1,2]:Integer, [-1,3]:Integer} +// CHECK-DAG: %{{[0-9]+}} = load i32, ptr %{{[0-9]+}}, align 4, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = mul i32 %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: ret i32 %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK: callee - {[-1]:Integer} |{[-1]:Pointer, [-1,0]:Integer, [-1,1]:Integer, [-1,2]:Integer, [-1,3]:Integer}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Integer, [-1,1]:Integer, [-1,2]:Integer, [-1,3]:Integer} +// CHECK-DAG: %{{[0-9]+}} = load i32, ptr %{{[0-9]+}}, align 4, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = mul i32 %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: ret i32 %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} \ No newline at end of file diff --git a/tests/run-make/autodiff/type-trees/type-analysis/i32/i32.rs b/tests/run-make/autodiff/type-trees/type-analysis/i32/i32.rs new file mode 100644 index 00000000000..e95068d5c49 --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/i32/i32.rs @@ -0,0 +1,14 @@ +#![feature(autodiff)] + +use std::autodiff::autodiff_reverse; + +#[autodiff_reverse(d_square, Duplicated, Active)] +#[no_mangle] +fn callee(x: &i32) -> i32 { + *x * *x +} + +fn main() { + let x: i32 = 7; + let _ = callee(&x); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/i32/rmake.rs b/tests/run-make/autodiff/type-trees/type-analysis/i32/rmake.rs new file mode 100644 index 00000000000..857017feeab --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/i32/rmake.rs @@ -0,0 +1,28 @@ +//@ needs-enzyme +//@ ignore-cross-compile + +use std::fs; + +use run_make_support::{llvm_filecheck, rfs, rustc}; + +fn main() { + // Compile the Rust file with the required flags, capturing both stdout and stderr + let output = rustc() + .input("i32.rs") + .arg("-Zautodiff=Enable,PrintTAFn=callee") + .arg("-Zautodiff=NoPostopt") + .opt_level("3") + .arg("-Clto=fat") + .arg("-g") + .run(); + + let stdout = output.stdout_utf8(); + let stderr = output.stderr_utf8(); + + // Write the outputs to files + rfs::write("i32.stdout", stdout); + rfs::write("i32.stderr", stderr); + + // Run FileCheck on the stdout using the check file + llvm_filecheck().patterns("i32.check").stdin_buf(rfs::read("i32.stdout")).run(); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/i8/i8.check b/tests/run-make/autodiff/type-trees/type-analysis/i8/i8.check new file mode 100644 index 00000000000..651a2085bc6 --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/i8/i8.check @@ -0,0 +1,10 @@ +// CHECK: callee - {[-1]:Integer} |{[-1]:Pointer}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Integer} +// CHECK-DAG: %{{[0-9]+}} = load i8, ptr %{{[0-9]+}}, align 1, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = mul i8 %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: ret i8 %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK: callee - {[-1]:Integer} |{[-1]:Pointer, [-1,0]:Integer}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Integer} +// CHECK-DAG: %{{[0-9]+}} = load i8, ptr %{{[0-9]+}}, align 1, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = mul i8 %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: ret i8 %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} \ No newline at end of file diff --git a/tests/run-make/autodiff/type-trees/type-analysis/i8/i8.rs b/tests/run-make/autodiff/type-trees/type-analysis/i8/i8.rs new file mode 100644 index 00000000000..afc0cad703c --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/i8/i8.rs @@ -0,0 +1,14 @@ +#![feature(autodiff)] + +use std::autodiff::autodiff_reverse; + +#[autodiff_reverse(d_square, Duplicated, Active)] +#[no_mangle] +fn callee(x: &i8) -> i8 { + *x * *x +} + +fn main() { + let x: i8 = 7; + let _ = callee(&x); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/i8/rmake.rs b/tests/run-make/autodiff/type-trees/type-analysis/i8/rmake.rs new file mode 100644 index 00000000000..6551e2d6c4e --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/i8/rmake.rs @@ -0,0 +1,28 @@ +//@ needs-enzyme +//@ ignore-cross-compile + +use std::fs; + +use run_make_support::{llvm_filecheck, rfs, rustc}; + +fn main() { + // Compile the Rust file with the required flags, capturing both stdout and stderr + let output = rustc() + .input("i8.rs") + .arg("-Zautodiff=Enable,PrintTAFn=callee") + .arg("-Zautodiff=NoPostopt") + .opt_level("3") + .arg("-Clto=fat") + .arg("-g") + .run(); + + let stdout = output.stdout_utf8(); + let stderr = output.stderr_utf8(); + + // Write the outputs to files + rfs::write("i8.stdout", stdout); + rfs::write("i8.stderr", stderr); + + // Run FileCheck on the stdout using the check file + llvm_filecheck().patterns("i8.check").stdin_buf(rfs::read("i8.stdout")).run(); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/isize/isize.check b/tests/run-make/autodiff/type-trees/type-analysis/isize/isize.check new file mode 100644 index 00000000000..40ee6edc02c --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/isize/isize.check @@ -0,0 +1,10 @@ +// CHECK: callee - {[-1]:Integer} |{[-1]:Pointer}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Integer, [-1,1]:Integer, [-1,2]:Integer, [-1,3]:Integer, [-1,4]:Integer, [-1,5]:Integer, [-1,6]:Integer, [-1,7]:Integer} +// CHECK-DAG: %{{[0-9]+}} = load i64, ptr %{{[0-9]+}}, align 8, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = mul i64 %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: ret i64 %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK: callee - {[-1]:Integer} |{[-1]:Pointer, [-1,0]:Integer, [-1,1]:Integer, [-1,2]:Integer, [-1,3]:Integer, [-1,4]:Integer, [-1,5]:Integer, [-1,6]:Integer, [-1,7]:Integer}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Integer, [-1,1]:Integer, [-1,2]:Integer, [-1,3]:Integer, [-1,4]:Integer, [-1,5]:Integer, [-1,6]:Integer, [-1,7]:Integer} +// CHECK-DAG: %{{[0-9]+}} = load i64, ptr %{{[0-9]+}}, align 8, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = mul i64 %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: ret i64 %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} \ No newline at end of file diff --git a/tests/run-make/autodiff/type-trees/type-analysis/isize/isize.rs b/tests/run-make/autodiff/type-trees/type-analysis/isize/isize.rs new file mode 100644 index 00000000000..dd160984a4e --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/isize/isize.rs @@ -0,0 +1,14 @@ +#![feature(autodiff)] + +use std::autodiff::autodiff_reverse; + +#[autodiff_reverse(d_square, Duplicated, Active)] +#[no_mangle] +fn callee(x: &isize) -> isize { + *x * *x +} + +fn main() { + let x: isize = 7; + let _ = callee(&x); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/isize/rmake.rs b/tests/run-make/autodiff/type-trees/type-analysis/isize/rmake.rs new file mode 100644 index 00000000000..09277f63ed4 --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/isize/rmake.rs @@ -0,0 +1,28 @@ +//@ needs-enzyme +//@ ignore-cross-compile + +use std::fs; + +use run_make_support::{llvm_filecheck, rfs, rustc}; + +fn main() { + // Compile the Rust file with the required flags, capturing both stdout and stderr + let output = rustc() + .input("isize.rs") + .arg("-Zautodiff=Enable,PrintTAFn=callee") + .arg("-Zautodiff=NoPostopt") + .opt_level("3") + .arg("-Clto=fat") + .arg("-g") + .run(); + + let stdout = output.stdout_utf8(); + let stderr = output.stderr_utf8(); + + // Write the outputs to files + rfs::write("isize.stdout", stdout); + rfs::write("isize.stderr", stderr); + + // Run FileCheck on the stdout using the check file + llvm_filecheck().patterns("isize.check").stdin_buf(rfs::read("isize.stdout")).run(); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/mut_pointer/mut_pointer.check b/tests/run-make/autodiff/type-trees/type-analysis/mut_pointer/mut_pointer.check new file mode 100644 index 00000000000..e7503453f8e --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/mut_pointer/mut_pointer.check @@ -0,0 +1,10 @@ +// CHECK: callee - {[-1]:Float@float} |{[-1]:Pointer}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = load float, ptr %{{[0-9]+}}, align 4, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = fmul float %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: ret float %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK: callee - {[-1]:Float@float} |{[-1]:Pointer, [-1,0]:Float@float}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = load float, ptr %{{[0-9]+}}, align 4, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = fmul float %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: ret float %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} \ No newline at end of file diff --git a/tests/run-make/autodiff/type-trees/type-analysis/mut_pointer/mut_pointer.rs b/tests/run-make/autodiff/type-trees/type-analysis/mut_pointer/mut_pointer.rs new file mode 100644 index 00000000000..2b672f6d3f8 --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/mut_pointer/mut_pointer.rs @@ -0,0 +1,18 @@ +#![feature(autodiff)] + +use std::autodiff::autodiff_reverse; + +#[autodiff_reverse(d_square, Duplicated, Active)] +#[no_mangle] +fn callee(x: *mut f32) -> f32 { + unsafe { *x * *x } +} + +fn main() { + let mut x: f32 = 7.0; + let out = callee(&mut x as *mut f32); + let mut df_dx: f32 = 0.0; + let out_ = d_square(&mut x as *mut f32, &mut df_dx, 1.0); + assert_eq!(out, out_); + assert_eq!(14.0, df_dx); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/mut_pointer/rmake.rs b/tests/run-make/autodiff/type-trees/type-analysis/mut_pointer/rmake.rs new file mode 100644 index 00000000000..4d5a5042141 --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/mut_pointer/rmake.rs @@ -0,0 +1,28 @@ +//@ needs-enzyme +//@ ignore-cross-compile + +use std::fs; + +use run_make_support::{llvm_filecheck, rfs, rustc}; + +fn main() { + // Compile the Rust file with the required flags, capturing both stdout and stderr + let output = rustc() + .input("mut_pointer.rs") + .arg("-Zautodiff=Enable,PrintTAFn=callee") + .arg("-Zautodiff=NoPostopt") + .opt_level("3") + .arg("-Clto=fat") + .arg("-g") + .run(); + + let stdout = output.stdout_utf8(); + let stderr = output.stderr_utf8(); + + // Write the outputs to files + rfs::write("mut_pointer.stdout", stdout); + rfs::write("mut_pointer.stderr", stderr); + + // Run FileCheck on the stdout using the check file + llvm_filecheck().patterns("mut_pointer.check").stdin_buf(rfs::read("mut_pointer.stdout")).run(); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/mut_ref/mut_ref.check b/tests/run-make/autodiff/type-trees/type-analysis/mut_ref/mut_ref.check new file mode 100644 index 00000000000..e7503453f8e --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/mut_ref/mut_ref.check @@ -0,0 +1,10 @@ +// CHECK: callee - {[-1]:Float@float} |{[-1]:Pointer}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = load float, ptr %{{[0-9]+}}, align 4, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = fmul float %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: ret float %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK: callee - {[-1]:Float@float} |{[-1]:Pointer, [-1,0]:Float@float}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = load float, ptr %{{[0-9]+}}, align 4, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = fmul float %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: ret float %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} \ No newline at end of file diff --git a/tests/run-make/autodiff/type-trees/type-analysis/mut_ref/mut_ref.rs b/tests/run-make/autodiff/type-trees/type-analysis/mut_ref/mut_ref.rs new file mode 100644 index 00000000000..7019e3f71ed --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/mut_ref/mut_ref.rs @@ -0,0 +1,18 @@ +#![feature(autodiff)] + +use std::autodiff::autodiff_reverse; + +#[autodiff_reverse(d_square, Duplicated, Active)] +#[no_mangle] +fn callee(x: &mut f32) -> f32 { + *x * *x +} + +fn main() { + let mut x: f32 = 7.0; + let mut df_dx: f32 = 0.0; + let out = callee(&mut x); + let out_ = d_square(&mut x, &mut df_dx, 1.0); + assert_eq!(out, out_); + assert_eq!(14.0, df_dx); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/mut_ref/rmake.rs b/tests/run-make/autodiff/type-trees/type-analysis/mut_ref/rmake.rs new file mode 100644 index 00000000000..13668c54e78 --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/mut_ref/rmake.rs @@ -0,0 +1,28 @@ +//@ needs-enzyme +//@ ignore-cross-compile + +use std::fs; + +use run_make_support::{llvm_filecheck, rfs, rustc}; + +fn main() { + // Compile the Rust file with the required flags, capturing both stdout and stderr + let output = rustc() + .input("mut_ref.rs") + .arg("-Zautodiff=Enable,PrintTAFn=callee") + .arg("-Zautodiff=NoPostopt") + .opt_level("3") + .arg("-Clto=fat") + .arg("-g") + .run(); + + let stdout = output.stdout_utf8(); + let stderr = output.stderr_utf8(); + + // Write the outputs to files + rfs::write("mut_ref.stdout", stdout); + rfs::write("mut_ref.stderr", stderr); + + // Run FileCheck on the stdout using the check file + llvm_filecheck().patterns("mut_ref.check").stdin_buf(rfs::read("mut_ref.stdout")).run(); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/ref/ref.check b/tests/run-make/autodiff/type-trees/type-analysis/ref/ref.check new file mode 100644 index 00000000000..e7503453f8e --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/ref/ref.check @@ -0,0 +1,10 @@ +// CHECK: callee - {[-1]:Float@float} |{[-1]:Pointer}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = load float, ptr %{{[0-9]+}}, align 4, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = fmul float %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: ret float %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK: callee - {[-1]:Float@float} |{[-1]:Pointer, [-1,0]:Float@float}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = load float, ptr %{{[0-9]+}}, align 4, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = fmul float %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: ret float %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} \ No newline at end of file diff --git a/tests/run-make/autodiff/type-trees/type-analysis/ref/ref.rs b/tests/run-make/autodiff/type-trees/type-analysis/ref/ref.rs new file mode 100644 index 00000000000..3ced164b86f --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/ref/ref.rs @@ -0,0 +1,18 @@ +#![feature(autodiff)] + +use std::autodiff::autodiff_reverse; + +#[autodiff_reverse(d_square, Duplicated, Active)] +#[no_mangle] +fn callee(x: &f32) -> f32 { + *x * *x +} + +fn main() { + let x: f32 = 7.0; + let mut df_dx: f32 = 0.0; + let out = callee(&x); + let out_ = d_square(&x, &mut df_dx, 1.0); + assert_eq!(out, out_); + assert_eq!(14.0, df_dx); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/ref/rmake.rs b/tests/run-make/autodiff/type-trees/type-analysis/ref/rmake.rs new file mode 100644 index 00000000000..b68e4e5b8ac --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/ref/rmake.rs @@ -0,0 +1,28 @@ +//@ needs-enzyme +//@ ignore-cross-compile + +use std::fs; + +use run_make_support::{llvm_filecheck, rfs, rustc}; + +fn main() { + // Compile the Rust file with the required flags, capturing both stdout and stderr + let output = rustc() + .input("ref.rs") + .arg("-Zautodiff=Enable,PrintTAFn=callee") + .arg("-Zautodiff=NoPostopt") + .opt_level("3") + .arg("-Clto=fat") + .arg("-g") + .run(); + + let stdout = output.stdout_utf8(); + let stderr = output.stderr_utf8(); + + // Write the outputs to files + rfs::write("ref.stdout", stdout); + rfs::write("ref.stderr", stderr); + + // Run FileCheck on the stdout using the check file + llvm_filecheck().patterns("ref.check").stdin_buf(rfs::read("ref.stdout")).run(); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/struct/rmake.rs b/tests/run-make/autodiff/type-trees/type-analysis/struct/rmake.rs new file mode 100644 index 00000000000..4073f7554cc --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/struct/rmake.rs @@ -0,0 +1,28 @@ +//@ needs-enzyme +//@ ignore-cross-compile + +use std::fs; + +use run_make_support::{llvm_filecheck, rfs, rustc}; + +fn main() { + // Compile the Rust file with the required flags, capturing both stdout and stderr + let output = rustc() + .input("struct.rs") + .arg("-Zautodiff=Enable,PrintTAFn=callee") + .arg("-Zautodiff=NoPostopt") + .opt_level("3") + .arg("-Clto=fat") + .arg("-g") + .run(); + + let stdout = output.stdout_utf8(); + let stderr = output.stderr_utf8(); + + // Write the outputs to files + rfs::write("struct.stdout", stdout); + rfs::write("struct.stderr", stderr); + + // Run FileCheck on the stdout using the check file + llvm_filecheck().patterns("struct.check").stdin_buf(rfs::read("struct.stdout")).run(); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/struct/struct.check b/tests/run-make/autodiff/type-trees/type-analysis/struct/struct.check new file mode 100644 index 00000000000..e7503453f8e --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/struct/struct.check @@ -0,0 +1,10 @@ +// CHECK: callee - {[-1]:Float@float} |{[-1]:Pointer}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = load float, ptr %{{[0-9]+}}, align 4, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = fmul float %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: ret float %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK: callee - {[-1]:Float@float} |{[-1]:Pointer, [-1,0]:Float@float}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = load float, ptr %{{[0-9]+}}, align 4, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = fmul float %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: ret float %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} \ No newline at end of file diff --git a/tests/run-make/autodiff/type-trees/type-analysis/struct/struct.rs b/tests/run-make/autodiff/type-trees/type-analysis/struct/struct.rs new file mode 100644 index 00000000000..52cb6a9a6b9 --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/struct/struct.rs @@ -0,0 +1,23 @@ +#![feature(autodiff)] + +use std::autodiff::autodiff_reverse; + +#[derive(Copy, Clone)] +struct MyStruct { + f: f32, +} + +#[autodiff_reverse(d_square, Duplicated, Active)] +#[no_mangle] +fn callee(x: &MyStruct) -> f32 { + x.f * x.f +} + +fn main() { + let x = MyStruct { f: 7.0 }; + let mut df_dx = MyStruct { f: 0.0 }; + let out = callee(&x); + let out_ = d_square(&x, &mut df_dx, 1.0); + assert_eq!(out, out_); + assert_eq!(14.0, df_dx.f); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/u128/rmake.rs b/tests/run-make/autodiff/type-trees/type-analysis/u128/rmake.rs new file mode 100644 index 00000000000..3f605d47c68 --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/u128/rmake.rs @@ -0,0 +1,28 @@ +//@ needs-enzyme +//@ ignore-cross-compile + +use std::fs; + +use run_make_support::{llvm_filecheck, rfs, rustc}; + +fn main() { + // Compile the Rust file with the required flags, capturing both stdout and stderr + let output = rustc() + .input("u128.rs") + .arg("-Zautodiff=Enable,PrintTAFn=callee") + .arg("-Zautodiff=NoPostopt") + .opt_level("3") + .arg("-Clto=fat") + .arg("-g") + .run(); + + let stdout = output.stdout_utf8(); + let stderr = output.stderr_utf8(); + + // Write the outputs to files + rfs::write("u128.stdout", stdout); + rfs::write("u128.stderr", stderr); + + // Run FileCheck on the stdout using the check file + llvm_filecheck().patterns("u128.check").stdin_buf(rfs::read("u128.stdout")).run(); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/u128/u128.check b/tests/run-make/autodiff/type-trees/type-analysis/u128/u128.check new file mode 100644 index 00000000000..31a07219e74 --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/u128/u128.check @@ -0,0 +1,10 @@ +// CHECK: callee - {[-1]:Integer} |{[-1]:Pointer}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Integer, [-1,1]:Integer, [-1,2]:Integer, [-1,3]:Integer, [-1,4]:Integer, [-1,5]:Integer, [-1,6]:Integer, [-1,7]:Integer, [-1,8]:Integer, [-1,9]:Integer, [-1,10]:Integer, [-1,11]:Integer, [-1,12]:Integer, [-1,13]:Integer, [-1,14]:Integer, [-1,15]:Integer} +// CHECK-DAG: %{{[0-9]+}} = load i128, ptr %{{[0-9]+}}, align 16, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = mul i128 %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: ret i128 %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK: callee - {[-1]:Integer} |{[-1]:Pointer, [-1,0]:Integer, [-1,1]:Integer, [-1,2]:Integer, [-1,3]:Integer, [-1,4]:Integer, [-1,5]:Integer, [-1,6]:Integer, [-1,7]:Integer, [-1,8]:Integer, [-1,9]:Integer, [-1,10]:Integer, [-1,11]:Integer, [-1,12]:Integer, [-1,13]:Integer, [-1,14]:Integer, [-1,15]:Integer}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Integer, [-1,1]:Integer, [-1,2]:Integer, [-1,3]:Integer, [-1,4]:Integer, [-1,5]:Integer, [-1,6]:Integer, [-1,7]:Integer, [-1,8]:Integer, [-1,9]:Integer, [-1,10]:Integer, [-1,11]:Integer, [-1,12]:Integer, [-1,13]:Integer, [-1,14]:Integer, [-1,15]:Integer} +// CHECK-DAG: %{{[0-9]+}} = load i128, ptr %{{[0-9]+}}, align 16, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = mul i128 %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: ret i128 %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} \ No newline at end of file diff --git a/tests/run-make/autodiff/type-trees/type-analysis/u128/u128.rs b/tests/run-make/autodiff/type-trees/type-analysis/u128/u128.rs new file mode 100644 index 00000000000..d19d2faa51b --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/u128/u128.rs @@ -0,0 +1,14 @@ +#![feature(autodiff)] + +use std::autodiff::autodiff_reverse; + +#[autodiff_reverse(d_square, Duplicated, Active)] +#[no_mangle] +fn callee(x: &u128) -> u128 { + *x * *x +} + +fn main() { + let x: u128 = 7; + let _ = callee(&x); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/u16/rmake.rs b/tests/run-make/autodiff/type-trees/type-analysis/u16/rmake.rs new file mode 100644 index 00000000000..0051f6f9795 --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/u16/rmake.rs @@ -0,0 +1,28 @@ +//@ needs-enzyme +//@ ignore-cross-compile + +use std::fs; + +use run_make_support::{llvm_filecheck, rfs, rustc}; + +fn main() { + // Compile the Rust file with the required flags, capturing both stdout and stderr + let output = rustc() + .input("u16.rs") + .arg("-Zautodiff=Enable,PrintTAFn=callee") + .arg("-Zautodiff=NoPostopt") + .opt_level("3") + .arg("-Clto=fat") + .arg("-g") + .run(); + + let stdout = output.stdout_utf8(); + let stderr = output.stderr_utf8(); + + // Write the outputs to files + rfs::write("u16.stdout", stdout); + rfs::write("u16.stderr", stderr); + + // Run FileCheck on the stdout using the check file + llvm_filecheck().patterns("u16.check").stdin_buf(rfs::read("u16.stdout")).run(); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/u16/u16.check b/tests/run-make/autodiff/type-trees/type-analysis/u16/u16.check new file mode 100644 index 00000000000..8cc299532c5 --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/u16/u16.check @@ -0,0 +1,10 @@ +// CHECK: callee - {[-1]:Integer} |{[-1]:Pointer}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Integer, [-1,1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = load i16, ptr %{{[0-9]+}}, align 2, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = mul i16 %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: ret i16 %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK: callee - {[-1]:Integer} |{[-1]:Pointer, [-1,0]:Integer, [-1,1]:Integer}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Integer, [-1,1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = load i16, ptr %{{[0-9]+}}, align 2, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = mul i16 %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: ret i16 %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} \ No newline at end of file diff --git a/tests/run-make/autodiff/type-trees/type-analysis/u16/u16.rs b/tests/run-make/autodiff/type-trees/type-analysis/u16/u16.rs new file mode 100644 index 00000000000..f5f5b50622b --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/u16/u16.rs @@ -0,0 +1,14 @@ +#![feature(autodiff)] + +use std::autodiff::autodiff_reverse; + +#[autodiff_reverse(d_square, Duplicated, Active)] +#[no_mangle] +fn callee(x: &u16) -> u16 { + *x * *x +} + +fn main() { + let x: u16 = 7; + let _ = callee(&x); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/u32/rmake.rs b/tests/run-make/autodiff/type-trees/type-analysis/u32/rmake.rs new file mode 100644 index 00000000000..0882230b1c6 --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/u32/rmake.rs @@ -0,0 +1,28 @@ +//@ needs-enzyme +//@ ignore-cross-compile + +use std::fs; + +use run_make_support::{llvm_filecheck, rfs, rustc}; + +fn main() { + // Compile the Rust file with the required flags, capturing both stdout and stderr + let output = rustc() + .input("u32.rs") + .arg("-Zautodiff=Enable,PrintTAFn=callee") + .arg("-Zautodiff=NoPostopt") + .opt_level("3") + .arg("-Clto=fat") + .arg("-g") + .run(); + + let stdout = output.stdout_utf8(); + let stderr = output.stderr_utf8(); + + // Write the outputs to files + rfs::write("u32.stdout", stdout); + rfs::write("u32.stderr", stderr); + + // Run FileCheck on the stdout using the check file + llvm_filecheck().patterns("u32.check").stdin_buf(rfs::read("u32.stdout")).run(); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/u32/u32.check b/tests/run-make/autodiff/type-trees/type-analysis/u32/u32.check new file mode 100644 index 00000000000..4df982887d7 --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/u32/u32.check @@ -0,0 +1,10 @@ +// CHECK: callee - {[-1]:Integer} |{[-1]:Pointer}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Integer, [-1,1]:Integer, [-1,2]:Integer, [-1,3]:Integer} +// CHECK-DAG: %{{[0-9]+}} = load i32, ptr %{{[0-9]+}}, align 4, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = mul i32 %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: ret i32 %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK: callee - {[-1]:Integer} |{[-1]:Pointer, [-1,0]:Integer, [-1,1]:Integer, [-1,2]:Integer, [-1,3]:Integer}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Integer, [-1,1]:Integer, [-1,2]:Integer, [-1,3]:Integer} +// CHECK-DAG: %{{[0-9]+}} = load i32, ptr %{{[0-9]+}}, align 4, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = mul i32 %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: ret i32 %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} \ No newline at end of file diff --git a/tests/run-make/autodiff/type-trees/type-analysis/u32/u32.rs b/tests/run-make/autodiff/type-trees/type-analysis/u32/u32.rs new file mode 100644 index 00000000000..66b4c222c51 --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/u32/u32.rs @@ -0,0 +1,14 @@ +#![feature(autodiff)] + +use std::autodiff::autodiff_reverse; + +#[autodiff_reverse(d_square, Duplicated, Active)] +#[no_mangle] +fn callee(x: &u32) -> u32 { + *x * *x +} + +fn main() { + let x: u32 = 7; + let _ = callee(&x); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/u8/rmake.rs b/tests/run-make/autodiff/type-trees/type-analysis/u8/rmake.rs new file mode 100644 index 00000000000..100b4f498f2 --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/u8/rmake.rs @@ -0,0 +1,28 @@ +//@ needs-enzyme +//@ ignore-cross-compile + +use std::fs; + +use run_make_support::{llvm_filecheck, rfs, rustc}; + +fn main() { + // Compile the Rust file with the required flags, capturing both stdout and stderr + let output = rustc() + .input("u8.rs") + .arg("-Zautodiff=Enable,PrintTAFn=callee") + .arg("-Zautodiff=NoPostopt") + .opt_level("3") + .arg("-Clto=fat") + .arg("-g") + .run(); + + let stdout = output.stdout_utf8(); + let stderr = output.stderr_utf8(); + + // Write the outputs to files + rfs::write("u8.stdout", stdout); + rfs::write("u8.stderr", stderr); + + // Run FileCheck on the stdout using the check file + llvm_filecheck().patterns("u8.check").stdin_buf(rfs::read("u8.stdout")).run(); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/u8/u8.check b/tests/run-make/autodiff/type-trees/type-analysis/u8/u8.check new file mode 100644 index 00000000000..651a2085bc6 --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/u8/u8.check @@ -0,0 +1,10 @@ +// CHECK: callee - {[-1]:Integer} |{[-1]:Pointer}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Integer} +// CHECK-DAG: %{{[0-9]+}} = load i8, ptr %{{[0-9]+}}, align 1, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = mul i8 %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: ret i8 %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK: callee - {[-1]:Integer} |{[-1]:Pointer, [-1,0]:Integer}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Integer} +// CHECK-DAG: %{{[0-9]+}} = load i8, ptr %{{[0-9]+}}, align 1, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = mul i8 %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: ret i8 %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} \ No newline at end of file diff --git a/tests/run-make/autodiff/type-trees/type-analysis/u8/u8.rs b/tests/run-make/autodiff/type-trees/type-analysis/u8/u8.rs new file mode 100644 index 00000000000..de9cdeb631e --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/u8/u8.rs @@ -0,0 +1,14 @@ +#![feature(autodiff)] + +use std::autodiff::autodiff_reverse; + +#[autodiff_reverse(d_square, Duplicated, Active)] +#[no_mangle] +fn callee(x: &u8) -> u8 { + *x * *x +} + +fn main() { + let x: u8 = 7; + let _ = callee(&x); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/union/rmake.rs b/tests/run-make/autodiff/type-trees/type-analysis/union/rmake.rs new file mode 100644 index 00000000000..67f0fe18481 --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/union/rmake.rs @@ -0,0 +1,28 @@ +//@ needs-enzyme +//@ ignore-cross-compile + +use std::fs; + +use run_make_support::{llvm_filecheck, rfs, rustc}; + +fn main() { + // Compile the Rust file with the required flags, capturing both stdout and stderr + let output = rustc() + .input("union.rs") + .arg("-Zautodiff=Enable,PrintTAFn=callee") + .arg("-Zautodiff=NoPostopt") + .opt_level("3") + .arg("-Clto=fat") + .arg("-g") + .run(); + + let stdout = output.stdout_utf8(); + let stderr = output.stderr_utf8(); + + // Write the outputs to files + rfs::write("union.stdout", stdout); + rfs::write("union.stderr", stderr); + + // Run FileCheck on the stdout using the check file + llvm_filecheck().patterns("union.check").stdin_buf(rfs::read("union.stdout")).run(); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/union/union.check b/tests/run-make/autodiff/type-trees/type-analysis/union/union.check new file mode 100644 index 00000000000..e7503453f8e --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/union/union.check @@ -0,0 +1,10 @@ +// CHECK: callee - {[-1]:Float@float} |{[-1]:Pointer}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = load float, ptr %{{[0-9]+}}, align 4, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = fmul float %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: ret float %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK: callee - {[-1]:Float@float} |{[-1]:Pointer, [-1,0]:Float@float}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = load float, ptr %{{[0-9]+}}, align 4, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = fmul float %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: ret float %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} \ No newline at end of file diff --git a/tests/run-make/autodiff/type-trees/type-analysis/union/union.rs b/tests/run-make/autodiff/type-trees/type-analysis/union/union.rs new file mode 100644 index 00000000000..8d997f8c839 --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/union/union.rs @@ -0,0 +1,20 @@ +#![feature(autodiff)] + +use std::autodiff::autodiff_reverse; + +#[allow(dead_code)] +union MyUnion { + f: f32, + i: i32, +} + +#[autodiff_reverse(d_square, Duplicated, Active)] +#[no_mangle] +fn callee(x: &MyUnion) -> f32 { + unsafe { x.f * x.f } +} + +fn main() { + let x = MyUnion { f: 7.0 }; + let _ = callee(&x); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/usize/rmake.rs b/tests/run-make/autodiff/type-trees/type-analysis/usize/rmake.rs new file mode 100644 index 00000000000..d5cfd708c3a --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/usize/rmake.rs @@ -0,0 +1,28 @@ +//@ needs-enzyme +//@ ignore-cross-compile + +use std::fs; + +use run_make_support::{llvm_filecheck, rfs, rustc}; + +fn main() { + // Compile the Rust file with the required flags, capturing both stdout and stderr + let output = rustc() + .input("usize.rs") + .arg("-Zautodiff=Enable,PrintTAFn=callee") + .arg("-Zautodiff=NoPostopt") + .opt_level("3") + .arg("-Clto=fat") + .arg("-g") + .run(); + + let stdout = output.stdout_utf8(); + let stderr = output.stderr_utf8(); + + // Write the outputs to files + rfs::write("usize.stdout", stdout); + rfs::write("usize.stderr", stderr); + + // Run FileCheck on the stdout using the check file + llvm_filecheck().patterns("usize.check").stdin_buf(rfs::read("usize.stdout")).run(); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/usize/usize.check b/tests/run-make/autodiff/type-trees/type-analysis/usize/usize.check new file mode 100644 index 00000000000..40ee6edc02c --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/usize/usize.check @@ -0,0 +1,10 @@ +// CHECK: callee - {[-1]:Integer} |{[-1]:Pointer}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Integer, [-1,1]:Integer, [-1,2]:Integer, [-1,3]:Integer, [-1,4]:Integer, [-1,5]:Integer, [-1,6]:Integer, [-1,7]:Integer} +// CHECK-DAG: %{{[0-9]+}} = load i64, ptr %{{[0-9]+}}, align 8, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = mul i64 %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: ret i64 %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK: callee - {[-1]:Integer} |{[-1]:Pointer, [-1,0]:Integer, [-1,1]:Integer, [-1,2]:Integer, [-1,3]:Integer, [-1,4]:Integer, [-1,5]:Integer, [-1,6]:Integer, [-1,7]:Integer}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Integer, [-1,1]:Integer, [-1,2]:Integer, [-1,3]:Integer, [-1,4]:Integer, [-1,5]:Integer, [-1,6]:Integer, [-1,7]:Integer} +// CHECK-DAG: %{{[0-9]+}} = load i64, ptr %{{[0-9]+}}, align 8, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = mul i64 %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: ret i64 %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} \ No newline at end of file diff --git a/tests/run-make/autodiff/type-trees/type-analysis/usize/usize.rs b/tests/run-make/autodiff/type-trees/type-analysis/usize/usize.rs new file mode 100644 index 00000000000..8e758be57d4 --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/usize/usize.rs @@ -0,0 +1,14 @@ +#![feature(autodiff)] + +use std::autodiff::autodiff_reverse; + +#[autodiff_reverse(d_square, Duplicated, Active)] +#[no_mangle] +fn callee(x: &usize) -> usize { + *x * *x +} + +fn main() { + let x: usize = 7; + let _ = callee(&x); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/vec/rmake.rs b/tests/run-make/autodiff/type-trees/type-analysis/vec/rmake.rs new file mode 100644 index 00000000000..94491fab8d6 --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/vec/rmake.rs @@ -0,0 +1,28 @@ +//@ needs-enzyme +//@ ignore-cross-compile + +use std::fs; + +use run_make_support::{llvm_filecheck, rfs, rustc}; + +fn main() { + // Compile the Rust file with the required flags, capturing both stdout and stderr + let output = rustc() + .input("vec.rs") + .arg("-Zautodiff=Enable,PrintTAFn=callee") + .arg("-Zautodiff=NoPostopt") + .opt_level("3") + .arg("-Clto=fat") + .arg("-g") + .run(); + + let stdout = output.stdout_utf8(); + let stderr = output.stderr_utf8(); + + // Write the outputs to files + rfs::write("vec.stdout", stdout); + rfs::write("vec.stderr", stderr); + + // Run FileCheck on the stdout using the check file + llvm_filecheck().patterns("vec.check").stdin_buf(rfs::read("vec.stdout")).run(); +} diff --git a/tests/run-make/autodiff/type-trees/type-analysis/vec/vec.check b/tests/run-make/autodiff/type-trees/type-analysis/vec/vec.check new file mode 100644 index 00000000000..dcf9508b69d --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/vec/vec.check @@ -0,0 +1,18 @@ +// CHECK: callee - {[-1]:Float@float} |{[-1]:Pointer}:{} +// CHECK: ptr %{{[0-9]+}}: {[-1]:Pointer} +// CHECK-DAG: %{{[0-9]+}} = getelementptr inbounds nuw i8, ptr %{{[0-9]+}}, i64 8, !dbg !{{[0-9]+}}: {[-1]:Pointer} +// CHECK-DAG: %{{[0-9]+}} = load ptr, ptr %{{[0-9]+}}, align 8, !dbg !{{[0-9]+}}, !nonnull !102, !noundef !{{[0-9]+}}: {} +// CHECK-DAG: %{{[0-9]+}} = getelementptr inbounds nuw i8, ptr %{{[0-9]+}}, i64 16, !dbg !{{[0-9]+}}: {[-1]:Pointer} +// CHECK-DAG: %{{[0-9]+}} = load i64, ptr %{{[0-9]+}}, align 8, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {} +// CHECK-DAG: %{{[0-9]+}} = icmp eq i64 %{{[0-9]+}}, 0, !dbg !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: br i1 %{{[0-9]+}}, label %{{[0-9]+}}, label %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK-DAG: %{{[0-9]+}} = phi i64 [ %{{[0-9]+}}, %{{[0-9]+}} ], [ 0, %{{[0-9]+}} ], !dbg !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = phi float [ %{{[0-9]+}}, %{{[0-9]+}} ], [ -0.000000e+00, %{{[0-9]+}} ], !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = getelementptr inbounds nuw float, ptr %{{[0-9]+}}, i64 %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Pointer, [-1,0]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = load float, ptr %{{[0-9]+}}, align 4, !dbg !{{[0-9]+}}, !noundef !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = fadd float %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: %{{[0-9]+}} = add nuw i64 %{{[0-9]+}}, 1, !dbg !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: %{{[0-9]+}} = icmp eq i64 %{{[0-9]+}}, %{{[0-9]+}}, !dbg !{{[0-9]+}}: {[-1]:Integer} +// CHECK-DAG: br i1 %{{[0-9]+}}, label %{{[0-9]+}}, label %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} +// CHECK-DAG: %{{[0-9]+}} = phi float [ -0.000000e+00, %{{[0-9]+}} ], [ %{{[0-9]+}}, %{{[0-9]+}} ], !dbg !{{[0-9]+}}: {[-1]:Float@float} +// CHECK-DAG: ret float %{{[0-9]+}}, !dbg !{{[0-9]+}}: {} \ No newline at end of file diff --git a/tests/run-make/autodiff/type-trees/type-analysis/vec/vec.rs b/tests/run-make/autodiff/type-trees/type-analysis/vec/vec.rs new file mode 100644 index 00000000000..b60c2a88064 --- /dev/null +++ b/tests/run-make/autodiff/type-trees/type-analysis/vec/vec.rs @@ -0,0 +1,14 @@ +#![feature(autodiff)] + +use std::autodiff::autodiff_reverse; + +#[autodiff_reverse(d_square, Duplicated, Active)] +#[no_mangle] +fn callee(arg: &std::vec::Vec<f32>) -> f32 { + arg.iter().sum() +} + +fn main() { + let v = vec![1.0f32, 2.0, 3.0]; + let _ = callee(&v); +} diff --git a/tests/run-make/link-eh-frame-terminator/rmake.rs b/tests/run-make/link-eh-frame-terminator/rmake.rs index 6bfae386ea1..06b77f011ec 100644 --- a/tests/run-make/link-eh-frame-terminator/rmake.rs +++ b/tests/run-make/link-eh-frame-terminator/rmake.rs @@ -9,6 +9,7 @@ //@ ignore-32bit // Reason: the usage of a large array in the test causes an out-of-memory // error on 32 bit systems. +//@ ignore-cross-compile use run_make_support::{bin_name, llvm_objdump, run, rustc}; diff --git a/tests/rustdoc-js-std/alias-lev.js b/tests/rustdoc-js-std/alias-lev.js new file mode 100644 index 00000000000..17f3dc25d76 --- /dev/null +++ b/tests/rustdoc-js-std/alias-lev.js @@ -0,0 +1,11 @@ +// This test ensures that aliases are also allowed to be partially matched. + +// ignore-order + +const EXPECTED = { + // The full alias name is `getcwd`. + 'query': 'getcw', + 'others': [ + { 'path': 'std::env', 'name': 'current_dir', 'alias': 'getcwd' }, + ], +}; diff --git a/tests/rustdoc-js/non-english-identifier.js b/tests/rustdoc-js/non-english-identifier.js index f2180b4c755..3d50bd3ee90 100644 --- a/tests/rustdoc-js/non-english-identifier.js +++ b/tests/rustdoc-js/non-english-identifier.js @@ -115,11 +115,10 @@ const EXPECTED = [ query: '加法', others: [ { - name: "add", + name: "加法", path: "non_english_identifier", - is_alias: true, - alias: "加法", - href: "../non_english_identifier/macro.add.html" + href: "../non_english_identifier/trait.加法.html", + desc: "Add" }, { name: "add", @@ -129,11 +128,13 @@ const EXPECTED = [ href: "../non_english_identifier/fn.add.html" }, { - name: "加法", + name: "add", path: "non_english_identifier", - href: "../non_english_identifier/trait.加法.html", - desc: "Add" - }], + is_alias: true, + alias: "加法", + href: "../non_english_identifier/macro.add.html" + }, + ], in_args: [{ name: "加上", path: "non_english_identifier::加法", diff --git a/tests/rustdoc-ui/check-doc-alias-attr-location.stderr b/tests/rustdoc-ui/check-doc-alias-attr-location.stderr index 85c9516236c..9d3ce5e63ef 100644 --- a/tests/rustdoc-ui/check-doc-alias-attr-location.stderr +++ b/tests/rustdoc-ui/check-doc-alias-attr-location.stderr @@ -4,13 +4,13 @@ error: `#[doc(alias = "...")]` isn't allowed on foreign module LL | #[doc(alias = "foo")] | ^^^^^^^^^^^^^ -error: `#[doc(alias = "...")]` isn't allowed on implementation block +error: `#[doc(alias = "...")]` isn't allowed on inherent implementation block --> $DIR/check-doc-alias-attr-location.rs:10:7 | LL | #[doc(alias = "bar")] | ^^^^^^^^^^^^^ -error: `#[doc(alias = "...")]` isn't allowed on implementation block +error: `#[doc(alias = "...")]` isn't allowed on trait implementation block --> $DIR/check-doc-alias-attr-location.rs:16:7 | LL | #[doc(alias = "foobar")] diff --git a/tests/rustdoc/reexport/auxiliary/reexports-attrs.rs b/tests/rustdoc/reexport/auxiliary/reexports-attrs.rs new file mode 100644 index 00000000000..96fa8209cde --- /dev/null +++ b/tests/rustdoc/reexport/auxiliary/reexports-attrs.rs @@ -0,0 +1,14 @@ +#[unsafe(no_mangle)] +pub fn f0() {} + +#[unsafe(link_section = ".here")] +pub fn f1() {} + +#[unsafe(export_name = "f2export")] +pub fn f2() {} + +#[repr(u8)] +pub enum T0 { V1 } + +#[non_exhaustive] +pub enum T1 {} diff --git a/tests/rustdoc/reexport/reexport-attrs.rs b/tests/rustdoc/reexport/reexport-attrs.rs new file mode 100644 index 00000000000..0ec645841f0 --- /dev/null +++ b/tests/rustdoc/reexport/reexport-attrs.rs @@ -0,0 +1,20 @@ +//@ aux-build: reexports-attrs.rs + +#![crate_name = "foo"] + +extern crate reexports_attrs; + +//@ has 'foo/fn.f0.html' '//pre[@class="rust item-decl"]' '#[no_mangle]' +pub use reexports_attrs::f0; + +//@ has 'foo/fn.f1.html' '//pre[@class="rust item-decl"]' '#[link_section = ".here"]' +pub use reexports_attrs::f1; + +//@ has 'foo/fn.f2.html' '//pre[@class="rust item-decl"]' '#[export_name = "f2export"]' +pub use reexports_attrs::f2; + +//@ has 'foo/enum.T0.html' '//pre[@class="rust item-decl"]' '#[repr(u8)]' +pub use reexports_attrs::T0; + +//@ has 'foo/enum.T1.html' '//pre[@class="rust item-decl"]' '#[non_exhaustive]' +pub use reexports_attrs::T1; diff --git a/tests/ui/associated-item/missing-associated_item_or_field_def_ids.rs b/tests/ui/associated-item/missing-associated_item_or_field_def_ids.rs index b90bb9ea4dd..029ce7d0e7e 100644 --- a/tests/ui/associated-item/missing-associated_item_or_field_def_ids.rs +++ b/tests/ui/associated-item/missing-associated_item_or_field_def_ids.rs @@ -1,8 +1,7 @@ // Regression test for <https://github.com/rust-lang/rust/issues/137554>. fn main() -> dyn Iterator + ?Iterator::advance_by(usize) { - //~^ ERROR `?Trait` is not permitted in trait object types - //~| ERROR expected trait, found associated function `Iterator::advance_by` - //~| ERROR the value of the associated type `Item` in `Iterator` must be specified + //~^ ERROR expected trait, found associated function `Iterator::advance_by` + //~| ERROR relaxed bounds are not permitted in trait object types todo!() } diff --git a/tests/ui/associated-item/missing-associated_item_or_field_def_ids.stderr b/tests/ui/associated-item/missing-associated_item_or_field_def_ids.stderr index 7f0fbc800ed..ffe0b14a030 100644 --- a/tests/ui/associated-item/missing-associated_item_or_field_def_ids.stderr +++ b/tests/ui/associated-item/missing-associated_item_or_field_def_ids.stderr @@ -1,25 +1,15 @@ -error[E0658]: `?Trait` is not permitted in trait object types - --> $DIR/missing-associated_item_or_field_def_ids.rs:3:29 - | -LL | fn main() -> dyn Iterator + ?Iterator::advance_by(usize) { - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = help: add `#![feature(more_maybe_bounds)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - error[E0404]: expected trait, found associated function `Iterator::advance_by` --> $DIR/missing-associated_item_or_field_def_ids.rs:3:30 | LL | fn main() -> dyn Iterator + ?Iterator::advance_by(usize) { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ not a trait -error[E0191]: the value of the associated type `Item` in `Iterator` must be specified - --> $DIR/missing-associated_item_or_field_def_ids.rs:3:18 +error: relaxed bounds are not permitted in trait object types + --> $DIR/missing-associated_item_or_field_def_ids.rs:3:29 | LL | fn main() -> dyn Iterator + ?Iterator::advance_by(usize) { - | ^^^^^^^^ help: specify the associated type: `Iterator<Item = Type>` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: aborting due to 3 previous errors +error: aborting due to 2 previous errors -Some errors have detailed explanations: E0191, E0404, E0658. -For more information about an error, try `rustc --explain E0191`. +For more information about this error, try `rustc --explain E0404`. diff --git a/tests/ui/associated-types/avoid-getting-associated-items-of-undefined-trait.rs b/tests/ui/associated-types/avoid-getting-associated-items-of-undefined-trait.rs index f6b749a5100..bac4e608867 100644 --- a/tests/ui/associated-types/avoid-getting-associated-items-of-undefined-trait.rs +++ b/tests/ui/associated-types/avoid-getting-associated-items-of-undefined-trait.rs @@ -6,7 +6,6 @@ trait Tr { fn main() { let _: dyn Tr + ?Foo<Assoc = ()>; - //~^ ERROR: `?Trait` is not permitted in trait object types - //~| ERROR: cannot find trait `Foo` in this scope - //~| ERROR: the value of the associated type `Item` in `Tr` must be specified + //~^ ERROR: cannot find trait `Foo` in this scope + //~| ERROR: relaxed bounds are not permitted in trait object types } diff --git a/tests/ui/associated-types/avoid-getting-associated-items-of-undefined-trait.stderr b/tests/ui/associated-types/avoid-getting-associated-items-of-undefined-trait.stderr index f31a1de76a7..3660fcece62 100644 --- a/tests/ui/associated-types/avoid-getting-associated-items-of-undefined-trait.stderr +++ b/tests/ui/associated-types/avoid-getting-associated-items-of-undefined-trait.stderr @@ -1,28 +1,15 @@ -error[E0658]: `?Trait` is not permitted in trait object types - --> $DIR/avoid-getting-associated-items-of-undefined-trait.rs:8:21 - | -LL | let _: dyn Tr + ?Foo<Assoc = ()>; - | ^^^^^^^^^^^^^^^^ - | - = help: add `#![feature(more_maybe_bounds)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - error[E0405]: cannot find trait `Foo` in this scope --> $DIR/avoid-getting-associated-items-of-undefined-trait.rs:8:22 | LL | let _: dyn Tr + ?Foo<Assoc = ()>; | ^^^ not found in this scope -error[E0191]: the value of the associated type `Item` in `Tr` must be specified - --> $DIR/avoid-getting-associated-items-of-undefined-trait.rs:8:16 +error: relaxed bounds are not permitted in trait object types + --> $DIR/avoid-getting-associated-items-of-undefined-trait.rs:8:21 | -LL | type Item; - | --------- `Item` defined here -... LL | let _: dyn Tr + ?Foo<Assoc = ()>; - | ^^ help: specify the associated type: `Tr<Item = Type>` + | ^^^^^^^^^^^^^^^^ -error: aborting due to 3 previous errors +error: aborting due to 2 previous errors -Some errors have detailed explanations: E0191, E0405, E0658. -For more information about an error, try `rustc --explain E0191`. +For more information about this error, try `rustc --explain E0405`. diff --git a/tests/ui/attributes/positions/used.stderr b/tests/ui/attributes/positions/used.stderr index 96dd43a3a93..64460c178cb 100644 --- a/tests/ui/attributes/positions/used.stderr +++ b/tests/ui/attributes/positions/used.stderr @@ -28,7 +28,7 @@ error: attribute must be applied to a `static` variable LL | #[used] | ^^^^^^^ LL | impl Bar for Foo {} - | ------------------- but this is a implementation block + | ------------------- but this is a trait implementation block error: attribute must be applied to a `static` variable --> $DIR/used.rs:21:5 diff --git a/tests/ui/cfg/crt-static-with-target-features-works.rs b/tests/ui/cfg/crt-static-with-target-features-works.rs new file mode 100644 index 00000000000..bce02229624 --- /dev/null +++ b/tests/ui/cfg/crt-static-with-target-features-works.rs @@ -0,0 +1,24 @@ +// Test to ensure that specifying a value for crt-static in target features +// does not result in skipping the features following it. +// This is a regression test for #144143 + +//@ add-core-stubs +//@ needs-llvm-components: x86 +//@ compile-flags: --target=x86_64-unknown-linux-gnu +//@ compile-flags: -Ctarget-feature=+crt-static,+avx2 + +#![crate_type = "rlib"] +#![feature(no_core, rustc_attrs, lang_items)] +#![no_core] + +extern crate minicore; +use minicore::*; + +#[rustc_builtin_macro] +macro_rules! compile_error { + () => {}; +} + +#[cfg(target_feature = "avx2")] +compile_error!("+avx2"); +//~^ ERROR: +avx2 diff --git a/tests/ui/cfg/crt-static-with-target-features-works.stderr b/tests/ui/cfg/crt-static-with-target-features-works.stderr new file mode 100644 index 00000000000..6f265c685bb --- /dev/null +++ b/tests/ui/cfg/crt-static-with-target-features-works.stderr @@ -0,0 +1,8 @@ +error: +avx2 + --> $DIR/crt-static-with-target-features-works.rs:23:1 + | +LL | compile_error!("+avx2"); + | ^^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 1 previous error + diff --git a/tests/ui/const-generics/min_const_generics/invalid-patterns.32bit.stderr b/tests/ui/const-generics/min_const_generics/invalid-patterns.32bit.stderr index 92b226fe0f7..0c57eddbe93 100644 --- a/tests/ui/const-generics/min_const_generics/invalid-patterns.32bit.stderr +++ b/tests/ui/const-generics/min_const_generics/invalid-patterns.32bit.stderr @@ -1,8 +1,12 @@ -error[E0080]: using uninitialized data, but this operation requires initialized memory +error[E0080]: reading memory at ALLOC0[0x0..0x4], but memory is uninitialized at [0x1..0x4], and this operation requires initialized memory --> $DIR/invalid-patterns.rs:40:32 | LL | get_flag::<false, { unsafe { char_raw.character } }>(); | ^^^^^^^^^^^^^^^^^^ evaluation of `main::{constant#7}` failed here + | + = note: the raw bytes of the constant (size: 4, align: 4) { + ff __ __ __ │ .░░░ + } error[E0080]: constructing invalid value: encountered 0x42, but expected a boolean --> $DIR/invalid-patterns.rs:42:14 @@ -26,11 +30,15 @@ LL | get_flag::<{ unsafe { bool_raw.boolean } }, { unsafe { char_raw.character 42 │ B } -error[E0080]: using uninitialized data, but this operation requires initialized memory +error[E0080]: reading memory at ALLOC1[0x0..0x4], but memory is uninitialized at [0x1..0x4], and this operation requires initialized memory --> $DIR/invalid-patterns.rs:44:58 | LL | get_flag::<{ unsafe { bool_raw.boolean } }, { unsafe { char_raw.character } }>(); | ^^^^^^^^^^^^^^^^^^ evaluation of `main::{constant#11}` failed here + | + = note: the raw bytes of the constant (size: 4, align: 4) { + ff __ __ __ │ .░░░ + } error[E0308]: mismatched types --> $DIR/invalid-patterns.rs:31:21 diff --git a/tests/ui/const-generics/min_const_generics/invalid-patterns.64bit.stderr b/tests/ui/const-generics/min_const_generics/invalid-patterns.64bit.stderr index 92b226fe0f7..0c57eddbe93 100644 --- a/tests/ui/const-generics/min_const_generics/invalid-patterns.64bit.stderr +++ b/tests/ui/const-generics/min_const_generics/invalid-patterns.64bit.stderr @@ -1,8 +1,12 @@ -error[E0080]: using uninitialized data, but this operation requires initialized memory +error[E0080]: reading memory at ALLOC0[0x0..0x4], but memory is uninitialized at [0x1..0x4], and this operation requires initialized memory --> $DIR/invalid-patterns.rs:40:32 | LL | get_flag::<false, { unsafe { char_raw.character } }>(); | ^^^^^^^^^^^^^^^^^^ evaluation of `main::{constant#7}` failed here + | + = note: the raw bytes of the constant (size: 4, align: 4) { + ff __ __ __ │ .░░░ + } error[E0080]: constructing invalid value: encountered 0x42, but expected a boolean --> $DIR/invalid-patterns.rs:42:14 @@ -26,11 +30,15 @@ LL | get_flag::<{ unsafe { bool_raw.boolean } }, { unsafe { char_raw.character 42 │ B } -error[E0080]: using uninitialized data, but this operation requires initialized memory +error[E0080]: reading memory at ALLOC1[0x0..0x4], but memory is uninitialized at [0x1..0x4], and this operation requires initialized memory --> $DIR/invalid-patterns.rs:44:58 | LL | get_flag::<{ unsafe { bool_raw.boolean } }, { unsafe { char_raw.character } }>(); | ^^^^^^^^^^^^^^^^^^ evaluation of `main::{constant#11}` failed here + | + = note: the raw bytes of the constant (size: 4, align: 4) { + ff __ __ __ │ .░░░ + } error[E0308]: mismatched types --> $DIR/invalid-patterns.rs:31:21 diff --git a/tests/ui/consts/const-compare-bytes-ub.stderr b/tests/ui/consts/const-compare-bytes-ub.stderr index c1706a8c4b0..770a55cc726 100644 --- a/tests/ui/consts/const-compare-bytes-ub.stderr +++ b/tests/ui/consts/const-compare-bytes-ub.stderr @@ -33,12 +33,20 @@ error[E0080]: reading memory at ALLOC2[0x0..0x1], but memory is uninitialized at | LL | compare_bytes(MaybeUninit::uninit().as_ptr(), [1].as_ptr(), 1) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `main::LHS_UNINIT` failed here + | + = note: the raw bytes of the constant (size: 1, align: 1) { + __ │ ░ + } error[E0080]: reading memory at ALLOC3[0x0..0x1], but memory is uninitialized at [0x0..0x1], and this operation requires initialized memory --> $DIR/const-compare-bytes-ub.rs:33:9 | LL | compare_bytes([1].as_ptr(), MaybeUninit::uninit().as_ptr(), 1) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `main::RHS_UNINIT` failed here + | + = note: the raw bytes of the constant (size: 1, align: 1) { + __ │ ░ + } error[E0080]: unable to turn pointer into integer --> $DIR/const-compare-bytes-ub.rs:37:9 diff --git a/tests/ui/consts/const-err-enum-discriminant.32bit.stderr b/tests/ui/consts/const-err-enum-discriminant.32bit.stderr new file mode 100644 index 00000000000..cc786108f64 --- /dev/null +++ b/tests/ui/consts/const-err-enum-discriminant.32bit.stderr @@ -0,0 +1,13 @@ +error[E0080]: reading memory at ALLOC0[0x0..0x4], but memory is uninitialized at [0x0..0x4], and this operation requires initialized memory + --> $DIR/const-err-enum-discriminant.rs:10:21 + | +LL | Boo = [unsafe { Foo { b: () }.a }; 4][3], + | ^^^^^^^^^^^^^^^ evaluation of `Bar::Boo::{constant#0}` failed here + | + = note: the raw bytes of the constant (size: 4, align: 4) { + __ __ __ __ │ ░░░░ + } + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0080`. diff --git a/tests/ui/consts/const-err-enum-discriminant.64bit.stderr b/tests/ui/consts/const-err-enum-discriminant.64bit.stderr new file mode 100644 index 00000000000..1d32851aac1 --- /dev/null +++ b/tests/ui/consts/const-err-enum-discriminant.64bit.stderr @@ -0,0 +1,13 @@ +error[E0080]: reading memory at ALLOC0[0x0..0x8], but memory is uninitialized at [0x0..0x8], and this operation requires initialized memory + --> $DIR/const-err-enum-discriminant.rs:10:21 + | +LL | Boo = [unsafe { Foo { b: () }.a }; 4][3], + | ^^^^^^^^^^^^^^^ evaluation of `Bar::Boo::{constant#0}` failed here + | + = note: the raw bytes of the constant (size: 8, align: 8) { + __ __ __ __ __ __ __ __ │ ░░░░░░░░ + } + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0080`. diff --git a/tests/ui/consts/const-err-enum-discriminant.rs b/tests/ui/consts/const-err-enum-discriminant.rs index 190ef47f436..55674600584 100644 --- a/tests/ui/consts/const-err-enum-discriminant.rs +++ b/tests/ui/consts/const-err-enum-discriminant.rs @@ -1,3 +1,5 @@ +//@ stderr-per-bitwidth + #[derive(Copy, Clone)] union Foo { a: isize, diff --git a/tests/ui/consts/const-err-enum-discriminant.stderr b/tests/ui/consts/const-err-enum-discriminant.stderr deleted file mode 100644 index 8724333ad7a..00000000000 --- a/tests/ui/consts/const-err-enum-discriminant.stderr +++ /dev/null @@ -1,9 +0,0 @@ -error[E0080]: using uninitialized data, but this operation requires initialized memory - --> $DIR/const-err-enum-discriminant.rs:8:21 - | -LL | Boo = [unsafe { Foo { b: () }.a }; 4][3], - | ^^^^^^^^^^^^^^^ evaluation of `Bar::Boo::{constant#0}` failed here - -error: aborting due to 1 previous error - -For more information about this error, try `rustc --explain E0080`. diff --git a/tests/ui/consts/const-eval/const-pointer-values-in-various-types.64bit.stderr b/tests/ui/consts/const-eval/const-pointer-values-in-various-types.64bit.stderr index d28d6841ca9..60f6ef0f64b 100644 --- a/tests/ui/consts/const-eval/const-pointer-values-in-various-types.64bit.stderr +++ b/tests/ui/consts/const-eval/const-pointer-values-in-various-types.64bit.stderr @@ -43,11 +43,15 @@ LL | const I32_REF_U64_UNION: u64 = unsafe { Nonsense { int_32_ref: &3 }.uin = help: this code performed an operation that depends on the underlying bytes representing a pointer = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported -error[E0080]: using uninitialized data, but this operation requires initialized memory +error[E0080]: reading memory at ALLOC2[0x0..0x10], but memory is uninitialized at [0x8..0x10], and this operation requires initialized memory --> $DIR/const-pointer-values-in-various-types.rs:42:47 | LL | const I32_REF_U128_UNION: u128 = unsafe { Nonsense { int_32_ref: &3 }.uint_128 }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `main::I32_REF_U128_UNION` failed here + | + = note: the raw bytes of the constant (size: 16, align: 16) { + ╾ALLOC0<imm>╼ __ __ __ __ __ __ __ __ │ ╾──────╼░░░░░░░░ + } error[E0080]: unable to turn pointer into integer --> $DIR/const-pointer-values-in-various-types.rs:45:43 @@ -85,11 +89,15 @@ LL | const I32_REF_I64_UNION: i64 = unsafe { Nonsense { int_32_ref: &3 }.int = help: this code performed an operation that depends on the underlying bytes representing a pointer = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported -error[E0080]: using uninitialized data, but this operation requires initialized memory +error[E0080]: reading memory at ALLOC3[0x0..0x10], but memory is uninitialized at [0x8..0x10], and this operation requires initialized memory --> $DIR/const-pointer-values-in-various-types.rs:57:47 | LL | const I32_REF_I128_UNION: i128 = unsafe { Nonsense { int_32_ref: &3 }.int_128 }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `main::I32_REF_I128_UNION` failed here + | + = note: the raw bytes of the constant (size: 16, align: 16) { + ╾ALLOC1<imm>╼ __ __ __ __ __ __ __ __ │ ╾──────╼░░░░░░░░ + } error[E0080]: unable to turn pointer into integer --> $DIR/const-pointer-values-in-various-types.rs:60:45 diff --git a/tests/ui/consts/const-eval/ub-enum-overwrite.stderr b/tests/ui/consts/const-eval/ub-enum-overwrite.stderr index 52af52d3236..2fd01b67c49 100644 --- a/tests/ui/consts/const-eval/ub-enum-overwrite.stderr +++ b/tests/ui/consts/const-eval/ub-enum-overwrite.stderr @@ -1,8 +1,12 @@ -error[E0080]: using uninitialized data, but this operation requires initialized memory +error[E0080]: reading memory at ALLOC0[0x1..0x2], but memory is uninitialized at [0x1..0x2], and this operation requires initialized memory --> $DIR/ub-enum-overwrite.rs:11:14 | LL | unsafe { *p } | ^^ evaluation of `_` failed here + | + = note: the raw bytes of the constant (size: 2, align: 1) { + 01 __ │ .░ + } error: aborting due to 1 previous error diff --git a/tests/ui/consts/const-eval/ub-enum.rs b/tests/ui/consts/const-eval/ub-enum.rs index 52fc9945068..9c78bb6efed 100644 --- a/tests/ui/consts/const-eval/ub-enum.rs +++ b/tests/ui/consts/const-eval/ub-enum.rs @@ -1,7 +1,8 @@ // Strip out raw byte dumps to make comparison platform-independent: //@ normalize-stderr: "(the raw bytes of the constant) \(size: [0-9]*, align: [0-9]*\)" -> "$1 (size: $$SIZE, align: $$ALIGN)" -//@ normalize-stderr: "([0-9a-f][0-9a-f] |╾─*ALLOC[0-9]+(\+[a-z0-9]+)?(<imm>)?─*╼ )+ *│.*" -> "HEX_DUMP" +//@ normalize-stderr: "([0-9a-f][0-9a-f] |__ |╾─*ALLOC[0-9]+(\+[a-z0-9]+)?(<imm>)?─*╼ )+ *│.*" -> "HEX_DUMP" //@ normalize-stderr: "0x0+" -> "0x0" +//@ normalize-stderr: "0x[0-9](\.\.|\])" -> "0x%$1" //@ dont-require-annotations: NOTE #![feature(never_type)] diff --git a/tests/ui/consts/const-eval/ub-enum.stderr b/tests/ui/consts/const-eval/ub-enum.stderr index 29f7a1f051a..5cbd6176c92 100644 --- a/tests/ui/consts/const-eval/ub-enum.stderr +++ b/tests/ui/consts/const-eval/ub-enum.stderr @@ -1,5 +1,5 @@ error[E0080]: constructing invalid value at .<enum-tag>: encountered 0x01, but expected a valid enum tag - --> $DIR/ub-enum.rs:29:1 + --> $DIR/ub-enum.rs:30:1 | LL | const BAD_ENUM: Enum = unsafe { mem::transmute(1usize) }; | ^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -10,7 +10,7 @@ LL | const BAD_ENUM: Enum = unsafe { mem::transmute(1usize) }; } error[E0080]: unable to turn pointer into integer - --> $DIR/ub-enum.rs:32:1 + --> $DIR/ub-enum.rs:33:1 | LL | const BAD_ENUM_PTR: Enum = unsafe { mem::transmute(&1) }; | ^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `BAD_ENUM_PTR` failed here @@ -19,7 +19,7 @@ LL | const BAD_ENUM_PTR: Enum = unsafe { mem::transmute(&1) }; = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported error[E0080]: unable to turn pointer into integer - --> $DIR/ub-enum.rs:35:1 + --> $DIR/ub-enum.rs:36:1 | LL | const BAD_ENUM_WRAPPED: Wrap<Enum> = unsafe { mem::transmute(&1) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `BAD_ENUM_WRAPPED` failed here @@ -28,7 +28,7 @@ LL | const BAD_ENUM_WRAPPED: Wrap<Enum> = unsafe { mem::transmute(&1) }; = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported error[E0080]: constructing invalid value at .<enum-tag>: encountered 0x0, but expected a valid enum tag - --> $DIR/ub-enum.rs:47:1 + --> $DIR/ub-enum.rs:48:1 | LL | const BAD_ENUM2: Enum2 = unsafe { mem::transmute(0usize) }; | ^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -39,7 +39,7 @@ LL | const BAD_ENUM2: Enum2 = unsafe { mem::transmute(0usize) }; } error[E0080]: unable to turn pointer into integer - --> $DIR/ub-enum.rs:49:1 + --> $DIR/ub-enum.rs:50:1 | LL | const BAD_ENUM2_PTR: Enum2 = unsafe { mem::transmute(&0) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `BAD_ENUM2_PTR` failed here @@ -48,7 +48,7 @@ LL | const BAD_ENUM2_PTR: Enum2 = unsafe { mem::transmute(&0) }; = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported error[E0080]: unable to turn pointer into integer - --> $DIR/ub-enum.rs:52:1 + --> $DIR/ub-enum.rs:53:1 | LL | const BAD_ENUM2_WRAPPED: Wrap<Enum2> = unsafe { mem::transmute(&0) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `BAD_ENUM2_WRAPPED` failed here @@ -56,14 +56,18 @@ LL | const BAD_ENUM2_WRAPPED: Wrap<Enum2> = unsafe { mem::transmute(&0) }; = help: this code performed an operation that depends on the underlying bytes representing a pointer = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported -error[E0080]: using uninitialized data, but this operation requires initialized memory - --> $DIR/ub-enum.rs:61:41 +error[E0080]: reading memory at ALLOC0[0x%..0x%], but memory is uninitialized at [0x%..0x%], and this operation requires initialized memory + --> $DIR/ub-enum.rs:62:41 | LL | const BAD_ENUM2_UNDEF: Enum2 = unsafe { MaybeUninit { uninit: () }.init }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `BAD_ENUM2_UNDEF` failed here + | + = note: the raw bytes of the constant (size: $SIZE, align: $ALIGN) { + HEX_DUMP + } error[E0080]: unable to turn pointer into integer - --> $DIR/ub-enum.rs:65:1 + --> $DIR/ub-enum.rs:66:1 | LL | const BAD_ENUM2_OPTION_PTR: Option<Enum2> = unsafe { mem::transmute(&0) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `BAD_ENUM2_OPTION_PTR` failed here @@ -72,7 +76,7 @@ LL | const BAD_ENUM2_OPTION_PTR: Option<Enum2> = unsafe { mem::transmute(&0) }; = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported error[E0080]: constructing invalid value at .<enum-tag>: encountered an uninhabited enum variant - --> $DIR/ub-enum.rs:82:1 + --> $DIR/ub-enum.rs:83:1 | LL | const BAD_UNINHABITED_VARIANT1: UninhDiscriminant = unsafe { mem::transmute(1u8) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -83,7 +87,7 @@ LL | const BAD_UNINHABITED_VARIANT1: UninhDiscriminant = unsafe { mem::transmute } error[E0080]: constructing invalid value at .<enum-tag>: encountered an uninhabited enum variant - --> $DIR/ub-enum.rs:84:1 + --> $DIR/ub-enum.rs:85:1 | LL | const BAD_UNINHABITED_VARIANT2: UninhDiscriminant = unsafe { mem::transmute(3u8) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -94,7 +98,7 @@ LL | const BAD_UNINHABITED_VARIANT2: UninhDiscriminant = unsafe { mem::transmute } error[E0080]: constructing invalid value at .<enum-variant(Some)>.0.1: encountered 0xffffffff, but expected a valid unicode scalar value (in `0..=0x10FFFF` but not in `0xD800..=0xDFFF`) - --> $DIR/ub-enum.rs:92:1 + --> $DIR/ub-enum.rs:93:1 | LL | const BAD_OPTION_CHAR: Option<(char, char)> = Some(('x', unsafe { mem::transmute(!0u32) })); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -105,19 +109,19 @@ LL | const BAD_OPTION_CHAR: Option<(char, char)> = Some(('x', unsafe { mem::tran } error[E0080]: constructing invalid value at .<enum-tag>: encountered an uninhabited enum variant - --> $DIR/ub-enum.rs:97:77 + --> $DIR/ub-enum.rs:98:77 | LL | const BAD_UNINHABITED_WITH_DATA1: Result<(i32, Never), (i32, !)> = unsafe { mem::transmute(0u64) }; | ^^^^^^^^^^^^^^^^^^^^ evaluation of `BAD_UNINHABITED_WITH_DATA1` failed here error[E0080]: constructing invalid value at .<enum-tag>: encountered an uninhabited enum variant - --> $DIR/ub-enum.rs:99:77 + --> $DIR/ub-enum.rs:100:77 | LL | const BAD_UNINHABITED_WITH_DATA2: Result<(i32, !), (i32, Never)> = unsafe { mem::transmute(0u64) }; | ^^^^^^^^^^^^^^^^^^^^ evaluation of `BAD_UNINHABITED_WITH_DATA2` failed here error[E0080]: read discriminant of an uninhabited enum variant - --> $DIR/ub-enum.rs:105:9 + --> $DIR/ub-enum.rs:106:9 | LL | std::mem::discriminant(&*(&() as *const () as *const Never)); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `TEST_ICE_89765` failed inside this call diff --git a/tests/ui/consts/const-eval/ub-nonnull.stderr b/tests/ui/consts/const-eval/ub-nonnull.stderr index 314141e4837..19ae66cf3c6 100644 --- a/tests/ui/consts/const-eval/ub-nonnull.stderr +++ b/tests/ui/consts/const-eval/ub-nonnull.stderr @@ -37,11 +37,15 @@ LL | const NULL_USIZE: NonZero<usize> = unsafe { mem::transmute(0usize) }; HEX_DUMP } -error[E0080]: using uninitialized data, but this operation requires initialized memory +error[E0080]: reading memory at ALLOC2[0x0..0x1], but memory is uninitialized at [0x0..0x1], and this operation requires initialized memory --> $DIR/ub-nonnull.rs:36:38 | LL | const UNINIT: NonZero<u8> = unsafe { MaybeUninit { uninit: () }.init }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `UNINIT` failed here + | + = note: the raw bytes of the constant (size: $SIZE, align: $ALIGN) { + __ │ ░ + } error[E0080]: constructing invalid value: encountered 42, but expected something in the range 10..=30 --> $DIR/ub-nonnull.rs:44:1 diff --git a/tests/ui/consts/const-eval/ub-ref-ptr.rs b/tests/ui/consts/const-eval/ub-ref-ptr.rs index 64b48939be6..d8e5102fcbe 100644 --- a/tests/ui/consts/const-eval/ub-ref-ptr.rs +++ b/tests/ui/consts/const-eval/ub-ref-ptr.rs @@ -1,8 +1,9 @@ // ignore-tidy-linelength // Strip out raw byte dumps to make comparison platform-independent: //@ normalize-stderr: "(the raw bytes of the constant) \(size: [0-9]*, align: [0-9]*\)" -> "$1 (size: $$SIZE, align: $$ALIGN)" -//@ normalize-stderr: "([0-9a-f][0-9a-f] |╾─*ALLOC[0-9]+(\+[a-z0-9]+)?(<imm>)?─*╼ )+ *│.*" -> "HEX_DUMP" +//@ normalize-stderr: "([0-9a-f][0-9a-f] |__ |╾─*ALLOC[0-9]+(\+[a-z0-9]+)?(<imm>)?─*╼ )+ *│.*" -> "HEX_DUMP" //@ dont-require-annotations: NOTE +//@ normalize-stderr: "0x[0-9](\.\.|\])" -> "0x%$1" #![allow(invalid_value)] diff --git a/tests/ui/consts/const-eval/ub-ref-ptr.stderr b/tests/ui/consts/const-eval/ub-ref-ptr.stderr index d5ccc396b90..451ebb6eba1 100644 --- a/tests/ui/consts/const-eval/ub-ref-ptr.stderr +++ b/tests/ui/consts/const-eval/ub-ref-ptr.stderr @@ -1,5 +1,5 @@ error[E0080]: constructing invalid value: encountered an unaligned reference (required 2 byte alignment but found 1) - --> $DIR/ub-ref-ptr.rs:17:1 + --> $DIR/ub-ref-ptr.rs:18:1 | LL | const UNALIGNED: &u16 = unsafe { mem::transmute(&[0u8; 4]) }; | ^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -10,7 +10,7 @@ LL | const UNALIGNED: &u16 = unsafe { mem::transmute(&[0u8; 4]) }; } error[E0080]: constructing invalid value: encountered an unaligned box (required 2 byte alignment but found 1) - --> $DIR/ub-ref-ptr.rs:20:1 + --> $DIR/ub-ref-ptr.rs:21:1 | LL | const UNALIGNED_BOX: Box<u16> = unsafe { mem::transmute(&[0u8; 4]) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -21,7 +21,7 @@ LL | const UNALIGNED_BOX: Box<u16> = unsafe { mem::transmute(&[0u8; 4]) }; } error[E0080]: constructing invalid value: encountered a null reference - --> $DIR/ub-ref-ptr.rs:23:1 + --> $DIR/ub-ref-ptr.rs:24:1 | LL | const NULL: &u16 = unsafe { mem::transmute(0usize) }; | ^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -32,7 +32,7 @@ LL | const NULL: &u16 = unsafe { mem::transmute(0usize) }; } error[E0080]: constructing invalid value: encountered a null box - --> $DIR/ub-ref-ptr.rs:26:1 + --> $DIR/ub-ref-ptr.rs:27:1 | LL | const NULL_BOX: Box<u16> = unsafe { mem::transmute(0usize) }; | ^^^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -43,7 +43,7 @@ LL | const NULL_BOX: Box<u16> = unsafe { mem::transmute(0usize) }; } error[E0080]: unable to turn pointer into integer - --> $DIR/ub-ref-ptr.rs:33:1 + --> $DIR/ub-ref-ptr.rs:34:1 | LL | const REF_AS_USIZE: usize = unsafe { mem::transmute(&0) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `REF_AS_USIZE` failed here @@ -52,7 +52,7 @@ LL | const REF_AS_USIZE: usize = unsafe { mem::transmute(&0) }; = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported error[E0080]: unable to turn pointer into integer - --> $DIR/ub-ref-ptr.rs:36:39 + --> $DIR/ub-ref-ptr.rs:37:39 | LL | const REF_AS_USIZE_SLICE: &[usize] = &[unsafe { mem::transmute(&0) }]; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `REF_AS_USIZE_SLICE` failed here @@ -61,13 +61,13 @@ LL | const REF_AS_USIZE_SLICE: &[usize] = &[unsafe { mem::transmute(&0) }]; = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported note: erroneous constant encountered - --> $DIR/ub-ref-ptr.rs:36:38 + --> $DIR/ub-ref-ptr.rs:37:38 | LL | const REF_AS_USIZE_SLICE: &[usize] = &[unsafe { mem::transmute(&0) }]; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0080]: unable to turn pointer into integer - --> $DIR/ub-ref-ptr.rs:39:86 + --> $DIR/ub-ref-ptr.rs:40:86 | LL | const REF_AS_USIZE_BOX_SLICE: Box<[usize]> = unsafe { mem::transmute::<&[usize], _>(&[mem::transmute(&0)]) }; | ^^^^^^^^^^^^^^^^^^^^ evaluation of `REF_AS_USIZE_BOX_SLICE` failed here @@ -76,13 +76,13 @@ LL | const REF_AS_USIZE_BOX_SLICE: Box<[usize]> = unsafe { mem::transmute::<&[us = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported note: erroneous constant encountered - --> $DIR/ub-ref-ptr.rs:39:85 + --> $DIR/ub-ref-ptr.rs:40:85 | LL | const REF_AS_USIZE_BOX_SLICE: Box<[usize]> = unsafe { mem::transmute::<&[usize], _>(&[mem::transmute(&0)]) }; | ^^^^^^^^^^^^^^^^^^^^^ error[E0080]: constructing invalid value: encountered a dangling reference (0x539[noalloc] has no provenance) - --> $DIR/ub-ref-ptr.rs:42:1 + --> $DIR/ub-ref-ptr.rs:43:1 | LL | const USIZE_AS_REF: &'static u8 = unsafe { mem::transmute(1337usize) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -93,7 +93,7 @@ LL | const USIZE_AS_REF: &'static u8 = unsafe { mem::transmute(1337usize) }; } error[E0080]: constructing invalid value: encountered a dangling box (0x539[noalloc] has no provenance) - --> $DIR/ub-ref-ptr.rs:45:1 + --> $DIR/ub-ref-ptr.rs:46:1 | LL | const USIZE_AS_BOX: Box<u8> = unsafe { mem::transmute(1337usize) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -103,14 +103,18 @@ LL | const USIZE_AS_BOX: Box<u8> = unsafe { mem::transmute(1337usize) }; HEX_DUMP } -error[E0080]: using uninitialized data, but this operation requires initialized memory - --> $DIR/ub-ref-ptr.rs:48:41 +error[E0080]: reading memory at ALLOC3[0x%..0x%], but memory is uninitialized at [0x%..0x%], and this operation requires initialized memory + --> $DIR/ub-ref-ptr.rs:49:41 | LL | const UNINIT_PTR: *const i32 = unsafe { MaybeUninit { uninit: () }.init }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `UNINIT_PTR` failed here + | + = note: the raw bytes of the constant (size: $SIZE, align: $ALIGN) { + HEX_DUMP + } error[E0080]: constructing invalid value: encountered null pointer, but expected a function pointer - --> $DIR/ub-ref-ptr.rs:51:1 + --> $DIR/ub-ref-ptr.rs:52:1 | LL | const NULL_FN_PTR: fn() = unsafe { mem::transmute(0usize) }; | ^^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -120,14 +124,18 @@ LL | const NULL_FN_PTR: fn() = unsafe { mem::transmute(0usize) }; HEX_DUMP } -error[E0080]: using uninitialized data, but this operation requires initialized memory - --> $DIR/ub-ref-ptr.rs:53:38 +error[E0080]: reading memory at ALLOC4[0x%..0x%], but memory is uninitialized at [0x%..0x%], and this operation requires initialized memory + --> $DIR/ub-ref-ptr.rs:54:38 | LL | const UNINIT_FN_PTR: fn() = unsafe { MaybeUninit { uninit: () }.init }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `UNINIT_FN_PTR` failed here + | + = note: the raw bytes of the constant (size: $SIZE, align: $ALIGN) { + HEX_DUMP + } error[E0080]: constructing invalid value: encountered 0xd[noalloc], but expected a function pointer - --> $DIR/ub-ref-ptr.rs:55:1 + --> $DIR/ub-ref-ptr.rs:56:1 | LL | const DANGLING_FN_PTR: fn() = unsafe { mem::transmute(13usize) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -138,7 +146,7 @@ LL | const DANGLING_FN_PTR: fn() = unsafe { mem::transmute(13usize) }; } error[E0080]: constructing invalid value: encountered ALLOC2<imm>, but expected a function pointer - --> $DIR/ub-ref-ptr.rs:57:1 + --> $DIR/ub-ref-ptr.rs:58:1 | LL | const DATA_FN_PTR: fn() = unsafe { mem::transmute(&13) }; | ^^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -149,7 +157,7 @@ LL | const DATA_FN_PTR: fn() = unsafe { mem::transmute(&13) }; } error[E0080]: accessing memory based on pointer with alignment 1, but alignment 4 is required - --> $DIR/ub-ref-ptr.rs:64:5 + --> $DIR/ub-ref-ptr.rs:65:5 | LL | ptr.read(); | ^^^^^^^^^^ evaluation of `UNALIGNED_READ` failed here diff --git a/tests/ui/consts/const-eval/ub-wide-ptr.rs b/tests/ui/consts/const-eval/ub-wide-ptr.rs index 86235897e7e..0bbb104c032 100644 --- a/tests/ui/consts/const-eval/ub-wide-ptr.rs +++ b/tests/ui/consts/const-eval/ub-wide-ptr.rs @@ -6,9 +6,10 @@ use std::{ptr, mem}; // Strip out raw byte dumps to make comparison platform-independent: //@ normalize-stderr: "(the raw bytes of the constant) \(size: [0-9]*, align: [0-9]*\)" -> "$1 (size: $$SIZE, align: $$ALIGN)" -//@ normalize-stderr: "([0-9a-f][0-9a-f] |╾─*ALLOC[0-9]+(\+[a-z0-9]+)?(<imm>)?─*╼ )+ *│.*" -> "HEX_DUMP" +//@ normalize-stderr: "([0-9a-f][0-9a-f] |__ |╾─*ALLOC[0-9]+(\+[a-z0-9]+)?(<imm>)?─*╼ )+ *│.*" -> "HEX_DUMP" //@ normalize-stderr: "offset \d+" -> "offset N" //@ normalize-stderr: "size \d+" -> "size N" +//@ normalize-stderr: "0x[0-9](\.\.|\])" -> "0x%$1" //@ dont-require-annotations: NOTE /// A newtype wrapper to prevent MIR generation from inserting reborrows that would affect the error @@ -61,7 +62,7 @@ const MYSTR_NO_INIT: &MyStr = unsafe { mem::transmute::<&[_], _>(&[MaybeUninit:: const SLICE_VALID: &[u8] = unsafe { mem::transmute((&42u8, 1usize)) }; // bad slice: length uninit const SLICE_LENGTH_UNINIT: &[u8] = unsafe { -//~^ ERROR uninitialized + //~^ ERROR uninitialized let uninit_len = MaybeUninit::<usize> { uninit: () }; mem::transmute((42, uninit_len)) }; @@ -99,7 +100,7 @@ const RAW_SLICE_VALID: *const [u8] = unsafe { mem::transmute((&42u8, 1usize)) }; const RAW_SLICE_TOO_LONG: *const [u8] = unsafe { mem::transmute((&42u8, 999usize)) }; // ok because raw const RAW_SLICE_MUCH_TOO_LONG: *const [u8] = unsafe { mem::transmute((&42u8, usize::MAX)) }; // ok because raw const RAW_SLICE_LENGTH_UNINIT: *const [u8] = unsafe { -//~^ ERROR uninitialized + //~^ ERROR uninitialized let uninit_len = MaybeUninit::<usize> { uninit: () }; mem::transmute((42, uninit_len)) }; diff --git a/tests/ui/consts/const-eval/ub-wide-ptr.stderr b/tests/ui/consts/const-eval/ub-wide-ptr.stderr index 8724dd9a3c0..ab15ba826a5 100644 --- a/tests/ui/consts/const-eval/ub-wide-ptr.stderr +++ b/tests/ui/consts/const-eval/ub-wide-ptr.stderr @@ -1,5 +1,5 @@ error[E0080]: constructing invalid value: encountered a dangling reference (going beyond the bounds of its allocation) - --> $DIR/ub-wide-ptr.rs:39:1 + --> $DIR/ub-wide-ptr.rs:40:1 | LL | const STR_TOO_LONG: &str = unsafe { mem::transmute((&42u8, 999usize)) }; | ^^^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -10,7 +10,7 @@ LL | const STR_TOO_LONG: &str = unsafe { mem::transmute((&42u8, 999usize)) }; } error[E0080]: constructing invalid value at .0: encountered invalid reference metadata: slice is bigger than largest supported object - --> $DIR/ub-wide-ptr.rs:41:1 + --> $DIR/ub-wide-ptr.rs:42:1 | LL | const NESTED_STR_MUCH_TOO_LONG: (&str,) = (unsafe { mem::transmute((&42, usize::MAX)) },); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -21,7 +21,7 @@ LL | const NESTED_STR_MUCH_TOO_LONG: (&str,) = (unsafe { mem::transmute((&42, us } error[E0080]: unable to turn pointer into integer - --> $DIR/ub-wide-ptr.rs:44:1 + --> $DIR/ub-wide-ptr.rs:45:1 | LL | const STR_LENGTH_PTR: &str = unsafe { mem::transmute((&42u8, &3)) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `STR_LENGTH_PTR` failed here @@ -30,7 +30,7 @@ LL | const STR_LENGTH_PTR: &str = unsafe { mem::transmute((&42u8, &3)) }; = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported error[E0080]: unable to turn pointer into integer - --> $DIR/ub-wide-ptr.rs:47:1 + --> $DIR/ub-wide-ptr.rs:48:1 | LL | const MY_STR_LENGTH_PTR: &MyStr = unsafe { mem::transmute((&42u8, &3)) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `MY_STR_LENGTH_PTR` failed here @@ -39,7 +39,7 @@ LL | const MY_STR_LENGTH_PTR: &MyStr = unsafe { mem::transmute((&42u8, &3)) }; = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported error[E0080]: constructing invalid value: encountered invalid reference metadata: slice is bigger than largest supported object - --> $DIR/ub-wide-ptr.rs:49:1 + --> $DIR/ub-wide-ptr.rs:50:1 | LL | const MY_STR_MUCH_TOO_LONG: &MyStr = unsafe { mem::transmute((&42u8, usize::MAX)) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -50,7 +50,7 @@ LL | const MY_STR_MUCH_TOO_LONG: &MyStr = unsafe { mem::transmute((&42u8, usize: } error[E0080]: constructing invalid value at .<deref>: encountered uninitialized memory, but expected a string - --> $DIR/ub-wide-ptr.rs:53:1 + --> $DIR/ub-wide-ptr.rs:54:1 | LL | const STR_NO_INIT: &str = unsafe { mem::transmute::<&[_], _>(&[MaybeUninit::<u8> { uninit: () }]) }; | ^^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -61,7 +61,7 @@ LL | const STR_NO_INIT: &str = unsafe { mem::transmute::<&[_], _>(&[MaybeUninit: } error[E0080]: constructing invalid value at .<deref>.0: encountered uninitialized memory, but expected a string - --> $DIR/ub-wide-ptr.rs:56:1 + --> $DIR/ub-wide-ptr.rs:57:1 | LL | const MYSTR_NO_INIT: &MyStr = unsafe { mem::transmute::<&[_], _>(&[MaybeUninit::<u8> { uninit: () }]) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -71,14 +71,18 @@ LL | const MYSTR_NO_INIT: &MyStr = unsafe { mem::transmute::<&[_], _>(&[MaybeUni HEX_DUMP } -error[E0080]: using uninitialized data, but this operation requires initialized memory - --> $DIR/ub-wide-ptr.rs:63:1 +error[E0080]: reading memory at ALLOC32[0x%..0x%], but memory is uninitialized at [0x%..0x%], and this operation requires initialized memory + --> $DIR/ub-wide-ptr.rs:64:1 | LL | const SLICE_LENGTH_UNINIT: &[u8] = unsafe { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `SLICE_LENGTH_UNINIT` failed here + | + = note: the raw bytes of the constant (size: $SIZE, align: $ALIGN) { + HEX_DUMP + } error[E0080]: constructing invalid value: encountered a dangling reference (going beyond the bounds of its allocation) - --> $DIR/ub-wide-ptr.rs:69:1 + --> $DIR/ub-wide-ptr.rs:70:1 | LL | const SLICE_TOO_LONG: &[u8] = unsafe { mem::transmute((&42u8, 999usize)) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -89,7 +93,7 @@ LL | const SLICE_TOO_LONG: &[u8] = unsafe { mem::transmute((&42u8, 999usize)) }; } error[E0080]: constructing invalid value: encountered invalid reference metadata: slice is bigger than largest supported object - --> $DIR/ub-wide-ptr.rs:72:1 + --> $DIR/ub-wide-ptr.rs:73:1 | LL | const SLICE_TOO_LONG_OVERFLOW: &[u32] = unsafe { mem::transmute((&42u32, isize::MAX)) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -100,7 +104,7 @@ LL | const SLICE_TOO_LONG_OVERFLOW: &[u32] = unsafe { mem::transmute((&42u32, is } error[E0080]: unable to turn pointer into integer - --> $DIR/ub-wide-ptr.rs:75:1 + --> $DIR/ub-wide-ptr.rs:76:1 | LL | const SLICE_LENGTH_PTR: &[u8] = unsafe { mem::transmute((&42u8, &3)) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `SLICE_LENGTH_PTR` failed here @@ -109,7 +113,7 @@ LL | const SLICE_LENGTH_PTR: &[u8] = unsafe { mem::transmute((&42u8, &3)) }; = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported error[E0080]: constructing invalid value: encountered a dangling box (going beyond the bounds of its allocation) - --> $DIR/ub-wide-ptr.rs:78:1 + --> $DIR/ub-wide-ptr.rs:79:1 | LL | const SLICE_TOO_LONG_BOX: Box<[u8]> = unsafe { mem::transmute((&42u8, 999usize)) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -120,7 +124,7 @@ LL | const SLICE_TOO_LONG_BOX: Box<[u8]> = unsafe { mem::transmute((&42u8, 999us } error[E0080]: unable to turn pointer into integer - --> $DIR/ub-wide-ptr.rs:81:1 + --> $DIR/ub-wide-ptr.rs:82:1 | LL | const SLICE_LENGTH_PTR_BOX: Box<[u8]> = unsafe { mem::transmute((&42u8, &3)) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `SLICE_LENGTH_PTR_BOX` failed here @@ -129,7 +133,7 @@ LL | const SLICE_LENGTH_PTR_BOX: Box<[u8]> = unsafe { mem::transmute((&42u8, &3) = help: the absolute address of a pointer is not known at compile-time, so such operations are not supported error[E0080]: constructing invalid value at .<deref>[0]: encountered 0x03, but expected a boolean - --> $DIR/ub-wide-ptr.rs:85:1 + --> $DIR/ub-wide-ptr.rs:86:1 | LL | const SLICE_CONTENT_INVALID: &[bool] = &[unsafe { mem::transmute(3u8) }]; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -140,13 +144,13 @@ LL | const SLICE_CONTENT_INVALID: &[bool] = &[unsafe { mem::transmute(3u8) }]; } note: erroneous constant encountered - --> $DIR/ub-wide-ptr.rs:85:40 + --> $DIR/ub-wide-ptr.rs:86:40 | LL | const SLICE_CONTENT_INVALID: &[bool] = &[unsafe { mem::transmute(3u8) }]; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0080]: constructing invalid value at .<deref>.0: encountered 0x03, but expected a boolean - --> $DIR/ub-wide-ptr.rs:91:1 + --> $DIR/ub-wide-ptr.rs:92:1 | LL | const MYSLICE_PREFIX_BAD: &MySliceBool = &MySlice(unsafe { mem::transmute(3u8) }, [false]); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -157,13 +161,13 @@ LL | const MYSLICE_PREFIX_BAD: &MySliceBool = &MySlice(unsafe { mem::transmute(3 } note: erroneous constant encountered - --> $DIR/ub-wide-ptr.rs:91:42 + --> $DIR/ub-wide-ptr.rs:92:42 | LL | const MYSLICE_PREFIX_BAD: &MySliceBool = &MySlice(unsafe { mem::transmute(3u8) }, [false]); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0080]: constructing invalid value at .<deref>.1[0]: encountered 0x03, but expected a boolean - --> $DIR/ub-wide-ptr.rs:94:1 + --> $DIR/ub-wide-ptr.rs:95:1 | LL | const MYSLICE_SUFFIX_BAD: &MySliceBool = &MySlice(true, [unsafe { mem::transmute(3u8) }]); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -174,19 +178,23 @@ LL | const MYSLICE_SUFFIX_BAD: &MySliceBool = &MySlice(true, [unsafe { mem::tran } note: erroneous constant encountered - --> $DIR/ub-wide-ptr.rs:94:42 + --> $DIR/ub-wide-ptr.rs:95:42 | LL | const MYSLICE_SUFFIX_BAD: &MySliceBool = &MySlice(true, [unsafe { mem::transmute(3u8) }]); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error[E0080]: using uninitialized data, but this operation requires initialized memory - --> $DIR/ub-wide-ptr.rs:101:1 +error[E0080]: reading memory at ALLOC33[0x%..0x%], but memory is uninitialized at [0x%..0x%], and this operation requires initialized memory + --> $DIR/ub-wide-ptr.rs:102:1 | LL | const RAW_SLICE_LENGTH_UNINIT: *const [u8] = unsafe { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `RAW_SLICE_LENGTH_UNINIT` failed here + | + = note: the raw bytes of the constant (size: $SIZE, align: $ALIGN) { + HEX_DUMP + } error[E0080]: constructing invalid value at .0: encountered ALLOC12<imm>, but expected a vtable pointer - --> $DIR/ub-wide-ptr.rs:109:1 + --> $DIR/ub-wide-ptr.rs:110:1 | LL | const TRAIT_OBJ_SHORT_VTABLE_1: W<&dyn Trait> = unsafe { mem::transmute(W((&92u8, &3u8))) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -197,7 +205,7 @@ LL | const TRAIT_OBJ_SHORT_VTABLE_1: W<&dyn Trait> = unsafe { mem::transmute(W(( } error[E0080]: constructing invalid value at .0: encountered ALLOC14<imm>, but expected a vtable pointer - --> $DIR/ub-wide-ptr.rs:112:1 + --> $DIR/ub-wide-ptr.rs:113:1 | LL | const TRAIT_OBJ_SHORT_VTABLE_2: W<&dyn Trait> = unsafe { mem::transmute(W((&92u8, &3u64))) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -208,7 +216,7 @@ LL | const TRAIT_OBJ_SHORT_VTABLE_2: W<&dyn Trait> = unsafe { mem::transmute(W(( } error[E0080]: constructing invalid value at .0: encountered 0x4[noalloc], but expected a vtable pointer - --> $DIR/ub-wide-ptr.rs:115:1 + --> $DIR/ub-wide-ptr.rs:116:1 | LL | const TRAIT_OBJ_INT_VTABLE: W<&dyn Trait> = unsafe { mem::transmute(W((&92u8, 4usize))) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -219,7 +227,7 @@ LL | const TRAIT_OBJ_INT_VTABLE: W<&dyn Trait> = unsafe { mem::transmute(W((&92u } error[E0080]: constructing invalid value: encountered ALLOC17<imm>, but expected a vtable pointer - --> $DIR/ub-wide-ptr.rs:117:1 + --> $DIR/ub-wide-ptr.rs:118:1 | LL | const TRAIT_OBJ_UNALIGNED_VTABLE: &dyn Trait = unsafe { mem::transmute((&92u8, &[0u8; 128])) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -230,7 +238,7 @@ LL | const TRAIT_OBJ_UNALIGNED_VTABLE: &dyn Trait = unsafe { mem::transmute((&92 } error[E0080]: constructing invalid value: encountered ALLOC19<imm>, but expected a vtable pointer - --> $DIR/ub-wide-ptr.rs:119:1 + --> $DIR/ub-wide-ptr.rs:120:1 | LL | const TRAIT_OBJ_BAD_DROP_FN_NULL: &dyn Trait = unsafe { mem::transmute((&92u8, &[0usize; 8])) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -241,7 +249,7 @@ LL | const TRAIT_OBJ_BAD_DROP_FN_NULL: &dyn Trait = unsafe { mem::transmute((&92 } error[E0080]: constructing invalid value: encountered ALLOC21<imm>, but expected a vtable pointer - --> $DIR/ub-wide-ptr.rs:121:1 + --> $DIR/ub-wide-ptr.rs:122:1 | LL | const TRAIT_OBJ_BAD_DROP_FN_INT: &dyn Trait = unsafe { mem::transmute((&92u8, &[1usize; 8])) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -252,7 +260,7 @@ LL | const TRAIT_OBJ_BAD_DROP_FN_INT: &dyn Trait = unsafe { mem::transmute((&92u } error[E0080]: constructing invalid value at .0: encountered ALLOC23<imm>, but expected a vtable pointer - --> $DIR/ub-wide-ptr.rs:123:1 + --> $DIR/ub-wide-ptr.rs:124:1 | LL | const TRAIT_OBJ_BAD_DROP_FN_NOT_FN_PTR: W<&dyn Trait> = unsafe { mem::transmute(W((&92u8, &[&42u8; 8]))) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -263,7 +271,7 @@ LL | const TRAIT_OBJ_BAD_DROP_FN_NOT_FN_PTR: W<&dyn Trait> = unsafe { mem::trans } error[E0080]: constructing invalid value at .<deref>.<dyn-downcast>: encountered 0x03, but expected a boolean - --> $DIR/ub-wide-ptr.rs:127:1 + --> $DIR/ub-wide-ptr.rs:128:1 | LL | const TRAIT_OBJ_CONTENT_INVALID: &dyn Trait = unsafe { mem::transmute::<_, &bool>(&3u8) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -274,7 +282,7 @@ LL | const TRAIT_OBJ_CONTENT_INVALID: &dyn Trait = unsafe { mem::transmute::<_, } error[E0080]: constructing invalid value: encountered null pointer, but expected a vtable pointer - --> $DIR/ub-wide-ptr.rs:131:1 + --> $DIR/ub-wide-ptr.rs:132:1 | LL | const RAW_TRAIT_OBJ_VTABLE_NULL: *const dyn Trait = unsafe { mem::transmute((&92u8, 0usize)) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -285,7 +293,7 @@ LL | const RAW_TRAIT_OBJ_VTABLE_NULL: *const dyn Trait = unsafe { mem::transmute } error[E0080]: constructing invalid value: encountered ALLOC28<imm>, but expected a vtable pointer - --> $DIR/ub-wide-ptr.rs:133:1 + --> $DIR/ub-wide-ptr.rs:134:1 | LL | const RAW_TRAIT_OBJ_VTABLE_INVALID: *const dyn Trait = unsafe { mem::transmute((&92u8, &3u64)) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -296,7 +304,7 @@ LL | const RAW_TRAIT_OBJ_VTABLE_INVALID: *const dyn Trait = unsafe { mem::transm } error[E0080]: constructing invalid value: encountered null pointer, but expected a vtable pointer - --> $DIR/ub-wide-ptr.rs:140:1 + --> $DIR/ub-wide-ptr.rs:141:1 | LL | static mut RAW_TRAIT_OBJ_VTABLE_NULL_THROUGH_REF: *const dyn Trait = unsafe { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value @@ -307,7 +315,7 @@ LL | static mut RAW_TRAIT_OBJ_VTABLE_NULL_THROUGH_REF: *const dyn Trait = unsafe } error[E0080]: constructing invalid value: encountered ALLOC31<imm>, but expected a vtable pointer - --> $DIR/ub-wide-ptr.rs:144:1 + --> $DIR/ub-wide-ptr.rs:145:1 | LL | static mut RAW_TRAIT_OBJ_VTABLE_INVALID_THROUGH_REF: *const dyn Trait = unsafe { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ it is undefined behavior to use this value diff --git a/tests/ui/consts/const-eval/union-const-eval-field.rs b/tests/ui/consts/const-eval/union-const-eval-field.rs index 0ad94eee7f4..719e59b007c 100644 --- a/tests/ui/consts/const-eval/union-const-eval-field.rs +++ b/tests/ui/consts/const-eval/union-const-eval-field.rs @@ -1,4 +1,5 @@ //@ dont-require-annotations: NOTE +//@ normalize-stderr: "(the raw bytes of the constant) \(size: [0-9]*, align: [0-9]*\)" -> "$1 (size: $$SIZE, align: $$ALIGN)" type Field1 = i32; type Field2 = f32; diff --git a/tests/ui/consts/const-eval/union-const-eval-field.stderr b/tests/ui/consts/const-eval/union-const-eval-field.stderr index 07ff4c3ca36..1843ce273ac 100644 --- a/tests/ui/consts/const-eval/union-const-eval-field.stderr +++ b/tests/ui/consts/const-eval/union-const-eval-field.stderr @@ -1,17 +1,21 @@ -error[E0080]: using uninitialized data, but this operation requires initialized memory - --> $DIR/union-const-eval-field.rs:28:37 +error[E0080]: reading memory at ALLOC0[0x0..0x8], but memory is uninitialized at [0x4..0x8], and this operation requires initialized memory + --> $DIR/union-const-eval-field.rs:29:37 | LL | const FIELD3: Field3 = unsafe { UNION.field3 }; | ^^^^^^^^^^^^ evaluation of `read_field3::FIELD3` failed here + | + = note: the raw bytes of the constant (size: $SIZE, align: $ALIGN) { + 00 00 80 3f __ __ __ __ │ ...?░░░░ + } note: erroneous constant encountered - --> $DIR/union-const-eval-field.rs:30:5 + --> $DIR/union-const-eval-field.rs:31:5 | LL | FIELD3 | ^^^^^^ note: erroneous constant encountered - --> $DIR/union-const-eval-field.rs:30:5 + --> $DIR/union-const-eval-field.rs:31:5 | LL | FIELD3 | ^^^^^^ diff --git a/tests/ui/consts/const-eval/union-ice.stderr b/tests/ui/consts/const-eval/union-ice.stderr index b00fcc91d68..0506be63ea6 100644 --- a/tests/ui/consts/const-eval/union-ice.stderr +++ b/tests/ui/consts/const-eval/union-ice.stderr @@ -1,20 +1,32 @@ -error[E0080]: using uninitialized data, but this operation requires initialized memory +error[E0080]: reading memory at ALLOC0[0x0..0x8], but memory is uninitialized at [0x4..0x8], and this operation requires initialized memory --> $DIR/union-ice.rs:14:33 | LL | const FIELD3: Field3 = unsafe { UNION.field3 }; | ^^^^^^^^^^^^ evaluation of `FIELD3` failed here + | + = note: the raw bytes of the constant (size: 8, align: 8) { + 00 00 80 3f __ __ __ __ │ ...?░░░░ + } -error[E0080]: using uninitialized data, but this operation requires initialized memory +error[E0080]: reading memory at ALLOC1[0x0..0x8], but memory is uninitialized at [0x4..0x8], and this operation requires initialized memory --> $DIR/union-ice.rs:19:17 | LL | b: unsafe { UNION.field3 }, | ^^^^^^^^^^^^ evaluation of `FIELD_PATH` failed here + | + = note: the raw bytes of the constant (size: 8, align: 8) { + 00 00 80 3f __ __ __ __ │ ...?░░░░ + } -error[E0080]: using uninitialized data, but this operation requires initialized memory +error[E0080]: reading memory at ALLOC2[0x0..0x8], but memory is uninitialized at [0x4..0x8], and this operation requires initialized memory --> $DIR/union-ice.rs:31:18 | LL | unsafe { UNION.field3 }, | ^^^^^^^^^^^^ evaluation of `FIELD_PATH2` failed here + | + = note: the raw bytes of the constant (size: 8, align: 8) { + 00 00 80 3f __ __ __ __ │ ...?░░░░ + } error: aborting due to 3 previous errors diff --git a/tests/ui/consts/const-eval/union-ub.32bit.stderr b/tests/ui/consts/const-eval/union-ub.32bit.stderr index 9f0697984e4..757bcea91c3 100644 --- a/tests/ui/consts/const-eval/union-ub.32bit.stderr +++ b/tests/ui/consts/const-eval/union-ub.32bit.stderr @@ -9,11 +9,15 @@ LL | const BAD_BOOL: bool = unsafe { DummyUnion { u8: 42 }.bool }; 2a │ * } -error[E0080]: using uninitialized data, but this operation requires initialized memory +error[E0080]: reading memory at ALLOC0[0x0..0x1], but memory is uninitialized at [0x0..0x1], and this operation requires initialized memory --> $DIR/union-ub.rs:35:36 | LL | const UNINIT_BOOL: bool = unsafe { DummyUnion { unit: () }.bool }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `UNINIT_BOOL` failed here + | + = note: the raw bytes of the constant (size: 1, align: 1) { + __ │ ░ + } error: aborting due to 2 previous errors diff --git a/tests/ui/consts/const-eval/union-ub.64bit.stderr b/tests/ui/consts/const-eval/union-ub.64bit.stderr index 9f0697984e4..757bcea91c3 100644 --- a/tests/ui/consts/const-eval/union-ub.64bit.stderr +++ b/tests/ui/consts/const-eval/union-ub.64bit.stderr @@ -9,11 +9,15 @@ LL | const BAD_BOOL: bool = unsafe { DummyUnion { u8: 42 }.bool }; 2a │ * } -error[E0080]: using uninitialized data, but this operation requires initialized memory +error[E0080]: reading memory at ALLOC0[0x0..0x1], but memory is uninitialized at [0x0..0x1], and this operation requires initialized memory --> $DIR/union-ub.rs:35:36 | LL | const UNINIT_BOOL: bool = unsafe { DummyUnion { unit: () }.bool }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `UNINIT_BOOL` failed here + | + = note: the raw bytes of the constant (size: 1, align: 1) { + __ │ ░ + } error: aborting due to 2 previous errors diff --git a/tests/ui/consts/const-try-feature-gate.rs b/tests/ui/consts/const-try-feature-gate.rs index 09985079e8e..4a98185a18a 100644 --- a/tests/ui/consts/const-try-feature-gate.rs +++ b/tests/ui/consts/const-try-feature-gate.rs @@ -4,6 +4,8 @@ const fn t() -> Option<()> { Some(())?; //~^ ERROR `?` is not allowed //~| ERROR `?` is not allowed + //~| ERROR `Try` is not yet stable as a const trait + //~| ERROR `FromResidual` is not yet stable as a const trait None } diff --git a/tests/ui/consts/const-try-feature-gate.stderr b/tests/ui/consts/const-try-feature-gate.stderr index 0ad19d05b38..62a4a5fba4f 100644 --- a/tests/ui/consts/const-try-feature-gate.stderr +++ b/tests/ui/consts/const-try-feature-gate.stderr @@ -1,19 +1,47 @@ -error[E0015]: `?` is not allowed on `Option<()>` in constant functions +error[E0658]: `?` is not allowed on `Option<()>` in constant functions --> $DIR/const-try-feature-gate.rs:4:5 | LL | Some(())?; | ^^^^^^^^^ | = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants + = note: see issue #143874 <https://github.com/rust-lang/rust/issues/143874> for more information + = help: add `#![feature(const_trait_impl)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date -error[E0015]: `?` is not allowed on `Option<()>` in constant functions +error: `Try` is not yet stable as a const trait + --> $DIR/const-try-feature-gate.rs:4:5 + | +LL | Some(())?; + | ^^^^^^^^^ + | +help: add `#![feature(const_try)]` to the crate attributes to enable + | +LL + #![feature(const_try)] + | + +error[E0658]: `?` is not allowed on `Option<()>` in constant functions --> $DIR/const-try-feature-gate.rs:4:5 | LL | Some(())?; | ^^^^^^^^^ | = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants + = note: see issue #143874 <https://github.com/rust-lang/rust/issues/143874> for more information + = help: add `#![feature(const_trait_impl)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error: `FromResidual` is not yet stable as a const trait + --> $DIR/const-try-feature-gate.rs:4:5 + | +LL | Some(())?; + | ^^^^^^^^^ + | +help: add `#![feature(const_try)]` to the crate attributes to enable + | +LL + #![feature(const_try)] + | -error: aborting due to 2 previous errors +error: aborting due to 4 previous errors -For more information about this error, try `rustc --explain E0015`. +For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/consts/const-try.rs b/tests/ui/consts/const-try.rs index e13fad78441..152400d702e 100644 --- a/tests/ui/consts/const-try.rs +++ b/tests/ui/consts/const-try.rs @@ -1,4 +1,6 @@ -//@ compile-flags: -Znext-solver +//@ check-pass +//@ revisions: current next +//@[next] compile-flags: -Znext-solver // Demonstrates what's needed to make use of `?` in const contexts. @@ -13,14 +15,12 @@ struct TryMe; struct Error; impl const FromResidual<Error> for TryMe { - //~^ ERROR const `impl` for trait `FromResidual` which is not `const` fn from_residual(residual: Error) -> Self { TryMe } } impl const Try for TryMe { - //~^ ERROR const `impl` for trait `Try` which is not `const` type Output = (); type Residual = Error; fn from_output(output: Self::Output) -> Self { @@ -33,8 +33,6 @@ impl const Try for TryMe { const fn t() -> TryMe { TryMe?; - //~^ ERROR `?` is not allowed on - //~| ERROR `?` is not allowed on TryMe } diff --git a/tests/ui/consts/const-try.stderr b/tests/ui/consts/const-try.stderr deleted file mode 100644 index 7004ea3e6db..00000000000 --- a/tests/ui/consts/const-try.stderr +++ /dev/null @@ -1,37 +0,0 @@ -error: const `impl` for trait `FromResidual` which is not `const` - --> $DIR/const-try.rs:15:12 - | -LL | impl const FromResidual<Error> for TryMe { - | ^^^^^^^^^^^^^^^^^^^ this trait is not `const` - | - = note: marking a trait with `const` ensures all default method bodies are `const` - = note: adding a non-const method body in the future would be a breaking change - -error: const `impl` for trait `Try` which is not `const` - --> $DIR/const-try.rs:22:12 - | -LL | impl const Try for TryMe { - | ^^^ this trait is not `const` - | - = note: marking a trait with `const` ensures all default method bodies are `const` - = note: adding a non-const method body in the future would be a breaking change - -error[E0015]: `?` is not allowed on `TryMe` in constant functions - --> $DIR/const-try.rs:35:5 - | -LL | TryMe?; - | ^^^^^^ - | - = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants - -error[E0015]: `?` is not allowed on `TryMe` in constant functions - --> $DIR/const-try.rs:35:5 - | -LL | TryMe?; - | ^^^^^^ - | - = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants - -error: aborting due to 4 previous errors - -For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/consts/control-flow/try.rs b/tests/ui/consts/control-flow/try.rs index 67083e1a39b..6d762f9194e 100644 --- a/tests/ui/consts/control-flow/try.rs +++ b/tests/ui/consts/control-flow/try.rs @@ -1,11 +1,12 @@ -// The `?` operator is still not const-evaluatable because it calls `From::from` on the error -// variant. +//@ check-pass + +#![allow(dead_code)] +#![feature(const_trait_impl)] +#![feature(const_try)] const fn opt() -> Option<i32> { let x = Some(2); x?; - //~^ ERROR: `?` is not allowed - //~| ERROR: `?` is not allowed None } diff --git a/tests/ui/consts/control-flow/try.stderr b/tests/ui/consts/control-flow/try.stderr deleted file mode 100644 index 62a3e3ce6bc..00000000000 --- a/tests/ui/consts/control-flow/try.stderr +++ /dev/null @@ -1,19 +0,0 @@ -error[E0015]: `?` is not allowed on `Option<i32>` in constant functions - --> $DIR/try.rs:6:5 - | -LL | x?; - | ^^ - | - = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants - -error[E0015]: `?` is not allowed on `Option<i32>` in constant functions - --> $DIR/try.rs:6:5 - | -LL | x?; - | ^^ - | - = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants - -error: aborting due to 2 previous errors - -For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/consts/rustc-const-stability-require-const.stderr b/tests/ui/consts/rustc-const-stability-require-const.stderr index 4b13826584d..8d10bddaa45 100644 --- a/tests/ui/consts/rustc-const-stability-require-const.stderr +++ b/tests/ui/consts/rustc-const-stability-require-const.stderr @@ -23,30 +23,6 @@ LL | pub fn bar() {} | ^^^^^^^^^^^^ error: attributes `#[rustc_const_unstable]`, `#[rustc_const_stable]` and `#[rustc_const_stable_indirect]` require the function or method to be `const` - --> $DIR/rustc-const-stability-require-const.rs:21:5 - | -LL | pub fn salad(&self) -> &'static str { "mmmmmm" } - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | -help: make the function or method const - --> $DIR/rustc-const-stability-require-const.rs:21:5 - | -LL | pub fn salad(&self) -> &'static str { "mmmmmm" } - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -error: attributes `#[rustc_const_unstable]`, `#[rustc_const_stable]` and `#[rustc_const_stable_indirect]` require the function or method to be `const` - --> $DIR/rustc-const-stability-require-const.rs:26:5 - | -LL | pub fn roasted(&self) -> &'static str { "mmmmmmmmmm" } - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | -help: make the function or method const - --> $DIR/rustc-const-stability-require-const.rs:26:5 - | -LL | pub fn roasted(&self) -> &'static str { "mmmmmmmmmm" } - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -error: attributes `#[rustc_const_unstable]`, `#[rustc_const_stable]` and `#[rustc_const_stable_indirect]` require the function or method to be `const` --> $DIR/rustc-const-stability-require-const.rs:32:1 | LL | pub extern "C" fn bar_c() {} @@ -86,5 +62,29 @@ LL | #[rustc_const_stable(feature = "barfoo_const", since = "1.0.0")] LL | pub const fn barfoo_unstable() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +error: attributes `#[rustc_const_unstable]`, `#[rustc_const_stable]` and `#[rustc_const_stable_indirect]` require the function or method to be `const` + --> $DIR/rustc-const-stability-require-const.rs:21:5 + | +LL | pub fn salad(&self) -> &'static str { "mmmmmm" } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: make the function or method const + --> $DIR/rustc-const-stability-require-const.rs:21:5 + | +LL | pub fn salad(&self) -> &'static str { "mmmmmm" } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: attributes `#[rustc_const_unstable]`, `#[rustc_const_stable]` and `#[rustc_const_stable_indirect]` require the function or method to be `const` + --> $DIR/rustc-const-stability-require-const.rs:26:5 + | +LL | pub fn roasted(&self) -> &'static str { "mmmmmmmmmm" } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: make the function or method const + --> $DIR/rustc-const-stability-require-const.rs:26:5 + | +LL | pub fn roasted(&self) -> &'static str { "mmmmmmmmmm" } + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + error: aborting due to 8 previous errors diff --git a/tests/ui/consts/try-operator.rs b/tests/ui/consts/try-operator.rs index 352dbeefa8a..59d9fcb1cbd 100644 --- a/tests/ui/consts/try-operator.rs +++ b/tests/ui/consts/try-operator.rs @@ -1,9 +1,8 @@ -//@ known-bug: #110395 +//@ run-pass #![feature(try_trait_v2)] #![feature(const_trait_impl)] #![feature(const_try)] -#![feature(const_convert)] fn main() { const fn result() -> Result<bool, ()> { diff --git a/tests/ui/consts/try-operator.stderr b/tests/ui/consts/try-operator.stderr deleted file mode 100644 index fc37039d260..00000000000 --- a/tests/ui/consts/try-operator.stderr +++ /dev/null @@ -1,42 +0,0 @@ -error[E0635]: unknown feature `const_convert` - --> $DIR/try-operator.rs:6:12 - | -LL | #![feature(const_convert)] - | ^^^^^^^^^^^^^ - -error[E0015]: `?` is not allowed on `Result<(), ()>` in constant functions - --> $DIR/try-operator.rs:10:9 - | -LL | Err(())?; - | ^^^^^^^^ - | - = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants - -error[E0015]: `?` is not allowed on `Result<bool, ()>` in constant functions - --> $DIR/try-operator.rs:10:9 - | -LL | Err(())?; - | ^^^^^^^^ - | - = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants - -error[E0015]: `?` is not allowed on `Option<()>` in constant functions - --> $DIR/try-operator.rs:18:9 - | -LL | None?; - | ^^^^^ - | - = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants - -error[E0015]: `?` is not allowed on `Option<()>` in constant functions - --> $DIR/try-operator.rs:18:9 - | -LL | None?; - | ^^^^^ - | - = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants - -error: aborting due to 5 previous errors - -Some errors have detailed explanations: E0015, E0635. -For more information about an error, try `rustc --explain E0015`. diff --git a/tests/ui/contracts/contract-attributes-generics.rs b/tests/ui/contracts/contract-attributes-generics.rs index fd79c6abedd..3763ce116f8 100644 --- a/tests/ui/contracts/contract-attributes-generics.rs +++ b/tests/ui/contracts/contract-attributes-generics.rs @@ -5,9 +5,9 @@ //@ [unchk_pass] run-pass //@ [chk_pass] run-pass // -//@ [chk_fail_pre] run-fail -//@ [chk_fail_post] run-fail -//@ [chk_const_fail] run-fail +//@ [chk_fail_pre] run-crash +//@ [chk_fail_post] run-crash +//@ [chk_const_fail] run-crash // //@ [unchk_pass] compile-flags: -Zcontract-checks=no // diff --git a/tests/ui/contracts/contract-attributes-nest.rs b/tests/ui/contracts/contract-attributes-nest.rs index e1e61b88f28..d367687b84e 100644 --- a/tests/ui/contracts/contract-attributes-nest.rs +++ b/tests/ui/contracts/contract-attributes-nest.rs @@ -5,8 +5,8 @@ //@ [unchk_fail_post] run-pass //@ [chk_pass] run-pass // -//@ [chk_fail_pre] run-fail -//@ [chk_fail_post] run-fail +//@ [chk_fail_pre] run-crash +//@ [chk_fail_post] run-crash // //@ [unchk_pass] compile-flags: -Zcontract-checks=no //@ [unchk_fail_pre] compile-flags: -Zcontract-checks=no diff --git a/tests/ui/contracts/contract-attributes-tail.rs b/tests/ui/contracts/contract-attributes-tail.rs index ce4a6be5b82..43edfe5e803 100644 --- a/tests/ui/contracts/contract-attributes-tail.rs +++ b/tests/ui/contracts/contract-attributes-tail.rs @@ -5,8 +5,8 @@ //@ [unchk_fail_post] run-pass //@ [chk_pass] run-pass // -//@ [chk_fail_pre] run-fail -//@ [chk_fail_post] run-fail +//@ [chk_fail_pre] run-crash +//@ [chk_fail_post] run-crash // //@ [unchk_pass] compile-flags: -Zcontract-checks=no //@ [unchk_fail_pre] compile-flags: -Zcontract-checks=no diff --git a/tests/ui/contracts/contract-captures-via-closure-copy.rs b/tests/ui/contracts/contract-captures-via-closure-copy.rs index 32c6d2bf4fe..bc7e5b9b6f1 100644 --- a/tests/ui/contracts/contract-captures-via-closure-copy.rs +++ b/tests/ui/contracts/contract-captures-via-closure-copy.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -Zcontract-checks=yes #![feature(contracts)] diff --git a/tests/ui/contracts/contract-const-fn.rs b/tests/ui/contracts/contract-const-fn.rs index 733a06ae570..fe8dd37b1f5 100644 --- a/tests/ui/contracts/contract-const-fn.rs +++ b/tests/ui/contracts/contract-const-fn.rs @@ -8,8 +8,8 @@ // //@ [all_pass] run-pass // -//@ [runtime_fail_pre] run-fail -//@ [runtime_fail_post] run-fail +//@ [runtime_fail_pre] run-crash +//@ [runtime_fail_post] run-crash // //@ [all_pass] compile-flags: -Zcontract-checks=yes //@ [runtime_fail_pre] compile-flags: -Zcontract-checks=yes diff --git a/tests/ui/contracts/contracts-ensures-early-fn-exit.rs b/tests/ui/contracts/contracts-ensures-early-fn-exit.rs index 034cead3b4e..44ae07d8c95 100644 --- a/tests/ui/contracts/contracts-ensures-early-fn-exit.rs +++ b/tests/ui/contracts/contracts-ensures-early-fn-exit.rs @@ -2,9 +2,9 @@ // //@ [unchk_pass] run-pass //@ [chk_pass] run-pass -//@ [chk_fail_try] run-fail -//@ [chk_fail_ret] run-fail -//@ [chk_fail_yeet] run-fail +//@ [chk_fail_try] run-crash +//@ [chk_fail_ret] run-crash +//@ [chk_fail_yeet] run-crash // //@ [unchk_pass] compile-flags: -Zcontract-checks=no //@ [chk_pass] compile-flags: -Zcontract-checks=yes diff --git a/tests/ui/contracts/internal_machinery/contract-ast-extensions-nest.rs b/tests/ui/contracts/internal_machinery/contract-ast-extensions-nest.rs index 6d8cd3949ee..4da0480f8bc 100644 --- a/tests/ui/contracts/internal_machinery/contract-ast-extensions-nest.rs +++ b/tests/ui/contracts/internal_machinery/contract-ast-extensions-nest.rs @@ -5,8 +5,8 @@ //@ [unchk_fail_post] run-pass //@ [chk_pass] run-pass // -//@ [chk_fail_pre] run-fail -//@ [chk_fail_post] run-fail +//@ [chk_fail_pre] run-crash +//@ [chk_fail_post] run-crash // //@ [unchk_pass] compile-flags: -Zcontract-checks=no //@ [unchk_fail_pre] compile-flags: -Zcontract-checks=no diff --git a/tests/ui/contracts/internal_machinery/contract-ast-extensions-tail.rs b/tests/ui/contracts/internal_machinery/contract-ast-extensions-tail.rs index 07ec26f921b..f3cf5ce082c 100644 --- a/tests/ui/contracts/internal_machinery/contract-ast-extensions-tail.rs +++ b/tests/ui/contracts/internal_machinery/contract-ast-extensions-tail.rs @@ -5,8 +5,8 @@ //@ [unchk_fail_post] run-pass //@ [chk_pass] run-pass // -//@ [chk_fail_pre] run-fail -//@ [chk_fail_post] run-fail +//@ [chk_fail_pre] run-crash +//@ [chk_fail_post] run-crash // //@ [unchk_pass] compile-flags: -Zcontract-checks=no //@ [unchk_fail_pre] compile-flags: -Zcontract-checks=no diff --git a/tests/ui/contracts/internal_machinery/contract-intrinsics.rs b/tests/ui/contracts/internal_machinery/contract-intrinsics.rs index c62b8cca75a..6e613b53fc9 100644 --- a/tests/ui/contracts/internal_machinery/contract-intrinsics.rs +++ b/tests/ui/contracts/internal_machinery/contract-intrinsics.rs @@ -3,8 +3,8 @@ //@ [default] run-pass //@ [unchk_pass] run-pass //@ [chk_pass] run-pass -//@ [chk_fail_requires] run-fail -//@ [chk_fail_ensures] run-fail +//@ [chk_fail_requires] run-crash +//@ [chk_fail_ensures] run-crash // //@ [unchk_pass] compile-flags: -Zcontract-checks=no //@ [chk_pass] compile-flags: -Zcontract-checks=yes diff --git a/tests/ui/contracts/internal_machinery/contract-lang-items.rs b/tests/ui/contracts/internal_machinery/contract-lang-items.rs index 73c59194531..ac72d233bf6 100644 --- a/tests/ui/contracts/internal_machinery/contract-lang-items.rs +++ b/tests/ui/contracts/internal_machinery/contract-lang-items.rs @@ -4,7 +4,7 @@ //@ [unchk_fail_post] run-pass //@ [chk_pass] run-pass // -//@ [chk_fail_post] run-fail +//@ [chk_fail_post] run-crash // //@ [unchk_pass] compile-flags: -Zcontract-checks=no //@ [unchk_fail_post] compile-flags: -Zcontract-checks=no diff --git a/tests/ui/extern/extern-types-field-offset.rs b/tests/ui/extern/extern-types-field-offset.rs index 75f3eab3e27..035f063cd50 100644 --- a/tests/ui/extern/extern-types-field-offset.rs +++ b/tests/ui/extern/extern-types-field-offset.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ check-run-results //@ exec-env:RUST_BACKTRACE=0 //@ normalize-stderr: "(core/src/panicking\.rs):[0-9]+:[0-9]+" -> "$1:$$LINE:$$COL" diff --git a/tests/ui/feature-gates/feature-gate-more-maybe-bounds.rs b/tests/ui/feature-gates/feature-gate-more-maybe-bounds.rs index 6a832744e3e..9c727ae3aad 100644 --- a/tests/ui/feature-gates/feature-gate-more-maybe-bounds.rs +++ b/tests/ui/feature-gates/feature-gate-more-maybe-bounds.rs @@ -2,23 +2,13 @@ trait Trait1 {} auto trait Trait2 {} -trait Trait3: ?Trait1 {} -//~^ ERROR `?Trait` is not permitted in supertraits -trait Trait4 where Self: ?Trait1 {} -//~^ ERROR ?Trait` bounds are only permitted at the point where a type parameter is declared +trait Trait3: ?Trait1 {} //~ ERROR relaxed bounds are not permitted in supertrait bounds +trait Trait4 where Self: ?Trait1 {} //~ ERROR this relaxed bound is not permitted here fn foo(_: Box<dyn Trait1 + ?Trait2>) {} -//~^ ERROR `?Trait` is not permitted in trait object types +//~^ ERROR relaxed bounds are not permitted in trait object types fn bar<T: ?Trait1 + ?Trait2>(_: T) {} -//~^ ERROR type parameter has more than one relaxed default bound, only one is supported -//~| ERROR relaxing a default bound only does something for `?Sized`; all other traits are not bound by default -//~| ERROR relaxing a default bound only does something for `?Sized`; all other traits are not bound by default - -trait Trait {} -// Do not suggest `#![feature(more_maybe_bounds)]` for repetitions -fn baz<T: ?Trait + ?Trait>(_ : T) {} -//~^ ERROR type parameter has more than one relaxed default bound, only one is supported -//~| ERROR relaxing a default bound only does something for `?Sized`; all other traits are not bound by default -//~| ERROR relaxing a default bound only does something for `?Sized`; all other traits are not bound by default +//~^ ERROR bound modifier `?` can only be applied to `Sized` +//~| ERROR bound modifier `?` can only be applied to `Sized` fn main() {} diff --git a/tests/ui/feature-gates/feature-gate-more-maybe-bounds.stderr b/tests/ui/feature-gates/feature-gate-more-maybe-bounds.stderr index 729df4eb37c..da6ad5f16e2 100644 --- a/tests/ui/feature-gates/feature-gate-more-maybe-bounds.stderr +++ b/tests/ui/feature-gates/feature-gate-more-maybe-bounds.stderr @@ -1,71 +1,34 @@ -error[E0658]: `?Trait` is not permitted in supertraits +error: relaxed bounds are not permitted in supertrait bounds --> $DIR/feature-gate-more-maybe-bounds.rs:5:15 | LL | trait Trait3: ?Trait1 {} | ^^^^^^^ - | - = note: traits are `?Trait1` by default - = help: add `#![feature(more_maybe_bounds)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - -error[E0658]: `?Trait` is not permitted in trait object types - --> $DIR/feature-gate-more-maybe-bounds.rs:10:28 - | -LL | fn foo(_: Box<dyn Trait1 + ?Trait2>) {} - | ^^^^^^^ - | - = help: add `#![feature(more_maybe_bounds)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date -error[E0658]: `?Trait` bounds are only permitted at the point where a type parameter is declared - --> $DIR/feature-gate-more-maybe-bounds.rs:7:26 +error: this relaxed bound is not permitted here + --> $DIR/feature-gate-more-maybe-bounds.rs:6:26 | LL | trait Trait4 where Self: ?Trait1 {} | ^^^^^^^ | - = help: add `#![feature(more_maybe_bounds)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + = note: in this context, relaxed bounds are only allowed on type parameters defined by the closest item -error[E0203]: type parameter has more than one relaxed default bound, only one is supported - --> $DIR/feature-gate-more-maybe-bounds.rs:12:11 - | -LL | fn bar<T: ?Trait1 + ?Trait2>(_: T) {} - | ^^^^^^^ ^^^^^^^ +error: relaxed bounds are not permitted in trait object types + --> $DIR/feature-gate-more-maybe-bounds.rs:8:28 | - = help: add `#![feature(more_maybe_bounds)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date +LL | fn foo(_: Box<dyn Trait1 + ?Trait2>) {} + | ^^^^^^^ -error: relaxing a default bound only does something for `?Sized`; all other traits are not bound by default - --> $DIR/feature-gate-more-maybe-bounds.rs:12:11 +error: bound modifier `?` can only be applied to `Sized` + --> $DIR/feature-gate-more-maybe-bounds.rs:10:11 | LL | fn bar<T: ?Trait1 + ?Trait2>(_: T) {} | ^^^^^^^ -error: relaxing a default bound only does something for `?Sized`; all other traits are not bound by default - --> $DIR/feature-gate-more-maybe-bounds.rs:12:21 +error: bound modifier `?` can only be applied to `Sized` + --> $DIR/feature-gate-more-maybe-bounds.rs:10:21 | LL | fn bar<T: ?Trait1 + ?Trait2>(_: T) {} | ^^^^^^^ -error[E0203]: type parameter has more than one relaxed default bound, only one is supported - --> $DIR/feature-gate-more-maybe-bounds.rs:19:11 - | -LL | fn baz<T: ?Trait + ?Trait>(_ : T) {} - | ^^^^^^ ^^^^^^ - -error: relaxing a default bound only does something for `?Sized`; all other traits are not bound by default - --> $DIR/feature-gate-more-maybe-bounds.rs:19:11 - | -LL | fn baz<T: ?Trait + ?Trait>(_ : T) {} - | ^^^^^^ - -error: relaxing a default bound only does something for `?Sized`; all other traits are not bound by default - --> $DIR/feature-gate-more-maybe-bounds.rs:19:20 - | -LL | fn baz<T: ?Trait + ?Trait>(_ : T) {} - | ^^^^^^ - -error: aborting due to 9 previous errors +error: aborting due to 5 previous errors -Some errors have detailed explanations: E0203, E0658. -For more information about an error, try `rustc --explain E0203`. diff --git a/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.rs b/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.rs index d07201ebbd1..9740eaaf1e9 100644 --- a/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.rs +++ b/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.rs @@ -269,7 +269,13 @@ mod automatically_derived { #[automatically_derived] type T = S; //~^ WARN `#[automatically_derived] + #[automatically_derived] trait W { } + //~^ WARN `#[automatically_derived] + #[automatically_derived] impl S { } + //~^ WARN `#[automatically_derived] + + #[automatically_derived] impl W for S { } } #[no_mangle] diff --git a/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.stderr b/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.stderr index 5d7d1caeeab..9016ca1efa7 100644 --- a/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.stderr +++ b/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.stderr @@ -1,5 +1,5 @@ warning: `#[macro_escape]` is a deprecated synonym for `#[macro_use]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:391:17 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:397:17 | LL | mod inner { #![macro_escape] } | ^^^^^^^^^^^^^^^^ @@ -7,7 +7,7 @@ LL | mod inner { #![macro_escape] } = help: try an outer attribute: `#[macro_use]` warning: `#[macro_escape]` is a deprecated synonym for `#[macro_use]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:388:1 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:394:1 | LL | #[macro_escape] | ^^^^^^^^^^^^^^^ @@ -198,14 +198,14 @@ note: the lint level is defined here LL | #![warn(unused_attributes, unknown_lints)] | ^^^^^^^^^^^^^^^^^ -warning: `#[automatically_derived]` only has an effect on implementation blocks +warning: `#[automatically_derived]` only has an effect on trait implementation blocks --> $DIR/issue-43106-gating-of-builtin-attrs.rs:257:1 | LL | #[automatically_derived] | ^^^^^^^^^^^^^^^^^^^^^^^^ warning: attribute should be applied to a free function, impl method or static - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:275:1 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:281:1 | LL | #[no_mangle] | ^^^^^^^^^^^^ @@ -220,31 +220,31 @@ LL | | } = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! warning: `#[should_panic]` only has an effect on functions - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:315:1 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:321:1 | LL | #[should_panic] | ^^^^^^^^^^^^^^^ warning: `#[ignore]` only has an effect on functions - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:333:1 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:339:1 | LL | #[ignore] | ^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:368:1 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:374:1 | LL | #[reexport_test_harness_main = "2900"] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:408:1 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:414:1 | LL | #[no_std] | ^^^^^^^^^ warning: attribute should be applied to a function definition - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:444:1 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:450:1 | LL | #[cold] | ^^^^^^^ @@ -260,7 +260,7 @@ LL | | } = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! warning: attribute should be applied to a foreign function or static - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:473:1 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:479:1 | LL | #[link_name = "1900"] | ^^^^^^^^^^^^^^^^^^^^^ @@ -276,7 +276,7 @@ LL | | } = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! warning: attribute should be applied to a function or static - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:512:1 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:518:1 | LL | #[link_section = "1800"] | ^^^^^^^^^^^^^^^^^^^^^^^^ @@ -292,7 +292,7 @@ LL | | } = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! warning: attribute should be applied to an `extern` block with non-Rust ABI - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:544:1 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:550:1 | LL | #[link()] | ^^^^^^^^^ @@ -308,55 +308,55 @@ LL | | } = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! warning: `#[must_use]` has no effect when applied to a module - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:595:1 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:601:1 | LL | #[must_use] | ^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:608:1 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:614:1 | LL | #[windows_subsystem = "windows"] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:629:1 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:635:1 | LL | #[crate_name = "0900"] | ^^^^^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:648:1 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:654:1 | LL | #[crate_type = "0800"] | ^^^^^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:667:1 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:673:1 | LL | #[feature(x0600)] | ^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:687:1 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:693:1 | LL | #[no_main] | ^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:706:1 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:712:1 | LL | #[no_builtins] | ^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:725:1 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:731:1 | LL | #[recursion_limit="0200"] | ^^^^^^^^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:744:1 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:750:1 | LL | #[type_length_limit="0100"] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -417,6 +417,14 @@ LL | #![cold] | = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! +warning: the feature `rust1` has been stable since 1.0.0 and no longer requires an attribute to enable + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:85:12 + | +LL | #![feature(rust1)] + | ^^^^^ + | + = note: `#[warn(stable_features)]` on by default + warning: `#[macro_use]` only has an effect on `extern crate` and modules --> $DIR/issue-43106-gating-of-builtin-attrs.rs:176:5 | @@ -495,32 +503,44 @@ warning: `#[path]` only has an effect on modules LL | #[path = "3800"] impl S { } | ^^^^^^^^^^^^^^^^ -warning: `#[automatically_derived]` only has an effect on implementation blocks +warning: `#[automatically_derived]` only has an effect on trait implementation blocks --> $DIR/issue-43106-gating-of-builtin-attrs.rs:260:17 | LL | mod inner { #![automatically_derived] } | ^^^^^^^^^^^^^^^^^^^^^^^^^ -warning: `#[automatically_derived]` only has an effect on implementation blocks +warning: `#[automatically_derived]` only has an effect on trait implementation blocks --> $DIR/issue-43106-gating-of-builtin-attrs.rs:263:5 | LL | #[automatically_derived] fn f() { } | ^^^^^^^^^^^^^^^^^^^^^^^^ -warning: `#[automatically_derived]` only has an effect on implementation blocks +warning: `#[automatically_derived]` only has an effect on trait implementation blocks --> $DIR/issue-43106-gating-of-builtin-attrs.rs:266:5 | LL | #[automatically_derived] struct S; | ^^^^^^^^^^^^^^^^^^^^^^^^ -warning: `#[automatically_derived]` only has an effect on implementation blocks +warning: `#[automatically_derived]` only has an effect on trait implementation blocks --> $DIR/issue-43106-gating-of-builtin-attrs.rs:269:5 | LL | #[automatically_derived] type T = S; | ^^^^^^^^^^^^^^^^^^^^^^^^ +warning: `#[automatically_derived]` only has an effect on trait implementation blocks + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:272:5 + | +LL | #[automatically_derived] trait W { } + | ^^^^^^^^^^^^^^^^^^^^^^^^ + +warning: `#[automatically_derived]` only has an effect on trait implementation blocks + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:275:5 + | +LL | #[automatically_derived] impl S { } + | ^^^^^^^^^^^^^^^^^^^^^^^^ + warning: attribute should be applied to a free function, impl method or static - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:280:17 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:286:17 | LL | mod inner { #![no_mangle] } | ------------^^^^^^^^^^^^^-- not a free function, impl method or static @@ -528,7 +548,7 @@ LL | mod inner { #![no_mangle] } = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! warning: attribute should be applied to a free function, impl method or static - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:287:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:293:5 | LL | #[no_mangle] struct S; | ^^^^^^^^^^^^ --------- not a free function, impl method or static @@ -536,7 +556,7 @@ LL | #[no_mangle] struct S; = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! warning: attribute should be applied to a free function, impl method or static - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:292:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:298:5 | LL | #[no_mangle] type T = S; | ^^^^^^^^^^^^ ----------- not a free function, impl method or static @@ -544,7 +564,7 @@ LL | #[no_mangle] type T = S; = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! warning: attribute should be applied to a free function, impl method or static - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:297:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:303:5 | LL | #[no_mangle] impl S { } | ^^^^^^^^^^^^ ---------- not a free function, impl method or static @@ -552,7 +572,7 @@ LL | #[no_mangle] impl S { } = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! warning: attribute should be applied to a free function, impl method or static - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:303:9 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:309:9 | LL | #[no_mangle] fn foo(); | ^^^^^^^^^^^^ --------- not a free function, impl method or static @@ -560,7 +580,7 @@ LL | #[no_mangle] fn foo(); = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! warning: attribute should be applied to a free function, impl method or static - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:308:9 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:314:9 | LL | #[no_mangle] fn bar() {} | ^^^^^^^^^^^^ ----------- not a free function, impl method or static @@ -568,163 +588,163 @@ LL | #[no_mangle] fn bar() {} = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! warning: `#[should_panic]` only has an effect on functions - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:318:17 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:324:17 | LL | mod inner { #![should_panic] } | ^^^^^^^^^^^^^^^^ warning: `#[should_panic]` only has an effect on functions - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:323:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:329:5 | LL | #[should_panic] struct S; | ^^^^^^^^^^^^^^^ warning: `#[should_panic]` only has an effect on functions - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:326:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:332:5 | LL | #[should_panic] type T = S; | ^^^^^^^^^^^^^^^ warning: `#[should_panic]` only has an effect on functions - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:329:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:335:5 | LL | #[should_panic] impl S { } | ^^^^^^^^^^^^^^^ warning: `#[ignore]` only has an effect on functions - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:336:17 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:342:17 | LL | mod inner { #![ignore] } | ^^^^^^^^^^ warning: `#[ignore]` only has an effect on functions - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:341:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:347:5 | LL | #[ignore] struct S; | ^^^^^^^^^ warning: `#[ignore]` only has an effect on functions - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:344:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:350:5 | LL | #[ignore] type T = S; | ^^^^^^^^^ warning: `#[ignore]` only has an effect on functions - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:347:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:353:5 | LL | #[ignore] impl S { } | ^^^^^^^^^ warning: `#[no_implicit_prelude]` only has an effect on modules - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:355:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:361:5 | LL | #[no_implicit_prelude] fn f() { } | ^^^^^^^^^^^^^^^^^^^^^^ warning: `#[no_implicit_prelude]` only has an effect on modules - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:358:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:364:5 | LL | #[no_implicit_prelude] struct S; | ^^^^^^^^^^^^^^^^^^^^^^ warning: `#[no_implicit_prelude]` only has an effect on modules - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:361:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:367:5 | LL | #[no_implicit_prelude] type T = S; | ^^^^^^^^^^^^^^^^^^^^^^ warning: `#[no_implicit_prelude]` only has an effect on modules - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:364:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:370:5 | LL | #[no_implicit_prelude] impl S { } | ^^^^^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be in the root module - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:371:17 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:377:17 | LL | mod inner { #![reexport_test_harness_main="2900"] } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:374:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:380:5 | LL | #[reexport_test_harness_main = "2900"] fn f() { } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:377:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:383:5 | LL | #[reexport_test_harness_main = "2900"] struct S; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:380:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:386:5 | LL | #[reexport_test_harness_main = "2900"] type T = S; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:383:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:389:5 | LL | #[reexport_test_harness_main = "2900"] impl S { } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ warning: `#[macro_escape]` only has an effect on `extern crate` and modules - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:395:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:401:5 | LL | #[macro_escape] fn f() { } | ^^^^^^^^^^^^^^^ warning: `#[macro_escape]` only has an effect on `extern crate` and modules - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:398:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:404:5 | LL | #[macro_escape] struct S; | ^^^^^^^^^^^^^^^ warning: `#[macro_escape]` only has an effect on `extern crate` and modules - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:401:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:407:5 | LL | #[macro_escape] type T = S; | ^^^^^^^^^^^^^^^ warning: `#[macro_escape]` only has an effect on `extern crate` and modules - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:404:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:410:5 | LL | #[macro_escape] impl S { } | ^^^^^^^^^^^^^^^ warning: crate-level attribute should be in the root module - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:411:17 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:417:17 | LL | mod inner { #![no_std] } | ^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:414:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:420:5 | LL | #[no_std] fn f() { } | ^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:417:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:423:5 | LL | #[no_std] struct S; | ^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:420:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:426:5 | LL | #[no_std] type T = S; | ^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:423:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:429:5 | LL | #[no_std] impl S { } | ^^^^^^^^^ warning: attribute should be applied to a function definition - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:450:17 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:456:17 | LL | mod inner { #![cold] } | ------------^^^^^^^^-- not a function definition @@ -732,7 +752,7 @@ LL | mod inner { #![cold] } = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! warning: attribute should be applied to a function definition - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:457:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:463:5 | LL | #[cold] struct S; | ^^^^^^^ --------- not a function definition @@ -740,7 +760,7 @@ LL | #[cold] struct S; = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! warning: attribute should be applied to a function definition - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:462:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:468:5 | LL | #[cold] type T = S; | ^^^^^^^ ----------- not a function definition @@ -748,7 +768,7 @@ LL | #[cold] type T = S; = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! warning: attribute should be applied to a function definition - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:467:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:473:5 | LL | #[cold] impl S { } | ^^^^^^^ ---------- not a function definition @@ -756,7 +776,7 @@ LL | #[cold] impl S { } = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! warning: attribute should be applied to a foreign function or static - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:479:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:485:5 | LL | #[link_name = "1900"] | ^^^^^^^^^^^^^^^^^^^^^ @@ -766,13 +786,13 @@ LL | extern "C" { } | = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! help: try `#[link(name = "1900")]` instead - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:479:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:485:5 | LL | #[link_name = "1900"] | ^^^^^^^^^^^^^^^^^^^^^ warning: attribute should be applied to a foreign function or static - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:486:17 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:492:17 | LL | mod inner { #![link_name="1900"] } | ------------^^^^^^^^^^^^^^^^^^^^-- not a foreign function or static @@ -780,7 +800,7 @@ LL | mod inner { #![link_name="1900"] } = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! warning: attribute should be applied to a foreign function or static - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:491:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:497:5 | LL | #[link_name = "1900"] fn f() { } | ^^^^^^^^^^^^^^^^^^^^^ ---------- not a foreign function or static @@ -788,7 +808,7 @@ LL | #[link_name = "1900"] fn f() { } = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! warning: attribute should be applied to a foreign function or static - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:496:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:502:5 | LL | #[link_name = "1900"] struct S; | ^^^^^^^^^^^^^^^^^^^^^ --------- not a foreign function or static @@ -796,7 +816,7 @@ LL | #[link_name = "1900"] struct S; = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! warning: attribute should be applied to a foreign function or static - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:501:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:507:5 | LL | #[link_name = "1900"] type T = S; | ^^^^^^^^^^^^^^^^^^^^^ ----------- not a foreign function or static @@ -804,7 +824,7 @@ LL | #[link_name = "1900"] type T = S; = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! warning: attribute should be applied to a foreign function or static - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:506:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:512:5 | LL | #[link_name = "1900"] impl S { } | ^^^^^^^^^^^^^^^^^^^^^ ---------- not a foreign function or static @@ -812,7 +832,7 @@ LL | #[link_name = "1900"] impl S { } = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! warning: attribute should be applied to a function or static - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:518:17 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:524:17 | LL | mod inner { #![link_section="1800"] } | ------------^^^^^^^^^^^^^^^^^^^^^^^-- not a function or static @@ -820,7 +840,7 @@ LL | mod inner { #![link_section="1800"] } = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! warning: attribute should be applied to a function or static - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:525:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:531:5 | LL | #[link_section = "1800"] struct S; | ^^^^^^^^^^^^^^^^^^^^^^^^ --------- not a function or static @@ -828,7 +848,7 @@ LL | #[link_section = "1800"] struct S; = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! warning: attribute should be applied to a function or static - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:530:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:536:5 | LL | #[link_section = "1800"] type T = S; | ^^^^^^^^^^^^^^^^^^^^^^^^ ----------- not a function or static @@ -836,7 +856,7 @@ LL | #[link_section = "1800"] type T = S; = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! warning: attribute should be applied to a function or static - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:535:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:541:5 | LL | #[link_section = "1800"] impl S { } | ^^^^^^^^^^^^^^^^^^^^^^^^ ---------- not a function or static @@ -844,7 +864,7 @@ LL | #[link_section = "1800"] impl S { } = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! warning: attribute should be applied to an `extern` block with non-Rust ABI - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:550:17 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:556:17 | LL | mod inner { #![link()] } | ------------^^^^^^^^^^-- not an `extern` block @@ -852,7 +872,7 @@ LL | mod inner { #![link()] } = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! warning: attribute should be applied to an `extern` block with non-Rust ABI - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:555:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:561:5 | LL | #[link()] fn f() { } | ^^^^^^^^^ ---------- not an `extern` block @@ -860,7 +880,7 @@ LL | #[link()] fn f() { } = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! warning: attribute should be applied to an `extern` block with non-Rust ABI - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:560:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:566:5 | LL | #[link()] struct S; | ^^^^^^^^^ --------- not an `extern` block @@ -868,7 +888,7 @@ LL | #[link()] struct S; = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! warning: attribute should be applied to an `extern` block with non-Rust ABI - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:565:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:571:5 | LL | #[link()] type T = S; | ^^^^^^^^^ ----------- not an `extern` block @@ -876,7 +896,7 @@ LL | #[link()] type T = S; = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! warning: attribute should be applied to an `extern` block with non-Rust ABI - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:570:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:576:5 | LL | #[link()] impl S { } | ^^^^^^^^^ ---------- not an `extern` block @@ -884,7 +904,7 @@ LL | #[link()] impl S { } = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! warning: attribute should be applied to an `extern` block with non-Rust ABI - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:575:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:581:5 | LL | #[link()] extern "Rust" {} | ^^^^^^^^^ @@ -892,270 +912,262 @@ LL | #[link()] extern "Rust" {} = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! warning: `#[must_use]` has no effect when applied to a module - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:597:17 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:603:17 | LL | mod inner { #![must_use] } | ^^^^^^^^^^^^ warning: `#[must_use]` has no effect when applied to a type alias - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:603:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:609:5 | LL | #[must_use] type T = S; | ^^^^^^^^^^^ -warning: `#[must_use]` has no effect when applied to an implementation block - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:605:5 +warning: `#[must_use]` has no effect when applied to an inherent implementation block + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:611:5 | LL | #[must_use] impl S { } | ^^^^^^^^^^^ warning: crate-level attribute should be in the root module - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:611:17 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:617:17 | LL | mod inner { #![windows_subsystem="windows"] } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:614:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:620:5 | LL | #[windows_subsystem = "windows"] fn f() { } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:617:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:623:5 | LL | #[windows_subsystem = "windows"] struct S; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:620:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:626:5 | LL | #[windows_subsystem = "windows"] type T = S; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:623:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:629:5 | LL | #[windows_subsystem = "windows"] impl S { } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be in the root module - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:632:17 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:638:17 | LL | mod inner { #![crate_name="0900"] } | ^^^^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:635:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:641:5 | LL | #[crate_name = "0900"] fn f() { } | ^^^^^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:638:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:644:5 | LL | #[crate_name = "0900"] struct S; | ^^^^^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:641:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:647:5 | LL | #[crate_name = "0900"] type T = S; | ^^^^^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:644:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:650:5 | LL | #[crate_name = "0900"] impl S { } | ^^^^^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be in the root module - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:651:17 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:657:17 | LL | mod inner { #![crate_type="0800"] } | ^^^^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:654:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:660:5 | LL | #[crate_type = "0800"] fn f() { } | ^^^^^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:657:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:663:5 | LL | #[crate_type = "0800"] struct S; | ^^^^^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:660:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:666:5 | LL | #[crate_type = "0800"] type T = S; | ^^^^^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:663:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:669:5 | LL | #[crate_type = "0800"] impl S { } | ^^^^^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be in the root module - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:670:17 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:676:17 | LL | mod inner { #![feature(x0600)] } | ^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:673:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:679:5 | LL | #[feature(x0600)] fn f() { } | ^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:676:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:682:5 | LL | #[feature(x0600)] struct S; | ^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:679:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:685:5 | LL | #[feature(x0600)] type T = S; | ^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:682:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:688:5 | LL | #[feature(x0600)] impl S { } | ^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be in the root module - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:690:17 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:696:17 | LL | mod inner { #![no_main] } | ^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:693:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:699:5 | LL | #[no_main] fn f() { } | ^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:696:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:702:5 | LL | #[no_main] struct S; | ^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:699:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:705:5 | LL | #[no_main] type T = S; | ^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:702:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:708:5 | LL | #[no_main] impl S { } | ^^^^^^^^^^ warning: crate-level attribute should be in the root module - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:709:17 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:715:17 | LL | mod inner { #![no_builtins] } | ^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:712:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:718:5 | LL | #[no_builtins] fn f() { } | ^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:715:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:721:5 | LL | #[no_builtins] struct S; | ^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:718:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:724:5 | LL | #[no_builtins] type T = S; | ^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:721:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:727:5 | LL | #[no_builtins] impl S { } | ^^^^^^^^^^^^^^ warning: crate-level attribute should be in the root module - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:728:17 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:734:17 | LL | mod inner { #![recursion_limit="0200"] } | ^^^^^^^^^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:731:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:737:5 | LL | #[recursion_limit="0200"] fn f() { } | ^^^^^^^^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:734:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:740:5 | LL | #[recursion_limit="0200"] struct S; | ^^^^^^^^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:737:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:743:5 | LL | #[recursion_limit="0200"] type T = S; | ^^^^^^^^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:740:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:746:5 | LL | #[recursion_limit="0200"] impl S { } | ^^^^^^^^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be in the root module - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:747:17 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:753:17 | LL | mod inner { #![type_length_limit="0100"] } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:750:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:756:5 | LL | #[type_length_limit="0100"] fn f() { } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:753:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:759:5 | LL | #[type_length_limit="0100"] struct S; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:756:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:762:5 | LL | #[type_length_limit="0100"] type T = S; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ warning: crate-level attribute should be an inner attribute: add an exclamation mark: `#![foo]` - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:759:5 + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:765:5 | LL | #[type_length_limit="0100"] impl S { } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ -warning: the feature `rust1` has been stable since 1.0.0 and no longer requires an attribute to enable - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:85:12 - | -LL | #![feature(rust1)] - | ^^^^^ - | - = note: `#[warn(stable_features)]` on by default - -warning: 171 warnings emitted +warning: 173 warnings emitted diff --git a/tests/ui/feature-gates/unstable-attribute-rejects-already-stable-features.stderr b/tests/ui/feature-gates/unstable-attribute-rejects-already-stable-features.stderr index 319056a9c88..d599523c727 100644 --- a/tests/ui/feature-gates/unstable-attribute-rejects-already-stable-features.stderr +++ b/tests/ui/feature-gates/unstable-attribute-rejects-already-stable-features.stderr @@ -1,31 +1,31 @@ error: can't mark as unstable using an already stable feature - --> $DIR/unstable-attribute-rejects-already-stable-features.rs:6:1 + --> $DIR/unstable-attribute-rejects-already-stable-features.rs:7:1 | -LL | #[unstable(feature = "arbitrary_enum_discriminant", issue = "42")] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this feature is already stable LL | #[rustc_const_unstable(feature = "arbitrary_enum_discriminant", issue = "42")] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this feature is already stable LL | const fn my_fun() {} | -------------------- the stability attribute annotates this item | help: consider removing the attribute - --> $DIR/unstable-attribute-rejects-already-stable-features.rs:6:1 + --> $DIR/unstable-attribute-rejects-already-stable-features.rs:7:1 | -LL | #[unstable(feature = "arbitrary_enum_discriminant", issue = "42")] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | #[rustc_const_unstable(feature = "arbitrary_enum_discriminant", issue = "42")] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: can't mark as unstable using an already stable feature - --> $DIR/unstable-attribute-rejects-already-stable-features.rs:7:1 + --> $DIR/unstable-attribute-rejects-already-stable-features.rs:6:1 | +LL | #[unstable(feature = "arbitrary_enum_discriminant", issue = "42")] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this feature is already stable LL | #[rustc_const_unstable(feature = "arbitrary_enum_discriminant", issue = "42")] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this feature is already stable LL | const fn my_fun() {} | -------------------- the stability attribute annotates this item | help: consider removing the attribute - --> $DIR/unstable-attribute-rejects-already-stable-features.rs:7:1 + --> $DIR/unstable-attribute-rejects-already-stable-features.rs:6:1 | -LL | #[rustc_const_unstable(feature = "arbitrary_enum_discriminant", issue = "42")] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | #[unstable(feature = "arbitrary_enum_discriminant", issue = "42")] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 2 previous errors diff --git a/tests/ui/impl-trait/in-bindings/implicit-sized.rs b/tests/ui/impl-trait/in-bindings/implicit-sized.rs new file mode 100644 index 00000000000..2f16db94189 --- /dev/null +++ b/tests/ui/impl-trait/in-bindings/implicit-sized.rs @@ -0,0 +1,19 @@ +#![feature(impl_trait_in_bindings)] + +trait Trait {} +impl<T: ?Sized> Trait for T {} + +fn doesnt_work() { + let x: &impl Trait = "hi"; + //~^ ERROR the size for values of type `str` cannot be known at compilation time +} + +fn works() { + let x: &(impl Trait + ?Sized) = "hi"; + // No implicit sized. + + let x: &impl Trait = &(); + // Is actually sized. +} + +fn main() {} diff --git a/tests/ui/impl-trait/in-bindings/implicit-sized.stderr b/tests/ui/impl-trait/in-bindings/implicit-sized.stderr new file mode 100644 index 00000000000..465a928cf86 --- /dev/null +++ b/tests/ui/impl-trait/in-bindings/implicit-sized.stderr @@ -0,0 +1,11 @@ +error[E0277]: the size for values of type `str` cannot be known at compilation time + --> $DIR/implicit-sized.rs:7:13 + | +LL | let x: &impl Trait = "hi"; + | ^^^^^^^^^^ doesn't have a size known at compile-time + | + = help: the trait `Sized` is not implemented for `str` + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/impl-trait/opt-out-bound-not-satisfied.rs b/tests/ui/impl-trait/opt-out-bound-not-satisfied.rs index 27c493a13bf..7e0e1eadf9c 100644 --- a/tests/ui/impl-trait/opt-out-bound-not-satisfied.rs +++ b/tests/ui/impl-trait/opt-out-bound-not-satisfied.rs @@ -3,8 +3,8 @@ use std::future::Future; fn foo() -> impl ?Future<Output = impl Send> { - //~^ ERROR: relaxing a default bound only does something for `?Sized` - //~| ERROR: relaxing a default bound only does something for `?Sized` + //~^ ERROR: bound modifier `?` can only be applied to `Sized` + //~| ERROR: bound modifier `?` can only be applied to `Sized` () } diff --git a/tests/ui/impl-trait/opt-out-bound-not-satisfied.stderr b/tests/ui/impl-trait/opt-out-bound-not-satisfied.stderr index dc4314c58ad..f99d6a7e5f6 100644 --- a/tests/ui/impl-trait/opt-out-bound-not-satisfied.stderr +++ b/tests/ui/impl-trait/opt-out-bound-not-satisfied.stderr @@ -1,10 +1,10 @@ -error: relaxing a default bound only does something for `?Sized`; all other traits are not bound by default +error: bound modifier `?` can only be applied to `Sized` --> $DIR/opt-out-bound-not-satisfied.rs:5:18 | LL | fn foo() -> impl ?Future<Output = impl Send> { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: relaxing a default bound only does something for `?Sized`; all other traits are not bound by default +error: bound modifier `?` can only be applied to `Sized` --> $DIR/opt-out-bound-not-satisfied.rs:5:18 | LL | fn foo() -> impl ?Future<Output = impl Send> { diff --git a/tests/ui/intrinsics/intrinsic-raw_eq-const-bad.stderr b/tests/ui/intrinsics/intrinsic-raw_eq-const-bad.stderr index 10f4d8d1a71..5f4ef14d586 100644 --- a/tests/ui/intrinsics/intrinsic-raw_eq-const-bad.stderr +++ b/tests/ui/intrinsics/intrinsic-raw_eq-const-bad.stderr @@ -3,6 +3,10 @@ error[E0080]: reading memory at ALLOC0[0x0..0x4], but memory is uninitialized at | LL | std::intrinsics::raw_eq(&(1_u8, 2_u16), &(1_u8, 2_u16)) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `RAW_EQ_PADDING` failed here + | + = note: the raw bytes of the constant (size: 4, align: 2) { + 01 __ 02 00 │ .░.. + } error[E0080]: unable to turn pointer into integer --> $DIR/intrinsic-raw_eq-const-bad.rs:9:5 diff --git a/tests/ui/issues/issue-37534.rs b/tests/ui/issues/issue-37534.rs index 09d60b7786b..63f6479ae2e 100644 --- a/tests/ui/issues/issue-37534.rs +++ b/tests/ui/issues/issue-37534.rs @@ -1,5 +1,5 @@ struct Foo<T: ?Hash> {} //~^ ERROR expected trait, found derive macro `Hash` -//~| ERROR relaxing a default bound only does something for `?Sized` +//~| ERROR bound modifier `?` can only be applied to `Sized` fn main() {} diff --git a/tests/ui/issues/issue-37534.stderr b/tests/ui/issues/issue-37534.stderr index 3219854bc70..08607354203 100644 --- a/tests/ui/issues/issue-37534.stderr +++ b/tests/ui/issues/issue-37534.stderr @@ -9,7 +9,7 @@ help: consider importing this trait instead LL + use std::hash::Hash; | -error: relaxing a default bound only does something for `?Sized`; all other traits are not bound by default +error: bound modifier `?` can only be applied to `Sized` --> $DIR/issue-37534.rs:1:15 | LL | struct Foo<T: ?Hash> {} diff --git a/tests/ui/issues/issue-87199.rs b/tests/ui/issues/issue-87199.rs index 4e4e35c6a71..dd9dfc74ca3 100644 --- a/tests/ui/issues/issue-87199.rs +++ b/tests/ui/issues/issue-87199.rs @@ -6,12 +6,12 @@ // Check that these function definitions only emit warnings, not errors fn arg<T: ?Send>(_: T) {} -//~^ ERROR: relaxing a default bound only does something for `?Sized` +//~^ ERROR: bound modifier `?` can only be applied to `Sized` fn ref_arg<T: ?Send>(_: &T) {} -//~^ ERROR: relaxing a default bound only does something for `?Sized` +//~^ ERROR: bound modifier `?` can only be applied to `Sized` fn ret() -> impl Iterator<Item = ()> + ?Send { std::iter::empty() } -//~^ ERROR: relaxing a default bound only does something for `?Sized` -//~| ERROR: relaxing a default bound only does something for `?Sized` +//~^ ERROR: bound modifier `?` can only be applied to `Sized` +//~| ERROR: bound modifier `?` can only be applied to `Sized` // Check that there's no `?Sized` relaxation! fn main() { diff --git a/tests/ui/issues/issue-87199.stderr b/tests/ui/issues/issue-87199.stderr index acc4e84779c..8a930a3d704 100644 --- a/tests/ui/issues/issue-87199.stderr +++ b/tests/ui/issues/issue-87199.stderr @@ -1,22 +1,22 @@ -error: relaxing a default bound only does something for `?Sized`; all other traits are not bound by default +error: bound modifier `?` can only be applied to `Sized` --> $DIR/issue-87199.rs:8:11 | LL | fn arg<T: ?Send>(_: T) {} | ^^^^^ -error: relaxing a default bound only does something for `?Sized`; all other traits are not bound by default +error: bound modifier `?` can only be applied to `Sized` --> $DIR/issue-87199.rs:10:15 | LL | fn ref_arg<T: ?Send>(_: &T) {} | ^^^^^ -error: relaxing a default bound only does something for `?Sized`; all other traits are not bound by default +error: bound modifier `?` can only be applied to `Sized` --> $DIR/issue-87199.rs:12:40 | LL | fn ret() -> impl Iterator<Item = ()> + ?Send { std::iter::empty() } | ^^^^^ -error: relaxing a default bound only does something for `?Sized`; all other traits are not bound by default +error: bound modifier `?` can only be applied to `Sized` --> $DIR/issue-87199.rs:12:40 | LL | fn ret() -> impl Iterator<Item = ()> + ?Send { std::iter::empty() } diff --git a/tests/ui/lifetimes/elided-lifetime-in-const-param-type.rs b/tests/ui/lifetimes/elided-lifetime-in-const-param-type.rs new file mode 100644 index 00000000000..cdfd1327eae --- /dev/null +++ b/tests/ui/lifetimes/elided-lifetime-in-const-param-type.rs @@ -0,0 +1,12 @@ +//! Regression test for <https://github.com/rust-lang/rust/issues/143413> +//! The anonymous lifetime in `c(&())` is desugared by the resolver as an extra lifetime parameter +//! at the end of the `for` binder. Verify that lowering creates the definition for that extra +//! lifetime parameter before lowering `c(&())`. + +trait D {} + +type A = dyn for<const B: c(&())> D; +//~^ ERROR cannot find type `c` in this scope +//~| ERROR only lifetime parameters can be used in this context + +fn main() {} diff --git a/tests/ui/lifetimes/elided-lifetime-in-const-param-type.stderr b/tests/ui/lifetimes/elided-lifetime-in-const-param-type.stderr new file mode 100644 index 00000000000..c7f3c0cc0cd --- /dev/null +++ b/tests/ui/lifetimes/elided-lifetime-in-const-param-type.stderr @@ -0,0 +1,20 @@ +error[E0412]: cannot find type `c` in this scope + --> $DIR/elided-lifetime-in-const-param-type.rs:8:27 + | +LL | type A = dyn for<const B: c(&())> D; + | ^ not found in this scope + +error[E0658]: only lifetime parameters can be used in this context + --> $DIR/elided-lifetime-in-const-param-type.rs:8:24 + | +LL | type A = dyn for<const B: c(&())> D; + | ^ + | + = note: see issue #108185 <https://github.com/rust-lang/rust/issues/108185> for more information + = help: add `#![feature(non_lifetime_binders)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error: aborting due to 2 previous errors + +Some errors have detailed explanations: E0412, E0658. +For more information about an error, try `rustc --explain E0412`. diff --git a/tests/ui/lint/invalid_null_args.rs b/tests/ui/lint/invalid_null_args.rs index f40f06a0d36..ee29d622ad7 100644 --- a/tests/ui/lint/invalid_null_args.rs +++ b/tests/ui/lint/invalid_null_args.rs @@ -58,10 +58,9 @@ unsafe fn null_ptr() { let _a: A = ptr::read_unaligned(ptr::null_mut()); //~^ ERROR calling this function with a null pointer is undefined behavior + // These two should *not* fire the lint. let _a: A = ptr::read_volatile(ptr::null()); - //~^ ERROR calling this function with a null pointer is undefined behavior let _a: A = ptr::read_volatile(ptr::null_mut()); - //~^ ERROR calling this function with a null pointer is undefined behavior let _a: A = ptr::replace(ptr::null_mut(), v); //~^ ERROR calling this function with a null pointer is undefined behavior @@ -82,8 +81,8 @@ unsafe fn null_ptr() { ptr::write_unaligned(ptr::null_mut(), v); //~^ ERROR calling this function with a null pointer is undefined behavior + // This one should *not* fire the lint. ptr::write_volatile(ptr::null_mut(), v); - //~^ ERROR calling this function with a null pointer is undefined behavior ptr::write_bytes::<usize>(ptr::null_mut(), 42, 0); //~^ ERROR calling this function with a null pointer is undefined behavior diff --git a/tests/ui/lint/invalid_null_args.stderr b/tests/ui/lint/invalid_null_args.stderr index 11c6270cfb7..028bd7051dc 100644 --- a/tests/ui/lint/invalid_null_args.stderr +++ b/tests/ui/lint/invalid_null_args.stderr @@ -164,27 +164,7 @@ LL | let _a: A = ptr::read_unaligned(ptr::null_mut()); = help: for more information, visit <https://doc.rust-lang.org/std/ptr/index.html> and <https://doc.rust-lang.org/reference/behavior-considered-undefined.html> error: calling this function with a null pointer is undefined behavior, even if the result of the function is unused - --> $DIR/invalid_null_args.rs:61:17 - | -LL | let _a: A = ptr::read_volatile(ptr::null()); - | ^^^^^^^^^^^^^^^^^^^-----------^ - | | - | null pointer originates from here - | - = help: for more information, visit <https://doc.rust-lang.org/std/ptr/index.html> and <https://doc.rust-lang.org/reference/behavior-considered-undefined.html> - -error: calling this function with a null pointer is undefined behavior, even if the result of the function is unused - --> $DIR/invalid_null_args.rs:63:17 - | -LL | let _a: A = ptr::read_volatile(ptr::null_mut()); - | ^^^^^^^^^^^^^^^^^^^---------------^ - | | - | null pointer originates from here - | - = help: for more information, visit <https://doc.rust-lang.org/std/ptr/index.html> and <https://doc.rust-lang.org/reference/behavior-considered-undefined.html> - -error: calling this function with a null pointer is undefined behavior, even if the result of the function is unused - --> $DIR/invalid_null_args.rs:66:17 + --> $DIR/invalid_null_args.rs:65:17 | LL | let _a: A = ptr::replace(ptr::null_mut(), v); | ^^^^^^^^^^^^^---------------^^^^ @@ -194,7 +174,7 @@ LL | let _a: A = ptr::replace(ptr::null_mut(), v); = help: for more information, visit <https://doc.rust-lang.org/std/ptr/index.html> and <https://doc.rust-lang.org/reference/behavior-considered-undefined.html> error: calling this function with a null pointer is undefined behavior, even if the result of the function is unused - --> $DIR/invalid_null_args.rs:69:5 + --> $DIR/invalid_null_args.rs:68:5 | LL | ptr::swap::<A>(ptr::null_mut(), &mut v); | ^^^^^^^^^^^^^^^---------------^^^^^^^^^ @@ -204,7 +184,7 @@ LL | ptr::swap::<A>(ptr::null_mut(), &mut v); = help: for more information, visit <https://doc.rust-lang.org/std/ptr/index.html> and <https://doc.rust-lang.org/reference/behavior-considered-undefined.html> error: calling this function with a null pointer is undefined behavior, even if the result of the function is unused - --> $DIR/invalid_null_args.rs:71:5 + --> $DIR/invalid_null_args.rs:70:5 | LL | ptr::swap::<A>(&mut v, ptr::null_mut()); | ^^^^^^^^^^^^^^^^^^^^^^^---------------^ @@ -214,7 +194,7 @@ LL | ptr::swap::<A>(&mut v, ptr::null_mut()); = help: for more information, visit <https://doc.rust-lang.org/std/ptr/index.html> and <https://doc.rust-lang.org/reference/behavior-considered-undefined.html> error: calling this function with a null pointer is undefined behavior, even if the result of the function is unused - --> $DIR/invalid_null_args.rs:74:5 + --> $DIR/invalid_null_args.rs:73:5 | LL | ptr::swap_nonoverlapping::<A>(ptr::null_mut(), &mut v, 0); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^---------------^^^^^^^^^^^^ @@ -224,7 +204,7 @@ LL | ptr::swap_nonoverlapping::<A>(ptr::null_mut(), &mut v, 0); = help: for more information, visit <https://doc.rust-lang.org/std/ptr/index.html> and <https://doc.rust-lang.org/reference/behavior-considered-undefined.html> error: calling this function with a null pointer is undefined behavior, even if the result of the function is unused - --> $DIR/invalid_null_args.rs:76:5 + --> $DIR/invalid_null_args.rs:75:5 | LL | ptr::swap_nonoverlapping::<A>(&mut v, ptr::null_mut(), 0); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^---------------^^^^ @@ -234,7 +214,7 @@ LL | ptr::swap_nonoverlapping::<A>(&mut v, ptr::null_mut(), 0); = help: for more information, visit <https://doc.rust-lang.org/std/ptr/index.html> and <https://doc.rust-lang.org/reference/behavior-considered-undefined.html> error: calling this function with a null pointer is undefined behavior, even if the result of the function is unused - --> $DIR/invalid_null_args.rs:79:5 + --> $DIR/invalid_null_args.rs:78:5 | LL | ptr::write(ptr::null_mut(), v); | ^^^^^^^^^^^---------------^^^^ @@ -244,7 +224,7 @@ LL | ptr::write(ptr::null_mut(), v); = help: for more information, visit <https://doc.rust-lang.org/std/ptr/index.html> and <https://doc.rust-lang.org/reference/behavior-considered-undefined.html> error: calling this function with a null pointer is undefined behavior, even if the result of the function is unused - --> $DIR/invalid_null_args.rs:82:5 + --> $DIR/invalid_null_args.rs:81:5 | LL | ptr::write_unaligned(ptr::null_mut(), v); | ^^^^^^^^^^^^^^^^^^^^^---------------^^^^ @@ -254,17 +234,7 @@ LL | ptr::write_unaligned(ptr::null_mut(), v); = help: for more information, visit <https://doc.rust-lang.org/std/ptr/index.html> and <https://doc.rust-lang.org/reference/behavior-considered-undefined.html> error: calling this function with a null pointer is undefined behavior, even if the result of the function is unused - --> $DIR/invalid_null_args.rs:85:5 - | -LL | ptr::write_volatile(ptr::null_mut(), v); - | ^^^^^^^^^^^^^^^^^^^^---------------^^^^ - | | - | null pointer originates from here - | - = help: for more information, visit <https://doc.rust-lang.org/std/ptr/index.html> and <https://doc.rust-lang.org/reference/behavior-considered-undefined.html> - -error: calling this function with a null pointer is undefined behavior, even if the result of the function is unused - --> $DIR/invalid_null_args.rs:88:5 + --> $DIR/invalid_null_args.rs:87:5 | LL | ptr::write_bytes::<usize>(ptr::null_mut(), 42, 0); | ^^^^^^^^^^^^^^^^^^^^^^^^^^---------------^^^^^^^^ @@ -274,7 +244,7 @@ LL | ptr::write_bytes::<usize>(ptr::null_mut(), 42, 0); = help: for more information, visit <https://doc.rust-lang.org/std/ptr/index.html> and <https://doc.rust-lang.org/reference/behavior-considered-undefined.html> error: calling this function with a null pointer is undefined behavior, even if the result of the function is unused - --> $DIR/invalid_null_args.rs:93:18 + --> $DIR/invalid_null_args.rs:92:18 | LL | let _a: u8 = ptr::read(const_ptr); | ^^^^^^^^^^^^^^^^^^^^ @@ -287,7 +257,7 @@ LL | let null_ptr = ptr::null_mut(); | ^^^^^^^^^^^^^^^ error: calling this function with a null pointer is undefined behavior, even if the result of the function is unused - --> $DIR/invalid_null_args.rs:100:5 + --> $DIR/invalid_null_args.rs:99:5 | LL | std::slice::from_raw_parts::<()>(ptr::null(), 0); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-----------^^^^ @@ -297,7 +267,7 @@ LL | std::slice::from_raw_parts::<()>(ptr::null(), 0); = help: for more information, visit <https://doc.rust-lang.org/std/ptr/index.html> and <https://doc.rust-lang.org/reference/behavior-considered-undefined.html> error: calling this function with a null pointer is undefined behavior, even if the result of the function is unused - --> $DIR/invalid_null_args.rs:102:5 + --> $DIR/invalid_null_args.rs:101:5 | LL | std::slice::from_raw_parts::<Zst>(ptr::null(), 0); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-----------^^^^ @@ -307,7 +277,7 @@ LL | std::slice::from_raw_parts::<Zst>(ptr::null(), 0); = help: for more information, visit <https://doc.rust-lang.org/std/ptr/index.html> and <https://doc.rust-lang.org/reference/behavior-considered-undefined.html> error: calling this function with a null pointer is undefined behavior, even if the result of the function is unused - --> $DIR/invalid_null_args.rs:104:5 + --> $DIR/invalid_null_args.rs:103:5 | LL | std::slice::from_raw_parts_mut::<()>(ptr::null_mut(), 0); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^---------------^^^^ @@ -317,7 +287,7 @@ LL | std::slice::from_raw_parts_mut::<()>(ptr::null_mut(), 0); = help: for more information, visit <https://doc.rust-lang.org/std/ptr/index.html> and <https://doc.rust-lang.org/reference/behavior-considered-undefined.html> error: calling this function with a null pointer is undefined behavior, even if the result of the function is unused - --> $DIR/invalid_null_args.rs:106:5 + --> $DIR/invalid_null_args.rs:105:5 | LL | std::slice::from_raw_parts_mut::<Zst>(ptr::null_mut(), 0); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^---------------^^^^ @@ -326,5 +296,5 @@ LL | std::slice::from_raw_parts_mut::<Zst>(ptr::null_mut(), 0); | = help: for more information, visit <https://doc.rust-lang.org/std/ptr/index.html> and <https://doc.rust-lang.org/reference/behavior-considered-undefined.html> -error: aborting due to 31 previous errors +error: aborting due to 28 previous errors diff --git a/tests/ui/lint/lint-stability-deprecated.stderr b/tests/ui/lint/lint-stability-deprecated.stderr index 51205ff4340..0399fab746e 100644 --- a/tests/ui/lint/lint-stability-deprecated.stderr +++ b/tests/ui/lint/lint-stability-deprecated.stderr @@ -1,8 +1,8 @@ -warning: use of deprecated function `lint_stability::deprecated`: text - --> $DIR/lint-stability-deprecated.rs:24:9 +warning: use of deprecated associated type `lint_stability::TraitWithAssociatedTypes::TypeDeprecated`: text + --> $DIR/lint-stability-deprecated.rs:97:48 | -LL | deprecated(); - | ^^^^^^^^^^ +LL | struct S2<T: TraitWithAssociatedTypes>(T::TypeDeprecated); + | ^^^^^^^^^^^^^^^^^ | note: the lint level is defined here --> $DIR/lint-stability-deprecated.rs:6:9 @@ -10,6 +10,12 @@ note: the lint level is defined here LL | #![warn(deprecated)] | ^^^^^^^^^^ +warning: use of deprecated function `lint_stability::deprecated`: text + --> $DIR/lint-stability-deprecated.rs:24:9 + | +LL | deprecated(); + | ^^^^^^^^^^ + warning: use of deprecated method `lint_stability::Trait::trait_deprecated`: text --> $DIR/lint-stability-deprecated.rs:29:16 | @@ -317,12 +323,6 @@ LL | fn_in_body(); | ^^^^^^^^^^ warning: use of deprecated associated type `lint_stability::TraitWithAssociatedTypes::TypeDeprecated`: text - --> $DIR/lint-stability-deprecated.rs:97:48 - | -LL | struct S2<T: TraitWithAssociatedTypes>(T::TypeDeprecated); - | ^^^^^^^^^^^^^^^^^ - -warning: use of deprecated associated type `lint_stability::TraitWithAssociatedTypes::TypeDeprecated`: text --> $DIR/lint-stability-deprecated.rs:101:13 | LL | TypeDeprecated = u16, diff --git a/tests/ui/lint/lint-stability.stderr b/tests/ui/lint/lint-stability.stderr index fd57908a77b..249f3ccaa54 100644 --- a/tests/ui/lint/lint-stability.stderr +++ b/tests/ui/lint/lint-stability.stderr @@ -1,4 +1,13 @@ error[E0658]: use of unstable library feature `unstable_test_feature` + --> $DIR/lint-stability.rs:88:48 + | +LL | struct S1<T: TraitWithAssociatedTypes>(T::TypeUnstable); + | ^^^^^^^^^^^^^^^ + | + = help: add `#![feature(unstable_test_feature)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error[E0658]: use of unstable library feature `unstable_test_feature` --> $DIR/lint-stability.rs:17:5 | LL | extern crate stability_cfg2; @@ -368,15 +377,6 @@ LL | let _ = Unstable::StableVariant; = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date error[E0658]: use of unstable library feature `unstable_test_feature` - --> $DIR/lint-stability.rs:88:48 - | -LL | struct S1<T: TraitWithAssociatedTypes>(T::TypeUnstable); - | ^^^^^^^^^^^^^^^ - | - = help: add `#![feature(unstable_test_feature)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - -error[E0658]: use of unstable library feature `unstable_test_feature` --> $DIR/lint-stability.rs:92:13 | LL | TypeUnstable = u8, diff --git a/tests/ui/lint/unused/unused-attr-duplicate.rs b/tests/ui/lint/unused/unused-attr-duplicate.rs index bf94a42f6e0..cfa6c2b4228 100644 --- a/tests/ui/lint/unused/unused-attr-duplicate.rs +++ b/tests/ui/lint/unused/unused-attr-duplicate.rs @@ -66,9 +66,11 @@ fn t1() {} #[non_exhaustive] //~ ERROR unused attribute pub struct X; +trait Trait {} + #[automatically_derived] #[automatically_derived] //~ ERROR unused attribute -impl X {} +impl Trait for X {} #[inline(always)] #[inline(never)] //~ ERROR unused attribute diff --git a/tests/ui/lint/unused/unused-attr-duplicate.stderr b/tests/ui/lint/unused/unused-attr-duplicate.stderr index 6db6af823f4..ecc1b7ff5a4 100644 --- a/tests/ui/lint/unused/unused-attr-duplicate.stderr +++ b/tests/ui/lint/unused/unused-attr-duplicate.stderr @@ -179,112 +179,112 @@ LL | #[non_exhaustive] | ^^^^^^^^^^^^^^^^^ error: unused attribute - --> $DIR/unused-attr-duplicate.rs:70:1 + --> $DIR/unused-attr-duplicate.rs:72:1 | LL | #[automatically_derived] | ^^^^^^^^^^^^^^^^^^^^^^^^ help: remove this attribute | note: attribute also specified here - --> $DIR/unused-attr-duplicate.rs:69:1 + --> $DIR/unused-attr-duplicate.rs:71:1 | LL | #[automatically_derived] | ^^^^^^^^^^^^^^^^^^^^^^^^ error: unused attribute - --> $DIR/unused-attr-duplicate.rs:74:1 + --> $DIR/unused-attr-duplicate.rs:76:1 | LL | #[inline(never)] | ^^^^^^^^^^^^^^^^ help: remove this attribute | note: attribute also specified here - --> $DIR/unused-attr-duplicate.rs:73:1 + --> $DIR/unused-attr-duplicate.rs:75:1 | LL | #[inline(always)] | ^^^^^^^^^^^^^^^^^ = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! error: unused attribute - --> $DIR/unused-attr-duplicate.rs:77:1 + --> $DIR/unused-attr-duplicate.rs:79:1 | LL | #[cold] | ^^^^^^^ help: remove this attribute | note: attribute also specified here - --> $DIR/unused-attr-duplicate.rs:76:1 + --> $DIR/unused-attr-duplicate.rs:78:1 | LL | #[cold] | ^^^^^^^ error: unused attribute - --> $DIR/unused-attr-duplicate.rs:79:1 + --> $DIR/unused-attr-duplicate.rs:81:1 | LL | #[track_caller] | ^^^^^^^^^^^^^^^ help: remove this attribute | note: attribute also specified here - --> $DIR/unused-attr-duplicate.rs:78:1 + --> $DIR/unused-attr-duplicate.rs:80:1 | LL | #[track_caller] | ^^^^^^^^^^^^^^^ error: unused attribute - --> $DIR/unused-attr-duplicate.rs:86:5 + --> $DIR/unused-attr-duplicate.rs:88:5 | LL | #[link_name = "this_does_not_exist"] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: remove this attribute | note: attribute also specified here - --> $DIR/unused-attr-duplicate.rs:88:5 + --> $DIR/unused-attr-duplicate.rs:90:5 | LL | #[link_name = "rust_dbg_extern_identity_u32"] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! error: unused attribute - --> $DIR/unused-attr-duplicate.rs:92:1 + --> $DIR/unused-attr-duplicate.rs:94:1 | LL | #[export_name = "exported_symbol_name"] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: remove this attribute | note: attribute also specified here - --> $DIR/unused-attr-duplicate.rs:94:1 + --> $DIR/unused-attr-duplicate.rs:96:1 | LL | #[export_name = "exported_symbol_name2"] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! error: unused attribute - --> $DIR/unused-attr-duplicate.rs:98:1 + --> $DIR/unused-attr-duplicate.rs:100:1 | LL | #[no_mangle] | ^^^^^^^^^^^^ help: remove this attribute | note: attribute also specified here - --> $DIR/unused-attr-duplicate.rs:97:1 + --> $DIR/unused-attr-duplicate.rs:99:1 | LL | #[no_mangle] | ^^^^^^^^^^^^ error: unused attribute - --> $DIR/unused-attr-duplicate.rs:102:1 + --> $DIR/unused-attr-duplicate.rs:104:1 | LL | #[used] | ^^^^^^^ help: remove this attribute | note: attribute also specified here - --> $DIR/unused-attr-duplicate.rs:101:1 + --> $DIR/unused-attr-duplicate.rs:103:1 | LL | #[used] | ^^^^^^^ error: unused attribute - --> $DIR/unused-attr-duplicate.rs:105:1 + --> $DIR/unused-attr-duplicate.rs:107:1 | LL | #[link_section = ".text"] | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: remove this attribute | note: attribute also specified here - --> $DIR/unused-attr-duplicate.rs:108:1 + --> $DIR/unused-attr-duplicate.rs:110:1 | LL | #[link_section = ".bss"] | ^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/lint/unused/unused_attributes-must_use.stderr b/tests/ui/lint/unused/unused_attributes-must_use.stderr index 28fd8eeb8cb..862ffa42d80 100644 --- a/tests/ui/lint/unused/unused_attributes-must_use.stderr +++ b/tests/ui/lint/unused/unused_attributes-must_use.stderr @@ -45,7 +45,7 @@ error: `#[must_use]` has no effect when applied to a static item LL | #[must_use] | ^^^^^^^^^^^ -error: `#[must_use]` has no effect when applied to an implementation block +error: `#[must_use]` has no effect when applied to an inherent implementation block --> $DIR/unused_attributes-must_use.rs:33:1 | LL | #[must_use] @@ -69,7 +69,7 @@ error: `#[must_use]` has no effect when applied to a type parameter LL | fn qux<#[must_use] T>(_: T) {} | ^^^^^^^^^^^ -error: `#[must_use]` has no effect when applied to an implementation block +error: `#[must_use]` has no effect when applied to an trait implementation block --> $DIR/unused_attributes-must_use.rs:79:1 | LL | #[must_use] diff --git a/tests/ui/lto/debuginfo-lto-alloc.rs b/tests/ui/lto/debuginfo-lto-alloc.rs index 89043275329..d6855f8760d 100644 --- a/tests/ui/lto/debuginfo-lto-alloc.rs +++ b/tests/ui/lto/debuginfo-lto-alloc.rs @@ -8,8 +8,9 @@ // This test reproduces the circumstances that caused the error to appear, and checks // that compilation is successful. -//@ check-pass +//@ build-pass //@ compile-flags: --test -C debuginfo=2 -C lto=fat +//@ no-prefer-dynamic //@ incremental extern crate alloc; diff --git a/tests/ui/mir/alignment/borrow_misaligned_field_projection.rs b/tests/ui/mir/alignment/borrow_misaligned_field_projection.rs index a22965ce1d8..6ba895f172d 100644 --- a/tests/ui/mir/alignment/borrow_misaligned_field_projection.rs +++ b/tests/ui/mir/alignment/borrow_misaligned_field_projection.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ ignore-i686-pc-windows-msvc: #112480 //@ compile-flags: -C debug-assertions //@ error-pattern: misaligned pointer dereference: address must be a multiple of 0x4 but is diff --git a/tests/ui/mir/alignment/misaligned_borrow.rs b/tests/ui/mir/alignment/misaligned_borrow.rs index de8912c7038..60c21deaba5 100644 --- a/tests/ui/mir/alignment/misaligned_borrow.rs +++ b/tests/ui/mir/alignment/misaligned_borrow.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ ignore-i686-pc-windows-msvc: #112480 //@ compile-flags: -C debug-assertions //@ error-pattern: misaligned pointer dereference: address must be a multiple of 0x4 but is diff --git a/tests/ui/mir/alignment/misaligned_lhs.rs b/tests/ui/mir/alignment/misaligned_lhs.rs index b169823bc08..e8ddb10fd9c 100644 --- a/tests/ui/mir/alignment/misaligned_lhs.rs +++ b/tests/ui/mir/alignment/misaligned_lhs.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ ignore-i686-pc-windows-msvc: #112480 //@ compile-flags: -C debug-assertions //@ error-pattern: misaligned pointer dereference: address must be a multiple of 0x4 but is diff --git a/tests/ui/mir/alignment/misaligned_mut_borrow.rs b/tests/ui/mir/alignment/misaligned_mut_borrow.rs index bba20edecfd..c066cc0efcd 100644 --- a/tests/ui/mir/alignment/misaligned_mut_borrow.rs +++ b/tests/ui/mir/alignment/misaligned_mut_borrow.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ ignore-i686-pc-windows-msvc: #112480 //@ compile-flags: -C debug-assertions //@ error-pattern: misaligned pointer dereference: address must be a multiple of 0x4 but is diff --git a/tests/ui/mir/alignment/misaligned_rhs.rs b/tests/ui/mir/alignment/misaligned_rhs.rs index 55da30a2fd7..6bdc39c9d91 100644 --- a/tests/ui/mir/alignment/misaligned_rhs.rs +++ b/tests/ui/mir/alignment/misaligned_rhs.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ ignore-i686-pc-windows-msvc: #112480 //@ compile-flags: -C debug-assertions //@ error-pattern: misaligned pointer dereference: address must be a multiple of 0x4 but is diff --git a/tests/ui/mir/alignment/two_pointers.rs b/tests/ui/mir/alignment/two_pointers.rs index 198a1c9853d..fd8b2f543aa 100644 --- a/tests/ui/mir/alignment/two_pointers.rs +++ b/tests/ui/mir/alignment/two_pointers.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ ignore-i686-pc-windows-msvc: #112480 //@ compile-flags: -C debug-assertions //@ error-pattern: misaligned pointer dereference: address must be a multiple of 0x4 but is diff --git a/tests/ui/mir/enum/convert_non_integer_break.rs b/tests/ui/mir/enum/convert_non_integer_break.rs index 29795190bf6..b0778e2024f 100644 --- a/tests/ui/mir/enum/convert_non_integer_break.rs +++ b/tests/ui/mir/enum/convert_non_integer_break.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -C debug-assertions //@ error-pattern: trying to construct an enum from an invalid value diff --git a/tests/ui/mir/enum/convert_non_integer_niche_break.rs b/tests/ui/mir/enum/convert_non_integer_niche_break.rs index 9ff4849c5b1..d26a3aeb506 100644 --- a/tests/ui/mir/enum/convert_non_integer_niche_break.rs +++ b/tests/ui/mir/enum/convert_non_integer_niche_break.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -C debug-assertions //@ error-pattern: trying to construct an enum from an invalid value 0x5 diff --git a/tests/ui/mir/enum/negative_discr_break.rs b/tests/ui/mir/enum/negative_discr_break.rs index fa1284f72a0..35ee8aa3fc8 100644 --- a/tests/ui/mir/enum/negative_discr_break.rs +++ b/tests/ui/mir/enum/negative_discr_break.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -C debug-assertions //@ error-pattern: trying to construct an enum from an invalid value 0xfd diff --git a/tests/ui/mir/enum/niche_option_tuple_break.rs b/tests/ui/mir/enum/niche_option_tuple_break.rs index affdc4784a3..0a933afa153 100644 --- a/tests/ui/mir/enum/niche_option_tuple_break.rs +++ b/tests/ui/mir/enum/niche_option_tuple_break.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -C debug-assertions //@ error-pattern: trying to construct an enum from an invalid value diff --git a/tests/ui/mir/enum/numbered_variants_break.rs b/tests/ui/mir/enum/numbered_variants_break.rs index e3e71dc8aec..fbe7d6627a3 100644 --- a/tests/ui/mir/enum/numbered_variants_break.rs +++ b/tests/ui/mir/enum/numbered_variants_break.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -C debug-assertions //@ error-pattern: trying to construct an enum from an invalid value 0x3 diff --git a/tests/ui/mir/enum/option_with_bigger_niche_break.rs b/tests/ui/mir/enum/option_with_bigger_niche_break.rs index c66614b845b..675d27f0ec2 100644 --- a/tests/ui/mir/enum/option_with_bigger_niche_break.rs +++ b/tests/ui/mir/enum/option_with_bigger_niche_break.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -C debug-assertions //@ error-pattern: trying to construct an enum from an invalid value 0x0 diff --git a/tests/ui/mir/enum/plain_no_data_break.rs b/tests/ui/mir/enum/plain_no_data_break.rs index db68e752479..966dd641873 100644 --- a/tests/ui/mir/enum/plain_no_data_break.rs +++ b/tests/ui/mir/enum/plain_no_data_break.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -C debug-assertions //@ error-pattern: trying to construct an enum from an invalid value 0x1 diff --git a/tests/ui/mir/enum/single_with_repr_break.rs b/tests/ui/mir/enum/single_with_repr_break.rs index 5a4ec85a9b5..53e4932d5fd 100644 --- a/tests/ui/mir/enum/single_with_repr_break.rs +++ b/tests/ui/mir/enum/single_with_repr_break.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -C debug-assertions //@ error-pattern: trying to construct an enum from an invalid value 0x1 diff --git a/tests/ui/mir/enum/with_niche_int_break.rs b/tests/ui/mir/enum/with_niche_int_break.rs index 6a97eaa8f4f..d363dc7568a 100644 --- a/tests/ui/mir/enum/with_niche_int_break.rs +++ b/tests/ui/mir/enum/with_niche_int_break.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -C debug-assertions //@ error-pattern: trying to construct an enum from an invalid value diff --git a/tests/ui/mir/enum/wrap_break.rs b/tests/ui/mir/enum/wrap_break.rs index 4491394ca5a..5c410afa511 100644 --- a/tests/ui/mir/enum/wrap_break.rs +++ b/tests/ui/mir/enum/wrap_break.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -C debug-assertions //@ error-pattern: trying to construct an enum from an invalid value 0x0 #![feature(never_type)] diff --git a/tests/ui/mir/null/borrowed_mut_null.rs b/tests/ui/mir/null/borrowed_mut_null.rs index d26452b9dac..a4660f4bf57 100644 --- a/tests/ui/mir/null/borrowed_mut_null.rs +++ b/tests/ui/mir/null/borrowed_mut_null.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -C debug-assertions //@ error-pattern: null pointer dereference occurred diff --git a/tests/ui/mir/null/borrowed_null.rs b/tests/ui/mir/null/borrowed_null.rs index fefac3a7212..2a50058a482 100644 --- a/tests/ui/mir/null/borrowed_null.rs +++ b/tests/ui/mir/null/borrowed_null.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -C debug-assertions //@ error-pattern: null pointer dereference occurred diff --git a/tests/ui/mir/null/borrowed_null_zst.rs b/tests/ui/mir/null/borrowed_null_zst.rs index 835727c068b..106fa00b1db 100644 --- a/tests/ui/mir/null/borrowed_null_zst.rs +++ b/tests/ui/mir/null/borrowed_null_zst.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -C debug-assertions //@ error-pattern: null pointer dereference occurred diff --git a/tests/ui/mir/null/null_lhs.rs b/tests/ui/mir/null/null_lhs.rs index 238d350d1bd..b59338588a5 100644 --- a/tests/ui/mir/null/null_lhs.rs +++ b/tests/ui/mir/null/null_lhs.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -C debug-assertions //@ error-pattern: null pointer dereference occurred diff --git a/tests/ui/mir/null/null_rhs.rs b/tests/ui/mir/null/null_rhs.rs index 18eafb61869..18fdad759fd 100644 --- a/tests/ui/mir/null/null_rhs.rs +++ b/tests/ui/mir/null/null_rhs.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -C debug-assertions //@ error-pattern: null pointer dereference occurred diff --git a/tests/ui/mir/null/two_pointers.rs b/tests/ui/mir/null/two_pointers.rs index 52b9510be12..b2aa7cf0384 100644 --- a/tests/ui/mir/null/two_pointers.rs +++ b/tests/ui/mir/null/two_pointers.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -C debug-assertions //@ error-pattern: null pointer dereference occurred diff --git a/tests/ui/mir/validate/critical-edge.rs b/tests/ui/mir/validate/critical-edge.rs index 2a3bf6a6181..7fe3891d642 100644 --- a/tests/ui/mir/validate/critical-edge.rs +++ b/tests/ui/mir/validate/critical-edge.rs @@ -21,6 +21,8 @@ pub fn f(a: u32) -> u32 { } bb1 = { Call(RET = f(1), ReturnTo(bb2), UnwindTerminate(ReasonAbi)) +//~^ ERROR broken MIR in Item +//~| ERROR encountered critical edge in `Call` terminator } bb2 = { @@ -29,5 +31,3 @@ pub fn f(a: u32) -> u32 { } } } - -//~? RAW encountered critical edge in `Call` terminator diff --git a/tests/ui/mir/validate/project-into-simd.rs b/tests/ui/mir/validate/project-into-simd.rs new file mode 100644 index 00000000000..67766c8c4b0 --- /dev/null +++ b/tests/ui/mir/validate/project-into-simd.rs @@ -0,0 +1,18 @@ +// Optimized MIR shouldn't have critical call edges +// +//@ build-fail +//@ edition: 2021 +//@ compile-flags: --crate-type=lib +//@ failure-status: 101 +//@ dont-check-compiler-stderr + +#![feature(repr_simd)] + +#[repr(simd)] +pub struct U32x4([u32; 4]); + +pub fn f(a: U32x4) -> [u32; 4] { + a.0 + //~^ ERROR broken MIR in Item + //~| ERROR Projecting into SIMD type U32x4 is banned by MCP#838 +} diff --git a/tests/ui/missing/missing-stability.stderr b/tests/ui/missing/missing-stability.stderr index 659f8c78cae..bf8046c4e12 100644 --- a/tests/ui/missing/missing-stability.stderr +++ b/tests/ui/missing/missing-stability.stderr @@ -1,17 +1,14 @@ error: function has missing stability attribute --> $DIR/missing-stability.rs:8:1 | -LL | / pub fn unmarked() { -LL | | -LL | | () -LL | | } - | |_^ +LL | pub fn unmarked() { + | ^^^^^^^^^^^^^^^^^ error: function has missing stability attribute --> $DIR/missing-stability.rs:22:5 | LL | pub fn unmarked() {} - | ^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^ error: aborting due to 2 previous errors diff --git a/tests/ui/panics/panic-in-cleanup.rs b/tests/ui/panics/panic-in-cleanup.rs index 8cddeb37348..2e307de4393 100644 --- a/tests/ui/panics/panic-in-cleanup.rs +++ b/tests/ui/panics/panic-in-cleanup.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ exec-env:RUST_BACKTRACE=0 //@ check-run-results //@ error-pattern: panic in a destructor during cleanup diff --git a/tests/ui/panics/panic-in-ffi.rs b/tests/ui/panics/panic-in-ffi.rs index 6068e4fdc59..b926d0fa776 100644 --- a/tests/ui/panics/panic-in-ffi.rs +++ b/tests/ui/panics/panic-in-ffi.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ exec-env:RUST_BACKTRACE=0 //@ check-run-results //@ error-pattern: panic in a function that cannot unwind diff --git a/tests/ui/panics/panic-in-message-fmt.rs b/tests/ui/panics/panic-in-message-fmt.rs index 1e9bbaf45c5..4d539f17a0a 100644 --- a/tests/ui/panics/panic-in-message-fmt.rs +++ b/tests/ui/panics/panic-in-message-fmt.rs @@ -1,6 +1,6 @@ // Checks what happens when formatting the panic message panics. -//@ run-fail +//@ run-crash //@ exec-env:RUST_BACKTRACE=0 //@ check-run-results //@ error-pattern: panicked while processing panic diff --git a/tests/ui/panics/panic-main.rs b/tests/ui/panics/panic-main.rs index bf79de78a57..2009f69e19e 100644 --- a/tests/ui/panics/panic-main.rs +++ b/tests/ui/panics/panic-main.rs @@ -1,27 +1,37 @@ //@ revisions: default abort-zero abort-one abort-full unwind-zero unwind-one unwind-full +//@[default] run-fail + //@[abort-zero] compile-flags: -Cpanic=abort //@[abort-zero] no-prefer-dynamic //@[abort-zero] exec-env:RUST_BACKTRACE=0 +//@[abort-zero] run-crash //@[abort-one] compile-flags: -Cpanic=abort //@[abort-one] no-prefer-dynamic //@[abort-one] exec-env:RUST_BACKTRACE=1 +//@[abort-one] run-crash //@[abort-full] compile-flags: -Cpanic=abort //@[abort-full] no-prefer-dynamic //@[abort-full] exec-env:RUST_BACKTRACE=full +//@[abort-full] run-crash //@[unwind-zero] compile-flags: -Cpanic=unwind //@[unwind-zero] exec-env:RUST_BACKTRACE=0 +//@[unwind-zero] needs-unwind +//@[unwind-zero] run-fail //@[unwind-one] compile-flags: -Cpanic=unwind //@[unwind-one] exec-env:RUST_BACKTRACE=1 +//@[unwind-one] needs-unwind +//@[unwind-one] run-fail //@[unwind-full] compile-flags: -Cpanic=unwind //@[unwind-full] exec-env:RUST_BACKTRACE=full +//@[unwind-full] needs-unwind +//@[unwind-full] run-fail -//@ run-fail //@ error-pattern:moop //@ needs-subprocess diff --git a/tests/ui/parser/deli-ident-issue-2.rs b/tests/ui/parser/deli-ident-issue-2.rs index 5394760df70..419933c68ad 100644 --- a/tests/ui/parser/deli-ident-issue-2.rs +++ b/tests/ui/parser/deli-ident-issue-2.rs @@ -1,6 +1,6 @@ fn main() { if 1 < 2 { - let _a = vec!]; //~ ERROR mismatched closing delimiter + let _a = vec!]; } } //~ ERROR unexpected closing delimiter diff --git a/tests/ui/parser/deli-ident-issue-2.stderr b/tests/ui/parser/deli-ident-issue-2.stderr index e0188cdfb4a..703cbf19626 100644 --- a/tests/ui/parser/deli-ident-issue-2.stderr +++ b/tests/ui/parser/deli-ident-issue-2.stderr @@ -1,19 +1,13 @@ -error: mismatched closing delimiter: `]` - --> $DIR/deli-ident-issue-2.rs:2:14 - | -LL | if 1 < 2 { - | ^ unclosed delimiter -LL | let _a = vec!]; - | ^ mismatched closing delimiter - error: unexpected closing delimiter: `}` --> $DIR/deli-ident-issue-2.rs:5:1 | +LL | if 1 < 2 { + | - the nearest open delimiter LL | let _a = vec!]; | - missing open `[` for this delimiter LL | } LL | } | ^ unexpected closing delimiter -error: aborting due to 2 previous errors +error: aborting due to 1 previous error diff --git a/tests/ui/parser/issues/issue-104367.stderr b/tests/ui/parser/issues/issue-104367.stderr index c067d12e2d9..f01fa4a1265 100644 --- a/tests/ui/parser/issues/issue-104367.stderr +++ b/tests/ui/parser/issues/issue-104367.stderr @@ -18,7 +18,6 @@ LL | d: [u32; { LL | #![cfg] { | - unclosed delimiter LL | #![w,) - | - missing open `(` for this delimiter LL | | ^ diff --git a/tests/ui/parser/issues/issue-105209.rs b/tests/ui/parser/issues/issue-105209.rs index f4e331523bf..12c902e1d80 100644 --- a/tests/ui/parser/issues/issue-105209.rs +++ b/tests/ui/parser/issues/issue-105209.rs @@ -1,3 +1,3 @@ //@ compile-flags: -Zunpretty=ast-tree #![c={#![c[)x //~ ERROR mismatched closing delimiter - //~ ERROR this file contains an unclosed delimiter + //~ ERROR this file contains an unclosed delimiter diff --git a/tests/ui/parser/issues/issue-105209.stderr b/tests/ui/parser/issues/issue-105209.stderr index 72017e4327d..75643d18029 100644 --- a/tests/ui/parser/issues/issue-105209.stderr +++ b/tests/ui/parser/issues/issue-105209.stderr @@ -7,16 +7,15 @@ LL | #![c={#![c[)x | unclosed delimiter error: this file contains an unclosed delimiter - --> $DIR/issue-105209.rs:3:68 + --> $DIR/issue-105209.rs:3:56 | LL | #![c={#![c[)x - | - - - - missing open `(` for this delimiter - | | | | - | | | unclosed delimiter + | - - - unclosed delimiter + | | | | | unclosed delimiter | unclosed delimiter LL | - | ^ + | ^ error: aborting due to 2 previous errors diff --git a/tests/ui/parser/issues/issue-62973.stderr b/tests/ui/parser/issues/issue-62973.stderr index ea3e2bebee4..c7fc5bc29ed 100644 --- a/tests/ui/parser/issues/issue-62973.stderr +++ b/tests/ui/parser/issues/issue-62973.stderr @@ -18,10 +18,8 @@ error: this file contains an unclosed delimiter --> $DIR/issue-62973.rs:10:2 | LL | fn p() { match s { v, E { [) {) } - | - - - - missing open `(` for this delimiter - | | | | - | | | missing open `(` for this delimiter - | | unclosed delimiter + | - - unclosed delimiter + | | | unclosed delimiter LL | LL | diff --git a/tests/ui/parser/issues/issue-63116.stderr b/tests/ui/parser/issues/issue-63116.stderr index e5bad84d112..736a0ac2cf6 100644 --- a/tests/ui/parser/issues/issue-63116.stderr +++ b/tests/ui/parser/issues/issue-63116.stderr @@ -10,9 +10,8 @@ error: this file contains an unclosed delimiter --> $DIR/issue-63116.rs:4:18 | LL | impl W <s(f;Y(;] - | - -^ - | | | - | | missing open `[` for this delimiter + | - ^ + | | | unclosed delimiter error: aborting due to 2 previous errors diff --git a/tests/ui/parser/issues/issue-67377-invalid-syntax-in-enum-discriminant.stderr b/tests/ui/parser/issues/issue-67377-invalid-syntax-in-enum-discriminant.stderr index b82b0f3255b..5301d43e2ae 100644 --- a/tests/ui/parser/issues/issue-67377-invalid-syntax-in-enum-discriminant.stderr +++ b/tests/ui/parser/issues/issue-67377-invalid-syntax-in-enum-discriminant.stderr @@ -28,18 +28,14 @@ LL | V = [Vec::new; { [0].len() ].len() as isize, error: this file contains an unclosed delimiter --> $DIR/issue-67377-invalid-syntax-in-enum-discriminant.rs:23:65 | -LL | V = [PhantomData; { [ () ].len() ].len() as isize, - | - missing open `[` for this delimiter -... -LL | V = [Vec::new; { [].len() ].len() as isize, - | - missing open `[` for this delimiter -... LL | mod c { | - unclosed delimiter LL | enum Bug { -LL | V = [Vec::new; { [0].len() ].len() as isize, - | - missing open `[` for this delimiter + | - this delimiter might not be properly closed... ... +LL | } + | - ...as it matches this but it has different indentation +LL | LL | fn main() {} | ^ diff --git a/tests/ui/parser/issues/issue-68987-unmatch-issue-2.rs b/tests/ui/parser/issues/issue-68987-unmatch-issue-2.rs index 89aaa68ba40..9b4452ed2a1 100644 --- a/tests/ui/parser/issues/issue-68987-unmatch-issue-2.rs +++ b/tests/ui/parser/issues/issue-68987-unmatch-issue-2.rs @@ -1,7 +1,7 @@ // FIXME: this case need more work to fix // currently the TokenTree matching ')' with '{', which is not user friendly for diagnostics async fn obstest() -> Result<> { - let obs_connect = || -> Result<(), MyError) { //~ ERROR mismatched closing delimiter + let obs_connect = || -> Result<(), MyError) { async { } } diff --git a/tests/ui/parser/issues/issue-68987-unmatch-issue-2.stderr b/tests/ui/parser/issues/issue-68987-unmatch-issue-2.stderr index 0ecb748a0a4..c29a4ff8dbe 100644 --- a/tests/ui/parser/issues/issue-68987-unmatch-issue-2.stderr +++ b/tests/ui/parser/issues/issue-68987-unmatch-issue-2.stderr @@ -1,19 +1,13 @@ -error: mismatched closing delimiter: `)` - --> $DIR/issue-68987-unmatch-issue-2.rs:3:32 - | -LL | async fn obstest() -> Result<> { - | ^ unclosed delimiter -LL | let obs_connect = || -> Result<(), MyError) { - | ^ mismatched closing delimiter - error: unexpected closing delimiter: `}` --> $DIR/issue-68987-unmatch-issue-2.rs:14:1 | +LL | async fn obstest() -> Result<> { + | - the nearest open delimiter LL | let obs_connect = || -> Result<(), MyError) { | - missing open `(` for this delimiter ... LL | } | ^ unexpected closing delimiter -error: aborting due to 2 previous errors +error: aborting due to 1 previous error diff --git a/tests/ui/parser/issues/issue-68987-unmatch-issue-3.rs b/tests/ui/parser/issues/issue-68987-unmatch-issue-3.rs index e98df8d7c3c..e71e2730980 100644 --- a/tests/ui/parser/issues/issue-68987-unmatch-issue-3.rs +++ b/tests/ui/parser/issues/issue-68987-unmatch-issue-3.rs @@ -3,6 +3,6 @@ fn f(i: u32, j: u32) { let res = String::new(); let mut cnt = i; while cnt < j { - write!&mut res, " "); //~ ERROR mismatched closing delimiter + write!&mut res, " "); } } //~ ERROR unexpected closing delimiter diff --git a/tests/ui/parser/issues/issue-68987-unmatch-issue-3.stderr b/tests/ui/parser/issues/issue-68987-unmatch-issue-3.stderr index dfc4407ed65..6b012af1af3 100644 --- a/tests/ui/parser/issues/issue-68987-unmatch-issue-3.stderr +++ b/tests/ui/parser/issues/issue-68987-unmatch-issue-3.stderr @@ -1,19 +1,13 @@ -error: mismatched closing delimiter: `)` - --> $DIR/issue-68987-unmatch-issue-3.rs:5:19 - | -LL | while cnt < j { - | ^ unclosed delimiter -LL | write!&mut res, " "); - | ^ mismatched closing delimiter - error: unexpected closing delimiter: `}` --> $DIR/issue-68987-unmatch-issue-3.rs:8:1 | +LL | while cnt < j { + | - the nearest open delimiter LL | write!&mut res, " "); | - missing open `(` for this delimiter LL | } LL | } | ^ unexpected closing delimiter -error: aborting due to 2 previous errors +error: aborting due to 1 previous error diff --git a/tests/ui/parser/issues/issue-81827.stderr b/tests/ui/parser/issues/issue-81827.stderr index 986ed6b7e70..9737c8c90ae 100644 --- a/tests/ui/parser/issues/issue-81827.stderr +++ b/tests/ui/parser/issues/issue-81827.stderr @@ -11,9 +11,8 @@ error: this file contains an unclosed delimiter --> $DIR/issue-81827.rs:7:27 | LL | fn r()->i{0|{#[cfg(r(0{]0 - | - - - ^ - | | | | - | | | missing open `[` for this delimiter + | - - ^ + | | | | | unclosed delimiter | unclosed delimiter diff --git a/tests/ui/parser/issues/unnessary-error-issue-138401.rs b/tests/ui/parser/issues/unnessary-error-issue-138401.rs new file mode 100644 index 00000000000..208c516365a --- /dev/null +++ b/tests/ui/parser/issues/unnessary-error-issue-138401.rs @@ -0,0 +1,6 @@ +pub fn foo(x: i64) -> i64 { + x.abs) +} +//~^ ERROR unexpected closing delimiter: `}` + +fn main() {} diff --git a/tests/ui/parser/issues/unnessary-error-issue-138401.stderr b/tests/ui/parser/issues/unnessary-error-issue-138401.stderr new file mode 100644 index 00000000000..54c73b50a42 --- /dev/null +++ b/tests/ui/parser/issues/unnessary-error-issue-138401.stderr @@ -0,0 +1,12 @@ +error: unexpected closing delimiter: `}` + --> $DIR/unnessary-error-issue-138401.rs:3:1 + | +LL | pub fn foo(x: i64) -> i64 { + | - the nearest open delimiter +LL | x.abs) + | - missing open `(` for this delimiter +LL | } + | ^ unexpected closing delimiter + +error: aborting due to 1 previous error + diff --git a/tests/ui/parser/trait-object-trait-parens.rs b/tests/ui/parser/trait-object-trait-parens.rs index 438034bc38a..51f0e2de611 100644 --- a/tests/ui/parser/trait-object-trait-parens.rs +++ b/tests/ui/parser/trait-object-trait-parens.rs @@ -6,17 +6,17 @@ fn f<T: (Copy) + (?Sized) + (for<'a> Trait<'a>)>() {} fn main() { let _: Box<(Obj) + (?Sized) + (for<'a> Trait<'a>)>; - //~^ ERROR `?Trait` is not permitted in trait object types + //~^ ERROR relaxed bounds are not permitted in trait object types //~| ERROR only auto traits can be used as additional traits //~| WARN trait objects without an explicit `dyn` are deprecated //~| WARN this is accepted in the current edition let _: Box<?Sized + (for<'a> Trait<'a>) + (Obj)>; - //~^ ERROR `?Trait` is not permitted in trait object types + //~^ ERROR relaxed bounds are not permitted in trait object types //~| ERROR only auto traits can be used as additional traits //~| WARN trait objects without an explicit `dyn` are deprecated //~| WARN this is accepted in the current edition let _: Box<for<'a> Trait<'a> + (Obj) + (?Sized)>; - //~^ ERROR `?Trait` is not permitted in trait object types + //~^ ERROR relaxed bounds are not permitted in trait object types //~| ERROR only auto traits can be used as additional traits //~| WARN trait objects without an explicit `dyn` are deprecated //~| WARN this is accepted in the current edition diff --git a/tests/ui/parser/trait-object-trait-parens.stderr b/tests/ui/parser/trait-object-trait-parens.stderr index d75352b6811..26d388f8779 100644 --- a/tests/ui/parser/trait-object-trait-parens.stderr +++ b/tests/ui/parser/trait-object-trait-parens.stderr @@ -1,29 +1,20 @@ -error[E0658]: `?Trait` is not permitted in trait object types +error: relaxed bounds are not permitted in trait object types --> $DIR/trait-object-trait-parens.rs:8:24 | LL | let _: Box<(Obj) + (?Sized) + (for<'a> Trait<'a>)>; | ^^^^^^^^ - | - = help: add `#![feature(more_maybe_bounds)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date -error[E0658]: `?Trait` is not permitted in trait object types +error: relaxed bounds are not permitted in trait object types --> $DIR/trait-object-trait-parens.rs:13:16 | LL | let _: Box<?Sized + (for<'a> Trait<'a>) + (Obj)>; | ^^^^^^ - | - = help: add `#![feature(more_maybe_bounds)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date -error[E0658]: `?Trait` is not permitted in trait object types +error: relaxed bounds are not permitted in trait object types --> $DIR/trait-object-trait-parens.rs:18:44 | LL | let _: Box<for<'a> Trait<'a> + (Obj) + (?Sized)>; | ^^^^^^^^ - | - = help: add `#![feature(more_maybe_bounds)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date warning: trait objects without an explicit `dyn` are deprecated --> $DIR/trait-object-trait-parens.rs:8:16 @@ -100,5 +91,4 @@ LL | let _: Box<for<'a> Trait<'a> + (Obj) + (?Sized)>; error: aborting due to 6 previous errors; 3 warnings emitted -Some errors have detailed explanations: E0225, E0658. -For more information about an error, try `rustc --explain E0225`. +For more information about this error, try `rustc --explain E0225`. diff --git a/tests/ui/precondition-checks/alignment.rs b/tests/ui/precondition-checks/alignment.rs index 92400528fa0..038a625bed7 100644 --- a/tests/ui/precondition-checks/alignment.rs +++ b/tests/ui/precondition-checks/alignment.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -Copt-level=3 -Cdebug-assertions=no -Zub-checks=yes //@ error-pattern: unsafe precondition(s) violated: Alignment::new_unchecked requires diff --git a/tests/ui/precondition-checks/ascii-char-digit_unchecked.rs b/tests/ui/precondition-checks/ascii-char-digit_unchecked.rs index 30c6f79fb08..41ba2c5254a 100644 --- a/tests/ui/precondition-checks/ascii-char-digit_unchecked.rs +++ b/tests/ui/precondition-checks/ascii-char-digit_unchecked.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -Copt-level=3 -Cdebug-assertions=no -Zub-checks=yes //@ error-pattern: unsafe precondition(s) violated: `ascii::Char::digit_unchecked` input cannot exceed 9 diff --git a/tests/ui/precondition-checks/assert_unchecked.rs b/tests/ui/precondition-checks/assert_unchecked.rs index 22b2b414550..da5383cdea0 100644 --- a/tests/ui/precondition-checks/assert_unchecked.rs +++ b/tests/ui/precondition-checks/assert_unchecked.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -Copt-level=3 -Cdebug-assertions=no -Zub-checks=yes //@ error-pattern: unsafe precondition(s) violated: hint::assert_unchecked must never be called when the condition is false diff --git a/tests/ui/precondition-checks/char-from_u32_unchecked.rs b/tests/ui/precondition-checks/char-from_u32_unchecked.rs index d950f20c772..7c34d926d3e 100644 --- a/tests/ui/precondition-checks/char-from_u32_unchecked.rs +++ b/tests/ui/precondition-checks/char-from_u32_unchecked.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -Copt-level=3 -Cdebug-assertions=no -Zub-checks=yes //@ error-pattern: unsafe precondition(s) violated: invalid value for `char` diff --git a/tests/ui/precondition-checks/copy-nonoverlapping.rs b/tests/ui/precondition-checks/copy-nonoverlapping.rs index eacaa63e543..1d584ddef4c 100644 --- a/tests/ui/precondition-checks/copy-nonoverlapping.rs +++ b/tests/ui/precondition-checks/copy-nonoverlapping.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -Copt-level=3 -Cdebug-assertions=no -Zub-checks=yes //@ error-pattern: unsafe precondition(s) violated: ptr::copy_nonoverlapping requires //@ revisions: null_src null_dst misaligned_src misaligned_dst overlapping diff --git a/tests/ui/precondition-checks/copy.rs b/tests/ui/precondition-checks/copy.rs index 1fadd90bf70..8faa56a880e 100644 --- a/tests/ui/precondition-checks/copy.rs +++ b/tests/ui/precondition-checks/copy.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -Copt-level=3 -Cdebug-assertions=no -Zub-checks=yes //@ error-pattern: unsafe precondition(s) violated: ptr::copy requires //@ revisions: null_src null_dst misaligned_src misaligned_dst diff --git a/tests/ui/precondition-checks/layout.rs b/tests/ui/precondition-checks/layout.rs index 4ee66cc9328..6755ebce854 100644 --- a/tests/ui/precondition-checks/layout.rs +++ b/tests/ui/precondition-checks/layout.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -Copt-level=3 -Cdebug-assertions=no -Zub-checks=yes //@ error-pattern: unsafe precondition(s) violated: Layout::from_size_align_unchecked requires //@ revisions: toolarge badalign diff --git a/tests/ui/precondition-checks/nonnull.rs b/tests/ui/precondition-checks/nonnull.rs index 6b8edd4e582..75bbd65b486 100644 --- a/tests/ui/precondition-checks/nonnull.rs +++ b/tests/ui/precondition-checks/nonnull.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -Copt-level=3 -Cdebug-assertions=no -Zub-checks=yes //@ error-pattern: unsafe precondition(s) violated: NonNull::new_unchecked requires diff --git a/tests/ui/precondition-checks/nonzero-from_mut_unchecked.rs b/tests/ui/precondition-checks/nonzero-from_mut_unchecked.rs index 46ce7dc356f..d55707fdd0b 100644 --- a/tests/ui/precondition-checks/nonzero-from_mut_unchecked.rs +++ b/tests/ui/precondition-checks/nonzero-from_mut_unchecked.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -Copt-level=3 -Cdebug-assertions=no -Zub-checks=yes //@ error-pattern: unsafe precondition(s) violated: NonZero::from_mut_unchecked requires diff --git a/tests/ui/precondition-checks/nonzero-new_unchecked.rs b/tests/ui/precondition-checks/nonzero-new_unchecked.rs index 7827a42844f..978f01f150f 100644 --- a/tests/ui/precondition-checks/nonzero-new_unchecked.rs +++ b/tests/ui/precondition-checks/nonzero-new_unchecked.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -Copt-level=3 -Cdebug-assertions=no -Zub-checks=yes //@ error-pattern: unsafe precondition(s) violated: NonZero::new_unchecked requires diff --git a/tests/ui/precondition-checks/read_volatile.rs b/tests/ui/precondition-checks/read_volatile.rs index ada8932c398..33350dfbc4f 100644 --- a/tests/ui/precondition-checks/read_volatile.rs +++ b/tests/ui/precondition-checks/read_volatile.rs @@ -1,9 +1,7 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -Copt-level=3 -Cdebug-assertions=no -Zub-checks=yes //@ error-pattern: unsafe precondition(s) violated: ptr::read_volatile requires -//@ revisions: null misaligned - -#![allow(invalid_null_arguments)] +//@ revisions: misaligned use std::ptr; @@ -11,8 +9,6 @@ fn main() { let src = [0u16; 2]; let src = src.as_ptr(); unsafe { - #[cfg(null)] - ptr::read_volatile(ptr::null::<u8>()); #[cfg(misaligned)] ptr::read_volatile(src.byte_add(1)); } diff --git a/tests/ui/precondition-checks/replace.rs b/tests/ui/precondition-checks/replace.rs index 44afbd8174c..447a00c6572 100644 --- a/tests/ui/precondition-checks/replace.rs +++ b/tests/ui/precondition-checks/replace.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -Copt-level=3 -Cdebug-assertions=no -Zub-checks=yes //@ error-pattern: unsafe precondition(s) violated: ptr::replace requires //@ revisions: null misaligned diff --git a/tests/ui/precondition-checks/slice-from-raw-parts-mut.rs b/tests/ui/precondition-checks/slice-from-raw-parts-mut.rs index 9b9ded69a83..b6397ab2a12 100644 --- a/tests/ui/precondition-checks/slice-from-raw-parts-mut.rs +++ b/tests/ui/precondition-checks/slice-from-raw-parts-mut.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -Copt-level=3 -Cdebug-assertions=no -Zub-checks=yes //@ error-pattern: unsafe precondition(s) violated: slice::from_raw_parts_mut requires //@ revisions: null misaligned toolarge diff --git a/tests/ui/precondition-checks/slice-from-raw-parts.rs b/tests/ui/precondition-checks/slice-from-raw-parts.rs index 96578c1eae5..a317e3d41a0 100644 --- a/tests/ui/precondition-checks/slice-from-raw-parts.rs +++ b/tests/ui/precondition-checks/slice-from-raw-parts.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -Copt-level=3 -Cdebug-assertions=no -Zub-checks=yes //@ error-pattern: unsafe precondition(s) violated: slice::from_raw_parts requires //@ revisions: null misaligned toolarge diff --git a/tests/ui/precondition-checks/slice-get_unchecked.rs b/tests/ui/precondition-checks/slice-get_unchecked.rs index 1d8188fb953..7bcb8442540 100644 --- a/tests/ui/precondition-checks/slice-get_unchecked.rs +++ b/tests/ui/precondition-checks/slice-get_unchecked.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -Copt-level=3 -Cdebug-assertions=no -Zub-checks=yes //@ error-pattern: unsafe precondition(s) violated: slice::get_unchecked requires //@ revisions: usize range range_to range_from backwards_range diff --git a/tests/ui/precondition-checks/slice-get_unchecked_mut.rs b/tests/ui/precondition-checks/slice-get_unchecked_mut.rs index 34c1454af43..2ba3227f39e 100644 --- a/tests/ui/precondition-checks/slice-get_unchecked_mut.rs +++ b/tests/ui/precondition-checks/slice-get_unchecked_mut.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -Copt-level=3 -Cdebug-assertions=no -Zub-checks=yes //@ error-pattern: unsafe precondition(s) violated: slice::get_unchecked_mut requires //@ revisions: usize range range_to range_from backwards_range diff --git a/tests/ui/precondition-checks/str-get_unchecked.rs b/tests/ui/precondition-checks/str-get_unchecked.rs index 14d17f997ec..2273190e9f4 100644 --- a/tests/ui/precondition-checks/str-get_unchecked.rs +++ b/tests/ui/precondition-checks/str-get_unchecked.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -Copt-level=3 -Cdebug-assertions=no -Zub-checks=yes //@ error-pattern: unsafe precondition(s) violated: str::get_unchecked requires //@ revisions: range range_to range_from backwards_range diff --git a/tests/ui/precondition-checks/str-get_unchecked_mut.rs b/tests/ui/precondition-checks/str-get_unchecked_mut.rs index ca1b1690055..53e6ee64d47 100644 --- a/tests/ui/precondition-checks/str-get_unchecked_mut.rs +++ b/tests/ui/precondition-checks/str-get_unchecked_mut.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -Copt-level=3 -Cdebug-assertions=no -Zub-checks=yes //@ error-pattern: unsafe precondition(s) violated: str::get_unchecked_mut requires //@ revisions: range range_to range_from backwards_range diff --git a/tests/ui/precondition-checks/swap-nonoverlapping.rs b/tests/ui/precondition-checks/swap-nonoverlapping.rs index ea1f6f36ad7..81ba72382c0 100644 --- a/tests/ui/precondition-checks/swap-nonoverlapping.rs +++ b/tests/ui/precondition-checks/swap-nonoverlapping.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -Copt-level=3 -Cdebug-assertions=no -Zub-checks=yes //@ error-pattern: unsafe precondition(s) violated: ptr::swap_nonoverlapping requires //@ revisions: null_src null_dst misaligned_src misaligned_dst overlapping diff --git a/tests/ui/precondition-checks/unchecked_add.rs b/tests/ui/precondition-checks/unchecked_add.rs index f44a6ea32ad..b7727aeb968 100644 --- a/tests/ui/precondition-checks/unchecked_add.rs +++ b/tests/ui/precondition-checks/unchecked_add.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -Copt-level=3 -Cdebug-assertions=no -Zub-checks=yes //@ error-pattern: unsafe precondition(s) violated: u8::unchecked_add cannot overflow diff --git a/tests/ui/precondition-checks/unchecked_mul.rs b/tests/ui/precondition-checks/unchecked_mul.rs index 66655dda136..3eea8b66abb 100644 --- a/tests/ui/precondition-checks/unchecked_mul.rs +++ b/tests/ui/precondition-checks/unchecked_mul.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -Copt-level=3 -Cdebug-assertions=no -Zub-checks=yes //@ error-pattern: unsafe precondition(s) violated: u8::unchecked_add cannot overflow diff --git a/tests/ui/precondition-checks/unchecked_shl.rs b/tests/ui/precondition-checks/unchecked_shl.rs index 1c96db0b1ec..57c617e0845 100644 --- a/tests/ui/precondition-checks/unchecked_shl.rs +++ b/tests/ui/precondition-checks/unchecked_shl.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -Copt-level=3 -Cdebug-assertions=no -Zub-checks=yes //@ error-pattern: unsafe precondition(s) violated: u8::unchecked_shl cannot overflow diff --git a/tests/ui/precondition-checks/unchecked_shr.rs b/tests/ui/precondition-checks/unchecked_shr.rs index 4a6d9ffb1d3..18502d2b645 100644 --- a/tests/ui/precondition-checks/unchecked_shr.rs +++ b/tests/ui/precondition-checks/unchecked_shr.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -Copt-level=3 -Cdebug-assertions=no -Zub-checks=yes //@ error-pattern: unsafe precondition(s) violated: u8::unchecked_shr cannot overflow diff --git a/tests/ui/precondition-checks/unchecked_sub.rs b/tests/ui/precondition-checks/unchecked_sub.rs index 545dde0e278..bfe8f5849f5 100644 --- a/tests/ui/precondition-checks/unchecked_sub.rs +++ b/tests/ui/precondition-checks/unchecked_sub.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -Copt-level=3 -Cdebug-assertions=no -Zub-checks=yes //@ error-pattern: unsafe precondition(s) violated: u8::unchecked_sub cannot overflow diff --git a/tests/ui/precondition-checks/unreachable_unchecked.rs b/tests/ui/precondition-checks/unreachable_unchecked.rs index 2435450c4b5..f2855d03a3e 100644 --- a/tests/ui/precondition-checks/unreachable_unchecked.rs +++ b/tests/ui/precondition-checks/unreachable_unchecked.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -Copt-level=3 -Cdebug-assertions=no -Zub-checks=yes //@ error-pattern: unsafe precondition(s) violated: hint::unreachable_unchecked must never be reached diff --git a/tests/ui/precondition-checks/vec-from-parts.rs b/tests/ui/precondition-checks/vec-from-parts.rs index 0bafb5aa715..ace90770360 100644 --- a/tests/ui/precondition-checks/vec-from-parts.rs +++ b/tests/ui/precondition-checks/vec-from-parts.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -Cdebug-assertions=yes //@ error-pattern: unsafe precondition(s) violated: Vec::from_parts_in requires that length <= capacity #![feature(allocator_api)] diff --git a/tests/ui/precondition-checks/vec-from-raw-parts.rs b/tests/ui/precondition-checks/vec-from-raw-parts.rs index 884d34c0a56..1bc8e6ada10 100644 --- a/tests/ui/precondition-checks/vec-from-raw-parts.rs +++ b/tests/ui/precondition-checks/vec-from-raw-parts.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -Cdebug-assertions=yes //@ error-pattern: unsafe precondition(s) violated: Vec::from_raw_parts_in requires that length <= capacity //@ revisions: vec_from_raw_parts vec_from_raw_parts_in string_from_raw_parts diff --git a/tests/ui/precondition-checks/vec-set-len.rs b/tests/ui/precondition-checks/vec-set-len.rs index 0987e7fe028..c6bdee7dc67 100644 --- a/tests/ui/precondition-checks/vec-set-len.rs +++ b/tests/ui/precondition-checks/vec-set-len.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -Cdebug-assertions=yes //@ error-pattern: unsafe precondition(s) violated: Vec::set_len requires that new_len <= capacity() diff --git a/tests/ui/precondition-checks/write_volatile.rs b/tests/ui/precondition-checks/write_volatile.rs index 0d5ecb014b3..d6ad6320e41 100644 --- a/tests/ui/precondition-checks/write_volatile.rs +++ b/tests/ui/precondition-checks/write_volatile.rs @@ -1,9 +1,7 @@ -//@ run-fail +//@ run-crash //@ compile-flags: -Copt-level=3 -Cdebug-assertions=no -Zub-checks=yes //@ error-pattern: unsafe precondition(s) violated: ptr::write_volatile requires -//@ revisions: null misaligned - -#![allow(invalid_null_arguments)] +//@ revisions: misaligned use std::ptr; @@ -11,8 +9,6 @@ fn main() { let mut dst = [0u16; 2]; let mut dst = dst.as_mut_ptr(); unsafe { - #[cfg(null)] - ptr::write_volatile(ptr::null_mut::<u8>(), 1u8); #[cfg(misaligned)] ptr::write_volatile(dst.byte_add(1), 1u16); } diff --git a/tests/ui/print-request/supported-crate-types.rs b/tests/ui/print-request/supported-crate-types.rs index c8b4c0c1a41..50185a231ee 100644 --- a/tests/ui/print-request/supported-crate-types.rs +++ b/tests/ui/print-request/supported-crate-types.rs @@ -8,6 +8,11 @@ //@ check-pass +// FIXME: musl targets are currently statically linked, but running on a musl host +// requires dynamic linkage, which in turn changes the supported crate types for +// x86_64-unknown-linux-musl. +//@ ignore-musl + //@ revisions: wasm musl linux //@[wasm] compile-flags: --target=wasm32-unknown-unknown --print=supported-crate-types -Zunstable-options diff --git a/tests/ui/privacy/effective_visibilities_invariants.stderr b/tests/ui/privacy/effective_visibilities_invariants.stderr index 64d0402f84e..97bee1e2d8d 100644 --- a/tests/ui/privacy/effective_visibilities_invariants.stderr +++ b/tests/ui/privacy/effective_visibilities_invariants.stderr @@ -23,7 +23,7 @@ error: module has missing stability attribute --> $DIR/effective_visibilities_invariants.rs:5:1 | LL | pub mod m {} - | ^^^^^^^^^^^^ + | ^^^^^^^^^ error: aborting due to 3 previous errors diff --git a/tests/ui/privacy/issue-113860-1.stderr b/tests/ui/privacy/issue-113860-1.stderr index dad9ebadf04..764c9f4925b 100644 --- a/tests/ui/privacy/issue-113860-1.stderr +++ b/tests/ui/privacy/issue-113860-1.stderr @@ -20,28 +20,20 @@ LL | | fn main() {} error: trait has missing stability attribute --> $DIR/issue-113860-1.rs:4:1 | -LL | / pub trait Trait { -LL | | -LL | | fn fun() {} -LL | | -LL | | } - | |_^ +LL | pub trait Trait { + | ^^^^^^^^^^^^^^^ error: implementation has missing stability attribute --> $DIR/issue-113860-1.rs:10:1 | -LL | / impl Trait for u8 { -LL | | -LL | | pub(self) fn fun() {} -LL | | -LL | | } - | |_^ +LL | impl Trait for u8 { + | ^^^^^^^^^^^^^^^^^ error: associated function has missing stability attribute --> $DIR/issue-113860-1.rs:6:5 | LL | fn fun() {} - | ^^^^^^^^^^^ + | ^^^^^^^^ error: aborting due to 5 previous errors diff --git a/tests/ui/privacy/issue-113860-2.stderr b/tests/ui/privacy/issue-113860-2.stderr index 9805c22dbdf..d0847aa2b49 100644 --- a/tests/ui/privacy/issue-113860-2.stderr +++ b/tests/ui/privacy/issue-113860-2.stderr @@ -20,28 +20,20 @@ LL | | fn main() {} error: trait has missing stability attribute --> $DIR/issue-113860-2.rs:4:1 | -LL | / pub trait Trait { -LL | | -LL | | type X; -LL | | -LL | | } - | |_^ +LL | pub trait Trait { + | ^^^^^^^^^^^^^^^ error: implementation has missing stability attribute --> $DIR/issue-113860-2.rs:10:1 | -LL | / impl Trait for u8 { -LL | | -LL | | pub(self) type X = Self; -LL | | -LL | | } - | |_^ +LL | impl Trait for u8 { + | ^^^^^^^^^^^^^^^^^ error: associated type has missing stability attribute --> $DIR/issue-113860-2.rs:6:5 | LL | type X; - | ^^^^^^^ + | ^^^^^^ error: aborting due to 5 previous errors diff --git a/tests/ui/privacy/issue-113860.stderr b/tests/ui/privacy/issue-113860.stderr index 88efcae4a85..d7a15255b15 100644 --- a/tests/ui/privacy/issue-113860.stderr +++ b/tests/ui/privacy/issue-113860.stderr @@ -20,28 +20,20 @@ LL | | fn main() {} error: trait has missing stability attribute --> $DIR/issue-113860.rs:4:1 | -LL | / pub trait Trait { -LL | | -LL | | const X: u32; -LL | | -LL | | } - | |_^ +LL | pub trait Trait { + | ^^^^^^^^^^^^^^^ error: implementation has missing stability attribute --> $DIR/issue-113860.rs:10:1 | -LL | / impl Trait for u8 { -LL | | -LL | | pub(self) const X: u32 = 3; -LL | | -LL | | } - | |_^ +LL | impl Trait for u8 { + | ^^^^^^^^^^^^^^^^^ error: associated constant has missing stability attribute --> $DIR/issue-113860.rs:6:5 | LL | const X: u32; - | ^^^^^^^^^^^^^ + | ^^^^^^^^^^^^ error: aborting due to 5 previous errors diff --git a/tests/ui/privacy/private-in-public-warn.rs b/tests/ui/privacy/private-in-public-warn.rs index 746b98fbd07..f79e4641312 100644 --- a/tests/ui/privacy/private-in-public-warn.rs +++ b/tests/ui/privacy/private-in-public-warn.rs @@ -35,6 +35,7 @@ mod types { mod traits { trait PrivTr {} + impl PrivTr for () {} pub struct Pub<T>(T); pub trait PubTr {} @@ -45,7 +46,10 @@ mod traits { pub trait Tr3 { type Alias: PrivTr; //~^ ERROR trait `traits::PrivTr` is more private than the item `traits::Tr3::Alias` - fn f<T: PrivTr>(arg: T) {} //~ ERROR trait `traits::PrivTr` is more private than the item `traits::Tr3::f` + fn f<T: PrivTr>(arg: T) {} + //~^ ERROR trait `traits::PrivTr` is more private than the item `traits::Tr3::f` + fn g() -> impl PrivTr; + fn h() -> impl PrivTr {} } impl<T: PrivTr> Pub<T> {} //~ ERROR trait `traits::PrivTr` is more private than the item `traits::Pub<T>` impl<T: PrivTr> PubTr for Pub<T> {} // OK, trait impl predicates @@ -75,12 +79,18 @@ mod generics { pub struct Pub<T = u8>(T); trait PrivTr<T> {} pub trait PubTr<T> {} + impl PrivTr<Priv<()>> for () {} pub trait Tr1: PrivTr<Pub> {} //~^ ERROR trait `generics::PrivTr<generics::Pub>` is more private than the item `generics::Tr1` pub trait Tr2: PubTr<Priv> {} //~ ERROR type `generics::Priv` is more private than the item `generics::Tr2` pub trait Tr3: PubTr<[Priv; 1]> {} //~ ERROR type `generics::Priv` is more private than the item `generics::Tr3` pub trait Tr4: PubTr<Pub<Priv>> {} //~ ERROR type `generics::Priv` is more private than the item `Tr4` + + pub trait Tr5 { + fn required() -> impl PrivTr<Priv<()>>; + fn provided() -> impl PrivTr<Priv<()>> {} + } } mod impls { diff --git a/tests/ui/privacy/private-in-public-warn.stderr b/tests/ui/privacy/private-in-public-warn.stderr index 3743879ffa6..c2a57e3b82c 100644 --- a/tests/ui/privacy/private-in-public-warn.stderr +++ b/tests/ui/privacy/private-in-public-warn.stderr @@ -130,7 +130,7 @@ LL | type Alias = Priv; | ^^^^^^^^^^ can't leak private type error: trait `traits::PrivTr` is more private than the item `traits::Alias` - --> $DIR/private-in-public-warn.rs:41:5 + --> $DIR/private-in-public-warn.rs:42:5 | LL | pub type Alias<T: PrivTr> = T; | ^^^^^^^^^^^^^^^^^^^^^^^^^ type alias `traits::Alias` is reachable at visibility `pub(crate)` @@ -147,7 +147,7 @@ LL | #![deny(private_interfaces, private_bounds)] | ^^^^^^^^^^^^^^ error: trait `traits::PrivTr` is more private than the item `traits::Tr1` - --> $DIR/private-in-public-warn.rs:43:5 + --> $DIR/private-in-public-warn.rs:44:5 | LL | pub trait Tr1: PrivTr {} | ^^^^^^^^^^^^^^^^^^^^^ trait `traits::Tr1` is reachable at visibility `pub(crate)` @@ -159,7 +159,7 @@ LL | trait PrivTr {} | ^^^^^^^^^^^^ error: trait `traits::PrivTr` is more private than the item `traits::Tr2` - --> $DIR/private-in-public-warn.rs:44:5 + --> $DIR/private-in-public-warn.rs:45:5 | LL | pub trait Tr2<T: PrivTr> {} | ^^^^^^^^^^^^^^^^^^^^^^^^ trait `traits::Tr2` is reachable at visibility `pub(crate)` @@ -171,7 +171,7 @@ LL | trait PrivTr {} | ^^^^^^^^^^^^ error: trait `traits::PrivTr` is more private than the item `traits::Tr3::Alias` - --> $DIR/private-in-public-warn.rs:46:9 + --> $DIR/private-in-public-warn.rs:47:9 | LL | type Alias: PrivTr; | ^^^^^^^^^^^^^^^^^^ associated type `traits::Tr3::Alias` is reachable at visibility `pub(crate)` @@ -183,7 +183,7 @@ LL | trait PrivTr {} | ^^^^^^^^^^^^ error: trait `traits::PrivTr` is more private than the item `traits::Tr3::f` - --> $DIR/private-in-public-warn.rs:48:9 + --> $DIR/private-in-public-warn.rs:49:9 | LL | fn f<T: PrivTr>(arg: T) {} | ^^^^^^^^^^^^^^^^^^^^^^^ associated function `traits::Tr3::f` is reachable at visibility `pub(crate)` @@ -195,7 +195,7 @@ LL | trait PrivTr {} | ^^^^^^^^^^^^ error: trait `traits::PrivTr` is more private than the item `traits::Pub<T>` - --> $DIR/private-in-public-warn.rs:50:5 + --> $DIR/private-in-public-warn.rs:54:5 | LL | impl<T: PrivTr> Pub<T> {} | ^^^^^^^^^^^^^^^^^^^^^^ implementation `traits::Pub<T>` is reachable at visibility `pub(crate)` @@ -207,103 +207,103 @@ LL | trait PrivTr {} | ^^^^^^^^^^^^ error: trait `traits_where::PrivTr` is more private than the item `traits_where::Alias` - --> $DIR/private-in-public-warn.rs:59:5 + --> $DIR/private-in-public-warn.rs:63:5 | LL | pub type Alias<T> where T: PrivTr = T; | ^^^^^^^^^^^^^^^^^ type alias `traits_where::Alias` is reachable at visibility `pub(crate)` | note: but trait `traits_where::PrivTr` is only usable at visibility `pub(self)` - --> $DIR/private-in-public-warn.rs:55:5 + --> $DIR/private-in-public-warn.rs:59:5 | LL | trait PrivTr {} | ^^^^^^^^^^^^ error: trait `traits_where::PrivTr` is more private than the item `traits_where::Tr2` - --> $DIR/private-in-public-warn.rs:62:5 + --> $DIR/private-in-public-warn.rs:66:5 | LL | pub trait Tr2<T> where T: PrivTr {} | ^^^^^^^^^^^^^^^^ trait `traits_where::Tr2` is reachable at visibility `pub(crate)` | note: but trait `traits_where::PrivTr` is only usable at visibility `pub(self)` - --> $DIR/private-in-public-warn.rs:55:5 + --> $DIR/private-in-public-warn.rs:59:5 | LL | trait PrivTr {} | ^^^^^^^^^^^^ error: trait `traits_where::PrivTr` is more private than the item `traits_where::Tr3::f` - --> $DIR/private-in-public-warn.rs:65:9 + --> $DIR/private-in-public-warn.rs:69:9 | LL | fn f<T>(arg: T) where T: PrivTr {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ associated function `traits_where::Tr3::f` is reachable at visibility `pub(crate)` | note: but trait `traits_where::PrivTr` is only usable at visibility `pub(self)` - --> $DIR/private-in-public-warn.rs:55:5 + --> $DIR/private-in-public-warn.rs:59:5 | LL | trait PrivTr {} | ^^^^^^^^^^^^ error: trait `traits_where::PrivTr` is more private than the item `traits_where::Pub<T>` - --> $DIR/private-in-public-warn.rs:68:5 + --> $DIR/private-in-public-warn.rs:72:5 | LL | impl<T> Pub<T> where T: PrivTr {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ implementation `traits_where::Pub<T>` is reachable at visibility `pub(crate)` | note: but trait `traits_where::PrivTr` is only usable at visibility `pub(self)` - --> $DIR/private-in-public-warn.rs:55:5 + --> $DIR/private-in-public-warn.rs:59:5 | LL | trait PrivTr {} | ^^^^^^^^^^^^ error: trait `generics::PrivTr<generics::Pub>` is more private than the item `generics::Tr1` - --> $DIR/private-in-public-warn.rs:79:5 + --> $DIR/private-in-public-warn.rs:84:5 | LL | pub trait Tr1: PrivTr<Pub> {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^ trait `generics::Tr1` is reachable at visibility `pub(crate)` | note: but trait `generics::PrivTr<generics::Pub>` is only usable at visibility `pub(self)` - --> $DIR/private-in-public-warn.rs:76:5 + --> $DIR/private-in-public-warn.rs:80:5 | LL | trait PrivTr<T> {} | ^^^^^^^^^^^^^^^ error: type `generics::Priv` is more private than the item `generics::Tr2` - --> $DIR/private-in-public-warn.rs:81:5 + --> $DIR/private-in-public-warn.rs:86:5 | LL | pub trait Tr2: PubTr<Priv> {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^ trait `generics::Tr2` is reachable at visibility `pub(crate)` | note: but type `generics::Priv` is only usable at visibility `pub(self)` - --> $DIR/private-in-public-warn.rs:74:5 + --> $DIR/private-in-public-warn.rs:78:5 | LL | struct Priv<T = u8>(T); | ^^^^^^^^^^^^^^^^^^^ error: type `generics::Priv` is more private than the item `generics::Tr3` - --> $DIR/private-in-public-warn.rs:82:5 + --> $DIR/private-in-public-warn.rs:87:5 | LL | pub trait Tr3: PubTr<[Priv; 1]> {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ trait `generics::Tr3` is reachable at visibility `pub(crate)` | note: but type `generics::Priv` is only usable at visibility `pub(self)` - --> $DIR/private-in-public-warn.rs:74:5 + --> $DIR/private-in-public-warn.rs:78:5 | LL | struct Priv<T = u8>(T); | ^^^^^^^^^^^^^^^^^^^ error: type `generics::Priv` is more private than the item `Tr4` - --> $DIR/private-in-public-warn.rs:83:5 + --> $DIR/private-in-public-warn.rs:88:5 | LL | pub trait Tr4: PubTr<Pub<Priv>> {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ trait `Tr4` is reachable at visibility `pub(crate)` | note: but type `generics::Priv` is only usable at visibility `pub(self)` - --> $DIR/private-in-public-warn.rs:74:5 + --> $DIR/private-in-public-warn.rs:78:5 | LL | struct Priv<T = u8>(T); | ^^^^^^^^^^^^^^^^^^^ error[E0446]: private type `impls::Priv` in public interface - --> $DIR/private-in-public-warn.rs:109:9 + --> $DIR/private-in-public-warn.rs:119:9 | LL | struct Priv; | ----------- `impls::Priv` declared as private @@ -312,19 +312,19 @@ LL | type Alias = Priv; | ^^^^^^^^^^ can't leak private type error: type `aliases_pub::Priv` is more private than the item `aliases_pub::<impl Pub2>::f` - --> $DIR/private-in-public-warn.rs:180:9 + --> $DIR/private-in-public-warn.rs:190:9 | LL | pub fn f(arg: Priv) {} | ^^^^^^^^^^^^^^^^^^^ associated function `aliases_pub::<impl Pub2>::f` is reachable at visibility `pub(crate)` | note: but type `aliases_pub::Priv` is only usable at visibility `pub(self)` - --> $DIR/private-in-public-warn.rs:153:5 + --> $DIR/private-in-public-warn.rs:163:5 | LL | struct Priv; | ^^^^^^^^^^^ error[E0446]: private type `aliases_pub::Priv` in public interface - --> $DIR/private-in-public-warn.rs:183:9 + --> $DIR/private-in-public-warn.rs:193:9 | LL | struct Priv; | ----------- `aliases_pub::Priv` declared as private @@ -333,7 +333,7 @@ LL | type Check = Priv; | ^^^^^^^^^^ can't leak private type error[E0446]: private type `aliases_pub::Priv` in public interface - --> $DIR/private-in-public-warn.rs:186:9 + --> $DIR/private-in-public-warn.rs:196:9 | LL | struct Priv; | ----------- `aliases_pub::Priv` declared as private @@ -342,7 +342,7 @@ LL | type Check = Priv; | ^^^^^^^^^^ can't leak private type error[E0446]: private type `aliases_pub::Priv` in public interface - --> $DIR/private-in-public-warn.rs:189:9 + --> $DIR/private-in-public-warn.rs:199:9 | LL | struct Priv; | ----------- `aliases_pub::Priv` declared as private @@ -351,7 +351,7 @@ LL | type Check = Priv; | ^^^^^^^^^^ can't leak private type error[E0446]: private type `aliases_pub::Priv` in public interface - --> $DIR/private-in-public-warn.rs:192:9 + --> $DIR/private-in-public-warn.rs:202:9 | LL | struct Priv; | ----------- `aliases_pub::Priv` declared as private @@ -360,43 +360,43 @@ LL | type Check = Priv; | ^^^^^^^^^^ can't leak private type error: trait `PrivTr1` is more private than the item `aliases_priv::Tr1` - --> $DIR/private-in-public-warn.rs:222:5 + --> $DIR/private-in-public-warn.rs:232:5 | LL | pub trait Tr1: PrivUseAliasTr {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ trait `aliases_priv::Tr1` is reachable at visibility `pub(crate)` | note: but trait `PrivTr1` is only usable at visibility `pub(self)` - --> $DIR/private-in-public-warn.rs:208:5 + --> $DIR/private-in-public-warn.rs:218:5 | LL | trait PrivTr1<T = u8> { | ^^^^^^^^^^^^^^^^^^^^^ error: trait `PrivTr1<Priv2>` is more private than the item `aliases_priv::Tr2` - --> $DIR/private-in-public-warn.rs:224:5 + --> $DIR/private-in-public-warn.rs:234:5 | LL | pub trait Tr2: PrivUseAliasTr<PrivAlias> {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ trait `aliases_priv::Tr2` is reachable at visibility `pub(crate)` | note: but trait `PrivTr1<Priv2>` is only usable at visibility `pub(self)` - --> $DIR/private-in-public-warn.rs:208:5 + --> $DIR/private-in-public-warn.rs:218:5 | LL | trait PrivTr1<T = u8> { | ^^^^^^^^^^^^^^^^^^^^^ error: type `Priv2` is more private than the item `aliases_priv::Tr2` - --> $DIR/private-in-public-warn.rs:224:5 + --> $DIR/private-in-public-warn.rs:234:5 | LL | pub trait Tr2: PrivUseAliasTr<PrivAlias> {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ trait `aliases_priv::Tr2` is reachable at visibility `pub(crate)` | note: but type `Priv2` is only usable at visibility `pub(self)` - --> $DIR/private-in-public-warn.rs:206:5 + --> $DIR/private-in-public-warn.rs:216:5 | LL | struct Priv2; | ^^^^^^^^^^^^ warning: bounds on generic parameters in type aliases are not enforced - --> $DIR/private-in-public-warn.rs:41:23 + --> $DIR/private-in-public-warn.rs:42:23 | LL | pub type Alias<T: PrivTr> = T; | --^^^^^^ @@ -410,7 +410,7 @@ LL | pub type Alias<T: PrivTr> = T; = note: `#[warn(type_alias_bounds)]` on by default warning: where clauses on type aliases are not enforced - --> $DIR/private-in-public-warn.rs:59:29 + --> $DIR/private-in-public-warn.rs:63:29 | LL | pub type Alias<T> where T: PrivTr = T; | ------^^^^^^^^^ diff --git a/tests/ui/privacy/pub-priv-dep/auxiliary/priv_dep.rs b/tests/ui/privacy/pub-priv-dep/auxiliary/priv_dep.rs index 4eeecdc0569..75640147026 100644 --- a/tests/ui/privacy/pub-priv-dep/auxiliary/priv_dep.rs +++ b/tests/ui/privacy/pub-priv-dep/auxiliary/priv_dep.rs @@ -1,5 +1,6 @@ pub struct OtherType; pub trait OtherTrait {} +impl OtherTrait for OtherType {} #[macro_export] macro_rules! m { diff --git a/tests/ui/privacy/pub-priv-dep/pub-priv1.rs b/tests/ui/privacy/pub-priv-dep/pub-priv1.rs index 192ca0db8bd..b85f2754fb1 100644 --- a/tests/ui/privacy/pub-priv-dep/pub-priv1.rs +++ b/tests/ui/privacy/pub-priv-dep/pub-priv1.rs @@ -44,8 +44,12 @@ impl PublicType { pub trait MyPubTrait { type Foo: OtherTrait; + //~^ ERROR trait `OtherTrait` from private dependency 'priv_dep' in public interface + + fn required() -> impl OtherTrait; + + fn provided() -> impl OtherTrait { OtherType } } -//~^^ ERROR trait `OtherTrait` from private dependency 'priv_dep' in public interface pub trait WithSuperTrait: OtherTrait {} //~^ ERROR trait `OtherTrait` from private dependency 'priv_dep' in public interface diff --git a/tests/ui/privacy/pub-priv-dep/pub-priv1.stderr b/tests/ui/privacy/pub-priv-dep/pub-priv1.stderr index 9da47827be4..24bd071567f 100644 --- a/tests/ui/privacy/pub-priv-dep/pub-priv1.stderr +++ b/tests/ui/privacy/pub-priv-dep/pub-priv1.stderr @@ -11,31 +11,31 @@ LL | #![deny(exported_private_dependencies)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: macro `m` from private dependency 'priv_dep' is re-exported - --> $DIR/pub-priv1.rs:94:9 + --> $DIR/pub-priv1.rs:98:9 | LL | pub use priv_dep::m; | ^^^^^^^^^^^ error: macro `fn_like` from private dependency 'pm' is re-exported - --> $DIR/pub-priv1.rs:96:9 + --> $DIR/pub-priv1.rs:100:9 | LL | pub use pm::fn_like; | ^^^^^^^^^^^ error: derive macro `PmDerive` from private dependency 'pm' is re-exported - --> $DIR/pub-priv1.rs:98:9 + --> $DIR/pub-priv1.rs:102:9 | LL | pub use pm::PmDerive; | ^^^^^^^^^^^^ error: attribute macro `pm_attr` from private dependency 'pm' is re-exported - --> $DIR/pub-priv1.rs:100:9 + --> $DIR/pub-priv1.rs:104:9 | LL | pub use pm::pm_attr; | ^^^^^^^^^^^ error: variant `V1` from private dependency 'priv_dep' is re-exported - --> $DIR/pub-priv1.rs:103:9 + --> $DIR/pub-priv1.rs:107:9 | LL | pub use priv_dep::E::V1; | ^^^^^^^^^^^^^^^ @@ -65,61 +65,61 @@ LL | type Foo: OtherTrait; | ^^^^^^^^^^^^^^^^^^^^ error: trait `OtherTrait` from private dependency 'priv_dep' in public interface - --> $DIR/pub-priv1.rs:50:1 + --> $DIR/pub-priv1.rs:54:1 | LL | pub trait WithSuperTrait: OtherTrait {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: type `OtherType` from private dependency 'priv_dep' in public interface - --> $DIR/pub-priv1.rs:59:5 + --> $DIR/pub-priv1.rs:63:5 | LL | type X = OtherType; | ^^^^^^ error: trait `OtherTrait` from private dependency 'priv_dep' in public interface - --> $DIR/pub-priv1.rs:63:1 + --> $DIR/pub-priv1.rs:67:1 | LL | pub fn in_bounds<T: OtherTrait>(x: T) { unimplemented!() } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: type `OtherType` from private dependency 'priv_dep' in public interface - --> $DIR/pub-priv1.rs:66:1 + --> $DIR/pub-priv1.rs:70:1 | LL | pub fn private_in_generic() -> std::num::Saturating<OtherType> { unimplemented!() } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: type `OtherType` from private dependency 'priv_dep' in public interface - --> $DIR/pub-priv1.rs:69:1 + --> $DIR/pub-priv1.rs:73:1 | LL | pub static STATIC: OtherType = OtherType; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: type `OtherType` from private dependency 'priv_dep' in public interface - --> $DIR/pub-priv1.rs:72:1 + --> $DIR/pub-priv1.rs:76:1 | LL | pub const CONST: OtherType = OtherType; | ^^^^^^^^^^^^^^^^^^^^^^^^^^ error: type `OtherType` from private dependency 'priv_dep' in public interface - --> $DIR/pub-priv1.rs:75:1 + --> $DIR/pub-priv1.rs:79:1 | LL | pub type Alias = OtherType; | ^^^^^^^^^^^^^^ error: trait `OtherTrait` from private dependency 'priv_dep' in public interface - --> $DIR/pub-priv1.rs:80:1 + --> $DIR/pub-priv1.rs:84:1 | LL | impl OtherTrait for PublicWithPrivateImpl {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: type `OtherType` from private dependency 'priv_dep' in public interface - --> $DIR/pub-priv1.rs:85:1 + --> $DIR/pub-priv1.rs:89:1 | LL | impl PubTraitOnPrivate for OtherType {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: type `OtherType` from private dependency 'priv_dep' in public interface - --> $DIR/pub-priv1.rs:85:1 + --> $DIR/pub-priv1.rs:89:1 | LL | impl PubTraitOnPrivate for OtherType {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/resolve/underscore-bindings-disambiguators.rs b/tests/ui/resolve/underscore-bindings-disambiguators.rs new file mode 100644 index 00000000000..8c89b39f859 --- /dev/null +++ b/tests/ui/resolve/underscore-bindings-disambiguators.rs @@ -0,0 +1,27 @@ +// Regression test for issue #144168 where some `_` bindings were incorrectly only allowed once per +// module, failing with "error[E0428]: the name `_` is defined multiple times". + +// This weird/complex setup is reduced from `zerocopy-0.8.25` where the issue was encountered. + +#![crate_type = "lib"] + +macro_rules! impl_for_transmute_from { + () => { + const _: () = {}; + }; +} + +mod impls { + use super::*; + impl_for_transmute_from!(); + impl_for_transmute_from!(); + const _: () = todo!(); //~ ERROR: evaluation panicked + const _: () = todo!(); //~ ERROR: evaluation panicked + const _: () = todo!(); //~ ERROR: evaluation panicked + const _: () = todo!(); //~ ERROR: evaluation panicked + const _: () = todo!(); //~ ERROR: evaluation panicked +} +use X as Y; //~ ERROR: unresolved import +use Z as W; //~ ERROR: unresolved import + +const _: () = todo!(); //~ ERROR: evaluation panicked diff --git a/tests/ui/resolve/underscore-bindings-disambiguators.stderr b/tests/ui/resolve/underscore-bindings-disambiguators.stderr new file mode 100644 index 00000000000..0c8081a0c56 --- /dev/null +++ b/tests/ui/resolve/underscore-bindings-disambiguators.stderr @@ -0,0 +1,70 @@ +error[E0432]: unresolved import `X` + --> $DIR/underscore-bindings-disambiguators.rs:24:5 + | +LL | use X as Y; + | -^^^^^ + | | + | no `X` in the root + | help: a similar name exists in the module: `_` + +error[E0432]: unresolved import `Z` + --> $DIR/underscore-bindings-disambiguators.rs:25:5 + | +LL | use Z as W; + | -^^^^^ + | | + | no `Z` in the root + | help: a similar name exists in the module: `_` + +error[E0080]: evaluation panicked: not yet implemented + --> $DIR/underscore-bindings-disambiguators.rs:18:19 + | +LL | const _: () = todo!(); + | ^^^^^^^ evaluation of `impls::_` failed here + | + = note: this error originates in the macro `todo` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0080]: evaluation panicked: not yet implemented + --> $DIR/underscore-bindings-disambiguators.rs:19:19 + | +LL | const _: () = todo!(); + | ^^^^^^^ evaluation of `impls::_` failed here + | + = note: this error originates in the macro `todo` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0080]: evaluation panicked: not yet implemented + --> $DIR/underscore-bindings-disambiguators.rs:20:19 + | +LL | const _: () = todo!(); + | ^^^^^^^ evaluation of `impls::_` failed here + | + = note: this error originates in the macro `todo` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0080]: evaluation panicked: not yet implemented + --> $DIR/underscore-bindings-disambiguators.rs:21:19 + | +LL | const _: () = todo!(); + | ^^^^^^^ evaluation of `impls::_` failed here + | + = note: this error originates in the macro `todo` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0080]: evaluation panicked: not yet implemented + --> $DIR/underscore-bindings-disambiguators.rs:22:19 + | +LL | const _: () = todo!(); + | ^^^^^^^ evaluation of `impls::_` failed here + | + = note: this error originates in the macro `todo` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0080]: evaluation panicked: not yet implemented + --> $DIR/underscore-bindings-disambiguators.rs:27:15 + | +LL | const _: () = todo!(); + | ^^^^^^^ evaluation of `_` failed here + | + = note: this error originates in the macro `todo` (in Nightly builds, run with -Z macro-backtrace for more info) + +error: aborting due to 8 previous errors + +Some errors have detailed explanations: E0080, E0432. +For more information about an error, try `rustc --explain E0080`. diff --git a/tests/ui/rustdoc/check-doc-alias-attr-location.stderr b/tests/ui/rustdoc/check-doc-alias-attr-location.stderr index 23c93a4ed8b..4244c11eb3e 100644 --- a/tests/ui/rustdoc/check-doc-alias-attr-location.stderr +++ b/tests/ui/rustdoc/check-doc-alias-attr-location.stderr @@ -10,13 +10,13 @@ error: `#[doc(alias = "...")]` isn't allowed on foreign module LL | #[doc(alias = "foo")] | ^^^^^^^^^^^^^ -error: `#[doc(alias = "...")]` isn't allowed on implementation block +error: `#[doc(alias = "...")]` isn't allowed on inherent implementation block --> $DIR/check-doc-alias-attr-location.rs:12:7 | LL | #[doc(alias = "bar")] | ^^^^^^^^^^^^^ -error: `#[doc(alias = "...")]` isn't allowed on implementation block +error: `#[doc(alias = "...")]` isn't allowed on trait implementation block --> $DIR/check-doc-alias-attr-location.rs:18:7 | LL | #[doc(alias = "foobar")] diff --git a/tests/ui/sanitizer/address.rs b/tests/ui/sanitizer/address.rs index 7a5e767687c..704d84764c1 100644 --- a/tests/ui/sanitizer/address.rs +++ b/tests/ui/sanitizer/address.rs @@ -4,7 +4,7 @@ // //@ compile-flags: -Z sanitizer=address -O -g // -//@ run-fail +//@ run-fail-or-crash //@ error-pattern: AddressSanitizer: stack-buffer-overflow //@ error-pattern: 'xs' (line 14) <== Memory access at offset diff --git a/tests/ui/sanitizer/badfree.rs b/tests/ui/sanitizer/badfree.rs index ecbb58eba00..6b3aea7239c 100644 --- a/tests/ui/sanitizer/badfree.rs +++ b/tests/ui/sanitizer/badfree.rs @@ -4,7 +4,7 @@ // //@ compile-flags: -Z sanitizer=address -O // -//@ run-fail +//@ run-fail-or-crash //@ regex-error-pattern: AddressSanitizer: (SEGV|attempting free on address which was not malloc) use std::ffi::c_void; diff --git a/tests/ui/sanitizer/new-llvm-pass-manager-thin-lto.rs b/tests/ui/sanitizer/new-llvm-pass-manager-thin-lto.rs index b7dd4a43782..c1a2c2f26ac 100644 --- a/tests/ui/sanitizer/new-llvm-pass-manager-thin-lto.rs +++ b/tests/ui/sanitizer/new-llvm-pass-manager-thin-lto.rs @@ -11,7 +11,7 @@ //@ compile-flags: -Zsanitizer=address -Clto=thin //@[opt0]compile-flags: -Copt-level=0 //@[opt1]compile-flags: -Copt-level=1 -//@ run-fail +//@ run-fail-or-crash //@ error-pattern: ERROR: AddressSanitizer: stack-use-after-scope static mut P: *mut usize = std::ptr::null_mut(); diff --git a/tests/ui/sanitizer/thread.rs b/tests/ui/sanitizer/thread.rs index 566774d6b1d..9073124d1bd 100644 --- a/tests/ui/sanitizer/thread.rs +++ b/tests/ui/sanitizer/thread.rs @@ -15,7 +15,7 @@ // //@ compile-flags: -Z sanitizer=thread -O // -//@ run-fail +//@ run-fail-or-crash //@ error-pattern: WARNING: ThreadSanitizer: data race //@ error-pattern: Location is heap block of size 4 //@ error-pattern: allocated by main thread diff --git a/tests/ui/sanitizer/use-after-scope.rs b/tests/ui/sanitizer/use-after-scope.rs index 4d7f6f6c2f2..106dc6466d6 100644 --- a/tests/ui/sanitizer/use-after-scope.rs +++ b/tests/ui/sanitizer/use-after-scope.rs @@ -3,7 +3,7 @@ //@ ignore-cross-compile // //@ compile-flags: -Zsanitizer=address -//@ run-fail +//@ run-fail-or-crash //@ error-pattern: ERROR: AddressSanitizer: stack-use-after-scope static mut P: *mut usize = std::ptr::null_mut(); diff --git a/tests/ui/simd/generics.rs b/tests/ui/simd/generics.rs index 1ae08fef7cd..54e76f7bc5d 100644 --- a/tests/ui/simd/generics.rs +++ b/tests/ui/simd/generics.rs @@ -2,24 +2,18 @@ #![allow(non_camel_case_types)] #![feature(repr_simd, core_intrinsics)] +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; + use std::intrinsics::simd::simd_add; use std::ops; -#[repr(simd)] -#[derive(Copy, Clone)] -struct f32x4([f32; 4]); - -#[repr(simd)] -#[derive(Copy, Clone)] -struct A<const N: usize>([f32; N]); +type A<const N: usize> = Simd<f32, N>; -#[repr(simd)] -#[derive(Copy, Clone)] -struct B<T>([T; 4]); +type B<T> = Simd<T, 4>; -#[repr(simd)] -#[derive(Copy, Clone)] -struct C<T, const N: usize>([T; N]); +type C<T, const N: usize> = Simd<T, N>; fn add<T: ops::Add<Output = T>>(lhs: T, rhs: T) -> T { lhs + rhs @@ -33,48 +27,24 @@ impl ops::Add for f32x4 { } } -impl ops::Add for A<4> { - type Output = Self; - - fn add(self, rhs: Self) -> Self { - unsafe { simd_add(self, rhs) } - } -} - -impl ops::Add for B<f32> { - type Output = Self; - - fn add(self, rhs: Self) -> Self { - unsafe { simd_add(self, rhs) } - } -} - -impl ops::Add for C<f32, 4> { - type Output = Self; - - fn add(self, rhs: Self) -> Self { - unsafe { simd_add(self, rhs) } - } -} - pub fn main() { let x = [1.0f32, 2.0f32, 3.0f32, 4.0f32]; let y = [2.0f32, 4.0f32, 6.0f32, 8.0f32]; // lame-o - let a = f32x4([1.0f32, 2.0f32, 3.0f32, 4.0f32]); - let f32x4([a0, a1, a2, a3]) = add(a, a); + let a = f32x4::from_array([1.0f32, 2.0f32, 3.0f32, 4.0f32]); + let [a0, a1, a2, a3] = add(a, a).into_array(); assert_eq!(a0, 2.0f32); assert_eq!(a1, 4.0f32); assert_eq!(a2, 6.0f32); assert_eq!(a3, 8.0f32); - let a = A(x); - assert_eq!(add(a, a).0, y); + let a = A::from_array(x); + assert_eq!(add(a, a).into_array(), y); - let b = B(x); - assert_eq!(add(b, b).0, y); + let b = B::from_array(x); + assert_eq!(add(b, b).into_array(), y); - let c = C(x); - assert_eq!(add(c, c).0, y); + let c = C::from_array(x); + assert_eq!(add(c, c).into_array(), y); } diff --git a/tests/ui/simd/intrinsic/float-math-pass.rs b/tests/ui/simd/intrinsic/float-math-pass.rs index 01fed8537d0..743aae8d1c3 100644 --- a/tests/ui/simd/intrinsic/float-math-pass.rs +++ b/tests/ui/simd/intrinsic/float-math-pass.rs @@ -11,9 +11,9 @@ #![feature(repr_simd, intrinsics, core_intrinsics)] #![allow(non_camel_case_types)] -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -struct f32x4(pub [f32; 4]); +#[path = "../../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; use std::intrinsics::simd::*; @@ -27,19 +27,19 @@ macro_rules! assert_approx_eq { ($a:expr, $b:expr) => {{ let a = $a; let b = $b; - assert_approx_eq_f32!(a.0[0], b.0[0]); - assert_approx_eq_f32!(a.0[1], b.0[1]); - assert_approx_eq_f32!(a.0[2], b.0[2]); - assert_approx_eq_f32!(a.0[3], b.0[3]); + assert_approx_eq_f32!(a[0], b[0]); + assert_approx_eq_f32!(a[1], b[1]); + assert_approx_eq_f32!(a[2], b[2]); + assert_approx_eq_f32!(a[3], b[3]); }}; } fn main() { - let x = f32x4([1.0, 1.0, 1.0, 1.0]); - let y = f32x4([-1.0, -1.0, -1.0, -1.0]); - let z = f32x4([0.0, 0.0, 0.0, 0.0]); + let x = f32x4::from_array([1.0, 1.0, 1.0, 1.0]); + let y = f32x4::from_array([-1.0, -1.0, -1.0, -1.0]); + let z = f32x4::from_array([0.0, 0.0, 0.0, 0.0]); - let h = f32x4([0.5, 0.5, 0.5, 0.5]); + let h = f32x4::from_array([0.5, 0.5, 0.5, 0.5]); unsafe { let r = simd_fabs(y); diff --git a/tests/ui/simd/intrinsic/float-minmax-pass.rs b/tests/ui/simd/intrinsic/float-minmax-pass.rs index 00c0d8cea3f..12210ba0ad1 100644 --- a/tests/ui/simd/intrinsic/float-minmax-pass.rs +++ b/tests/ui/simd/intrinsic/float-minmax-pass.rs @@ -6,15 +6,15 @@ #![feature(repr_simd, core_intrinsics)] #![allow(non_camel_case_types)] -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -struct f32x4(pub [f32; 4]); +#[path = "../../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; use std::intrinsics::simd::*; fn main() { - let x = f32x4([1.0, 2.0, 3.0, 4.0]); - let y = f32x4([2.0, 1.0, 4.0, 3.0]); + let x = f32x4::from_array([1.0, 2.0, 3.0, 4.0]); + let y = f32x4::from_array([2.0, 1.0, 4.0, 3.0]); #[cfg(not(any(target_arch = "mips", target_arch = "mips64")))] let nan = f32::NAN; @@ -23,13 +23,13 @@ fn main() { #[cfg(any(target_arch = "mips", target_arch = "mips64"))] let nan = f32::from_bits(f32::NAN.to_bits() - 1); - let n = f32x4([nan, nan, nan, nan]); + let n = f32x4::from_array([nan, nan, nan, nan]); unsafe { let min0 = simd_fmin(x, y); let min1 = simd_fmin(y, x); assert_eq!(min0, min1); - let e = f32x4([1.0, 1.0, 3.0, 3.0]); + let e = f32x4::from_array([1.0, 1.0, 3.0, 3.0]); assert_eq!(min0, e); let minn = simd_fmin(x, n); assert_eq!(minn, x); @@ -39,7 +39,7 @@ fn main() { let max0 = simd_fmax(x, y); let max1 = simd_fmax(y, x); assert_eq!(max0, max1); - let e = f32x4([2.0, 2.0, 4.0, 4.0]); + let e = f32x4::from_array([2.0, 2.0, 4.0, 4.0]); assert_eq!(max0, e); let maxn = simd_fmax(x, n); assert_eq!(maxn, x); diff --git a/tests/ui/simd/intrinsic/generic-arithmetic-pass.rs b/tests/ui/simd/intrinsic/generic-arithmetic-pass.rs index 4c97fb2141d..bf38a8b1720 100644 --- a/tests/ui/simd/intrinsic/generic-arithmetic-pass.rs +++ b/tests/ui/simd/intrinsic/generic-arithmetic-pass.rs @@ -2,80 +2,77 @@ #![allow(non_camel_case_types)] #![feature(repr_simd, core_intrinsics)] -#[repr(simd)] -#[derive(Copy, Clone)] -struct i32x4(pub [i32; 4]); +#[path = "../../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; -#[repr(simd)] -#[derive(Copy, Clone)] -struct U32<const N: usize>([u32; N]); - -#[repr(simd)] -#[derive(Copy, Clone)] -struct f32x4(pub [f32; 4]); +type U32<const N: usize> = Simd<u32, N>; macro_rules! all_eq { - ($a: expr, $b: expr) => {{ + ($a: expr, $b: expr $(,)?) => {{ let a = $a; let b = $b; - assert!(a.0 == b.0); + assert!(a == b); }}; } use std::intrinsics::simd::*; fn main() { - let x1 = i32x4([1, 2, 3, 4]); - let y1 = U32::<4>([1, 2, 3, 4]); - let z1 = f32x4([1.0, 2.0, 3.0, 4.0]); - let x2 = i32x4([2, 3, 4, 5]); - let y2 = U32::<4>([2, 3, 4, 5]); - let z2 = f32x4([2.0, 3.0, 4.0, 5.0]); - let x3 = i32x4([0, i32::MAX, i32::MIN, -1_i32]); - let y3 = U32::<4>([0, i32::MAX as _, i32::MIN as _, -1_i32 as _]); + let x1 = i32x4::from_array([1, 2, 3, 4]); + let y1 = U32::<4>::from_array([1, 2, 3, 4]); + let z1 = f32x4::from_array([1.0, 2.0, 3.0, 4.0]); + let x2 = i32x4::from_array([2, 3, 4, 5]); + let y2 = U32::<4>::from_array([2, 3, 4, 5]); + let z2 = f32x4::from_array([2.0, 3.0, 4.0, 5.0]); + let x3 = i32x4::from_array([0, i32::MAX, i32::MIN, -1_i32]); + let y3 = U32::<4>::from_array([0, i32::MAX as _, i32::MIN as _, -1_i32 as _]); unsafe { - all_eq!(simd_add(x1, x2), i32x4([3, 5, 7, 9])); - all_eq!(simd_add(x2, x1), i32x4([3, 5, 7, 9])); - all_eq!(simd_add(y1, y2), U32::<4>([3, 5, 7, 9])); - all_eq!(simd_add(y2, y1), U32::<4>([3, 5, 7, 9])); - all_eq!(simd_add(z1, z2), f32x4([3.0, 5.0, 7.0, 9.0])); - all_eq!(simd_add(z2, z1), f32x4([3.0, 5.0, 7.0, 9.0])); - - all_eq!(simd_mul(x1, x2), i32x4([2, 6, 12, 20])); - all_eq!(simd_mul(x2, x1), i32x4([2, 6, 12, 20])); - all_eq!(simd_mul(y1, y2), U32::<4>([2, 6, 12, 20])); - all_eq!(simd_mul(y2, y1), U32::<4>([2, 6, 12, 20])); - all_eq!(simd_mul(z1, z2), f32x4([2.0, 6.0, 12.0, 20.0])); - all_eq!(simd_mul(z2, z1), f32x4([2.0, 6.0, 12.0, 20.0])); - - all_eq!(simd_sub(x2, x1), i32x4([1, 1, 1, 1])); - all_eq!(simd_sub(x1, x2), i32x4([-1, -1, -1, -1])); - all_eq!(simd_sub(y2, y1), U32::<4>([1, 1, 1, 1])); - all_eq!(simd_sub(y1, y2), U32::<4>([!0, !0, !0, !0])); - all_eq!(simd_sub(z2, z1), f32x4([1.0, 1.0, 1.0, 1.0])); - all_eq!(simd_sub(z1, z2), f32x4([-1.0, -1.0, -1.0, -1.0])); - - all_eq!(simd_div(x1, x1), i32x4([1, 1, 1, 1])); - all_eq!(simd_div(i32x4([2, 4, 6, 8]), i32x4([2, 2, 2, 2])), x1); - all_eq!(simd_div(y1, y1), U32::<4>([1, 1, 1, 1])); - all_eq!(simd_div(U32::<4>([2, 4, 6, 8]), U32::<4>([2, 2, 2, 2])), y1); - all_eq!(simd_div(z1, z1), f32x4([1.0, 1.0, 1.0, 1.0])); - all_eq!(simd_div(z1, z2), f32x4([1.0 / 2.0, 2.0 / 3.0, 3.0 / 4.0, 4.0 / 5.0])); - all_eq!(simd_div(z2, z1), f32x4([2.0 / 1.0, 3.0 / 2.0, 4.0 / 3.0, 5.0 / 4.0])); - - all_eq!(simd_rem(x1, x1), i32x4([0, 0, 0, 0])); - all_eq!(simd_rem(x2, x1), i32x4([0, 1, 1, 1])); - all_eq!(simd_rem(y1, y1), U32::<4>([0, 0, 0, 0])); - all_eq!(simd_rem(y2, y1), U32::<4>([0, 1, 1, 1])); - all_eq!(simd_rem(z1, z1), f32x4([0.0, 0.0, 0.0, 0.0])); + all_eq!(simd_add(x1, x2), i32x4::from_array([3, 5, 7, 9])); + all_eq!(simd_add(x2, x1), i32x4::from_array([3, 5, 7, 9])); + all_eq!(simd_add(y1, y2), U32::<4>::from_array([3, 5, 7, 9])); + all_eq!(simd_add(y2, y1), U32::<4>::from_array([3, 5, 7, 9])); + all_eq!(simd_add(z1, z2), f32x4::from_array([3.0, 5.0, 7.0, 9.0])); + all_eq!(simd_add(z2, z1), f32x4::from_array([3.0, 5.0, 7.0, 9.0])); + + all_eq!(simd_mul(x1, x2), i32x4::from_array([2, 6, 12, 20])); + all_eq!(simd_mul(x2, x1), i32x4::from_array([2, 6, 12, 20])); + all_eq!(simd_mul(y1, y2), U32::<4>::from_array([2, 6, 12, 20])); + all_eq!(simd_mul(y2, y1), U32::<4>::from_array([2, 6, 12, 20])); + all_eq!(simd_mul(z1, z2), f32x4::from_array([2.0, 6.0, 12.0, 20.0])); + all_eq!(simd_mul(z2, z1), f32x4::from_array([2.0, 6.0, 12.0, 20.0])); + + all_eq!(simd_sub(x2, x1), i32x4::from_array([1, 1, 1, 1])); + all_eq!(simd_sub(x1, x2), i32x4::from_array([-1, -1, -1, -1])); + all_eq!(simd_sub(y2, y1), U32::<4>::from_array([1, 1, 1, 1])); + all_eq!(simd_sub(y1, y2), U32::<4>::from_array([!0, !0, !0, !0])); + all_eq!(simd_sub(z2, z1), f32x4::from_array([1.0, 1.0, 1.0, 1.0])); + all_eq!(simd_sub(z1, z2), f32x4::from_array([-1.0, -1.0, -1.0, -1.0])); + + all_eq!(simd_div(x1, x1), i32x4::from_array([1, 1, 1, 1])); + all_eq!(simd_div(i32x4::from_array([2, 4, 6, 8]), i32x4::from_array([2, 2, 2, 2])), x1); + all_eq!(simd_div(y1, y1), U32::<4>::from_array([1, 1, 1, 1])); + all_eq!( + simd_div(U32::<4>::from_array([2, 4, 6, 8]), U32::<4>::from_array([2, 2, 2, 2])), + y1, + ); + all_eq!(simd_div(z1, z1), f32x4::from_array([1.0, 1.0, 1.0, 1.0])); + all_eq!(simd_div(z1, z2), f32x4::from_array([1.0 / 2.0, 2.0 / 3.0, 3.0 / 4.0, 4.0 / 5.0])); + all_eq!(simd_div(z2, z1), f32x4::from_array([2.0 / 1.0, 3.0 / 2.0, 4.0 / 3.0, 5.0 / 4.0])); + + all_eq!(simd_rem(x1, x1), i32x4::from_array([0, 0, 0, 0])); + all_eq!(simd_rem(x2, x1), i32x4::from_array([0, 1, 1, 1])); + all_eq!(simd_rem(y1, y1), U32::<4>::from_array([0, 0, 0, 0])); + all_eq!(simd_rem(y2, y1), U32::<4>::from_array([0, 1, 1, 1])); + all_eq!(simd_rem(z1, z1), f32x4::from_array([0.0, 0.0, 0.0, 0.0])); all_eq!(simd_rem(z1, z2), z1); - all_eq!(simd_rem(z2, z1), f32x4([0.0, 1.0, 1.0, 1.0])); + all_eq!(simd_rem(z2, z1), f32x4::from_array([0.0, 1.0, 1.0, 1.0])); - all_eq!(simd_shl(x1, x2), i32x4([1 << 2, 2 << 3, 3 << 4, 4 << 5])); - all_eq!(simd_shl(x2, x1), i32x4([2 << 1, 3 << 2, 4 << 3, 5 << 4])); - all_eq!(simd_shl(y1, y2), U32::<4>([1 << 2, 2 << 3, 3 << 4, 4 << 5])); - all_eq!(simd_shl(y2, y1), U32::<4>([2 << 1, 3 << 2, 4 << 3, 5 << 4])); + all_eq!(simd_shl(x1, x2), i32x4::from_array([1 << 2, 2 << 3, 3 << 4, 4 << 5])); + all_eq!(simd_shl(x2, x1), i32x4::from_array([2 << 1, 3 << 2, 4 << 3, 5 << 4])); + all_eq!(simd_shl(y1, y2), U32::<4>::from_array([1 << 2, 2 << 3, 3 << 4, 4 << 5])); + all_eq!(simd_shl(y2, y1), U32::<4>::from_array([2 << 1, 3 << 2, 4 << 3, 5 << 4])); // test right-shift by assuming left-shift is correct all_eq!(simd_shr(simd_shl(x1, x2), x2), x1); @@ -85,7 +82,7 @@ fn main() { all_eq!( simd_funnel_shl(x1, x2, x1), - i32x4([ + i32x4::from_array([ (1 << 1) | (2 >> 31), (2 << 2) | (3 >> 30), (3 << 3) | (4 >> 29), @@ -94,7 +91,7 @@ fn main() { ); all_eq!( simd_funnel_shl(x2, x1, x1), - i32x4([ + i32x4::from_array([ (2 << 1) | (1 >> 31), (3 << 2) | (2 >> 30), (4 << 3) | (3 >> 29), @@ -103,7 +100,7 @@ fn main() { ); all_eq!( simd_funnel_shl(y1, y2, y1), - U32::<4>([ + U32::<4>::from_array([ (1 << 1) | (2 >> 31), (2 << 2) | (3 >> 30), (3 << 3) | (4 >> 29), @@ -112,7 +109,7 @@ fn main() { ); all_eq!( simd_funnel_shl(y2, y1, y1), - U32::<4>([ + U32::<4>::from_array([ (2 << 1) | (1 >> 31), (3 << 2) | (2 >> 30), (4 << 3) | (3 >> 29), @@ -122,7 +119,7 @@ fn main() { all_eq!( simd_funnel_shr(x1, x2, x1), - i32x4([ + i32x4::from_array([ (1 << 31) | (2 >> 1), (2 << 30) | (3 >> 2), (3 << 29) | (4 >> 3), @@ -131,7 +128,7 @@ fn main() { ); all_eq!( simd_funnel_shr(x2, x1, x1), - i32x4([ + i32x4::from_array([ (2 << 31) | (1 >> 1), (3 << 30) | (2 >> 2), (4 << 29) | (3 >> 3), @@ -140,7 +137,7 @@ fn main() { ); all_eq!( simd_funnel_shr(y1, y2, y1), - U32::<4>([ + U32::<4>::from_array([ (1 << 31) | (2 >> 1), (2 << 30) | (3 >> 2), (3 << 29) | (4 >> 3), @@ -149,7 +146,7 @@ fn main() { ); all_eq!( simd_funnel_shr(y2, y1, y1), - U32::<4>([ + U32::<4>::from_array([ (2 << 31) | (1 >> 1), (3 << 30) | (2 >> 2), (4 << 29) | (3 >> 3), @@ -159,52 +156,69 @@ fn main() { // ensure we get logical vs. arithmetic shifts correct let (a, b, c, d) = (-12, -123, -1234, -12345); - all_eq!(simd_shr(i32x4([a, b, c, d]), x1), i32x4([a >> 1, b >> 2, c >> 3, d >> 4])); all_eq!( - simd_shr(U32::<4>([a as u32, b as u32, c as u32, d as u32]), y1), - U32::<4>([(a as u32) >> 1, (b as u32) >> 2, (c as u32) >> 3, (d as u32) >> 4]) + simd_shr(i32x4::from_array([a, b, c, d]), x1), + i32x4::from_array([a >> 1, b >> 2, c >> 3, d >> 4]), + ); + all_eq!( + simd_shr(U32::<4>::from_array([a as u32, b as u32, c as u32, d as u32]), y1), + U32::<4>::from_array([ + (a as u32) >> 1, + (b as u32) >> 2, + (c as u32) >> 3, + (d as u32) >> 4, + ]), ); - all_eq!(simd_and(x1, x2), i32x4([0, 2, 0, 4])); - all_eq!(simd_and(x2, x1), i32x4([0, 2, 0, 4])); - all_eq!(simd_and(y1, y2), U32::<4>([0, 2, 0, 4])); - all_eq!(simd_and(y2, y1), U32::<4>([0, 2, 0, 4])); + all_eq!(simd_and(x1, x2), i32x4::from_array([0, 2, 0, 4])); + all_eq!(simd_and(x2, x1), i32x4::from_array([0, 2, 0, 4])); + all_eq!(simd_and(y1, y2), U32::<4>::from_array([0, 2, 0, 4])); + all_eq!(simd_and(y2, y1), U32::<4>::from_array([0, 2, 0, 4])); - all_eq!(simd_or(x1, x2), i32x4([3, 3, 7, 5])); - all_eq!(simd_or(x2, x1), i32x4([3, 3, 7, 5])); - all_eq!(simd_or(y1, y2), U32::<4>([3, 3, 7, 5])); - all_eq!(simd_or(y2, y1), U32::<4>([3, 3, 7, 5])); + all_eq!(simd_or(x1, x2), i32x4::from_array([3, 3, 7, 5])); + all_eq!(simd_or(x2, x1), i32x4::from_array([3, 3, 7, 5])); + all_eq!(simd_or(y1, y2), U32::<4>::from_array([3, 3, 7, 5])); + all_eq!(simd_or(y2, y1), U32::<4>::from_array([3, 3, 7, 5])); - all_eq!(simd_xor(x1, x2), i32x4([3, 1, 7, 1])); - all_eq!(simd_xor(x2, x1), i32x4([3, 1, 7, 1])); - all_eq!(simd_xor(y1, y2), U32::<4>([3, 1, 7, 1])); - all_eq!(simd_xor(y2, y1), U32::<4>([3, 1, 7, 1])); + all_eq!(simd_xor(x1, x2), i32x4::from_array([3, 1, 7, 1])); + all_eq!(simd_xor(x2, x1), i32x4::from_array([3, 1, 7, 1])); + all_eq!(simd_xor(y1, y2), U32::<4>::from_array([3, 1, 7, 1])); + all_eq!(simd_xor(y2, y1), U32::<4>::from_array([3, 1, 7, 1])); - all_eq!(simd_neg(x1), i32x4([-1, -2, -3, -4])); - all_eq!(simd_neg(x2), i32x4([-2, -3, -4, -5])); - all_eq!(simd_neg(z1), f32x4([-1.0, -2.0, -3.0, -4.0])); - all_eq!(simd_neg(z2), f32x4([-2.0, -3.0, -4.0, -5.0])); + all_eq!(simd_neg(x1), i32x4::from_array([-1, -2, -3, -4])); + all_eq!(simd_neg(x2), i32x4::from_array([-2, -3, -4, -5])); + all_eq!(simd_neg(z1), f32x4::from_array([-1.0, -2.0, -3.0, -4.0])); + all_eq!(simd_neg(z2), f32x4::from_array([-2.0, -3.0, -4.0, -5.0])); - all_eq!(simd_bswap(x1), i32x4([0x01000000, 0x02000000, 0x03000000, 0x04000000])); - all_eq!(simd_bswap(y1), U32::<4>([0x01000000, 0x02000000, 0x03000000, 0x04000000])); + all_eq!( + simd_bswap(x1), + i32x4::from_array([0x01000000, 0x02000000, 0x03000000, 0x04000000]), + ); + all_eq!( + simd_bswap(y1), + U32::<4>::from_array([0x01000000, 0x02000000, 0x03000000, 0x04000000]), + ); all_eq!( simd_bitreverse(x1), - i32x4([0x80000000u32 as i32, 0x40000000, 0xc0000000u32 as i32, 0x20000000]) + i32x4::from_array([0x80000000u32 as i32, 0x40000000, 0xc0000000u32 as i32, 0x20000000]) + ); + all_eq!( + simd_bitreverse(y1), + U32::<4>::from_array([0x80000000, 0x40000000, 0xc0000000, 0x20000000]), ); - all_eq!(simd_bitreverse(y1), U32::<4>([0x80000000, 0x40000000, 0xc0000000, 0x20000000])); - all_eq!(simd_ctlz(x1), i32x4([31, 30, 30, 29])); - all_eq!(simd_ctlz(y1), U32::<4>([31, 30, 30, 29])); + all_eq!(simd_ctlz(x1), i32x4::from_array([31, 30, 30, 29])); + all_eq!(simd_ctlz(y1), U32::<4>::from_array([31, 30, 30, 29])); - all_eq!(simd_ctpop(x1), i32x4([1, 1, 2, 1])); - all_eq!(simd_ctpop(y1), U32::<4>([1, 1, 2, 1])); - all_eq!(simd_ctpop(x2), i32x4([1, 2, 1, 2])); - all_eq!(simd_ctpop(y2), U32::<4>([1, 2, 1, 2])); - all_eq!(simd_ctpop(x3), i32x4([0, 31, 1, 32])); - all_eq!(simd_ctpop(y3), U32::<4>([0, 31, 1, 32])); + all_eq!(simd_ctpop(x1), i32x4::from_array([1, 1, 2, 1])); + all_eq!(simd_ctpop(y1), U32::<4>::from_array([1, 1, 2, 1])); + all_eq!(simd_ctpop(x2), i32x4::from_array([1, 2, 1, 2])); + all_eq!(simd_ctpop(y2), U32::<4>::from_array([1, 2, 1, 2])); + all_eq!(simd_ctpop(x3), i32x4::from_array([0, 31, 1, 32])); + all_eq!(simd_ctpop(y3), U32::<4>::from_array([0, 31, 1, 32])); - all_eq!(simd_cttz(x1), i32x4([0, 1, 0, 2])); - all_eq!(simd_cttz(y1), U32::<4>([0, 1, 0, 2])); + all_eq!(simd_cttz(x1), i32x4::from_array([0, 1, 0, 2])); + all_eq!(simd_cttz(y1), U32::<4>::from_array([0, 1, 0, 2])); } } diff --git a/tests/ui/simd/intrinsic/generic-arithmetic-saturating-pass.rs b/tests/ui/simd/intrinsic/generic-arithmetic-saturating-pass.rs index 4d12a312331..a997f123703 100644 --- a/tests/ui/simd/intrinsic/generic-arithmetic-saturating-pass.rs +++ b/tests/ui/simd/intrinsic/generic-arithmetic-saturating-pass.rs @@ -4,26 +4,24 @@ #![allow(non_camel_case_types)] #![feature(repr_simd, core_intrinsics)] -use std::intrinsics::simd::{simd_saturating_add, simd_saturating_sub}; +#[path = "../../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -struct u32x4(pub [u32; 4]); +use std::intrinsics::simd::{simd_saturating_add, simd_saturating_sub}; -#[repr(simd)] -#[derive(Copy, Clone)] -struct I32<const N: usize>([i32; N]); +type I32<const N: usize> = Simd<i32, N>; fn main() { // unsigned { const M: u32 = u32::MAX; - let a = u32x4([1, 2, 3, 4]); - let b = u32x4([2, 4, 6, 8]); - let m = u32x4([M, M, M, M]); - let m1 = u32x4([M - 1, M - 1, M - 1, M - 1]); - let z = u32x4([0, 0, 0, 0]); + let a = u32x4::from_array([1, 2, 3, 4]); + let b = u32x4::from_array([2, 4, 6, 8]); + let m = u32x4::from_array([M, M, M, M]); + let m1 = u32x4::from_array([M - 1, M - 1, M - 1, M - 1]); + let z = u32x4::from_array([0, 0, 0, 0]); unsafe { assert_eq!(simd_saturating_add(z, z), z); @@ -48,41 +46,41 @@ fn main() { const MIN: i32 = i32::MIN; const MAX: i32 = i32::MAX; - let a = I32::<4>([1, 2, 3, 4]); - let b = I32::<4>([2, 4, 6, 8]); - let c = I32::<4>([-1, -2, -3, -4]); - let d = I32::<4>([-2, -4, -6, -8]); + let a = I32::<4>::from_array([1, 2, 3, 4]); + let b = I32::<4>::from_array([2, 4, 6, 8]); + let c = I32::<4>::from_array([-1, -2, -3, -4]); + let d = I32::<4>::from_array([-2, -4, -6, -8]); - let max = I32::<4>([MAX, MAX, MAX, MAX]); - let max1 = I32::<4>([MAX - 1, MAX - 1, MAX - 1, MAX - 1]); - let min = I32::<4>([MIN, MIN, MIN, MIN]); - let min1 = I32::<4>([MIN + 1, MIN + 1, MIN + 1, MIN + 1]); + let max = I32::<4>::from_array([MAX, MAX, MAX, MAX]); + let max1 = I32::<4>::from_array([MAX - 1, MAX - 1, MAX - 1, MAX - 1]); + let min = I32::<4>::from_array([MIN, MIN, MIN, MIN]); + let min1 = I32::<4>::from_array([MIN + 1, MIN + 1, MIN + 1, MIN + 1]); - let z = I32::<4>([0, 0, 0, 0]); + let z = I32::<4>::from_array([0, 0, 0, 0]); unsafe { - assert_eq!(simd_saturating_add(z, z).0, z.0); - assert_eq!(simd_saturating_add(z, a).0, a.0); - assert_eq!(simd_saturating_add(b, z).0, b.0); - assert_eq!(simd_saturating_add(a, a).0, b.0); - assert_eq!(simd_saturating_add(a, max).0, max.0); - assert_eq!(simd_saturating_add(max, b).0, max.0); - assert_eq!(simd_saturating_add(max1, a).0, max.0); - assert_eq!(simd_saturating_add(min1, z).0, min1.0); - assert_eq!(simd_saturating_add(min, z).0, min.0); - assert_eq!(simd_saturating_add(min1, c).0, min.0); - assert_eq!(simd_saturating_add(min, c).0, min.0); - assert_eq!(simd_saturating_add(min1, d).0, min.0); - assert_eq!(simd_saturating_add(min, d).0, min.0); + assert_eq!(simd_saturating_add(z, z), z); + assert_eq!(simd_saturating_add(z, a), a); + assert_eq!(simd_saturating_add(b, z), b); + assert_eq!(simd_saturating_add(a, a), b); + assert_eq!(simd_saturating_add(a, max), max); + assert_eq!(simd_saturating_add(max, b), max); + assert_eq!(simd_saturating_add(max1, a), max); + assert_eq!(simd_saturating_add(min1, z), min1); + assert_eq!(simd_saturating_add(min, z), min); + assert_eq!(simd_saturating_add(min1, c), min); + assert_eq!(simd_saturating_add(min, c), min); + assert_eq!(simd_saturating_add(min1, d), min); + assert_eq!(simd_saturating_add(min, d), min); - assert_eq!(simd_saturating_sub(b, z).0, b.0); - assert_eq!(simd_saturating_sub(b, a).0, a.0); - assert_eq!(simd_saturating_sub(a, a).0, z.0); - assert_eq!(simd_saturating_sub(a, b).0, c.0); - assert_eq!(simd_saturating_sub(z, max).0, min1.0); - assert_eq!(simd_saturating_sub(min1, z).0, min1.0); - assert_eq!(simd_saturating_sub(min1, a).0, min.0); - assert_eq!(simd_saturating_sub(min1, b).0, min.0); + assert_eq!(simd_saturating_sub(b, z), b); + assert_eq!(simd_saturating_sub(b, a), a); + assert_eq!(simd_saturating_sub(a, a), z); + assert_eq!(simd_saturating_sub(a, b), c); + assert_eq!(simd_saturating_sub(z, max), min1); + assert_eq!(simd_saturating_sub(min1, z), min1); + assert_eq!(simd_saturating_sub(min1, a), min); + assert_eq!(simd_saturating_sub(min1, b), min); } } } diff --git a/tests/ui/simd/intrinsic/generic-as.rs b/tests/ui/simd/intrinsic/generic-as.rs index da53211cbc7..f9ed416b6ff 100644 --- a/tests/ui/simd/intrinsic/generic-as.rs +++ b/tests/ui/simd/intrinsic/generic-as.rs @@ -2,45 +2,47 @@ #![feature(repr_simd, core_intrinsics)] +#[path = "../../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; + use std::intrinsics::simd::simd_as; -#[derive(Copy, Clone)] -#[repr(simd)] -struct V<T>([T; 2]); +type V<T> = Simd<T, 2>; fn main() { unsafe { - let u = V::<u32>([u32::MIN, u32::MAX]); + let u: V::<u32> = Simd([u32::MIN, u32::MAX]); let i: V<i16> = simd_as(u); - assert_eq!(i.0[0], u.0[0] as i16); - assert_eq!(i.0[1], u.0[1] as i16); + assert_eq!(i[0], u[0] as i16); + assert_eq!(i[1], u[1] as i16); } unsafe { - let f = V::<f32>([f32::MIN, f32::MAX]); + let f: V::<f32> = Simd([f32::MIN, f32::MAX]); let i: V<i16> = simd_as(f); - assert_eq!(i.0[0], f.0[0] as i16); - assert_eq!(i.0[1], f.0[1] as i16); + assert_eq!(i[0], f[0] as i16); + assert_eq!(i[1], f[1] as i16); } unsafe { - let f = V::<f32>([f32::MIN, f32::MAX]); + let f: V::<f32> = Simd([f32::MIN, f32::MAX]); let u: V<u8> = simd_as(f); - assert_eq!(u.0[0], f.0[0] as u8); - assert_eq!(u.0[1], f.0[1] as u8); + assert_eq!(u[0], f[0] as u8); + assert_eq!(u[1], f[1] as u8); } unsafe { - let f = V::<f64>([f64::MIN, f64::MAX]); + let f: V::<f64> = Simd([f64::MIN, f64::MAX]); let i: V<isize> = simd_as(f); - assert_eq!(i.0[0], f.0[0] as isize); - assert_eq!(i.0[1], f.0[1] as isize); + assert_eq!(i[0], f[0] as isize); + assert_eq!(i[1], f[1] as isize); } unsafe { - let f = V::<f64>([f64::MIN, f64::MAX]); + let f: V::<f64> = Simd([f64::MIN, f64::MAX]); let u: V<usize> = simd_as(f); - assert_eq!(u.0[0], f.0[0] as usize); - assert_eq!(u.0[1], f.0[1] as usize); + assert_eq!(u[0], f[0] as usize); + assert_eq!(u[1], f[1] as usize); } } diff --git a/tests/ui/simd/intrinsic/generic-bswap-byte.rs b/tests/ui/simd/intrinsic/generic-bswap-byte.rs index 903a07656a7..d30a560b1c2 100644 --- a/tests/ui/simd/intrinsic/generic-bswap-byte.rs +++ b/tests/ui/simd/intrinsic/generic-bswap-byte.rs @@ -2,19 +2,15 @@ #![feature(repr_simd, core_intrinsics)] #![allow(non_camel_case_types)] -use std::intrinsics::simd::simd_bswap; - -#[repr(simd)] -#[derive(Copy, Clone)] -struct i8x4([i8; 4]); +#[path = "../../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; -#[repr(simd)] -#[derive(Copy, Clone)] -struct u8x4([u8; 4]); +use std::intrinsics::simd::simd_bswap; fn main() { unsafe { - assert_eq!(simd_bswap(i8x4([0, 1, 2, 3])).0, [0, 1, 2, 3]); - assert_eq!(simd_bswap(u8x4([0, 1, 2, 3])).0, [0, 1, 2, 3]); + assert_eq!(simd_bswap(i8x4::from_array([0, 1, 2, 3])).into_array(), [0, 1, 2, 3]); + assert_eq!(simd_bswap(u8x4::from_array([0, 1, 2, 3])).into_array(), [0, 1, 2, 3]); } } diff --git a/tests/ui/simd/intrinsic/generic-cast-pass.rs b/tests/ui/simd/intrinsic/generic-cast-pass.rs index 7a4663bcad2..0c3b00d65bf 100644 --- a/tests/ui/simd/intrinsic/generic-cast-pass.rs +++ b/tests/ui/simd/intrinsic/generic-cast-pass.rs @@ -2,55 +2,57 @@ #![feature(repr_simd, core_intrinsics)] +#[path = "../../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; + use std::intrinsics::simd::simd_cast; use std::cmp::{max, min}; -#[derive(Copy, Clone)] -#[repr(simd)] -struct V<T>([T; 2]); +type V<T> = Simd<T, 2>; fn main() { unsafe { - let u = V::<u32>([i16::MIN as u32, i16::MAX as u32]); + let u: V::<u32> = Simd([i16::MIN as u32, i16::MAX as u32]); let i: V<i16> = simd_cast(u); - assert_eq!(i.0[0], u.0[0] as i16); - assert_eq!(i.0[1], u.0[1] as i16); + assert_eq!(i[0], u[0] as i16); + assert_eq!(i[1], u[1] as i16); } unsafe { - let f = V::<f32>([i16::MIN as f32, i16::MAX as f32]); + let f: V::<f32> = Simd([i16::MIN as f32, i16::MAX as f32]); let i: V<i16> = simd_cast(f); - assert_eq!(i.0[0], f.0[0] as i16); - assert_eq!(i.0[1], f.0[1] as i16); + assert_eq!(i[0], f[0] as i16); + assert_eq!(i[1], f[1] as i16); } unsafe { - let f = V::<f32>([u8::MIN as f32, u8::MAX as f32]); + let f: V::<f32> = Simd([u8::MIN as f32, u8::MAX as f32]); let u: V<u8> = simd_cast(f); - assert_eq!(u.0[0], f.0[0] as u8); - assert_eq!(u.0[1], f.0[1] as u8); + assert_eq!(u[0], f[0] as u8); + assert_eq!(u[1], f[1] as u8); } unsafe { // We would like to do isize::MIN..=isize::MAX, but those values are not representable in // an f64, so we clamp to the range of an i32 to prevent running into UB. - let f = V::<f64>([ + let f: V::<f64> = Simd([ max(isize::MIN, i32::MIN as isize) as f64, min(isize::MAX, i32::MAX as isize) as f64, ]); let i: V<isize> = simd_cast(f); - assert_eq!(i.0[0], f.0[0] as isize); - assert_eq!(i.0[1], f.0[1] as isize); + assert_eq!(i[0], f[0] as isize); + assert_eq!(i[1], f[1] as isize); } unsafe { - let f = V::<f64>([ + let f: V::<f64> = Simd([ max(usize::MIN, u32::MIN as usize) as f64, min(usize::MAX, u32::MAX as usize) as f64, ]); let u: V<usize> = simd_cast(f); - assert_eq!(u.0[0], f.0[0] as usize); - assert_eq!(u.0[1], f.0[1] as usize); + assert_eq!(u[0], f[0] as usize); + assert_eq!(u[1], f[1] as usize); } } diff --git a/tests/ui/simd/intrinsic/generic-cast-pointer-width.rs b/tests/ui/simd/intrinsic/generic-cast-pointer-width.rs index ea34e9ffeb8..594d1d25d16 100644 --- a/tests/ui/simd/intrinsic/generic-cast-pointer-width.rs +++ b/tests/ui/simd/intrinsic/generic-cast-pointer-width.rs @@ -1,18 +1,24 @@ //@ run-pass #![feature(repr_simd, core_intrinsics)] +#[path = "../../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; + use std::intrinsics::simd::simd_cast; -#[derive(Copy, Clone)] -#[repr(simd)] -struct V<T>([T; 4]); +type V<T> = Simd<T, 4>; fn main() { - let u = V::<usize>([0, 1, 2, 3]); + let u: V::<usize> = Simd([0, 1, 2, 3]); let uu32: V<u32> = unsafe { simd_cast(u) }; let ui64: V<i64> = unsafe { simd_cast(u) }; - for (u, (uu32, ui64)) in u.0.iter().zip(uu32.0.iter().zip(ui64.0.iter())) { + for (u, (uu32, ui64)) in u + .as_array() + .iter() + .zip(uu32.as_array().iter().zip(ui64.as_array().iter())) + { assert_eq!(*u as u32, *uu32); assert_eq!(*u as i64, *ui64); } diff --git a/tests/ui/simd/intrinsic/generic-comparison-pass.rs b/tests/ui/simd/intrinsic/generic-comparison-pass.rs index 50a05eecb03..3e803e8f603 100644 --- a/tests/ui/simd/intrinsic/generic-comparison-pass.rs +++ b/tests/ui/simd/intrinsic/generic-comparison-pass.rs @@ -3,17 +3,11 @@ #![feature(repr_simd, core_intrinsics, macro_metavar_expr_concat)] #![allow(non_camel_case_types)] -use std::intrinsics::simd::{simd_eq, simd_ge, simd_gt, simd_le, simd_lt, simd_ne}; +#[path = "../../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; -#[repr(simd)] -#[derive(Copy, Clone)] -struct i32x4([i32; 4]); -#[repr(simd)] -#[derive(Copy, Clone)] -struct u32x4(pub [u32; 4]); -#[repr(simd)] -#[derive(Copy, Clone)] -struct f32x4(pub [f32; 4]); +use std::intrinsics::simd::{simd_eq, simd_ge, simd_gt, simd_le, simd_lt, simd_ne}; macro_rules! cmp { ($method: ident($lhs: expr, $rhs: expr)) => {{ @@ -21,10 +15,11 @@ macro_rules! cmp { let rhs = $rhs; let e: u32x4 = ${concat(simd_, $method)}($lhs, $rhs); // assume the scalar version is correct/the behaviour we want. - assert!((e.0[0] != 0) == lhs.0[0].$method(&rhs.0[0])); - assert!((e.0[1] != 0) == lhs.0[1].$method(&rhs.0[1])); - assert!((e.0[2] != 0) == lhs.0[2].$method(&rhs.0[2])); - assert!((e.0[3] != 0) == lhs.0[3].$method(&rhs.0[3])); + let (lhs, rhs, e) = (lhs.as_array(), rhs.as_array(), e.as_array()); + assert!((e[0] != 0) == lhs[0].$method(&rhs[0])); + assert!((e[1] != 0) == lhs[1].$method(&rhs[1])); + assert!((e[2] != 0) == lhs[2].$method(&rhs[2])); + assert!((e[3] != 0) == lhs[3].$method(&rhs[3])); }}; } macro_rules! tests { @@ -53,17 +48,17 @@ macro_rules! tests { fn main() { // 13 vs. -100 tests that we get signed vs. unsigned comparisons // correct (i32: 13 > -100, u32: 13 < -100). let i1 = i32x4(10, -11, 12, 13); - let i1 = i32x4([10, -11, 12, 13]); - let i2 = i32x4([5, -5, 20, -100]); - let i3 = i32x4([10, -11, 20, -100]); + let i1 = i32x4::from_array([10, -11, 12, 13]); + let i2 = i32x4::from_array([5, -5, 20, -100]); + let i3 = i32x4::from_array([10, -11, 20, -100]); - let u1 = u32x4([10, !11 + 1, 12, 13]); - let u2 = u32x4([5, !5 + 1, 20, !100 + 1]); - let u3 = u32x4([10, !11 + 1, 20, !100 + 1]); + let u1 = u32x4::from_array([10, !11 + 1, 12, 13]); + let u2 = u32x4::from_array([5, !5 + 1, 20, !100 + 1]); + let u3 = u32x4::from_array([10, !11 + 1, 20, !100 + 1]); - let f1 = f32x4([10.0, -11.0, 12.0, 13.0]); - let f2 = f32x4([5.0, -5.0, 20.0, -100.0]); - let f3 = f32x4([10.0, -11.0, 20.0, -100.0]); + let f1 = f32x4::from_array([10.0, -11.0, 12.0, 13.0]); + let f2 = f32x4::from_array([5.0, -5.0, 20.0, -100.0]); + let f3 = f32x4::from_array([10.0, -11.0, 20.0, -100.0]); unsafe { tests! { @@ -84,7 +79,7 @@ fn main() { // NAN comparisons are special: // -11 (*) 13 // -5 -100 (*) - let f4 = f32x4([f32::NAN, f1.0[1], f32::NAN, f2.0[3]]); + let f4 = f32x4::from_array([f32::NAN, f1[1], f32::NAN, f2[3]]); unsafe { tests! { diff --git a/tests/ui/simd/intrinsic/generic-elements-pass.rs b/tests/ui/simd/intrinsic/generic-elements-pass.rs index e4d47cdb381..f441d992e11 100644 --- a/tests/ui/simd/intrinsic/generic-elements-pass.rs +++ b/tests/ui/simd/intrinsic/generic-elements-pass.rs @@ -2,24 +2,15 @@ #![feature(repr_simd, intrinsics, core_intrinsics)] +#[path = "../../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; + use std::intrinsics::simd::{ simd_extract, simd_extract_dyn, simd_insert, simd_insert_dyn, simd_shuffle, }; #[repr(simd)] -#[derive(Copy, Clone, Debug, PartialEq)] -#[allow(non_camel_case_types)] -struct i32x2([i32; 2]); -#[repr(simd)] -#[derive(Copy, Clone, Debug, PartialEq)] -#[allow(non_camel_case_types)] -struct i32x4([i32; 4]); -#[repr(simd)] -#[derive(Copy, Clone, Debug, PartialEq)] -#[allow(non_camel_case_types)] -struct i32x8([i32; 8]); - -#[repr(simd)] struct SimdShuffleIdx<const LEN: usize>([u32; LEN]); macro_rules! all_eq { @@ -34,26 +25,26 @@ macro_rules! all_eq { } fn main() { - let x2 = i32x2([20, 21]); - let x4 = i32x4([40, 41, 42, 43]); - let x8 = i32x8([80, 81, 82, 83, 84, 85, 86, 87]); + let x2 = i32x2::from_array([20, 21]); + let x4 = i32x4::from_array([40, 41, 42, 43]); + let x8 = i32x8::from_array([80, 81, 82, 83, 84, 85, 86, 87]); unsafe { - all_eq!(simd_insert(x2, 0, 100), i32x2([100, 21])); - all_eq!(simd_insert(x2, 1, 100), i32x2([20, 100])); - - all_eq!(simd_insert(x4, 0, 100), i32x4([100, 41, 42, 43])); - all_eq!(simd_insert(x4, 1, 100), i32x4([40, 100, 42, 43])); - all_eq!(simd_insert(x4, 2, 100), i32x4([40, 41, 100, 43])); - all_eq!(simd_insert(x4, 3, 100), i32x4([40, 41, 42, 100])); - - all_eq!(simd_insert(x8, 0, 100), i32x8([100, 81, 82, 83, 84, 85, 86, 87])); - all_eq!(simd_insert(x8, 1, 100), i32x8([80, 100, 82, 83, 84, 85, 86, 87])); - all_eq!(simd_insert(x8, 2, 100), i32x8([80, 81, 100, 83, 84, 85, 86, 87])); - all_eq!(simd_insert(x8, 3, 100), i32x8([80, 81, 82, 100, 84, 85, 86, 87])); - all_eq!(simd_insert(x8, 4, 100), i32x8([80, 81, 82, 83, 100, 85, 86, 87])); - all_eq!(simd_insert(x8, 5, 100), i32x8([80, 81, 82, 83, 84, 100, 86, 87])); - all_eq!(simd_insert(x8, 6, 100), i32x8([80, 81, 82, 83, 84, 85, 100, 87])); - all_eq!(simd_insert(x8, 7, 100), i32x8([80, 81, 82, 83, 84, 85, 86, 100])); + all_eq!(simd_insert(x2, 0, 100), i32x2::from_array([100, 21])); + all_eq!(simd_insert(x2, 1, 100), i32x2::from_array([20, 100])); + + all_eq!(simd_insert(x4, 0, 100), i32x4::from_array([100, 41, 42, 43])); + all_eq!(simd_insert(x4, 1, 100), i32x4::from_array([40, 100, 42, 43])); + all_eq!(simd_insert(x4, 2, 100), i32x4::from_array([40, 41, 100, 43])); + all_eq!(simd_insert(x4, 3, 100), i32x4::from_array([40, 41, 42, 100])); + + all_eq!(simd_insert(x8, 0, 100), i32x8::from_array([100, 81, 82, 83, 84, 85, 86, 87])); + all_eq!(simd_insert(x8, 1, 100), i32x8::from_array([80, 100, 82, 83, 84, 85, 86, 87])); + all_eq!(simd_insert(x8, 2, 100), i32x8::from_array([80, 81, 100, 83, 84, 85, 86, 87])); + all_eq!(simd_insert(x8, 3, 100), i32x8::from_array([80, 81, 82, 100, 84, 85, 86, 87])); + all_eq!(simd_insert(x8, 4, 100), i32x8::from_array([80, 81, 82, 83, 100, 85, 86, 87])); + all_eq!(simd_insert(x8, 5, 100), i32x8::from_array([80, 81, 82, 83, 84, 100, 86, 87])); + all_eq!(simd_insert(x8, 6, 100), i32x8::from_array([80, 81, 82, 83, 84, 85, 100, 87])); + all_eq!(simd_insert(x8, 7, 100), i32x8::from_array([80, 81, 82, 83, 84, 85, 86, 100])); all_eq!(simd_extract(x2, 0), 20); all_eq!(simd_extract(x2, 1), 21); @@ -73,22 +64,22 @@ fn main() { all_eq!(simd_extract(x8, 7), 87); } unsafe { - all_eq!(simd_insert_dyn(x2, 0, 100), i32x2([100, 21])); - all_eq!(simd_insert_dyn(x2, 1, 100), i32x2([20, 100])); - - all_eq!(simd_insert_dyn(x4, 0, 100), i32x4([100, 41, 42, 43])); - all_eq!(simd_insert_dyn(x4, 1, 100), i32x4([40, 100, 42, 43])); - all_eq!(simd_insert_dyn(x4, 2, 100), i32x4([40, 41, 100, 43])); - all_eq!(simd_insert_dyn(x4, 3, 100), i32x4([40, 41, 42, 100])); - - all_eq!(simd_insert_dyn(x8, 0, 100), i32x8([100, 81, 82, 83, 84, 85, 86, 87])); - all_eq!(simd_insert_dyn(x8, 1, 100), i32x8([80, 100, 82, 83, 84, 85, 86, 87])); - all_eq!(simd_insert_dyn(x8, 2, 100), i32x8([80, 81, 100, 83, 84, 85, 86, 87])); - all_eq!(simd_insert_dyn(x8, 3, 100), i32x8([80, 81, 82, 100, 84, 85, 86, 87])); - all_eq!(simd_insert_dyn(x8, 4, 100), i32x8([80, 81, 82, 83, 100, 85, 86, 87])); - all_eq!(simd_insert_dyn(x8, 5, 100), i32x8([80, 81, 82, 83, 84, 100, 86, 87])); - all_eq!(simd_insert_dyn(x8, 6, 100), i32x8([80, 81, 82, 83, 84, 85, 100, 87])); - all_eq!(simd_insert_dyn(x8, 7, 100), i32x8([80, 81, 82, 83, 84, 85, 86, 100])); + all_eq!(simd_insert_dyn(x2, 0, 100), i32x2::from_array([100, 21])); + all_eq!(simd_insert_dyn(x2, 1, 100), i32x2::from_array([20, 100])); + + all_eq!(simd_insert_dyn(x4, 0, 100), i32x4::from_array([100, 41, 42, 43])); + all_eq!(simd_insert_dyn(x4, 1, 100), i32x4::from_array([40, 100, 42, 43])); + all_eq!(simd_insert_dyn(x4, 2, 100), i32x4::from_array([40, 41, 100, 43])); + all_eq!(simd_insert_dyn(x4, 3, 100), i32x4::from_array([40, 41, 42, 100])); + + all_eq!(simd_insert_dyn(x8, 0, 100), i32x8::from_array([100, 81, 82, 83, 84, 85, 86, 87])); + all_eq!(simd_insert_dyn(x8, 1, 100), i32x8::from_array([80, 100, 82, 83, 84, 85, 86, 87])); + all_eq!(simd_insert_dyn(x8, 2, 100), i32x8::from_array([80, 81, 100, 83, 84, 85, 86, 87])); + all_eq!(simd_insert_dyn(x8, 3, 100), i32x8::from_array([80, 81, 82, 100, 84, 85, 86, 87])); + all_eq!(simd_insert_dyn(x8, 4, 100), i32x8::from_array([80, 81, 82, 83, 100, 85, 86, 87])); + all_eq!(simd_insert_dyn(x8, 5, 100), i32x8::from_array([80, 81, 82, 83, 84, 100, 86, 87])); + all_eq!(simd_insert_dyn(x8, 6, 100), i32x8::from_array([80, 81, 82, 83, 84, 85, 100, 87])); + all_eq!(simd_insert_dyn(x8, 7, 100), i32x8::from_array([80, 81, 82, 83, 84, 85, 86, 100])); all_eq!(simd_extract_dyn(x2, 0), 20); all_eq!(simd_extract_dyn(x2, 1), 21); @@ -108,38 +99,47 @@ fn main() { all_eq!(simd_extract_dyn(x8, 7), 87); } - let y2 = i32x2([120, 121]); - let y4 = i32x4([140, 141, 142, 143]); - let y8 = i32x8([180, 181, 182, 183, 184, 185, 186, 187]); + let y2 = i32x2::from_array([120, 121]); + let y4 = i32x4::from_array([140, 141, 142, 143]); + let y8 = i32x8::from_array([180, 181, 182, 183, 184, 185, 186, 187]); unsafe { - all_eq!(simd_shuffle(x2, y2, const { SimdShuffleIdx([3u32, 0]) }), i32x2([121, 20])); + all_eq!( + simd_shuffle(x2, y2, const { SimdShuffleIdx([3u32, 0]) }), + i32x2::from_array([121, 20]) + ); all_eq!( simd_shuffle(x2, y2, const { SimdShuffleIdx([3u32, 0, 1, 2]) }), - i32x4([121, 20, 21, 120]) + i32x4::from_array([121, 20, 21, 120]) ); all_eq!( simd_shuffle(x2, y2, const { SimdShuffleIdx([3u32, 0, 1, 2, 1, 2, 3, 0]) }), - i32x8([121, 20, 21, 120, 21, 120, 121, 20]) + i32x8::from_array([121, 20, 21, 120, 21, 120, 121, 20]) ); - all_eq!(simd_shuffle(x4, y4, const { SimdShuffleIdx([7u32, 2]) }), i32x2([143, 42])); + all_eq!( + simd_shuffle(x4, y4, const { SimdShuffleIdx([7u32, 2]) }), + i32x2::from_array([143, 42]) + ); all_eq!( simd_shuffle(x4, y4, const { SimdShuffleIdx([7u32, 2, 5, 0]) }), - i32x4([143, 42, 141, 40]) + i32x4::from_array([143, 42, 141, 40]) ); all_eq!( simd_shuffle(x4, y4, const { SimdShuffleIdx([7u32, 2, 5, 0, 3, 6, 4, 1]) }), - i32x8([143, 42, 141, 40, 43, 142, 140, 41]) + i32x8::from_array([143, 42, 141, 40, 43, 142, 140, 41]) ); - all_eq!(simd_shuffle(x8, y8, const { SimdShuffleIdx([11u32, 5]) }), i32x2([183, 85])); + all_eq!( + simd_shuffle(x8, y8, const { SimdShuffleIdx([11u32, 5]) }), + i32x2::from_array([183, 85]) + ); all_eq!( simd_shuffle(x8, y8, const { SimdShuffleIdx([11u32, 5, 15, 0]) }), - i32x4([183, 85, 187, 80]) + i32x4::from_array([183, 85, 187, 80]) ); all_eq!( simd_shuffle(x8, y8, const { SimdShuffleIdx([11u32, 5, 15, 0, 3, 8, 12, 1]) }), - i32x8([183, 85, 187, 80, 83, 180, 184, 81]) + i32x8::from_array([183, 85, 187, 80, 83, 180, 184, 81]) ); } } diff --git a/tests/ui/simd/intrinsic/generic-gather-scatter-pass.rs b/tests/ui/simd/intrinsic/generic-gather-scatter-pass.rs index b98d4d6575b..c2418c019ed 100644 --- a/tests/ui/simd/intrinsic/generic-gather-scatter-pass.rs +++ b/tests/ui/simd/intrinsic/generic-gather-scatter-pass.rs @@ -6,24 +6,26 @@ #![feature(repr_simd, core_intrinsics)] #![allow(non_camel_case_types)] +#[path = "../../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; + use std::intrinsics::simd::{simd_gather, simd_scatter}; -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -struct x4<T>(pub [T; 4]); +type x4<T> = Simd<T, 4>; fn main() { let mut x = [0_f32, 1., 2., 3., 4., 5., 6., 7.]; - let default = x4([-3_f32, -3., -3., -3.]); - let s_strided = x4([0_f32, 2., -3., 6.]); - let mask = x4([-1_i32, -1, 0, -1]); + let default = x4::from_array([-3_f32, -3., -3., -3.]); + let s_strided = x4::from_array([0_f32, 2., -3., 6.]); + let mask = x4::from_array([-1_i32, -1, 0, -1]); // reading from *const unsafe { let pointer = x.as_ptr(); let pointers = - x4([pointer.offset(0), pointer.offset(2), pointer.offset(4), pointer.offset(6)]); + x4::from_array(std::array::from_fn(|i| pointer.add(i * 2))); let r_strided = simd_gather(default, pointers, mask); @@ -34,7 +36,7 @@ fn main() { unsafe { let pointer = x.as_mut_ptr(); let pointers = - x4([pointer.offset(0), pointer.offset(2), pointer.offset(4), pointer.offset(6)]); + x4::from_array(std::array::from_fn(|i| pointer.add(i * 2))); let r_strided = simd_gather(default, pointers, mask); @@ -45,9 +47,9 @@ fn main() { unsafe { let pointer = x.as_mut_ptr(); let pointers = - x4([pointer.offset(0), pointer.offset(2), pointer.offset(4), pointer.offset(6)]); + x4::from_array(std::array::from_fn(|i| pointer.add(i * 2))); - let values = x4([42_f32, 43_f32, 44_f32, 45_f32]); + let values = x4::from_array([42_f32, 43_f32, 44_f32, 45_f32]); simd_scatter(values, pointers, mask); assert_eq!(x, [42., 1., 43., 3., 4., 5., 45., 7.]); @@ -65,14 +67,14 @@ fn main() { &x[7] as *const f32, ]; - let default = x4([y[0], y[0], y[0], y[0]]); - let s_strided = x4([y[0], y[2], y[0], y[6]]); + let default = x4::from_array([y[0], y[0], y[0], y[0]]); + let s_strided = x4::from_array([y[0], y[2], y[0], y[6]]); // reading from *const unsafe { let pointer = y.as_ptr(); let pointers = - x4([pointer.offset(0), pointer.offset(2), pointer.offset(4), pointer.offset(6)]); + x4::from_array(std::array::from_fn(|i| pointer.add(i * 2))); let r_strided = simd_gather(default, pointers, mask); @@ -83,7 +85,7 @@ fn main() { unsafe { let pointer = y.as_mut_ptr(); let pointers = - x4([pointer.offset(0), pointer.offset(2), pointer.offset(4), pointer.offset(6)]); + x4::from_array(std::array::from_fn(|i| pointer.add(i * 2))); let r_strided = simd_gather(default, pointers, mask); @@ -94,9 +96,9 @@ fn main() { unsafe { let pointer = y.as_mut_ptr(); let pointers = - x4([pointer.offset(0), pointer.offset(2), pointer.offset(4), pointer.offset(6)]); + x4::from_array(std::array::from_fn(|i| pointer.add(i * 2))); - let values = x4([y[7], y[6], y[5], y[1]]); + let values = x4::from_array([y[7], y[6], y[5], y[1]]); simd_scatter(values, pointers, mask); let s = [ diff --git a/tests/ui/simd/intrinsic/generic-select-pass.rs b/tests/ui/simd/intrinsic/generic-select-pass.rs index 0e5f7c4902f..ff2d70d6a97 100644 --- a/tests/ui/simd/intrinsic/generic-select-pass.rs +++ b/tests/ui/simd/intrinsic/generic-select-pass.rs @@ -6,38 +6,24 @@ // Test that the simd_select intrinsics produces correct results. #![feature(repr_simd, core_intrinsics)] -use std::intrinsics::simd::{simd_select, simd_select_bitmask}; - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -struct i32x4(pub [i32; 4]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -struct u32x4(pub [u32; 4]); +#[path = "../../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -struct u32x8([u32; 8]); - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -struct f32x4(pub [f32; 4]); +use std::intrinsics::simd::{simd_select, simd_select_bitmask}; -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -struct b8x4(pub [i8; 4]); +type b8x4 = i8x4; fn main() { - let m0 = b8x4([!0, !0, !0, !0]); - let m1 = b8x4([0, 0, 0, 0]); - let m2 = b8x4([!0, !0, 0, 0]); - let m3 = b8x4([0, 0, !0, !0]); - let m4 = b8x4([!0, 0, !0, 0]); + let m0 = b8x4::from_array([!0, !0, !0, !0]); + let m1 = b8x4::from_array([0, 0, 0, 0]); + let m2 = b8x4::from_array([!0, !0, 0, 0]); + let m3 = b8x4::from_array([0, 0, !0, !0]); + let m4 = b8x4::from_array([!0, 0, !0, 0]); unsafe { - let a = i32x4([1, -2, 3, 4]); - let b = i32x4([5, 6, -7, 8]); + let a = i32x4::from_array([1, -2, 3, 4]); + let b = i32x4::from_array([5, 6, -7, 8]); let r: i32x4 = simd_select(m0, a, b); let e = a; @@ -48,21 +34,21 @@ fn main() { assert_eq!(r, e); let r: i32x4 = simd_select(m2, a, b); - let e = i32x4([1, -2, -7, 8]); + let e = i32x4::from_array([1, -2, -7, 8]); assert_eq!(r, e); let r: i32x4 = simd_select(m3, a, b); - let e = i32x4([5, 6, 3, 4]); + let e = i32x4::from_array([5, 6, 3, 4]); assert_eq!(r, e); let r: i32x4 = simd_select(m4, a, b); - let e = i32x4([1, 6, 3, 8]); + let e = i32x4::from_array([1, 6, 3, 8]); assert_eq!(r, e); } unsafe { - let a = u32x4([1, 2, 3, 4]); - let b = u32x4([5, 6, 7, 8]); + let a = u32x4::from_array([1, 2, 3, 4]); + let b = u32x4::from_array([5, 6, 7, 8]); let r: u32x4 = simd_select(m0, a, b); let e = a; @@ -73,21 +59,21 @@ fn main() { assert_eq!(r, e); let r: u32x4 = simd_select(m2, a, b); - let e = u32x4([1, 2, 7, 8]); + let e = u32x4::from_array([1, 2, 7, 8]); assert_eq!(r, e); let r: u32x4 = simd_select(m3, a, b); - let e = u32x4([5, 6, 3, 4]); + let e = u32x4::from_array([5, 6, 3, 4]); assert_eq!(r, e); let r: u32x4 = simd_select(m4, a, b); - let e = u32x4([1, 6, 3, 8]); + let e = u32x4::from_array([1, 6, 3, 8]); assert_eq!(r, e); } unsafe { - let a = f32x4([1., 2., 3., 4.]); - let b = f32x4([5., 6., 7., 8.]); + let a = f32x4::from_array([1., 2., 3., 4.]); + let b = f32x4::from_array([5., 6., 7., 8.]); let r: f32x4 = simd_select(m0, a, b); let e = a; @@ -98,23 +84,23 @@ fn main() { assert_eq!(r, e); let r: f32x4 = simd_select(m2, a, b); - let e = f32x4([1., 2., 7., 8.]); + let e = f32x4::from_array([1., 2., 7., 8.]); assert_eq!(r, e); let r: f32x4 = simd_select(m3, a, b); - let e = f32x4([5., 6., 3., 4.]); + let e = f32x4::from_array([5., 6., 3., 4.]); assert_eq!(r, e); let r: f32x4 = simd_select(m4, a, b); - let e = f32x4([1., 6., 3., 8.]); + let e = f32x4::from_array([1., 6., 3., 8.]); assert_eq!(r, e); } unsafe { let t = !0 as i8; let f = 0 as i8; - let a = b8x4([t, f, t, f]); - let b = b8x4([f, f, f, t]); + let a = b8x4::from_array([t, f, t, f]); + let b = b8x4::from_array([f, f, f, t]); let r: b8x4 = simd_select(m0, a, b); let e = a; @@ -125,21 +111,21 @@ fn main() { assert_eq!(r, e); let r: b8x4 = simd_select(m2, a, b); - let e = b8x4([t, f, f, t]); + let e = b8x4::from_array([t, f, f, t]); assert_eq!(r, e); let r: b8x4 = simd_select(m3, a, b); - let e = b8x4([f, f, t, f]); + let e = b8x4::from_array([f, f, t, f]); assert_eq!(r, e); let r: b8x4 = simd_select(m4, a, b); - let e = b8x4([t, f, t, t]); + let e = b8x4::from_array([t, f, t, t]); assert_eq!(r, e); } unsafe { - let a = u32x8([0, 1, 2, 3, 4, 5, 6, 7]); - let b = u32x8([8, 9, 10, 11, 12, 13, 14, 15]); + let a = u32x8::from_array([0, 1, 2, 3, 4, 5, 6, 7]); + let b = u32x8::from_array([8, 9, 10, 11, 12, 13, 14, 15]); let r: u32x8 = simd_select_bitmask(0u8, a, b); let e = b; @@ -150,21 +136,21 @@ fn main() { assert_eq!(r, e); let r: u32x8 = simd_select_bitmask(0b01010101u8, a, b); - let e = u32x8([0, 9, 2, 11, 4, 13, 6, 15]); + let e = u32x8::from_array([0, 9, 2, 11, 4, 13, 6, 15]); assert_eq!(r, e); let r: u32x8 = simd_select_bitmask(0b10101010u8, a, b); - let e = u32x8([8, 1, 10, 3, 12, 5, 14, 7]); + let e = u32x8::from_array([8, 1, 10, 3, 12, 5, 14, 7]); assert_eq!(r, e); let r: u32x8 = simd_select_bitmask(0b11110000u8, a, b); - let e = u32x8([8, 9, 10, 11, 4, 5, 6, 7]); + let e = u32x8::from_array([8, 9, 10, 11, 4, 5, 6, 7]); assert_eq!(r, e); } unsafe { - let a = u32x4([0, 1, 2, 3]); - let b = u32x4([4, 5, 6, 7]); + let a = u32x4::from_array([0, 1, 2, 3]); + let b = u32x4::from_array([4, 5, 6, 7]); let r: u32x4 = simd_select_bitmask(0u8, a, b); let e = b; @@ -175,15 +161,15 @@ fn main() { assert_eq!(r, e); let r: u32x4 = simd_select_bitmask(0b0101u8, a, b); - let e = u32x4([0, 5, 2, 7]); + let e = u32x4::from_array([0, 5, 2, 7]); assert_eq!(r, e); let r: u32x4 = simd_select_bitmask(0b1010u8, a, b); - let e = u32x4([4, 1, 6, 3]); + let e = u32x4::from_array([4, 1, 6, 3]); assert_eq!(r, e); let r: u32x4 = simd_select_bitmask(0b1100u8, a, b); - let e = u32x4([4, 5, 2, 3]); + let e = u32x4::from_array([4, 5, 2, 3]); assert_eq!(r, e); } } diff --git a/tests/ui/simd/intrinsic/inlining-issue67557.rs b/tests/ui/simd/intrinsic/inlining-issue67557.rs index 13e7266b2a5..14f180425d8 100644 --- a/tests/ui/simd/intrinsic/inlining-issue67557.rs +++ b/tests/ui/simd/intrinsic/inlining-issue67557.rs @@ -5,11 +5,13 @@ //@ compile-flags: -Zmir-opt-level=4 #![feature(core_intrinsics, repr_simd)] +#[path = "../../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; + use std::intrinsics::simd::simd_shuffle; -#[repr(simd)] -#[derive(Debug, PartialEq)] -struct Simd2([u8; 2]); +type Simd2 = u8x2; #[repr(simd)] struct SimdShuffleIdx<const LEN: usize>([u32; LEN]); @@ -17,7 +19,11 @@ struct SimdShuffleIdx<const LEN: usize>([u32; LEN]); fn main() { unsafe { const IDX: SimdShuffleIdx<2> = SimdShuffleIdx([0, 1]); - let p_res: Simd2 = simd_shuffle(Simd2([10, 11]), Simd2([12, 13]), IDX); + let p_res: Simd2 = simd_shuffle( + Simd2::from_array([10, 11]), + Simd2::from_array([12, 13]), + IDX, + ); let a_res: Simd2 = inline_me(); assert_10_11(p_res); @@ -27,16 +33,16 @@ fn main() { #[inline(never)] fn assert_10_11(x: Simd2) { - assert_eq!(x, Simd2([10, 11])); + assert_eq!(x.into_array(), [10, 11]); } #[inline(never)] fn assert_10_13(x: Simd2) { - assert_eq!(x, Simd2([10, 13])); + assert_eq!(x.into_array(), [10, 13]); } #[inline(always)] unsafe fn inline_me() -> Simd2 { const IDX: SimdShuffleIdx<2> = SimdShuffleIdx([0, 3]); - simd_shuffle(Simd2([10, 11]), Simd2([12, 13]), IDX) + simd_shuffle(Simd2::from_array([10, 11]), Simd2::from_array([12, 13]), IDX) } diff --git a/tests/ui/simd/intrinsic/ptr-cast.rs b/tests/ui/simd/intrinsic/ptr-cast.rs index 3a73c0273e1..63b65d83f76 100644 --- a/tests/ui/simd/intrinsic/ptr-cast.rs +++ b/tests/ui/simd/intrinsic/ptr-cast.rs @@ -2,18 +2,20 @@ #![feature(repr_simd, core_intrinsics)] +#[path = "../../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; + use std::intrinsics::simd::{simd_cast_ptr, simd_expose_provenance, simd_with_exposed_provenance}; -#[derive(Copy, Clone)] -#[repr(simd)] -struct V<T>([T; 2]); +type V<T> = Simd<T, 2>; fn main() { unsafe { let mut foo = 4i8; let ptr = &mut foo as *mut i8; - let ptrs = V::<*mut i8>([ptr, core::ptr::null_mut()]); + let ptrs: V::<*mut i8> = Simd([ptr, core::ptr::null_mut()]); // change constness and type let const_ptrs: V<*const u8> = simd_cast_ptr(ptrs); @@ -22,8 +24,8 @@ fn main() { let with_exposed_provenance: V<*mut i8> = simd_with_exposed_provenance(exposed_addr); - assert!(const_ptrs.0 == [ptr as *const u8, core::ptr::null()]); - assert!(exposed_addr.0 == [ptr as usize, 0]); - assert!(with_exposed_provenance.0 == ptrs.0); + assert!(const_ptrs.into_array() == [ptr as *const u8, core::ptr::null()]); + assert!(exposed_addr.into_array() == [ptr as usize, 0]); + assert!(with_exposed_provenance.into_array() == ptrs.into_array()); } } diff --git a/tests/ui/simd/issue-105439.rs b/tests/ui/simd/issue-105439.rs index 0a44f36fb2e..1d57eff341c 100644 --- a/tests/ui/simd/issue-105439.rs +++ b/tests/ui/simd/issue-105439.rs @@ -10,7 +10,9 @@ struct i32x4([i32; 4]); #[inline(always)] fn to_array(a: i32x4) -> [i32; 4] { - a.0 + // This was originally just `a.0`, but that ended up being annoying enough + // that it was banned by <https://github.com/rust-lang/compiler-team/issues/838> + unsafe { std::mem::transmute(a) } } fn main() { diff --git a/tests/ui/simd/issue-39720.rs b/tests/ui/simd/issue-39720.rs index db441e55167..09d6142c920 100644 --- a/tests/ui/simd/issue-39720.rs +++ b/tests/ui/simd/issue-39720.rs @@ -2,16 +2,16 @@ #![feature(repr_simd, core_intrinsics)] -#[repr(simd)] -#[derive(Copy, Clone, Debug)] -pub struct Char3(pub [i8; 3]); +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; -#[repr(simd)] -#[derive(Copy, Clone, Debug)] -pub struct Short3(pub [i16; 3]); +pub type Char3 = Simd<i8, 3>; + +pub type Short3 = Simd<i16, 3>; fn main() { - let cast: Short3 = unsafe { std::intrinsics::simd::simd_cast(Char3([10, -3, -9])) }; + let cast: Short3 = unsafe { std::intrinsics::simd::simd_cast(Char3::from_array([10, -3, -9])) }; println!("{:?}", cast); } diff --git a/tests/ui/simd/issue-85915-simd-ptrs.rs b/tests/ui/simd/issue-85915-simd-ptrs.rs index 4e2379d0525..a74c36fabc1 100644 --- a/tests/ui/simd/issue-85915-simd-ptrs.rs +++ b/tests/ui/simd/issue-85915-simd-ptrs.rs @@ -6,35 +6,27 @@ #![feature(repr_simd, core_intrinsics)] #![allow(non_camel_case_types)] -use std::intrinsics::simd::{simd_gather, simd_scatter}; - -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -struct cptrx4<T>([*const T; 4]); +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -struct mptrx4<T>([*mut T; 4]); +use std::intrinsics::simd::{simd_gather, simd_scatter}; -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -struct f32x4([f32; 4]); +type cptrx4<T> = Simd<*const T, 4>; -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -struct i32x4([i32; 4]); +type mptrx4<T> = Simd<*mut T, 4>; fn main() { let mut x = [0_f32, 1., 2., 3., 4., 5., 6., 7.]; - let default = f32x4([-3_f32, -3., -3., -3.]); - let s_strided = f32x4([0_f32, 2., -3., 6.]); - let mask = i32x4([-1_i32, -1, 0, -1]); + let default = f32x4::from_array([-3_f32, -3., -3., -3.]); + let s_strided = f32x4::from_array([0_f32, 2., -3., 6.]); + let mask = i32x4::from_array([-1_i32, -1, 0, -1]); // reading from *const unsafe { let pointer = &x as *const f32; - let pointers = cptrx4([ + let pointers = cptrx4::from_array([ pointer.offset(0) as *const f32, pointer.offset(2), pointer.offset(4), @@ -49,14 +41,14 @@ fn main() { // writing to *mut unsafe { let pointer = &mut x as *mut f32; - let pointers = mptrx4([ + let pointers = mptrx4::from_array([ pointer.offset(0) as *mut f32, pointer.offset(2), pointer.offset(4), pointer.offset(6), ]); - let values = f32x4([42_f32, 43_f32, 44_f32, 45_f32]); + let values = f32x4::from_array([42_f32, 43_f32, 44_f32, 45_f32]); simd_scatter(values, pointers, mask); assert_eq!(x, [42., 1., 43., 3., 4., 5., 45., 7.]); diff --git a/tests/ui/simd/issue-89193.rs b/tests/ui/simd/issue-89193.rs index a6c3017572a..da4cd456589 100644 --- a/tests/ui/simd/issue-89193.rs +++ b/tests/ui/simd/issue-89193.rs @@ -6,36 +6,38 @@ #![feature(repr_simd, core_intrinsics)] #![allow(non_camel_case_types)] +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; + use std::intrinsics::simd::simd_gather; -#[repr(simd)] -#[derive(Copy, Clone, PartialEq, Debug)] -struct x4<T>(pub [T; 4]); +type x4<T> = Simd<T, 4>; fn main() { let x: [usize; 4] = [10, 11, 12, 13]; - let default = x4([0_usize, 1, 2, 3]); + let default = x4::from_array([0_usize, 1, 2, 3]); let all_set = u8::MAX as i8; // aka -1 - let mask = x4([all_set, all_set, all_set, all_set]); - let expected = x4([10_usize, 11, 12, 13]); + let mask = x4::from_array([all_set, all_set, all_set, all_set]); + let expected = x4::from_array([10_usize, 11, 12, 13]); unsafe { let pointer = x.as_ptr(); let pointers = - x4([pointer.offset(0), pointer.offset(1), pointer.offset(2), pointer.offset(3)]); + x4::from_array(std::array::from_fn(|i| pointer.add(i))); let result = simd_gather(default, pointers, mask); assert_eq!(result, expected); } // and again for isize let x: [isize; 4] = [10, 11, 12, 13]; - let default = x4([0_isize, 1, 2, 3]); - let expected = x4([10_isize, 11, 12, 13]); + let default = x4::from_array([0_isize, 1, 2, 3]); + let expected = x4::from_array([10_isize, 11, 12, 13]); unsafe { let pointer = x.as_ptr(); let pointers = - x4([pointer.offset(0), pointer.offset(1), pointer.offset(2), pointer.offset(3)]); + x4::from_array(std::array::from_fn(|i| pointer.add(i))); let result = simd_gather(default, pointers, mask); assert_eq!(result, expected); } diff --git a/tests/ui/simd/masked-load-store.rs b/tests/ui/simd/masked-load-store.rs index 69ea76581ee..da32ba611c4 100644 --- a/tests/ui/simd/masked-load-store.rs +++ b/tests/ui/simd/masked-load-store.rs @@ -1,11 +1,11 @@ //@ run-pass #![feature(repr_simd, core_intrinsics)] -use std::intrinsics::simd::{simd_masked_load, simd_masked_store}; +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; -#[derive(Copy, Clone)] -#[repr(simd)] -struct Simd<T, const N: usize>([T; N]); +use std::intrinsics::simd::{simd_masked_load, simd_masked_store}; fn main() { unsafe { @@ -15,7 +15,7 @@ fn main() { let b: Simd<u8, 4> = simd_masked_load(Simd::<i8, 4>([-1, 0, -1, -1]), b_src.as_ptr(), b_default); - assert_eq!(&b.0, &[4, 9, 6, 7]); + assert_eq!(b.as_array(), &[4, 9, 6, 7]); let mut output = [u8::MAX; 5]; diff --git a/tests/ui/simd/monomorphize-shuffle-index.rs b/tests/ui/simd/monomorphize-shuffle-index.rs index a56f2ea1452..1490f8e2319 100644 --- a/tests/ui/simd/monomorphize-shuffle-index.rs +++ b/tests/ui/simd/monomorphize-shuffle-index.rs @@ -11,6 +11,10 @@ )] #![allow(incomplete_features)] +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; + #[cfg(old)] use std::intrinsics::simd::simd_shuffle; @@ -18,10 +22,6 @@ use std::intrinsics::simd::simd_shuffle; #[rustc_intrinsic] unsafe fn simd_shuffle_const_generic<T, U, const I: &'static [u32]>(a: T, b: T) -> U; -#[derive(Copy, Clone)] -#[repr(simd)] -struct Simd<T, const N: usize>([T; N]); - trait Shuffle<const N: usize> { const I: Simd<u32, N>; const J: &'static [u32] = &Self::I.0; @@ -57,9 +57,9 @@ fn main() { let b = Simd::<u8, 4>([4, 5, 6, 7]); unsafe { let x: Simd<u8, 4> = I1.shuffle(a, b); - assert_eq!(x.0, [0, 2, 4, 6]); + assert_eq!(x.into_array(), [0, 2, 4, 6]); let y: Simd<u8, 2> = I2.shuffle(a, b); - assert_eq!(y.0, [1, 5]); + assert_eq!(y.into_array(), [1, 5]); } } diff --git a/tests/ui/simd/repr_packed.rs b/tests/ui/simd/repr_packed.rs index cc54477ae71..f0c6de7c402 100644 --- a/tests/ui/simd/repr_packed.rs +++ b/tests/ui/simd/repr_packed.rs @@ -3,15 +3,16 @@ #![feature(repr_simd, core_intrinsics)] #![allow(non_camel_case_types)] -use std::intrinsics::simd::simd_add; +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; -#[repr(simd, packed)] -struct Simd<T, const N: usize>([T; N]); +use std::intrinsics::simd::simd_add; fn check_size_align<T, const N: usize>() { use std::mem; - assert_eq!(mem::size_of::<Simd<T, N>>(), mem::size_of::<[T; N]>()); - assert_eq!(mem::size_of::<Simd<T, N>>() % mem::align_of::<Simd<T, N>>(), 0); + assert_eq!(mem::size_of::<PackedSimd<T, N>>(), mem::size_of::<[T; N]>()); + assert_eq!(mem::size_of::<PackedSimd<T, N>>() % mem::align_of::<PackedSimd<T, N>>(), 0); } fn check_ty<T>() { @@ -35,14 +36,21 @@ fn main() { unsafe { // powers-of-two have no padding and have the same layout as #[repr(simd)] - let x: Simd<f64, 4> = - simd_add(Simd::<f64, 4>([0., 1., 2., 3.]), Simd::<f64, 4>([2., 2., 2., 2.])); - assert_eq!(std::mem::transmute::<_, [f64; 4]>(x), [2., 3., 4., 5.]); + let x: PackedSimd<f64, 4> = + simd_add( + PackedSimd::<f64, 4>([0., 1., 2., 3.]), + PackedSimd::<f64, 4>([2., 2., 2., 2.]), + ); + assert_eq!(x.into_array(), [2., 3., 4., 5.]); // non-powers-of-two should have padding (which is removed by #[repr(packed)]), // but the intrinsic handles it - let x: Simd<f64, 3> = simd_add(Simd::<f64, 3>([0., 1., 2.]), Simd::<f64, 3>([2., 2., 2.])); - let arr: [f64; 3] = x.0; + let x: PackedSimd<f64, 3> = + simd_add( + PackedSimd::<f64, 3>([0., 1., 2.]), + PackedSimd::<f64, 3>([2., 2., 2.]), + ); + let arr: [f64; 3] = x.into_array(); assert_eq!(arr, [2., 3., 4.]); } } diff --git a/tests/ui/simd/shuffle.rs b/tests/ui/simd/shuffle.rs index cd270edcf00..061571a4786 100644 --- a/tests/ui/simd/shuffle.rs +++ b/tests/ui/simd/shuffle.rs @@ -10,10 +10,16 @@ use std::marker::ConstParamTy; use std::intrinsics::simd::simd_shuffle; +// not using `minisimd` because of the `ConstParamTy` #[derive(Copy, Clone, ConstParamTy, PartialEq, Eq)] #[repr(simd)] struct Simd<T, const N: usize>([T; N]); +fn into_array<T, const N: usize>(v: Simd<T, N>) -> [T; N] { + const { assert!(size_of::<Simd<T, N>>() == size_of::<[T; N]>()) } + unsafe { std::intrinsics::transmute_unchecked(v) } +} + unsafe fn __shuffle_vector16<const IDX: Simd<u32, 16>, T, U>(x: T, y: T) -> U { simd_shuffle(x, y, IDX) } @@ -25,10 +31,10 @@ fn main() { let b = Simd::<u8, 4>([4, 5, 6, 7]); unsafe { let x: Simd<u8, 4> = simd_shuffle(a, b, I1); - assert_eq!(x.0, [0, 2, 4, 6]); + assert_eq!(into_array(x), [0, 2, 4, 6]); let y: Simd<u8, 2> = simd_shuffle(a, b, I2); - assert_eq!(y.0, [1, 5]); + assert_eq!(into_array(y), [1, 5]); } // Test that an indirection (via an unnamed constant) diff --git a/tests/ui/simd/simd-bitmask-notpow2.rs b/tests/ui/simd/simd-bitmask-notpow2.rs index 4935097065e..b9af591d1b9 100644 --- a/tests/ui/simd/simd-bitmask-notpow2.rs +++ b/tests/ui/simd/simd-bitmask-notpow2.rs @@ -4,21 +4,23 @@ //@ ignore-endian-big #![feature(repr_simd, core_intrinsics)] +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; + use std::intrinsics::simd::{simd_bitmask, simd_select_bitmask}; fn main() { // Non-power-of-2 multi-byte mask. - #[repr(simd, packed)] #[allow(non_camel_case_types)] - #[derive(Copy, Clone, Debug, PartialEq)] - struct i32x10([i32; 10]); + type i32x10 = PackedSimd<i32, 10>; impl i32x10 { fn splat(x: i32) -> Self { Self([x; 10]) } } unsafe { - let mask = i32x10([!0, !0, 0, !0, 0, 0, !0, 0, !0, 0]); + let mask = i32x10::from_array([!0, !0, 0, !0, 0, 0, !0, 0, !0, 0]); let mask_bits = if cfg!(target_endian = "little") { 0b0101001011 } else { 0b1101001010 }; let mask_bytes = if cfg!(target_endian = "little") { [0b01001011, 0b01] } else { [0b11, 0b01001010] }; @@ -43,17 +45,20 @@ fn main() { } // Test for a mask where the next multiple of 8 is not a power of two. - #[repr(simd, packed)] #[allow(non_camel_case_types)] - #[derive(Copy, Clone, Debug, PartialEq)] - struct i32x20([i32; 20]); + type i32x20 = PackedSimd<i32, 20>; impl i32x20 { fn splat(x: i32) -> Self { Self([x; 20]) } } unsafe { - let mask = i32x20([!0, !0, 0, !0, 0, 0, !0, 0, !0, 0, 0, 0, 0, !0, !0, !0, !0, !0, !0, !0]); + let mask = i32x20::from_array([ + !0, !0, 0, !0, 0, + 0, !0, 0, !0, 0, + 0, 0, 0, !0, !0, + !0, !0, !0, !0, !0, + ]); let mask_bits = if cfg!(target_endian = "little") { 0b11111110000101001011 } else { diff --git a/tests/ui/simd/simd-bitmask.rs b/tests/ui/simd/simd-bitmask.rs index 6fcceeaa24b..609dae3647b 100644 --- a/tests/ui/simd/simd-bitmask.rs +++ b/tests/ui/simd/simd-bitmask.rs @@ -1,11 +1,11 @@ //@run-pass #![feature(repr_simd, core_intrinsics)] -use std::intrinsics::simd::{simd_bitmask, simd_select_bitmask}; +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; +use minisimd::*; -#[derive(Copy, Clone)] -#[repr(simd)] -struct Simd<T, const N: usize>([T; N]); +use std::intrinsics::simd::{simd_bitmask, simd_select_bitmask}; fn main() { unsafe { @@ -41,11 +41,11 @@ fn main() { let mask = if cfg!(target_endian = "little") { 0b0101u8 } else { 0b1010u8 }; let r = simd_select_bitmask(mask, a, b); - assert_eq!(r.0, e); + assert_eq!(r.into_array(), e); let mask = if cfg!(target_endian = "little") { [0b0101u8] } else { [0b1010u8] }; let r = simd_select_bitmask(mask, a, b); - assert_eq!(r.0, e); + assert_eq!(r.into_array(), e); let a = Simd::<i32, 16>([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]); let b = Simd::<i32, 16>([16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]); @@ -57,7 +57,7 @@ fn main() { 0b0011000000001010u16 }; let r = simd_select_bitmask(mask, a, b); - assert_eq!(r.0, e); + assert_eq!(r.into_array(), e); let mask = if cfg!(target_endian = "little") { [0b00001100u8, 0b01010000u8] @@ -65,6 +65,6 @@ fn main() { [0b00110000u8, 0b00001010u8] }; let r = simd_select_bitmask(mask, a, b); - assert_eq!(r.0, e); + assert_eq!(r.into_array(), e); } } diff --git a/tests/ui/simd/target-feature-mixup.rs b/tests/ui/simd/target-feature-mixup.rs index 77f18615248..82902891b97 100644 --- a/tests/ui/simd/target-feature-mixup.rs +++ b/tests/ui/simd/target-feature-mixup.rs @@ -8,6 +8,11 @@ #![feature(repr_simd, target_feature, cfg_target_feature)] +#[path = "../../auxiliary/minisimd.rs"] +mod minisimd; +#[allow(unused)] +use minisimd::*; + use std::process::{Command, ExitStatus}; use std::env; @@ -50,19 +55,13 @@ fn is_sigill(status: ExitStatus) -> bool { #[allow(nonstandard_style)] mod test { // An SSE type - #[repr(simd)] - #[derive(PartialEq, Debug, Clone, Copy)] - struct __m128i([u64; 2]); + type __m128i = super::u64x2; // An AVX type - #[repr(simd)] - #[derive(PartialEq, Debug, Clone, Copy)] - struct __m256i([u64; 4]); + type __m256i = super::u64x4; // An AVX-512 type - #[repr(simd)] - #[derive(PartialEq, Debug, Clone, Copy)] - struct __m512i([u64; 8]); + type __m512i = super::u64x8; pub fn main(level: &str) { unsafe { @@ -88,9 +87,9 @@ mod test { )*) => ($( $(#[$attr])* unsafe fn $main(level: &str) { - let m128 = __m128i([1, 2]); - let m256 = __m256i([3, 4, 5, 6]); - let m512 = __m512i([7, 8, 9, 10, 11, 12, 13, 14]); + let m128 = __m128i::from_array([1, 2]); + let m256 = __m256i::from_array([3, 4, 5, 6]); + let m512 = __m512i::from_array([7, 8, 9, 10, 11, 12, 13, 14]); assert_eq!(id_sse_128(m128), m128); assert_eq!(id_sse_256(m256), m256); assert_eq!(id_sse_512(m512), m512); @@ -125,55 +124,55 @@ mod test { #[target_feature(enable = "sse2")] unsafe fn id_sse_128(a: __m128i) -> __m128i { - assert_eq!(a, __m128i([1, 2])); + assert_eq!(a, __m128i::from_array([1, 2])); a.clone() } #[target_feature(enable = "sse2")] unsafe fn id_sse_256(a: __m256i) -> __m256i { - assert_eq!(a, __m256i([3, 4, 5, 6])); + assert_eq!(a, __m256i::from_array([3, 4, 5, 6])); a.clone() } #[target_feature(enable = "sse2")] unsafe fn id_sse_512(a: __m512i) -> __m512i { - assert_eq!(a, __m512i([7, 8, 9, 10, 11, 12, 13, 14])); + assert_eq!(a, __m512i::from_array([7, 8, 9, 10, 11, 12, 13, 14])); a.clone() } #[target_feature(enable = "avx")] unsafe fn id_avx_128(a: __m128i) -> __m128i { - assert_eq!(a, __m128i([1, 2])); + assert_eq!(a, __m128i::from_array([1, 2])); a.clone() } #[target_feature(enable = "avx")] unsafe fn id_avx_256(a: __m256i) -> __m256i { - assert_eq!(a, __m256i([3, 4, 5, 6])); + assert_eq!(a, __m256i::from_array([3, 4, 5, 6])); a.clone() } #[target_feature(enable = "avx")] unsafe fn id_avx_512(a: __m512i) -> __m512i { - assert_eq!(a, __m512i([7, 8, 9, 10, 11, 12, 13, 14])); + assert_eq!(a, __m512i::from_array([7, 8, 9, 10, 11, 12, 13, 14])); a.clone() } #[target_feature(enable = "avx512bw")] unsafe fn id_avx512_128(a: __m128i) -> __m128i { - assert_eq!(a, __m128i([1, 2])); + assert_eq!(a, __m128i::from_array([1, 2])); a.clone() } #[target_feature(enable = "avx512bw")] unsafe fn id_avx512_256(a: __m256i) -> __m256i { - assert_eq!(a, __m256i([3, 4, 5, 6])); + assert_eq!(a, __m256i::from_array([3, 4, 5, 6])); a.clone() } #[target_feature(enable = "avx512bw")] unsafe fn id_avx512_512(a: __m512i) -> __m512i { - assert_eq!(a, __m512i([7, 8, 9, 10, 11, 12, 13, 14])); + assert_eq!(a, __m512i::from_array([7, 8, 9, 10, 11, 12, 13, 14])); a.clone() } } diff --git a/tests/ui/sized-hierarchy/default-bound.rs b/tests/ui/sized-hierarchy/default-bound.rs index 12b2eb2b5c1..bbb2c6d96ba 100644 --- a/tests/ui/sized-hierarchy/default-bound.rs +++ b/tests/ui/sized-hierarchy/default-bound.rs @@ -14,13 +14,13 @@ fn neg_sized<T: ?Sized>() {} fn metasized<T: MetaSized>() {} fn neg_metasized<T: ?MetaSized>() {} -//~^ ERROR relaxing a default bound only does something for `?Sized`; all other traits are not bound by default +//~^ ERROR bound modifier `?` can only be applied to `Sized` fn pointeesized<T: PointeeSized>() { } fn neg_pointeesized<T: ?PointeeSized>() { } -//~^ ERROR relaxing a default bound only does something for `?Sized`; all other traits are not bound by default +//~^ ERROR bound modifier `?` can only be applied to `Sized` fn main() { diff --git a/tests/ui/sized-hierarchy/default-bound.stderr b/tests/ui/sized-hierarchy/default-bound.stderr index 22f0fa29d3e..0a4ea6f44d8 100644 --- a/tests/ui/sized-hierarchy/default-bound.stderr +++ b/tests/ui/sized-hierarchy/default-bound.stderr @@ -1,10 +1,10 @@ -error: relaxing a default bound only does something for `?Sized`; all other traits are not bound by default +error: bound modifier `?` can only be applied to `Sized` --> $DIR/default-bound.rs:16:21 | LL | fn neg_metasized<T: ?MetaSized>() {} | ^^^^^^^^^^ -error: relaxing a default bound only does something for `?Sized`; all other traits are not bound by default +error: bound modifier `?` can only be applied to `Sized` --> $DIR/default-bound.rs:22:24 | LL | fn neg_pointeesized<T: ?PointeeSized>() { } diff --git a/tests/ui/sized-hierarchy/default-supertrait.rs b/tests/ui/sized-hierarchy/default-supertrait.rs index b25acf9e6ea..ab3b28e84db 100644 --- a/tests/ui/sized-hierarchy/default-supertrait.rs +++ b/tests/ui/sized-hierarchy/default-supertrait.rs @@ -6,18 +6,18 @@ use std::marker::{MetaSized, PointeeSized}; trait Sized_: Sized { } trait NegSized: ?Sized { } -//~^ ERROR `?Trait` is not permitted in supertraits +//~^ ERROR relaxed bounds are not permitted in supertrait bounds trait MetaSized_: MetaSized { } trait NegMetaSized: ?MetaSized { } -//~^ ERROR `?Trait` is not permitted in supertraits +//~^ ERROR relaxed bounds are not permitted in supertrait bounds trait PointeeSized_: PointeeSized { } trait NegPointeeSized: ?PointeeSized { } -//~^ ERROR `?Trait` is not permitted in supertraits +//~^ ERROR relaxed bounds are not permitted in supertrait bounds trait Bare {} diff --git a/tests/ui/sized-hierarchy/default-supertrait.stderr b/tests/ui/sized-hierarchy/default-supertrait.stderr index de23936b900..f5589d6e279 100644 --- a/tests/ui/sized-hierarchy/default-supertrait.stderr +++ b/tests/ui/sized-hierarchy/default-supertrait.stderr @@ -1,32 +1,22 @@ -error[E0658]: `?Trait` is not permitted in supertraits +error: relaxed bounds are not permitted in supertrait bounds --> $DIR/default-supertrait.rs:8:17 | LL | trait NegSized: ?Sized { } | ^^^^^^ | = note: traits are `?Sized` by default - = help: add `#![feature(more_maybe_bounds)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date -error[E0658]: `?Trait` is not permitted in supertraits +error: relaxed bounds are not permitted in supertrait bounds --> $DIR/default-supertrait.rs:13:21 | LL | trait NegMetaSized: ?MetaSized { } | ^^^^^^^^^^ - | - = note: traits are `?MetaSized` by default - = help: add `#![feature(more_maybe_bounds)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date -error[E0658]: `?Trait` is not permitted in supertraits +error: relaxed bounds are not permitted in supertrait bounds --> $DIR/default-supertrait.rs:19:24 | LL | trait NegPointeeSized: ?PointeeSized { } | ^^^^^^^^^^^^^ - | - = note: traits are `?PointeeSized` by default - = help: add `#![feature(more_maybe_bounds)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date error[E0277]: the size for values of type `T` cannot be known --> $DIR/default-supertrait.rs:52:38 @@ -121,5 +111,4 @@ LL | fn with_bare_trait<T: PointeeSized + Bare + std::marker::MetaSized>() { error: aborting due to 9 previous errors -Some errors have detailed explanations: E0277, E0658. -For more information about an error, try `rustc --explain E0277`. +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/sized-hierarchy/incomplete-inference-issue-143992.next.stderr b/tests/ui/sized-hierarchy/incomplete-inference-issue-143992.current_sized_hierarchy.stderr index cf56f42afc8..b904b784df7 100644 --- a/tests/ui/sized-hierarchy/incomplete-inference-issue-143992.next.stderr +++ b/tests/ui/sized-hierarchy/incomplete-inference-issue-143992.current_sized_hierarchy.stderr @@ -1,5 +1,5 @@ error[E0308]: mismatched types - --> $DIR/incomplete-inference-issue-143992.rs:27:28 + --> $DIR/incomplete-inference-issue-143992.rs:30:28 | LL | let _x = T::Assoc::new(()); | ------------- ^^ expected `[u32; 1]`, found `()` @@ -7,7 +7,7 @@ LL | let _x = T::Assoc::new(()); | arguments to this function are incorrect | note: associated function defined here - --> $DIR/incomplete-inference-issue-143992.rs:18:8 + --> $DIR/incomplete-inference-issue-143992.rs:21:8 | LL | fn new(r: R) -> R { | ^^^ ---- diff --git a/tests/ui/sized-hierarchy/incomplete-inference-issue-143992.next_sized_hierarchy.stderr b/tests/ui/sized-hierarchy/incomplete-inference-issue-143992.next_sized_hierarchy.stderr new file mode 100644 index 00000000000..b904b784df7 --- /dev/null +++ b/tests/ui/sized-hierarchy/incomplete-inference-issue-143992.next_sized_hierarchy.stderr @@ -0,0 +1,17 @@ +error[E0308]: mismatched types + --> $DIR/incomplete-inference-issue-143992.rs:30:28 + | +LL | let _x = T::Assoc::new(()); + | ------------- ^^ expected `[u32; 1]`, found `()` + | | + | arguments to this function are incorrect + | +note: associated function defined here + --> $DIR/incomplete-inference-issue-143992.rs:21:8 + | +LL | fn new(r: R) -> R { + | ^^^ ---- + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0308`. diff --git a/tests/ui/sized-hierarchy/incomplete-inference-issue-143992.rs b/tests/ui/sized-hierarchy/incomplete-inference-issue-143992.rs index 3e3e1dc50e5..b9e65ed2839 100644 --- a/tests/ui/sized-hierarchy/incomplete-inference-issue-143992.rs +++ b/tests/ui/sized-hierarchy/incomplete-inference-issue-143992.rs @@ -1,9 +1,12 @@ //@ compile-flags: --crate-type=lib -//@ revisions: current next +//@ revisions: current next current_sized_hierarchy next_sized_hierarchy //@ ignore-compare-mode-next-solver (explicit revisions) //@[current] check-pass +//@[next] check-pass //@[next] compile-flags: -Znext-solver -//@[next] check-fail +//@[next_sized_hierarchy] compile-flags: -Znext-solver + +#![cfg_attr(any(current_sized_hierarchy, next_sized_hierarchy), feature(sized_hierarchy))] // Test that we avoid incomplete inference when normalizing. Without this, // `Trait`'s implicit `MetaSized` supertrait requires proving `T::Assoc<_>: MetaSized` @@ -25,5 +28,6 @@ where T::Assoc<[u32; 1]>: Clone, { let _x = T::Assoc::new(()); -//[next]~^ ERROR mismatched types + //[next_sized_hierarchy]~^ ERROR mismatched types + //[current_sized_hierarchy]~^^ ERROR mismatched types } diff --git a/tests/ui/sized-hierarchy/pointee-validation.rs b/tests/ui/sized-hierarchy/pointee-validation.rs new file mode 100644 index 00000000000..dfc28829e08 --- /dev/null +++ b/tests/ui/sized-hierarchy/pointee-validation.rs @@ -0,0 +1,20 @@ +// Test that despite us dropping `PointeeSized` bounds during HIR ty lowering +// we still validate it first. +// issue: <https://github.com/rust-lang/rust/issues/142718> +#![feature(sized_hierarchy)] + +use std::marker::PointeeSized; + +struct T where (): PointeeSized<(), Undefined = ()>; +//~^ ERROR trait takes 0 generic arguments but 1 generic argument was supplied +//~| ERROR associated type `Undefined` not found for `PointeeSized` + +const fn test<T, U>() where T: const PointeeSized, U: [const] PointeeSized {} +//~^ ERROR `const` can only be applied to `const` traits +//~| ERROR `const` can only be applied to `const` traits +//~| ERROR const trait impls are experimental +//~| ERROR `[const]` can only be applied to `const` traits +//~| ERROR `[const]` can only be applied to `const` traits +//~| ERROR const trait impls are experimental + +fn main() {} diff --git a/tests/ui/sized-hierarchy/pointee-validation.stderr b/tests/ui/sized-hierarchy/pointee-validation.stderr new file mode 100644 index 00000000000..a056d548356 --- /dev/null +++ b/tests/ui/sized-hierarchy/pointee-validation.stderr @@ -0,0 +1,76 @@ +error[E0658]: const trait impls are experimental + --> $DIR/pointee-validation.rs:12:32 + | +LL | const fn test<T, U>() where T: const PointeeSized, U: [const] PointeeSized {} + | ^^^^^ + | + = note: see issue #143874 <https://github.com/rust-lang/rust/issues/143874> for more information + = help: add `#![feature(const_trait_impl)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error[E0658]: const trait impls are experimental + --> $DIR/pointee-validation.rs:12:55 + | +LL | const fn test<T, U>() where T: const PointeeSized, U: [const] PointeeSized {} + | ^^^^^^^ + | + = note: see issue #143874 <https://github.com/rust-lang/rust/issues/143874> for more information + = help: add `#![feature(const_trait_impl)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error[E0107]: trait takes 0 generic arguments but 1 generic argument was supplied + --> $DIR/pointee-validation.rs:8:20 + | +LL | struct T where (): PointeeSized<(), Undefined = ()>; + | ^^^^^^^^^^^^-------------------- help: remove the unnecessary generics + | | + | expected 0 generic arguments + +error[E0220]: associated type `Undefined` not found for `PointeeSized` + --> $DIR/pointee-validation.rs:8:37 + | +LL | struct T where (): PointeeSized<(), Undefined = ()>; + | ^^^^^^^^^ associated type `Undefined` not found + +error: `const` can only be applied to `const` traits + --> $DIR/pointee-validation.rs:12:32 + | +LL | const fn test<T, U>() where T: const PointeeSized, U: [const] PointeeSized {} + | ^^^^^ can't be applied to `PointeeSized` + | +note: `PointeeSized` can't be used with `const` because it isn't `const` + --> $SRC_DIR/core/src/marker.rs:LL:COL + +error: `[const]` can only be applied to `const` traits + --> $DIR/pointee-validation.rs:12:55 + | +LL | const fn test<T, U>() where T: const PointeeSized, U: [const] PointeeSized {} + | ^^^^^^^ can't be applied to `PointeeSized` + | +note: `PointeeSized` can't be used with `[const]` because it isn't `const` + --> $SRC_DIR/core/src/marker.rs:LL:COL + +error: `const` can only be applied to `const` traits + --> $DIR/pointee-validation.rs:12:32 + | +LL | const fn test<T, U>() where T: const PointeeSized, U: [const] PointeeSized {} + | ^^^^^ can't be applied to `PointeeSized` + | +note: `PointeeSized` can't be used with `const` because it isn't `const` + --> $SRC_DIR/core/src/marker.rs:LL:COL + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + +error: `[const]` can only be applied to `const` traits + --> $DIR/pointee-validation.rs:12:55 + | +LL | const fn test<T, U>() where T: const PointeeSized, U: [const] PointeeSized {} + | ^^^^^^^ can't be applied to `PointeeSized` + | +note: `PointeeSized` can't be used with `[const]` because it isn't `const` + --> $SRC_DIR/core/src/marker.rs:LL:COL + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + +error: aborting due to 8 previous errors + +Some errors have detailed explanations: E0107, E0220, E0658. +For more information about an error, try `rustc --explain E0107`. diff --git a/tests/ui/sized-hierarchy/reject-dyn-pointeesized.rs b/tests/ui/sized-hierarchy/reject-dyn-pointeesized.rs index ece1702679d..89e4c15371d 100644 --- a/tests/ui/sized-hierarchy/reject-dyn-pointeesized.rs +++ b/tests/ui/sized-hierarchy/reject-dyn-pointeesized.rs @@ -3,7 +3,7 @@ use std::marker::PointeeSized; type Foo = dyn PointeeSized; -//~^ ERROR `PointeeSized` cannot be used with trait objects +//~^ ERROR at least one trait is required for an object type fn foo(f: &Foo) {} @@ -12,5 +12,5 @@ fn main() { let x = main; let y: Box<dyn PointeeSized> = x; -//~^ ERROR `PointeeSized` cannot be used with trait objects +//~^ ERROR at least one trait is required for an object type } diff --git a/tests/ui/sized-hierarchy/reject-dyn-pointeesized.stderr b/tests/ui/sized-hierarchy/reject-dyn-pointeesized.stderr index a833c6952fd..616b2400f86 100644 --- a/tests/ui/sized-hierarchy/reject-dyn-pointeesized.stderr +++ b/tests/ui/sized-hierarchy/reject-dyn-pointeesized.stderr @@ -1,10 +1,10 @@ -error: `PointeeSized` cannot be used with trait objects +error[E0224]: at least one trait is required for an object type --> $DIR/reject-dyn-pointeesized.rs:5:12 | LL | type Foo = dyn PointeeSized; | ^^^^^^^^^^^^^^^^ -error: `PointeeSized` cannot be used with trait objects +error[E0224]: at least one trait is required for an object type --> $DIR/reject-dyn-pointeesized.rs:14:16 | LL | let y: Box<dyn PointeeSized> = x; @@ -12,3 +12,4 @@ LL | let y: Box<dyn PointeeSized> = x; error: aborting due to 2 previous errors +For more information about this error, try `rustc --explain E0224`. diff --git a/tests/ui/stability-attribute/missing-const-stability.stderr b/tests/ui/stability-attribute/missing-const-stability.stderr index 70a2450c53a..5748e20cd2b 100644 --- a/tests/ui/stability-attribute/missing-const-stability.stderr +++ b/tests/ui/stability-attribute/missing-const-stability.stderr @@ -2,29 +2,25 @@ error: function has missing const stability attribute --> $DIR/missing-const-stability.rs:7:1 | LL | pub const fn foo() {} - | ^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^ error: trait has missing const stability attribute --> $DIR/missing-const-stability.rs:23:1 | -LL | / pub const trait Bar { -LL | | -LL | | #[stable(feature = "stable", since = "1.0.0")] -LL | | fn fun(); -LL | | } - | |_^ +LL | pub const trait Bar { + | ^^^^^^^^^^^^^^^^^^^ error: function has missing const stability attribute --> $DIR/missing-const-stability.rs:36:1 | LL | pub const unsafe fn size_of_val<T>(x: *const T) -> usize { 42 } - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: associated function has missing const stability attribute --> $DIR/missing-const-stability.rs:16:5 | LL | pub const fn foo() {} - | ^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^ error: aborting due to 4 previous errors diff --git a/tests/ui/stability-attribute/stability-attribute-sanity-3.stderr b/tests/ui/stability-attribute/stability-attribute-sanity-3.stderr index a6d1ebf2945..d33bb53360b 100644 --- a/tests/ui/stability-attribute/stability-attribute-sanity-3.stderr +++ b/tests/ui/stability-attribute/stability-attribute-sanity-3.stderr @@ -1,10 +1,8 @@ error: macro has missing stability attribute --> $DIR/stability-attribute-sanity-3.rs:8:1 | -LL | / macro_rules! mac { -LL | | () => () -LL | | } - | |_^ +LL | macro_rules! mac { + | ^^^^^^^^^^^^^^^^ error: aborting due to 1 previous error diff --git a/tests/ui/std/issue-81357-unsound-file-methods.rs b/tests/ui/std/issue-81357-unsound-file-methods.rs index 838df40c32d..99bd31aa260 100644 --- a/tests/ui/std/issue-81357-unsound-file-methods.rs +++ b/tests/ui/std/issue-81357-unsound-file-methods.rs @@ -1,4 +1,4 @@ -//@ run-fail +//@ run-crash //@ only-windows fn main() { diff --git a/tests/ui/suggestions/issue-94171.stderr b/tests/ui/suggestions/issue-94171.stderr index bcbd46cd8ec..52306a2465f 100644 --- a/tests/ui/suggestions/issue-94171.stderr +++ b/tests/ui/suggestions/issue-94171.stderr @@ -22,9 +22,7 @@ error: this file contains an unclosed delimiter --> $DIR/issue-94171.rs:5:52 | LL | fn L(]{match - | -- unclosed delimiter - | | - | missing open `[` for this delimiter + | - unclosed delimiter LL | (; {` | - - unclosed delimiter | | diff --git a/tests/ui/trait-bounds/duplicate-relaxed-bounds.rs b/tests/ui/trait-bounds/duplicate-relaxed-bounds.rs new file mode 100644 index 00000000000..a1681ddec77 --- /dev/null +++ b/tests/ui/trait-bounds/duplicate-relaxed-bounds.rs @@ -0,0 +1,22 @@ +fn dupes<T: ?Sized + ?Sized + ?Iterator + ?Iterator>() {} +//~^ ERROR duplicate relaxed `Sized` bounds +//~| ERROR duplicate relaxed `Iterator` bounds +//~| ERROR bound modifier `?` can only be applied to `Sized` +//~| ERROR bound modifier `?` can only be applied to `Sized` + +trait Trait { + // We used to say "type parameter has more than one relaxed default bound" + // even on *associated types* like here. Test that we no longer do that. + type Type: ?Sized + ?Sized; + //~^ ERROR duplicate relaxed `Sized` bounds + //~| ERROR duplicate relaxed `Sized` bounds +} + +// We used to emit an additional error about "multiple relaxed default bounds". +// However, multiple relaxed bounds are actually *fine* if they're distinct. +// Ultimately, we still reject this because `Sized` is +// the only (stable) default trait, so we're fine. +fn not_dupes<T: ?Sized + ?Iterator>() {} +//~^ ERROR bound modifier `?` can only be applied to `Sized` + +fn main() {} diff --git a/tests/ui/trait-bounds/duplicate-relaxed-bounds.stderr b/tests/ui/trait-bounds/duplicate-relaxed-bounds.stderr new file mode 100644 index 00000000000..ccc723fc7a6 --- /dev/null +++ b/tests/ui/trait-bounds/duplicate-relaxed-bounds.stderr @@ -0,0 +1,47 @@ +error[E0203]: duplicate relaxed `Sized` bounds + --> $DIR/duplicate-relaxed-bounds.rs:1:13 + | +LL | fn dupes<T: ?Sized + ?Sized + ?Iterator + ?Iterator>() {} + | ^^^^^^ ^^^^^^ + +error[E0203]: duplicate relaxed `Iterator` bounds + --> $DIR/duplicate-relaxed-bounds.rs:1:31 + | +LL | fn dupes<T: ?Sized + ?Sized + ?Iterator + ?Iterator>() {} + | ^^^^^^^^^ ^^^^^^^^^ + +error: bound modifier `?` can only be applied to `Sized` + --> $DIR/duplicate-relaxed-bounds.rs:1:31 + | +LL | fn dupes<T: ?Sized + ?Sized + ?Iterator + ?Iterator>() {} + | ^^^^^^^^^ + +error: bound modifier `?` can only be applied to `Sized` + --> $DIR/duplicate-relaxed-bounds.rs:1:43 + | +LL | fn dupes<T: ?Sized + ?Sized + ?Iterator + ?Iterator>() {} + | ^^^^^^^^^ + +error: bound modifier `?` can only be applied to `Sized` + --> $DIR/duplicate-relaxed-bounds.rs:19:26 + | +LL | fn not_dupes<T: ?Sized + ?Iterator>() {} + | ^^^^^^^^^ + +error[E0203]: duplicate relaxed `Sized` bounds + --> $DIR/duplicate-relaxed-bounds.rs:10:16 + | +LL | type Type: ?Sized + ?Sized; + | ^^^^^^ ^^^^^^ + +error[E0203]: duplicate relaxed `Sized` bounds + --> $DIR/duplicate-relaxed-bounds.rs:10:16 + | +LL | type Type: ?Sized + ?Sized; + | ^^^^^^ ^^^^^^ + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + +error: aborting due to 7 previous errors + +For more information about this error, try `rustc --explain E0203`. diff --git a/tests/ui/trait-bounds/bad-suggestionf-for-repeated-unsized-bound-127441.rs b/tests/ui/trait-bounds/fix-dyn-sized-fn-param-sugg.rs index e6d7f74880f..1aa36207bc3 100644 --- a/tests/ui/trait-bounds/bad-suggestionf-for-repeated-unsized-bound-127441.rs +++ b/tests/ui/trait-bounds/fix-dyn-sized-fn-param-sugg.rs @@ -1,39 +1,38 @@ -// Regression test for #127441 - -// Tests that we make the correct suggestion -// in case there are more than one `?Sized` -// bounds on a function parameter +// Test that we emit a correct structured suggestions for dynamically sized ("maybe unsized") +// function parameters. +// We used to emit a butchered suggestion if duplicate relaxed `Sized` bounds were present. +// issue: <https://github.com/rust-lang/rust/issues/127441>. use std::fmt::Debug; fn foo1<T: ?Sized>(a: T) {} -//~^ ERROR he size for values of type `T` cannot be known at compilation time +//~^ ERROR the size for values of type `T` cannot be known at compilation time fn foo2<T: ?Sized + ?Sized>(a: T) {} -//~^ ERROR type parameter has more than one relaxed default bound, only one is supported +//~^ ERROR duplicate relaxed `Sized` bounds //~| ERROR the size for values of type `T` cannot be known at compilation time fn foo3<T: ?Sized + ?Sized + Debug>(a: T) {} -//~^ ERROR type parameter has more than one relaxed default bound, only one is supported -//~| ERROR he size for values of type `T` cannot be known at compilation time +//~^ ERROR duplicate relaxed `Sized` bounds +//~| ERROR the size for values of type `T` cannot be known at compilation time fn foo4<T: ?Sized + Debug + ?Sized >(a: T) {} -//~^ ERROR type parameter has more than one relaxed default bound, only one is supported +//~^ ERROR duplicate relaxed `Sized` bounds //~| ERROR the size for values of type `T` cannot be known at compilation time fn foo5(_: impl ?Sized) {} //~^ ERROR the size for values of type `impl ?Sized` cannot be known at compilation time fn foo6(_: impl ?Sized + ?Sized) {} -//~^ ERROR type parameter has more than one relaxed default bound, only one is supported +//~^ ERROR duplicate relaxed `Sized` bounds //~| ERROR the size for values of type `impl ?Sized + ?Sized` cannot be known at compilation tim fn foo7(_: impl ?Sized + ?Sized + Debug) {} -//~^ ERROR type parameter has more than one relaxed default bound, only one is supported +//~^ ERROR duplicate relaxed `Sized` bounds //~| ERROR the size for values of type `impl ?Sized + ?Sized + Debug` cannot be known at compilation time fn foo8(_: impl ?Sized + Debug + ?Sized ) {} -//~^ ERROR type parameter has more than one relaxed default bound, only one is supported +//~^ ERROR duplicate relaxed `Sized` bounds //~| ERROR the size for values of type `impl ?Sized + Debug + ?Sized` cannot be known at compilation time fn main() {} diff --git a/tests/ui/trait-bounds/bad-suggestionf-for-repeated-unsized-bound-127441.stderr b/tests/ui/trait-bounds/fix-dyn-sized-fn-param-sugg.stderr index 363f52d6df8..7a9c2f043ac 100644 --- a/tests/ui/trait-bounds/bad-suggestionf-for-repeated-unsized-bound-127441.stderr +++ b/tests/ui/trait-bounds/fix-dyn-sized-fn-param-sugg.stderr @@ -1,41 +1,41 @@ -error[E0203]: type parameter has more than one relaxed default bound, only one is supported - --> $DIR/bad-suggestionf-for-repeated-unsized-bound-127441.rs:12:12 +error[E0203]: duplicate relaxed `Sized` bounds + --> $DIR/fix-dyn-sized-fn-param-sugg.rs:11:12 | LL | fn foo2<T: ?Sized + ?Sized>(a: T) {} | ^^^^^^ ^^^^^^ -error[E0203]: type parameter has more than one relaxed default bound, only one is supported - --> $DIR/bad-suggestionf-for-repeated-unsized-bound-127441.rs:16:12 +error[E0203]: duplicate relaxed `Sized` bounds + --> $DIR/fix-dyn-sized-fn-param-sugg.rs:15:12 | LL | fn foo3<T: ?Sized + ?Sized + Debug>(a: T) {} | ^^^^^^ ^^^^^^ -error[E0203]: type parameter has more than one relaxed default bound, only one is supported - --> $DIR/bad-suggestionf-for-repeated-unsized-bound-127441.rs:20:12 +error[E0203]: duplicate relaxed `Sized` bounds + --> $DIR/fix-dyn-sized-fn-param-sugg.rs:19:12 | LL | fn foo4<T: ?Sized + Debug + ?Sized >(a: T) {} | ^^^^^^ ^^^^^^ -error[E0203]: type parameter has more than one relaxed default bound, only one is supported - --> $DIR/bad-suggestionf-for-repeated-unsized-bound-127441.rs:27:17 +error[E0203]: duplicate relaxed `Sized` bounds + --> $DIR/fix-dyn-sized-fn-param-sugg.rs:26:17 | LL | fn foo6(_: impl ?Sized + ?Sized) {} | ^^^^^^ ^^^^^^ -error[E0203]: type parameter has more than one relaxed default bound, only one is supported - --> $DIR/bad-suggestionf-for-repeated-unsized-bound-127441.rs:31:17 +error[E0203]: duplicate relaxed `Sized` bounds + --> $DIR/fix-dyn-sized-fn-param-sugg.rs:30:17 | LL | fn foo7(_: impl ?Sized + ?Sized + Debug) {} | ^^^^^^ ^^^^^^ -error[E0203]: type parameter has more than one relaxed default bound, only one is supported - --> $DIR/bad-suggestionf-for-repeated-unsized-bound-127441.rs:35:17 +error[E0203]: duplicate relaxed `Sized` bounds + --> $DIR/fix-dyn-sized-fn-param-sugg.rs:34:17 | LL | fn foo8(_: impl ?Sized + Debug + ?Sized ) {} | ^^^^^^ ^^^^^^ error[E0277]: the size for values of type `T` cannot be known at compilation time - --> $DIR/bad-suggestionf-for-repeated-unsized-bound-127441.rs:9:23 + --> $DIR/fix-dyn-sized-fn-param-sugg.rs:8:23 | LL | fn foo1<T: ?Sized>(a: T) {} | - ^ doesn't have a size known at compile-time @@ -54,7 +54,7 @@ LL | fn foo1<T: ?Sized>(a: &T) {} | + error[E0277]: the size for values of type `T` cannot be known at compilation time - --> $DIR/bad-suggestionf-for-repeated-unsized-bound-127441.rs:12:32 + --> $DIR/fix-dyn-sized-fn-param-sugg.rs:11:32 | LL | fn foo2<T: ?Sized + ?Sized>(a: T) {} | - ^ doesn't have a size known at compile-time @@ -73,7 +73,7 @@ LL | fn foo2<T: ?Sized + ?Sized>(a: &T) {} | + error[E0277]: the size for values of type `T` cannot be known at compilation time - --> $DIR/bad-suggestionf-for-repeated-unsized-bound-127441.rs:16:40 + --> $DIR/fix-dyn-sized-fn-param-sugg.rs:15:40 | LL | fn foo3<T: ?Sized + ?Sized + Debug>(a: T) {} | - ^ doesn't have a size known at compile-time @@ -92,7 +92,7 @@ LL | fn foo3<T: ?Sized + ?Sized + Debug>(a: &T) {} | + error[E0277]: the size for values of type `T` cannot be known at compilation time - --> $DIR/bad-suggestionf-for-repeated-unsized-bound-127441.rs:20:41 + --> $DIR/fix-dyn-sized-fn-param-sugg.rs:19:41 | LL | fn foo4<T: ?Sized + Debug + ?Sized >(a: T) {} | - ^ doesn't have a size known at compile-time @@ -111,7 +111,7 @@ LL | fn foo4<T: ?Sized + Debug + ?Sized >(a: &T) {} | + error[E0277]: the size for values of type `impl ?Sized` cannot be known at compilation time - --> $DIR/bad-suggestionf-for-repeated-unsized-bound-127441.rs:24:12 + --> $DIR/fix-dyn-sized-fn-param-sugg.rs:23:12 | LL | fn foo5(_: impl ?Sized) {} | ^^^^^^^^^^^ @@ -131,7 +131,7 @@ LL | fn foo5(_: &impl ?Sized) {} | + error[E0277]: the size for values of type `impl ?Sized + ?Sized` cannot be known at compilation time - --> $DIR/bad-suggestionf-for-repeated-unsized-bound-127441.rs:27:12 + --> $DIR/fix-dyn-sized-fn-param-sugg.rs:26:12 | LL | fn foo6(_: impl ?Sized + ?Sized) {} | ^^^^^^^^^^^^^^^^^^^^ @@ -151,7 +151,7 @@ LL | fn foo6(_: &impl ?Sized + ?Sized) {} | + error[E0277]: the size for values of type `impl ?Sized + ?Sized + Debug` cannot be known at compilation time - --> $DIR/bad-suggestionf-for-repeated-unsized-bound-127441.rs:31:12 + --> $DIR/fix-dyn-sized-fn-param-sugg.rs:30:12 | LL | fn foo7(_: impl ?Sized + ?Sized + Debug) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -171,7 +171,7 @@ LL | fn foo7(_: &impl ?Sized + ?Sized + Debug) {} | + error[E0277]: the size for values of type `impl ?Sized + Debug + ?Sized` cannot be known at compilation time - --> $DIR/bad-suggestionf-for-repeated-unsized-bound-127441.rs:35:12 + --> $DIR/fix-dyn-sized-fn-param-sugg.rs:34:12 | LL | fn foo8(_: impl ?Sized + Debug + ?Sized ) {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/trait-bounds/maybe-bound-has-path-args.rs b/tests/ui/trait-bounds/maybe-bound-has-path-args.rs index e5abcae5d21..14a26670497 100644 --- a/tests/ui/trait-bounds/maybe-bound-has-path-args.rs +++ b/tests/ui/trait-bounds/maybe-bound-has-path-args.rs @@ -2,6 +2,6 @@ trait Trait {} fn test<T: ?self::<i32>::Trait>() {} //~^ ERROR type arguments are not allowed on module `maybe_bound_has_path_args` -//~| ERROR relaxing a default bound only does something for `?Sized` +//~| ERROR bound modifier `?` can only be applied to `Sized` fn main() {} diff --git a/tests/ui/trait-bounds/maybe-bound-has-path-args.stderr b/tests/ui/trait-bounds/maybe-bound-has-path-args.stderr index dc55b26c918..bf968b05af0 100644 --- a/tests/ui/trait-bounds/maybe-bound-has-path-args.stderr +++ b/tests/ui/trait-bounds/maybe-bound-has-path-args.stderr @@ -1,4 +1,4 @@ -error: relaxing a default bound only does something for `?Sized`; all other traits are not bound by default +error: bound modifier `?` can only be applied to `Sized` --> $DIR/maybe-bound-has-path-args.rs:3:12 | LL | fn test<T: ?self::<i32>::Trait>() {} diff --git a/tests/ui/trait-bounds/maybe-bound-with-assoc.rs b/tests/ui/trait-bounds/maybe-bound-with-assoc.rs index 9127c2de16d..e123f18474d 100644 --- a/tests/ui/trait-bounds/maybe-bound-with-assoc.rs +++ b/tests/ui/trait-bounds/maybe-bound-with-assoc.rs @@ -2,11 +2,11 @@ trait HasAssoc { type Assoc; } fn hasassoc<T: ?HasAssoc<Assoc = ()>>() {} -//~^ ERROR relaxing a default bound +//~^ ERROR bound modifier `?` can only be applied to `Sized` trait NoAssoc {} fn noassoc<T: ?NoAssoc<Missing = ()>>() {} -//~^ ERROR relaxing a default bound +//~^ ERROR bound modifier `?` can only be applied to `Sized` //~| ERROR associated type `Missing` not found for `NoAssoc` fn main() {} diff --git a/tests/ui/trait-bounds/maybe-bound-with-assoc.stderr b/tests/ui/trait-bounds/maybe-bound-with-assoc.stderr index 36a1e0ade20..b2ae0584aff 100644 --- a/tests/ui/trait-bounds/maybe-bound-with-assoc.stderr +++ b/tests/ui/trait-bounds/maybe-bound-with-assoc.stderr @@ -1,10 +1,10 @@ -error: relaxing a default bound only does something for `?Sized`; all other traits are not bound by default +error: bound modifier `?` can only be applied to `Sized` --> $DIR/maybe-bound-with-assoc.rs:4:16 | LL | fn hasassoc<T: ?HasAssoc<Assoc = ()>>() {} | ^^^^^^^^^^^^^^^^^^^^^ -error: relaxing a default bound only does something for `?Sized`; all other traits are not bound by default +error: bound modifier `?` can only be applied to `Sized` --> $DIR/maybe-bound-with-assoc.rs:8:15 | LL | fn noassoc<T: ?NoAssoc<Missing = ()>>() {} diff --git a/tests/ui/trait-bounds/more_maybe_bounds.rs b/tests/ui/trait-bounds/more_maybe_bounds.rs new file mode 100644 index 00000000000..47348b0a0dd --- /dev/null +++ b/tests/ui/trait-bounds/more_maybe_bounds.rs @@ -0,0 +1,29 @@ +// FIXME(more_maybe_bounds): Even under `more_maybe_bounds` / `-Zexperimental-default-bounds`, +// trying to relax non-default bounds should still be an error in all contexts! As you can see +// there are places like supertrait bounds and trait object types where we currently don't perform +// this check. +#![feature(auto_traits, more_maybe_bounds, negative_impls)] + +trait Trait1 {} +auto trait Trait2 {} + +// FIXME: `?Trait1` should be rejected, `Trait1` isn't marked `#[lang = "default_traitN"]`. +trait Trait3: ?Trait1 {} +trait Trait4 where Self: Trait1 {} + +// FIXME: `?Trait2` should be rejected, `Trait2` isn't marked `#[lang = "default_traitN"]`. +fn foo(_: Box<(dyn Trait3 + ?Trait2)>) {} +fn bar<T: ?Sized + ?Trait2 + ?Trait1 + ?Trait4>(_: &T) {} +//~^ ERROR bound modifier `?` can only be applied to default traits like `Sized` +//~| ERROR bound modifier `?` can only be applied to default traits like `Sized` +//~| ERROR bound modifier `?` can only be applied to default traits like `Sized` + +struct S; +impl !Trait2 for S {} +impl Trait1 for S {} +impl Trait3 for S {} + +fn main() { + foo(Box::new(S)); + bar(&S); +} diff --git a/tests/ui/trait-bounds/more_maybe_bounds.stderr b/tests/ui/trait-bounds/more_maybe_bounds.stderr new file mode 100644 index 00000000000..09c9fc31165 --- /dev/null +++ b/tests/ui/trait-bounds/more_maybe_bounds.stderr @@ -0,0 +1,20 @@ +error: bound modifier `?` can only be applied to default traits like `Sized` + --> $DIR/more_maybe_bounds.rs:16:20 + | +LL | fn bar<T: ?Sized + ?Trait2 + ?Trait1 + ?Trait4>(_: &T) {} + | ^^^^^^^ + +error: bound modifier `?` can only be applied to default traits like `Sized` + --> $DIR/more_maybe_bounds.rs:16:30 + | +LL | fn bar<T: ?Sized + ?Trait2 + ?Trait1 + ?Trait4>(_: &T) {} + | ^^^^^^^ + +error: bound modifier `?` can only be applied to default traits like `Sized` + --> $DIR/more_maybe_bounds.rs:16:40 + | +LL | fn bar<T: ?Sized + ?Trait2 + ?Trait1 + ?Trait4>(_: &T) {} + | ^^^^^^^ + +error: aborting due to 3 previous errors + diff --git a/tests/ui/traits/const-traits/hir-const-check.rs b/tests/ui/traits/const-traits/hir-const-check.rs index c485fb12184..1b6fa1afab9 100644 --- a/tests/ui/traits/const-traits/hir-const-check.rs +++ b/tests/ui/traits/const-traits/hir-const-check.rs @@ -1,8 +1,10 @@ +//@ check-pass //@ compile-flags: -Znext-solver // Regression test for #69615. #![feature(const_trait_impl)] +#![feature(const_try)] #[const_trait] pub trait MyTrait { @@ -12,8 +14,6 @@ pub trait MyTrait { impl const MyTrait for () { fn method(&self) -> Option<()> { Some(())?; - //~^ ERROR `?` is not allowed on - //~| ERROR `?` is not allowed on None } } diff --git a/tests/ui/traits/const-traits/hir-const-check.stderr b/tests/ui/traits/const-traits/hir-const-check.stderr deleted file mode 100644 index d66a7ea3144..00000000000 --- a/tests/ui/traits/const-traits/hir-const-check.stderr +++ /dev/null @@ -1,19 +0,0 @@ -error[E0015]: `?` is not allowed on `Option<()>` in constant functions - --> $DIR/hir-const-check.rs:14:9 - | -LL | Some(())?; - | ^^^^^^^^^ - | - = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants - -error[E0015]: `?` is not allowed on `Option<()>` in constant functions - --> $DIR/hir-const-check.rs:14:9 - | -LL | Some(())?; - | ^^^^^^^^^ - | - = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants - -error: aborting due to 2 previous errors - -For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/const-traits/ice-119717-constant-lifetime.rs b/tests/ui/traits/const-traits/ice-119717-constant-lifetime.rs index 47c85980aca..af552ac0c5e 100644 --- a/tests/ui/traits/const-traits/ice-119717-constant-lifetime.rs +++ b/tests/ui/traits/const-traits/ice-119717-constant-lifetime.rs @@ -1,11 +1,10 @@ #![allow(incomplete_features)] -#![feature(const_trait_impl, try_trait_v2)] +#![feature(const_trait_impl, const_try, try_trait_v2)] use std::ops::FromResidual; impl<T> const FromResidual for T { - //~^ ERROR const `impl` for trait `FromResidual` which is not `const` - //~| ERROR type parameter `T` must be used as the type parameter for some local type + //~^ ERROR type parameter `T` must be used as the type parameter for some local type fn from_residual(t: T) -> _ { //~^ ERROR the placeholder `_` is not allowed t diff --git a/tests/ui/traits/const-traits/ice-119717-constant-lifetime.stderr b/tests/ui/traits/const-traits/ice-119717-constant-lifetime.stderr index 5c5fba95f02..08fc73fe77b 100644 --- a/tests/ui/traits/const-traits/ice-119717-constant-lifetime.stderr +++ b/tests/ui/traits/const-traits/ice-119717-constant-lifetime.stderr @@ -1,12 +1,3 @@ -error: const `impl` for trait `FromResidual` which is not `const` - --> $DIR/ice-119717-constant-lifetime.rs:6:15 - | -LL | impl<T> const FromResidual for T { - | ^^^^^^^^^^^^ this trait is not `const` - | - = note: marking a trait with `const` ensures all default method bodies are `const` - = note: adding a non-const method body in the future would be a breaking change - error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct<T>`) --> $DIR/ice-119717-constant-lifetime.rs:6:6 | @@ -17,7 +8,7 @@ LL | impl<T> const FromResidual for T { = note: only traits defined in the current crate can be implemented for a type parameter error[E0121]: the placeholder `_` is not allowed within types on item signatures for associated functions - --> $DIR/ice-119717-constant-lifetime.rs:9:31 + --> $DIR/ice-119717-constant-lifetime.rs:8:31 | LL | fn from_residual(t: T) -> _ { | ^ not allowed in type signatures @@ -28,7 +19,7 @@ LL - fn from_residual(t: T) -> _ { LL + fn from_residual(t: T) -> T { | -error: aborting due to 3 previous errors +error: aborting due to 2 previous errors Some errors have detailed explanations: E0121, E0210. For more information about an error, try `rustc --explain E0121`. diff --git a/tests/ui/traits/const-traits/ice-126148-failed-to-normalize.rs b/tests/ui/traits/const-traits/ice-126148-failed-to-normalize.rs index 5e368b9e6a9..bfce9dc9c73 100644 --- a/tests/ui/traits/const-traits/ice-126148-failed-to-normalize.rs +++ b/tests/ui/traits/const-traits/ice-126148-failed-to-normalize.rs @@ -6,20 +6,16 @@ struct TryMe; struct Error; impl const FromResidual<Error> for TryMe {} -//~^ ERROR const `impl` for trait `FromResidual` which is not `const` -//~| ERROR not all trait items implemented +//~^ ERROR not all trait items implemented impl const Try for TryMe { - //~^ ERROR const `impl` for trait `Try` which is not `const` - //~| ERROR not all trait items implemented + //~^ ERROR not all trait items implemented type Output = (); type Residual = Error; } const fn t() -> TryMe { TryMe?; - //~^ ERROR `?` is not allowed on - //~| ERROR `?` is not allowed on TryMe } diff --git a/tests/ui/traits/const-traits/ice-126148-failed-to-normalize.stderr b/tests/ui/traits/const-traits/ice-126148-failed-to-normalize.stderr index 849d6522cd6..183203aa8ba 100644 --- a/tests/ui/traits/const-traits/ice-126148-failed-to-normalize.stderr +++ b/tests/ui/traits/const-traits/ice-126148-failed-to-normalize.stderr @@ -1,12 +1,3 @@ -error: const `impl` for trait `FromResidual` which is not `const` - --> $DIR/ice-126148-failed-to-normalize.rs:8:12 - | -LL | impl const FromResidual<Error> for TryMe {} - | ^^^^^^^^^^^^^^^^^^^ this trait is not `const` - | - = note: marking a trait with `const` ensures all default method bodies are `const` - = note: adding a non-const method body in the future would be a breaking change - error[E0046]: not all trait items implemented, missing: `from_residual` --> $DIR/ice-126148-failed-to-normalize.rs:8:1 | @@ -15,17 +6,8 @@ LL | impl const FromResidual<Error> for TryMe {} | = help: implement the missing item: `fn from_residual(_: Error) -> Self { todo!() }` -error: const `impl` for trait `Try` which is not `const` - --> $DIR/ice-126148-failed-to-normalize.rs:12:12 - | -LL | impl const Try for TryMe { - | ^^^ this trait is not `const` - | - = note: marking a trait with `const` ensures all default method bodies are `const` - = note: adding a non-const method body in the future would be a breaking change - error[E0046]: not all trait items implemented, missing: `from_output`, `branch` - --> $DIR/ice-126148-failed-to-normalize.rs:12:1 + --> $DIR/ice-126148-failed-to-normalize.rs:11:1 | LL | impl const Try for TryMe { | ^^^^^^^^^^^^^^^^^^^^^^^^ missing `from_output`, `branch` in implementation @@ -33,23 +15,6 @@ LL | impl const Try for TryMe { = help: implement the missing item: `fn from_output(_: <Self as Try>::Output) -> Self { todo!() }` = help: implement the missing item: `fn branch(self) -> ControlFlow<<Self as Try>::Residual, <Self as Try>::Output> { todo!() }` -error[E0015]: `?` is not allowed on `TryMe` in constant functions - --> $DIR/ice-126148-failed-to-normalize.rs:20:5 - | -LL | TryMe?; - | ^^^^^^ - | - = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants - -error[E0015]: `?` is not allowed on `TryMe` in constant functions - --> $DIR/ice-126148-failed-to-normalize.rs:20:5 - | -LL | TryMe?; - | ^^^^^^ - | - = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants - -error: aborting due to 6 previous errors +error: aborting due to 2 previous errors -Some errors have detailed explanations: E0015, E0046. -For more information about an error, try `rustc --explain E0015`. +For more information about this error, try `rustc --explain E0046`. diff --git a/tests/ui/traits/const-traits/mutually-exclusive-trait-bound-modifiers.rs b/tests/ui/traits/const-traits/mutually-exclusive-trait-bound-modifiers.rs index 5f47778a140..8d1d3a4c790 100644 --- a/tests/ui/traits/const-traits/mutually-exclusive-trait-bound-modifiers.rs +++ b/tests/ui/traits/const-traits/mutually-exclusive-trait-bound-modifiers.rs @@ -2,9 +2,12 @@ const fn maybe_const_maybe<T: [const] ?Sized>() {} //~^ ERROR `[const]` trait not allowed with `?` trait polarity modifier +//~| ERROR `[const]` can only be applied to `const` traits +//~| ERROR `[const]` can only be applied to `const` traits fn const_maybe<T: const ?Sized>() {} //~^ ERROR `const` trait not allowed with `?` trait polarity modifier +//~| ERROR `const` can only be applied to `const` traits const fn maybe_const_negative<T: [const] !Trait>() {} //~^ ERROR `[const]` trait not allowed with `!` trait polarity modifier diff --git a/tests/ui/traits/const-traits/mutually-exclusive-trait-bound-modifiers.stderr b/tests/ui/traits/const-traits/mutually-exclusive-trait-bound-modifiers.stderr index 429131f905f..0ac40c51270 100644 --- a/tests/ui/traits/const-traits/mutually-exclusive-trait-bound-modifiers.stderr +++ b/tests/ui/traits/const-traits/mutually-exclusive-trait-bound-modifiers.stderr @@ -7,7 +7,7 @@ LL | const fn maybe_const_maybe<T: [const] ?Sized>() {} | there is not a well-defined meaning for a `[const] ?` trait error: `const` trait not allowed with `?` trait polarity modifier - --> $DIR/mutually-exclusive-trait-bound-modifiers.rs:6:25 + --> $DIR/mutually-exclusive-trait-bound-modifiers.rs:8:25 | LL | fn const_maybe<T: const ?Sized>() {} | ----- ^ @@ -15,7 +15,7 @@ LL | fn const_maybe<T: const ?Sized>() {} | there is not a well-defined meaning for a `const ?` trait error: `[const]` trait not allowed with `!` trait polarity modifier - --> $DIR/mutually-exclusive-trait-bound-modifiers.rs:9:42 + --> $DIR/mutually-exclusive-trait-bound-modifiers.rs:12:42 | LL | const fn maybe_const_negative<T: [const] !Trait>() {} | ------- ^ @@ -23,7 +23,7 @@ LL | const fn maybe_const_negative<T: [const] !Trait>() {} | there is not a well-defined meaning for a `[const] !` trait error: `const` trait not allowed with `!` trait polarity modifier - --> $DIR/mutually-exclusive-trait-bound-modifiers.rs:13:28 + --> $DIR/mutually-exclusive-trait-bound-modifiers.rs:16:28 | LL | fn const_negative<T: const !Trait>() {} | ----- ^ @@ -31,16 +31,44 @@ LL | fn const_negative<T: const !Trait>() {} | there is not a well-defined meaning for a `const !` trait error: negative bounds are not supported - --> $DIR/mutually-exclusive-trait-bound-modifiers.rs:9:42 + --> $DIR/mutually-exclusive-trait-bound-modifiers.rs:12:42 | LL | const fn maybe_const_negative<T: [const] !Trait>() {} | ^ error: negative bounds are not supported - --> $DIR/mutually-exclusive-trait-bound-modifiers.rs:13:28 + --> $DIR/mutually-exclusive-trait-bound-modifiers.rs:16:28 | LL | fn const_negative<T: const !Trait>() {} | ^ -error: aborting due to 6 previous errors +error: `[const]` can only be applied to `const` traits + --> $DIR/mutually-exclusive-trait-bound-modifiers.rs:3:31 + | +LL | const fn maybe_const_maybe<T: [const] ?Sized>() {} + | ^^^^^^^ can't be applied to `Sized` + | +note: `Sized` can't be used with `[const]` because it isn't `const` + --> $SRC_DIR/core/src/marker.rs:LL:COL + +error: `[const]` can only be applied to `const` traits + --> $DIR/mutually-exclusive-trait-bound-modifiers.rs:3:31 + | +LL | const fn maybe_const_maybe<T: [const] ?Sized>() {} + | ^^^^^^^ can't be applied to `Sized` + | +note: `Sized` can't be used with `[const]` because it isn't `const` + --> $SRC_DIR/core/src/marker.rs:LL:COL + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + +error: `const` can only be applied to `const` traits + --> $DIR/mutually-exclusive-trait-bound-modifiers.rs:8:19 + | +LL | fn const_maybe<T: const ?Sized>() {} + | ^^^^^ can't be applied to `Sized` + | +note: `Sized` can't be used with `const` because it isn't `const` + --> $SRC_DIR/core/src/marker.rs:LL:COL + +error: aborting due to 9 previous errors diff --git a/tests/ui/traits/const-traits/trait-default-body-stability.rs b/tests/ui/traits/const-traits/trait-default-body-stability.rs index 567f1b3c284..a8157d37ce3 100644 --- a/tests/ui/traits/const-traits/trait-default-body-stability.rs +++ b/tests/ui/traits/const-traits/trait-default-body-stability.rs @@ -1,4 +1,4 @@ -//@ known-bug: #110395 +//@ check-pass //@ compile-flags: -Znext-solver #![allow(incomplete_features)] #![feature(staged_api)] diff --git a/tests/ui/traits/const-traits/trait-default-body-stability.stderr b/tests/ui/traits/const-traits/trait-default-body-stability.stderr deleted file mode 100644 index b995d6f4f3d..00000000000 --- a/tests/ui/traits/const-traits/trait-default-body-stability.stderr +++ /dev/null @@ -1,37 +0,0 @@ -error: const `impl` for trait `Try` which is not `const` - --> $DIR/trait-default-body-stability.rs:19:12 - | -LL | impl const Try for T { - | ^^^ this trait is not `const` - | - = note: marking a trait with `const` ensures all default method bodies are `const` - = note: adding a non-const method body in the future would be a breaking change - -error: const `impl` for trait `FromResidual` which is not `const` - --> $DIR/trait-default-body-stability.rs:34:12 - | -LL | impl const FromResidual for T { - | ^^^^^^^^^^^^ this trait is not `const` - | - = note: marking a trait with `const` ensures all default method bodies are `const` - = note: adding a non-const method body in the future would be a breaking change - -error[E0015]: `?` is not allowed on `T` in constant functions - --> $DIR/trait-default-body-stability.rs:46:9 - | -LL | T? - | ^^ - | - = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants - -error[E0015]: `?` is not allowed on `T` in constant functions - --> $DIR/trait-default-body-stability.rs:46:9 - | -LL | T? - | ^^ - | - = note: calls in constant functions are limited to constant functions, tuple structs and tuple variants - -error: aborting due to 4 previous errors - -For more information about this error, try `rustc --explain E0015`. diff --git a/tests/ui/traits/default_auto_traits/maybe-bounds-in-dyn-traits.rs b/tests/ui/traits/default_auto_traits/maybe-bounds-in-dyn-traits.rs index 5069cd256b2..e7cca41a47e 100644 --- a/tests/ui/traits/default_auto_traits/maybe-bounds-in-dyn-traits.rs +++ b/tests/ui/traits/default_auto_traits/maybe-bounds-in-dyn-traits.rs @@ -64,4 +64,8 @@ fn main() { x.leak_foo(); //~^ ERROR the trait bound `dyn Trait: Leak` is not satisfied x.maybe_leak_foo(); + // Ensure that we validate the generic args of relaxed bounds in trait object types. + let _: dyn Trait + ?Leak<(), Undefined = ()>; + //~^ ERROR trait takes 0 generic arguments but 1 generic argument was supplied + //~| ERROR associated type `Undefined` not found for `Leak` } diff --git a/tests/ui/traits/default_auto_traits/maybe-bounds-in-dyn-traits.stderr b/tests/ui/traits/default_auto_traits/maybe-bounds-in-dyn-traits.stderr index 48745e40268..350233b7cbe 100644 --- a/tests/ui/traits/default_auto_traits/maybe-bounds-in-dyn-traits.stderr +++ b/tests/ui/traits/default_auto_traits/maybe-bounds-in-dyn-traits.stderr @@ -18,6 +18,27 @@ note: required by a bound in `Trait::leak_foo` LL | fn leak_foo(&self) {} | ^^^^^^^^^^^^^^^^^^^^^ required by this bound in `Trait::leak_foo` -error: aborting due to 2 previous errors +error[E0107]: trait takes 0 generic arguments but 1 generic argument was supplied + --> $DIR/maybe-bounds-in-dyn-traits.rs:68:25 + | +LL | let _: dyn Trait + ?Leak<(), Undefined = ()>; + | ^^^^-------------------- help: remove the unnecessary generics + | | + | expected 0 generic arguments + | +note: trait defined here, with 0 generic parameters + --> $DIR/maybe-bounds-in-dyn-traits.rs:44:12 + | +LL | auto trait Leak {} + | ^^^^ + +error[E0220]: associated type `Undefined` not found for `Leak` + --> $DIR/maybe-bounds-in-dyn-traits.rs:68:34 + | +LL | let _: dyn Trait + ?Leak<(), Undefined = ()>; + | ^^^^^^^^^ associated type `Undefined` not found + +error: aborting due to 4 previous errors -For more information about this error, try `rustc --explain E0277`. +Some errors have detailed explanations: E0107, E0220, E0277. +For more information about an error, try `rustc --explain E0107`. diff --git a/tests/ui/traits/maybe-polarity-pass.rs b/tests/ui/traits/maybe-polarity-pass.rs deleted file mode 100644 index 1ccd52bc169..00000000000 --- a/tests/ui/traits/maybe-polarity-pass.rs +++ /dev/null @@ -1,25 +0,0 @@ -#![feature(auto_traits)] -#![feature(more_maybe_bounds)] -#![feature(negative_impls)] - -trait Trait1 {} -auto trait Trait2 {} - -trait Trait3 : ?Trait1 {} -trait Trait4 where Self: Trait1 {} - -fn foo(_: Box<(dyn Trait3 + ?Trait2)>) {} -fn bar<T: ?Sized + ?Trait2 + ?Trait1 + ?Trait4>(_: &T) {} -//~^ ERROR relaxing a default bound only does something for `?Sized`; all other traits are not bound by default -//~| ERROR relaxing a default bound only does something for `?Sized`; all other traits are not bound by default -//~| ERROR relaxing a default bound only does something for `?Sized`; all other traits are not bound by default - -struct S; -impl !Trait2 for S {} -impl Trait1 for S {} -impl Trait3 for S {} - -fn main() { - foo(Box::new(S)); - bar(&S); -} diff --git a/tests/ui/traits/maybe-polarity-pass.stderr b/tests/ui/traits/maybe-polarity-pass.stderr deleted file mode 100644 index 1f378dd665a..00000000000 --- a/tests/ui/traits/maybe-polarity-pass.stderr +++ /dev/null @@ -1,20 +0,0 @@ -error: relaxing a default bound only does something for `?Sized`; all other traits are not bound by default - --> $DIR/maybe-polarity-pass.rs:12:20 - | -LL | fn bar<T: ?Sized + ?Trait2 + ?Trait1 + ?Trait4>(_: &T) {} - | ^^^^^^^ - -error: relaxing a default bound only does something for `?Sized`; all other traits are not bound by default - --> $DIR/maybe-polarity-pass.rs:12:30 - | -LL | fn bar<T: ?Sized + ?Trait2 + ?Trait1 + ?Trait4>(_: &T) {} - | ^^^^^^^ - -error: relaxing a default bound only does something for `?Sized`; all other traits are not bound by default - --> $DIR/maybe-polarity-pass.rs:12:40 - | -LL | fn bar<T: ?Sized + ?Trait2 + ?Trait1 + ?Trait4>(_: &T) {} - | ^^^^^^^ - -error: aborting due to 3 previous errors - diff --git a/tests/ui/traits/maybe-polarity-repeated.rs b/tests/ui/traits/maybe-polarity-repeated.rs deleted file mode 100644 index fd1ef567b3e..00000000000 --- a/tests/ui/traits/maybe-polarity-repeated.rs +++ /dev/null @@ -1,9 +0,0 @@ -#![feature(more_maybe_bounds)] - -trait Trait {} -fn foo<T: ?Trait + ?Trait>(_: T) {} -//~^ ERROR type parameter has more than one relaxed default bound, only one is supported -//~| ERROR relaxing a default bound only does something for `?Sized`; all other traits are not bound by default -//~| ERROR relaxing a default bound only does something for `?Sized`; all other traits are not bound by default - -fn main() {} diff --git a/tests/ui/traits/maybe-polarity-repeated.stderr b/tests/ui/traits/maybe-polarity-repeated.stderr deleted file mode 100644 index 4fa1dc45bda..00000000000 --- a/tests/ui/traits/maybe-polarity-repeated.stderr +++ /dev/null @@ -1,21 +0,0 @@ -error[E0203]: type parameter has more than one relaxed default bound, only one is supported - --> $DIR/maybe-polarity-repeated.rs:4:11 - | -LL | fn foo<T: ?Trait + ?Trait>(_: T) {} - | ^^^^^^ ^^^^^^ - -error: relaxing a default bound only does something for `?Sized`; all other traits are not bound by default - --> $DIR/maybe-polarity-repeated.rs:4:11 - | -LL | fn foo<T: ?Trait + ?Trait>(_: T) {} - | ^^^^^^ - -error: relaxing a default bound only does something for `?Sized`; all other traits are not bound by default - --> $DIR/maybe-polarity-repeated.rs:4:20 - | -LL | fn foo<T: ?Trait + ?Trait>(_: T) {} - | ^^^^^^ - -error: aborting due to 3 previous errors - -For more information about this error, try `rustc --explain E0203`. diff --git a/tests/ui/traits/maybe-trait-bounds-forbidden-locations.rs b/tests/ui/traits/maybe-trait-bounds-forbidden-locations.rs deleted file mode 100644 index 04963c98765..00000000000 --- a/tests/ui/traits/maybe-trait-bounds-forbidden-locations.rs +++ /dev/null @@ -1,18 +0,0 @@ -//! Test that ?Trait bounds are forbidden in supertraits and trait object types. -//! -//! While `?Sized` and other maybe bounds are allowed in type parameter bounds and where clauses, -//! they are explicitly forbidden in certain syntactic positions: -//! - As supertraits in trait definitions -//! - In trait object type expressions -//! -//! See https://github.com/rust-lang/rust/issues/20503 - -trait Tr: ?Sized {} -//~^ ERROR `?Trait` is not permitted in supertraits - -type A1 = dyn Tr + (?Sized); -//~^ ERROR `?Trait` is not permitted in trait object types -type A2 = dyn for<'a> Tr + (?Sized); -//~^ ERROR `?Trait` is not permitted in trait object types - -fn main() {} diff --git a/tests/ui/traits/maybe-trait-bounds-forbidden-locations.stderr b/tests/ui/traits/maybe-trait-bounds-forbidden-locations.stderr deleted file mode 100644 index bd0baa580bd..00000000000 --- a/tests/ui/traits/maybe-trait-bounds-forbidden-locations.stderr +++ /dev/null @@ -1,31 +0,0 @@ -error[E0658]: `?Trait` is not permitted in supertraits - --> $DIR/maybe-trait-bounds-forbidden-locations.rs:10:11 - | -LL | trait Tr: ?Sized {} - | ^^^^^^ - | - = note: traits are `?Sized` by default - = help: add `#![feature(more_maybe_bounds)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - -error[E0658]: `?Trait` is not permitted in trait object types - --> $DIR/maybe-trait-bounds-forbidden-locations.rs:13:20 - | -LL | type A1 = dyn Tr + (?Sized); - | ^^^^^^^^ - | - = help: add `#![feature(more_maybe_bounds)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - -error[E0658]: `?Trait` is not permitted in trait object types - --> $DIR/maybe-trait-bounds-forbidden-locations.rs:15:28 - | -LL | type A2 = dyn for<'a> Tr + (?Sized); - | ^^^^^^^^ - | - = help: add `#![feature(more_maybe_bounds)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - -error: aborting due to 3 previous errors - -For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/traits/next-solver/cycles/normalizes-to-is-not-productive.stderr b/tests/ui/traits/next-solver/cycles/normalizes-to-is-not-productive.stderr index 1eb445f4848..8901805a20f 100644 --- a/tests/ui/traits/next-solver/cycles/normalizes-to-is-not-productive.stderr +++ b/tests/ui/traits/next-solver/cycles/normalizes-to-is-not-productive.stderr @@ -12,13 +12,6 @@ LL | impl<T: Bound, U> Trait<U> for T { | ----- ^^^^^^^^ ^ | | | unsatisfied trait bound introduced here -note: required by a bound in `Bound` - --> $DIR/normalizes-to-is-not-productive.rs:8:1 - | -LL | / trait Bound { -LL | | fn method(); -LL | | } - | |_^ required by this bound in `Bound` error[E0277]: the trait bound `Foo: Bound` is not satisfied --> $DIR/normalizes-to-is-not-productive.rs:47:19 diff --git a/tests/ui/traits/next-solver/normalize/normalize-param-env-2.stderr b/tests/ui/traits/next-solver/normalize/normalize-param-env-2.stderr index 8d8909625ff..d179c805962 100644 --- a/tests/ui/traits/next-solver/normalize/normalize-param-env-2.stderr +++ b/tests/ui/traits/next-solver/normalize/normalize-param-env-2.stderr @@ -19,23 +19,6 @@ error[E0275]: overflow evaluating the requirement `<() as A<T>>::Assoc: A<T>` LL | Self::Assoc: A<T>, | ^^^^ -error[E0275]: overflow evaluating the requirement `<() as A<T>>::Assoc: MetaSized` - --> $DIR/normalize-param-env-2.rs:24:22 - | -LL | Self::Assoc: A<T>, - | ^^^^ - | -note: required by a bound in `A` - --> $DIR/normalize-param-env-2.rs:9:1 - | -LL | / trait A<T> { -LL | | type Assoc; -LL | | -LL | | fn f() -... | -LL | | } - | |_^ required by this bound in `A` - error[E0275]: overflow evaluating the requirement `<() as A<T>>::Assoc well-formed` --> $DIR/normalize-param-env-2.rs:24:22 | @@ -63,6 +46,6 @@ LL | where LL | Self::Assoc: A<T>, | ^^^^ required by this bound in `A::f` -error: aborting due to 6 previous errors +error: aborting due to 5 previous errors For more information about this error, try `rustc --explain E0275`. diff --git a/tests/ui/traits/next-solver/normalize/normalize-param-env-4.next.stderr b/tests/ui/traits/next-solver/normalize/normalize-param-env-4.next.stderr index 9f7f74f9466..f5fd9ce9864 100644 --- a/tests/ui/traits/next-solver/normalize/normalize-param-env-4.next.stderr +++ b/tests/ui/traits/next-solver/normalize/normalize-param-env-4.next.stderr @@ -4,20 +4,6 @@ error[E0275]: overflow evaluating the requirement `<T as Trait>::Assoc: Trait` LL | <T as Trait>::Assoc: Trait, | ^^^^^ -error[E0275]: overflow evaluating the requirement `<T as Trait>::Assoc: MetaSized` - --> $DIR/normalize-param-env-4.rs:19:26 - | -LL | <T as Trait>::Assoc: Trait, - | ^^^^^ - | -note: required by a bound in `Trait` - --> $DIR/normalize-param-env-4.rs:7:1 - | -LL | / trait Trait { -LL | | type Assoc; -LL | | } - | |_^ required by this bound in `Trait` - -error: aborting due to 2 previous errors +error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0275`. diff --git a/tests/ui/traits/wf-object/maybe-bound.rs b/tests/ui/traits/wf-object/maybe-bound.rs deleted file mode 100644 index 17771e976ef..00000000000 --- a/tests/ui/traits/wf-object/maybe-bound.rs +++ /dev/null @@ -1,18 +0,0 @@ -// Test that `dyn ... + ?Sized + ...` is okay (though `?Sized` has no effect in trait objects). - -trait Foo {} - -type _0 = dyn ?Sized + Foo; -//~^ ERROR `?Trait` is not permitted in trait object types - -type _1 = dyn Foo + ?Sized; -//~^ ERROR `?Trait` is not permitted in trait object types - -type _2 = dyn Foo + ?Sized + ?Sized; -//~^ ERROR `?Trait` is not permitted in trait object types -//~| ERROR `?Trait` is not permitted in trait object types - -type _3 = dyn ?Sized + Foo; -//~^ ERROR `?Trait` is not permitted in trait object types - -fn main() {} diff --git a/tests/ui/traits/wf-object/maybe-bound.stderr b/tests/ui/traits/wf-object/maybe-bound.stderr deleted file mode 100644 index be7afabd0d0..00000000000 --- a/tests/ui/traits/wf-object/maybe-bound.stderr +++ /dev/null @@ -1,48 +0,0 @@ -error[E0658]: `?Trait` is not permitted in trait object types - --> $DIR/maybe-bound.rs:5:15 - | -LL | type _0 = dyn ?Sized + Foo; - | ^^^^^^ - | - = help: add `#![feature(more_maybe_bounds)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - -error[E0658]: `?Trait` is not permitted in trait object types - --> $DIR/maybe-bound.rs:8:21 - | -LL | type _1 = dyn Foo + ?Sized; - | ^^^^^^ - | - = help: add `#![feature(more_maybe_bounds)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - -error[E0658]: `?Trait` is not permitted in trait object types - --> $DIR/maybe-bound.rs:11:21 - | -LL | type _2 = dyn Foo + ?Sized + ?Sized; - | ^^^^^^ - | - = help: add `#![feature(more_maybe_bounds)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - -error[E0658]: `?Trait` is not permitted in trait object types - --> $DIR/maybe-bound.rs:11:30 - | -LL | type _2 = dyn Foo + ?Sized + ?Sized; - | ^^^^^^ - | - = help: add `#![feature(more_maybe_bounds)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - -error[E0658]: `?Trait` is not permitted in trait object types - --> $DIR/maybe-bound.rs:15:15 - | -LL | type _3 = dyn ?Sized + Foo; - | ^^^^^^ - | - = help: add `#![feature(more_maybe_bounds)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - -error: aborting due to 5 previous errors - -For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/traits/wf-object/only-maybe-bound.rs b/tests/ui/traits/wf-object/only-maybe-bound.rs index 3e6db3e997c..96360e0331c 100644 --- a/tests/ui/traits/wf-object/only-maybe-bound.rs +++ b/tests/ui/traits/wf-object/only-maybe-bound.rs @@ -2,6 +2,6 @@ type _0 = dyn ?Sized; //~^ ERROR at least one trait is required for an object type [E0224] -//~| ERROR ?Trait` is not permitted in trait object types +//~| ERROR relaxed bounds are not permitted in trait object types fn main() {} diff --git a/tests/ui/traits/wf-object/only-maybe-bound.stderr b/tests/ui/traits/wf-object/only-maybe-bound.stderr index 26269476eaa..6ae4568c699 100644 --- a/tests/ui/traits/wf-object/only-maybe-bound.stderr +++ b/tests/ui/traits/wf-object/only-maybe-bound.stderr @@ -1,11 +1,8 @@ -error[E0658]: `?Trait` is not permitted in trait object types +error: relaxed bounds are not permitted in trait object types --> $DIR/only-maybe-bound.rs:3:15 | LL | type _0 = dyn ?Sized; | ^^^^^^ - | - = help: add `#![feature(more_maybe_bounds)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date error[E0224]: at least one trait is required for an object type --> $DIR/only-maybe-bound.rs:3:11 @@ -15,5 +12,4 @@ LL | type _0 = dyn ?Sized; error: aborting due to 2 previous errors -Some errors have detailed explanations: E0224, E0658. -For more information about an error, try `rustc --explain E0224`. +For more information about this error, try `rustc --explain E0224`. diff --git a/tests/ui/type/pattern_types/validity.rs b/tests/ui/type/pattern_types/validity.rs index a4e49692c98..432aacb9be3 100644 --- a/tests/ui/type/pattern_types/validity.rs +++ b/tests/ui/type/pattern_types/validity.rs @@ -11,7 +11,7 @@ const BAD: pattern_type!(u32 is 1..) = unsafe { std::mem::transmute(0) }; //~^ ERROR: constructing invalid value: encountered 0 const BAD_UNINIT: pattern_type!(u32 is 1..) = - //~^ ERROR: using uninitialized data, but this operation requires initialized memory + //~^ ERROR: this operation requires initialized memory unsafe { std::mem::transmute(std::mem::MaybeUninit::<u32>::uninit()) }; const BAD_PTR: pattern_type!(usize is 1..) = unsafe { std::mem::transmute(&42) }; @@ -27,7 +27,7 @@ const BAD_FOO: Foo = Foo(Bar(unsafe { std::mem::transmute(0) })); //~^ ERROR: constructing invalid value at .0.0: encountered 0 const CHAR_UNINIT: pattern_type!(char is 'A'..'Z') = - //~^ ERROR: using uninitialized data, but this operation requires initialized memory + //~^ ERROR: this operation requires initialized memory unsafe { std::mem::transmute(std::mem::MaybeUninit::<u32>::uninit()) }; const CHAR_OOB_PAT: pattern_type!(char is 'A'..'Z') = unsafe { std::mem::transmute('a') }; diff --git a/tests/ui/type/pattern_types/validity.stderr b/tests/ui/type/pattern_types/validity.stderr index 4f4c16028f6..b545cd75ddb 100644 --- a/tests/ui/type/pattern_types/validity.stderr +++ b/tests/ui/type/pattern_types/validity.stderr @@ -9,11 +9,15 @@ LL | const BAD: pattern_type!(u32 is 1..) = unsafe { std::mem::transmute(0) }; HEX_DUMP } -error[E0080]: using uninitialized data, but this operation requires initialized memory +error[E0080]: reading memory at ALLOC0[0x0..0x4], but memory is uninitialized at [0x0..0x4], and this operation requires initialized memory --> $DIR/validity.rs:13:1 | LL | const BAD_UNINIT: pattern_type!(u32 is 1..) = | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `BAD_UNINIT` failed here + | + = note: the raw bytes of the constant (size: 4, align: 4) { + __ __ __ __ │ ░░░░ + } error[E0080]: unable to turn pointer into integer --> $DIR/validity.rs:17:1 @@ -46,11 +50,15 @@ LL | const BAD_FOO: Foo = Foo(Bar(unsafe { std::mem::transmute(0) })); HEX_DUMP } -error[E0080]: using uninitialized data, but this operation requires initialized memory +error[E0080]: reading memory at ALLOC1[0x0..0x4], but memory is uninitialized at [0x0..0x4], and this operation requires initialized memory --> $DIR/validity.rs:29:1 | LL | const CHAR_UNINIT: pattern_type!(char is 'A'..'Z') = | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ evaluation of `CHAR_UNINIT` failed here + | + = note: the raw bytes of the constant (size: 4, align: 4) { + __ __ __ __ │ ░░░░ + } error[E0080]: constructing invalid value: encountered 97, but expected something in the range 65..=89 --> $DIR/validity.rs:33:1 diff --git a/tests/ui/typeck/issue-91334.stderr b/tests/ui/typeck/issue-91334.stderr index 01e34919ce6..a348e1ebf7e 100644 --- a/tests/ui/typeck/issue-91334.stderr +++ b/tests/ui/typeck/issue-91334.stderr @@ -11,9 +11,8 @@ error: this file contains an unclosed delimiter --> $DIR/issue-91334.rs:7:23 | LL | fn f(){||yield(((){), - | - - - ^ - | | | | - | | | missing open `(` for this delimiter + | - - ^ + | | | | | unclosed delimiter | unclosed delimiter diff --git a/tests/ui/uninhabited/auxiliary/staged-api.rs b/tests/ui/uninhabited/auxiliary/staged-api.rs index 342ecf020ea..925bb1e0c65 100644 --- a/tests/ui/uninhabited/auxiliary/staged-api.rs +++ b/tests/ui/uninhabited/auxiliary/staged-api.rs @@ -6,3 +6,9 @@ pub struct Foo<T> { #[unstable(feature = "unstable", issue = "none")] pub field: T, } + +#[unstable(feature = "my_coro_state", issue = "none")] +pub enum MyCoroutineState<Y, R> { + Yielded(Y), + Complete(R), +} diff --git a/tests/ui/uninhabited/uninhabited-unstable-field.current.stderr b/tests/ui/uninhabited/uninhabited-unstable-field.current.stderr deleted file mode 100644 index 9e0feb4c473..00000000000 --- a/tests/ui/uninhabited/uninhabited-unstable-field.current.stderr +++ /dev/null @@ -1,22 +0,0 @@ -error[E0004]: non-exhaustive patterns: type `Foo<Void>` is non-empty - --> $DIR/uninhabited-unstable-field.rs:13:11 - | -LL | match x {} - | ^ - | -note: `Foo<Void>` defined here - --> $DIR/auxiliary/staged-api.rs:5:1 - | -LL | pub struct Foo<T> { - | ^^^^^^^^^^^^^^^^^ - = note: the matched value is of type `Foo<Void>` -help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern as shown - | -LL ~ match x { -LL + _ => todo!(), -LL ~ } - | - -error: aborting due to 1 previous error - -For more information about this error, try `rustc --explain E0004`. diff --git a/tests/ui/uninhabited/uninhabited-unstable-field.exhaustive.stderr b/tests/ui/uninhabited/uninhabited-unstable-field.exhaustive.stderr deleted file mode 100644 index 9e0feb4c473..00000000000 --- a/tests/ui/uninhabited/uninhabited-unstable-field.exhaustive.stderr +++ /dev/null @@ -1,22 +0,0 @@ -error[E0004]: non-exhaustive patterns: type `Foo<Void>` is non-empty - --> $DIR/uninhabited-unstable-field.rs:13:11 - | -LL | match x {} - | ^ - | -note: `Foo<Void>` defined here - --> $DIR/auxiliary/staged-api.rs:5:1 - | -LL | pub struct Foo<T> { - | ^^^^^^^^^^^^^^^^^ - = note: the matched value is of type `Foo<Void>` -help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern as shown - | -LL ~ match x { -LL + _ => todo!(), -LL ~ } - | - -error: aborting due to 1 previous error - -For more information about this error, try `rustc --explain E0004`. diff --git a/tests/ui/uninhabited/uninhabited-unstable-field.rs b/tests/ui/uninhabited/uninhabited-unstable-field.rs index 9b507c518ab..321b864aa27 100644 --- a/tests/ui/uninhabited/uninhabited-unstable-field.rs +++ b/tests/ui/uninhabited/uninhabited-unstable-field.rs @@ -1,29 +1,45 @@ //@ aux-build: staged-api.rs -//@ revisions: current exhaustive - +//! The field of `Pin` used to be public, which would cause `Pin<Void>` to be uninhabited. To remedy +//! this, we temporarily made it so unstable fields are always considered inhabited. This has now +//! been reverted, and this file ensures that we don't special-case unstable fields wrt +//! inhabitedness anymore. #![feature(exhaustive_patterns)] +#![feature(never_type)] +#![feature(my_coro_state)] // Custom feature from `staged-api.rs` +#![deny(unreachable_patterns)] extern crate staged_api; -use staged_api::Foo; +use staged_api::{Foo, MyCoroutineState}; enum Void {} fn demo(x: Foo<Void>) { match x {} - //~^ ERROR non-exhaustive patterns } -// Ensure that the pattern is not considered unreachable. +// Ensure that the pattern is considered unreachable. fn demo2(x: Foo<Void>) { match x { - Foo { .. } => {} + Foo { .. } => {} //~ ERROR unreachable } } // Same as above, but for wildcard. fn demo3(x: Foo<Void>) { - match x { _ => {} } + match x { + _ => {} //~ ERROR unreachable + } +} + +fn unstable_enum(x: MyCoroutineState<i32, !>) { + match x { + MyCoroutineState::Yielded(_) => {} + } + match x { + MyCoroutineState::Yielded(_) => {} + MyCoroutineState::Complete(_) => {} //~ ERROR unreachable + } } fn main() {} diff --git a/tests/ui/uninhabited/uninhabited-unstable-field.stderr b/tests/ui/uninhabited/uninhabited-unstable-field.stderr new file mode 100644 index 00000000000..a0c9f9366a6 --- /dev/null +++ b/tests/ui/uninhabited/uninhabited-unstable-field.stderr @@ -0,0 +1,40 @@ +error: unreachable pattern + --> $DIR/uninhabited-unstable-field.rs:24:9 + | +LL | Foo { .. } => {} + | ^^^^^^^^^^------ + | | + | matches no values because `Foo<Void>` is uninhabited + | help: remove the match arm + | + = note: to learn more about uninhabited types, see https://doc.rust-lang.org/nomicon/exotic-sizes.html#empty-types +note: the lint level is defined here + --> $DIR/uninhabited-unstable-field.rs:9:9 + | +LL | #![deny(unreachable_patterns)] + | ^^^^^^^^^^^^^^^^^^^^ + +error: unreachable pattern + --> $DIR/uninhabited-unstable-field.rs:31:9 + | +LL | _ => {} + | ^------ + | | + | matches no values because `Foo<Void>` is uninhabited + | help: remove the match arm + | + = note: to learn more about uninhabited types, see https://doc.rust-lang.org/nomicon/exotic-sizes.html#empty-types + +error: unreachable pattern + --> $DIR/uninhabited-unstable-field.rs:41:9 + | +LL | MyCoroutineState::Complete(_) => {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^------ + | | + | matches no values because `!` is uninhabited + | help: remove the match arm + | + = note: to learn more about uninhabited types, see https://doc.rust-lang.org/nomicon/exotic-sizes.html#empty-types + +error: aborting due to 3 previous errors + diff --git a/tests/ui/unsized/maybe-bounds-where.rs b/tests/ui/unsized/maybe-bounds-where.rs deleted file mode 100644 index 4c4141631a7..00000000000 --- a/tests/ui/unsized/maybe-bounds-where.rs +++ /dev/null @@ -1,28 +0,0 @@ -struct S1<T>(T) where (T): ?Sized; -//~^ ERROR `?Trait` bounds are only permitted at the point where a type parameter is declared - -struct S2<T>(T) where u8: ?Sized; -//~^ ERROR `?Trait` bounds are only permitted at the point where a type parameter is declared - -struct S3<T>(T) where &'static T: ?Sized; -//~^ ERROR `?Trait` bounds are only permitted at the point where a type parameter is declared - -trait Trait<'a> {} - -struct S4<T>(T) where for<'a> T: ?Trait<'a>; -//~^ ERROR `?Trait` bounds are only permitted at the point where a type parameter is declared -//~| ERROR relaxing a default bound only does something for `?Sized` - -struct S5<T>(*const T) where T: ?Trait<'static> + ?Sized; -//~^ ERROR type parameter has more than one relaxed default bound -//~| ERROR relaxing a default bound only does something for `?Sized` - -impl<T> S1<T> { - fn f() where T: ?Sized {} - //~^ ERROR `?Trait` bounds are only permitted at the point where a type parameter is declared -} - -fn main() { - let u = vec![1, 2, 3]; - let _s: S5<[u8]> = S5(&u[..]); // OK -} diff --git a/tests/ui/unsized/maybe-bounds-where.stderr b/tests/ui/unsized/maybe-bounds-where.stderr deleted file mode 100644 index fb6d37c2966..00000000000 --- a/tests/ui/unsized/maybe-bounds-where.stderr +++ /dev/null @@ -1,70 +0,0 @@ -error[E0658]: `?Trait` bounds are only permitted at the point where a type parameter is declared - --> $DIR/maybe-bounds-where.rs:1:28 - | -LL | struct S1<T>(T) where (T): ?Sized; - | ^^^^^^ - | - = help: add `#![feature(more_maybe_bounds)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - -error[E0658]: `?Trait` bounds are only permitted at the point where a type parameter is declared - --> $DIR/maybe-bounds-where.rs:4:27 - | -LL | struct S2<T>(T) where u8: ?Sized; - | ^^^^^^ - | - = help: add `#![feature(more_maybe_bounds)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - -error[E0658]: `?Trait` bounds are only permitted at the point where a type parameter is declared - --> $DIR/maybe-bounds-where.rs:7:35 - | -LL | struct S3<T>(T) where &'static T: ?Sized; - | ^^^^^^ - | - = help: add `#![feature(more_maybe_bounds)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - -error[E0658]: `?Trait` bounds are only permitted at the point where a type parameter is declared - --> $DIR/maybe-bounds-where.rs:12:34 - | -LL | struct S4<T>(T) where for<'a> T: ?Trait<'a>; - | ^^^^^^^^^^ - | - = help: add `#![feature(more_maybe_bounds)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - -error[E0658]: `?Trait` bounds are only permitted at the point where a type parameter is declared - --> $DIR/maybe-bounds-where.rs:21:21 - | -LL | fn f() where T: ?Sized {} - | ^^^^^^ - | - = help: add `#![feature(more_maybe_bounds)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - -error: relaxing a default bound only does something for `?Sized`; all other traits are not bound by default - --> $DIR/maybe-bounds-where.rs:12:34 - | -LL | struct S4<T>(T) where for<'a> T: ?Trait<'a>; - | ^^^^^^^^^^ - -error[E0203]: type parameter has more than one relaxed default bound, only one is supported - --> $DIR/maybe-bounds-where.rs:16:33 - | -LL | struct S5<T>(*const T) where T: ?Trait<'static> + ?Sized; - | ^^^^^^^^^^^^^^^ ^^^^^^ - | - = help: add `#![feature(more_maybe_bounds)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - -error: relaxing a default bound only does something for `?Sized`; all other traits are not bound by default - --> $DIR/maybe-bounds-where.rs:16:33 - | -LL | struct S5<T>(*const T) where T: ?Trait<'static> + ?Sized; - | ^^^^^^^^^^^^^^^ - -error: aborting due to 8 previous errors - -Some errors have detailed explanations: E0203, E0658. -For more information about an error, try `rustc --explain E0203`. diff --git a/tests/ui/unsized/relaxed-bounds-invalid-places.rs b/tests/ui/unsized/relaxed-bounds-invalid-places.rs new file mode 100644 index 00000000000..b8eda1e7786 --- /dev/null +++ b/tests/ui/unsized/relaxed-bounds-invalid-places.rs @@ -0,0 +1,34 @@ +// Test various places where relaxed bounds are not permitted. +// +// Relaxed bounds are only permitted inside impl-Trait, assoc ty item bounds and +// on type params defined by the closest item. + +struct S1<T>(T) where (T): ?Sized; //~ ERROR this relaxed bound is not permitted here + +struct S2<T>(T) where u8: ?Sized; //~ ERROR this relaxed bound is not permitted here + +struct S3<T>(T) where &'static T: ?Sized; //~ ERROR this relaxed bound is not permitted here + +trait Trait<'a> {} + +struct S4<T>(T) where for<'a> T: ?Trait<'a>; +//~^ ERROR this relaxed bound is not permitted here +//~| ERROR bound modifier `?` can only be applied to `Sized` + +struct S5<T>(*const T) where T: ?Trait<'static> + ?Sized; +//~^ ERROR bound modifier `?` can only be applied to `Sized` + +impl<T> S1<T> { + fn f() where T: ?Sized {} //~ ERROR this relaxed bound is not permitted here +} + +trait Tr: ?Sized {} //~ ERROR relaxed bounds are not permitted in supertrait bounds + +// Test that relaxed `Sized` bounds are rejected in trait object types: + +type O1 = dyn Tr + ?Sized; //~ ERROR relaxed bounds are not permitted in trait object types +type O2 = dyn ?Sized + ?Sized + Tr; +//~^ ERROR relaxed bounds are not permitted in trait object types +//~| ERROR relaxed bounds are not permitted in trait object types + +fn main() {} diff --git a/tests/ui/unsized/relaxed-bounds-invalid-places.stderr b/tests/ui/unsized/relaxed-bounds-invalid-places.stderr new file mode 100644 index 00000000000..30285d62693 --- /dev/null +++ b/tests/ui/unsized/relaxed-bounds-invalid-places.stderr @@ -0,0 +1,80 @@ +error: this relaxed bound is not permitted here + --> $DIR/relaxed-bounds-invalid-places.rs:6:28 + | +LL | struct S1<T>(T) where (T): ?Sized; + | ^^^^^^ + | + = note: in this context, relaxed bounds are only allowed on type parameters defined by the closest item + +error: this relaxed bound is not permitted here + --> $DIR/relaxed-bounds-invalid-places.rs:8:27 + | +LL | struct S2<T>(T) where u8: ?Sized; + | ^^^^^^ + | + = note: in this context, relaxed bounds are only allowed on type parameters defined by the closest item + +error: this relaxed bound is not permitted here + --> $DIR/relaxed-bounds-invalid-places.rs:10:35 + | +LL | struct S3<T>(T) where &'static T: ?Sized; + | ^^^^^^ + | + = note: in this context, relaxed bounds are only allowed on type parameters defined by the closest item + +error: this relaxed bound is not permitted here + --> $DIR/relaxed-bounds-invalid-places.rs:14:34 + | +LL | struct S4<T>(T) where for<'a> T: ?Trait<'a>; + | ^^^^^^^^^^ + | + = note: in this context, relaxed bounds are only allowed on type parameters defined by the closest item + +error: this relaxed bound is not permitted here + --> $DIR/relaxed-bounds-invalid-places.rs:22:21 + | +LL | fn f() where T: ?Sized {} + | ^^^^^^ + | + = note: in this context, relaxed bounds are only allowed on type parameters defined by the closest item + +error: relaxed bounds are not permitted in supertrait bounds + --> $DIR/relaxed-bounds-invalid-places.rs:25:11 + | +LL | trait Tr: ?Sized {} + | ^^^^^^ + | + = note: traits are `?Sized` by default + +error: relaxed bounds are not permitted in trait object types + --> $DIR/relaxed-bounds-invalid-places.rs:29:20 + | +LL | type O1 = dyn Tr + ?Sized; + | ^^^^^^ + +error: relaxed bounds are not permitted in trait object types + --> $DIR/relaxed-bounds-invalid-places.rs:30:15 + | +LL | type O2 = dyn ?Sized + ?Sized + Tr; + | ^^^^^^ + +error: relaxed bounds are not permitted in trait object types + --> $DIR/relaxed-bounds-invalid-places.rs:30:24 + | +LL | type O2 = dyn ?Sized + ?Sized + Tr; + | ^^^^^^ + +error: bound modifier `?` can only be applied to `Sized` + --> $DIR/relaxed-bounds-invalid-places.rs:14:34 + | +LL | struct S4<T>(T) where for<'a> T: ?Trait<'a>; + | ^^^^^^^^^^ + +error: bound modifier `?` can only be applied to `Sized` + --> $DIR/relaxed-bounds-invalid-places.rs:18:33 + | +LL | struct S5<T>(*const T) where T: ?Trait<'static> + ?Sized; + | ^^^^^^^^^^^^^^^ + +error: aborting due to 11 previous errors + diff --git a/tests/ui/wasm/simd-to-array-80108.rs b/tests/ui/wasm/simd-to-array-80108.rs index c7f8585eaa4..f6b368992be 100644 --- a/tests/ui/wasm/simd-to-array-80108.rs +++ b/tests/ui/wasm/simd-to-array-80108.rs @@ -10,6 +10,8 @@ pub struct Vector([i32; 4]); impl Vector { pub const fn to_array(self) -> [i32; 4] { - self.0 + // This used to just be `.0`, but that was banned in + // <https://github.com/rust-lang/compiler-team/issues/838> + unsafe { std::mem::transmute(self) } } } diff --git a/tests/ui/where-clauses/ignore-err-clauses.rs b/tests/ui/where-clauses/ignore-err-clauses.rs index 428ebf4b408..6f21e5ccbaa 100644 --- a/tests/ui/where-clauses/ignore-err-clauses.rs +++ b/tests/ui/where-clauses/ignore-err-clauses.rs @@ -1,13 +1,13 @@ use std::ops::Add; fn dbl<T>(x: T) -> <T as Add>::Output -//~^ ERROR type annotations needed where T: Copy + Add, UUU: Copy, //~^ ERROR cannot find type `UUU` in this scope { x + x + //~^ ERROR use of moved value: `x` } fn main() { diff --git a/tests/ui/where-clauses/ignore-err-clauses.stderr b/tests/ui/where-clauses/ignore-err-clauses.stderr index fbf1b99334f..9c76c1c6a04 100644 --- a/tests/ui/where-clauses/ignore-err-clauses.stderr +++ b/tests/ui/where-clauses/ignore-err-clauses.stderr @@ -1,16 +1,33 @@ error[E0412]: cannot find type `UUU` in this scope - --> $DIR/ignore-err-clauses.rs:7:5 + --> $DIR/ignore-err-clauses.rs:6:5 | LL | UUU: Copy, | ^^^ not found in this scope -error[E0282]: type annotations needed - --> $DIR/ignore-err-clauses.rs:3:14 +error[E0382]: use of moved value: `x` + --> $DIR/ignore-err-clauses.rs:9:9 | LL | fn dbl<T>(x: T) -> <T as Add>::Output - | ^ cannot infer type for type parameter `T` + | - move occurs because `x` has type `T`, which does not implement the `Copy` trait +... +LL | x + x + | ----^ + | | | + | | value used here after move + | `x` moved due to usage in operator + | +help: if `T` implemented `Clone`, you could clone the value + --> $DIR/ignore-err-clauses.rs:3:8 + | +LL | fn dbl<T>(x: T) -> <T as Add>::Output + | ^ consider constraining this type parameter with `Clone` +... +LL | x + x + | - you could clone this value +note: calling this operator moves the left-hand side + --> $SRC_DIR/core/src/ops/arith.rs:LL:COL error: aborting due to 2 previous errors -Some errors have detailed explanations: E0282, E0412. -For more information about an error, try `rustc --explain E0282`. +Some errors have detailed explanations: E0382, E0412. +For more information about an error, try `rustc --explain E0382`. |
